From nagle at animats.com Thu Sep 1 00:22:23 2011 From: nagle at animats.com (John Nagle) Date: Wed, 31 Aug 2011 21:22:23 -0700 Subject: try... except with unknown error types In-Reply-To: <4e51a32d$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e4ec405$0$29994$c3e8da3$5496439d@news.astraweb.com> <7xipprsxha.fsf@ruckus.brouhaha.com> <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> <4e51a32d$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e5f089b$0$2148$742ec2ed@news.sonic.net> On 8/21/2011 5:30 PM, Steven D'Aprano wrote: > Chris Angelico wrote: > > >> A new and surprising mode of network failure would be indicated by a >> new subclass of IOError or EnvironmentError. > > /s/would/should/ > > I don't see why you expect this, when *existing* network-related failures > aren't: > >>>> import socket >>>> issubclass(socket.error, EnvironmentError) > False > > (Fortunately that specific example is fixed in Python 3.) I think I reported that some years ago. There were some other errors in the URL and SSL area that weren't subclasses of EnvironmentError. It's also possible to get UnicodeError from URL operations. John Nagle From sahil at FreeBSD.org Thu Sep 1 00:56:50 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 1 Sep 2011 00:56:50 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } Message-ID: <20110901045650.GA3466@magic.hamla.org> I've been tasked with converting some programs from Perl -> Python, and am (as will soon be obvious) new to the language. A few archive/google searches were inconclusive on a consensus approach, which is OK, but I just wonder if there is a more Python-esque way to do the following in Python 2.7.1: %% # unbuffer STDOUT sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # process input, line-by-line, and print responses after parsing input while 1: rval = parse(raw_input()) if rval == None: print('foo') else: print('bar') %% This works, but while reading the documentation, I thought of using 'for line in fileinput.input()' in lieu of 'while 1:' construct. This does not work when debugging the program on the command line -- the script appears to just hang no matter what is typed into STDIN. I believe this is because of some internal buffering when using fileinput. Is there a recommended way to disable such buffering? Am I taking a totally wrong approach? Feel free to just link me to previous discussions on the topic(s) if I have missed them. Please be gentle with your cluebats. :-) Thanks, -- Sahil Tandon From kushal.kumaran+python at gmail.com Thu Sep 1 01:21:36 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 1 Sep 2011 10:51:36 +0530 Subject: How to daemonize a HTTPServer In-Reply-To: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On 1 Sep 2011 08:54, "babbu Pehlwan" wrote: > > I have written a http server using BaseHTTPServer module. Now I want > to instantiate it through another python script. The issue here is > after instantiate the control doesn't come back till the server is > running. Please suggest. What did a web search for "python daemon" lead to? I believe there's a python-daemon package available on pypi. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 1 02:02:54 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 01 Sep 2011 16:02:54 +1000 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: Message-ID: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. A few archive/google > searches were inconclusive on a consensus approach, which is OK, but I > just wonder if there is a more Python-esque way to do the following in > Python 2.7.1: > > %% > # unbuffer STDOUT > sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) I've never bothered with unbuffered stdout, but that looks fine to me. I'm not sure if it is necessary though, because print seems to automatically flush the buffer after each line in my testing. Unless you're printing repeatedly to the same line, I'm not sure unbuffered stdout is helpful. > # process input, line-by-line, and print responses after parsing input > while 1: > rval = parse(raw_input()) > if rval == None: > print('foo') > else: > print('bar') > %% "while True" is considered slightly more idiomatic (readable), but otherwise, that seems fine. > This works, but while reading the documentation, I thought of using 'for > line in fileinput.input()' in lieu of 'while 1:' construct. This does > not work when debugging the program on the command line -- the script > appears to just hang no matter what is typed into STDIN. I believe this > is because of some internal buffering when using fileinput. Is there a > recommended way to disable such buffering? Am I taking a totally wrong > approach? I'm not sure anything about fileinput is exactly *recommended*, it's kinda discouraged on account of being a bit slow. See help(fileinput) at the interactive prompt. For what it's worth, the default buffersize for fileinput.input is 0, so if that doesn't do what you want, I don't think fileinput is the right solution. -- Steven From __peter__ at web.de Thu Sep 1 02:31:32 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 08:31:32 +0200 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <20110901045650.GA3466@magic.hamla.org> Message-ID: Sahil Tandon wrote: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. A few archive/google > searches were inconclusive on a consensus approach, which is OK, but I > just wonder if there is a more Python-esque way to do the following in > Python 2.7.1: > > %% > # unbuffer STDOUT > sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) > > # process input, line-by-line, and print responses after parsing input > while 1: > rval = parse(raw_input()) > if rval == None: > print('foo') > else: > print('bar') > %% > > This works, but while reading the documentation, I thought of using 'for > line in fileinput.input()' in lieu of 'while 1:' construct. This does > not work when debugging the program on the command line -- the script > appears to just hang no matter what is typed into STDIN. I believe this > is because of some internal buffering when using fileinput. Is there a > recommended way to disable such buffering? Am I taking a totally wrong > approach? > > Feel free to just link me to previous discussions on the topic(s) if I > have missed them. Please be gentle with your cluebats. :-) A quick look into fileinput.py reveals that it uses readlines() and slurps in the complete "file". I'm not sure that was a clever design decision... Here's a partial reimplementation that should work for your use-case: import sys from itertools import chain def _open_many(files): for file in files: if file == "-": yield sys.stdin else: with open(file) as f: yield f def input(files=None, buffered=False): if files is None: files = sys.argv[1:] if not files: files = ["-"] files = _open_many(files) if not buffered: files = (iter(file.readline, "") for file in files) return chain.from_iterable(files) for line in input(): print line.strip().upper() From __peter__ at web.de Thu Sep 1 03:43:04 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 09:43:04 +0200 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <20110901045650.GA3466@magic.hamla.org> Message-ID: Peter Otten wrote: > A quick look into fileinput.py reveals that it uses readlines() and slurps > in the complete "file". I'm not sure that was a clever design decision... Correction: >>> with open("tmp.txt") as f: lines = f.readlines(0) ... >>> len(lines) 1000000 >>> with open("tmp.txt") as f: lines = f.readlines(1) ... >>> len(lines) 301 >>> len("".join(lines)) 8208 So on my system file.readlines(size) stops after about 2**13 bytes which is not a problem memorywise. Sorry for the confusion. From msamogh at gmail.com Thu Sep 1 03:48:52 2011 From: msamogh at gmail.com (Amogh M S) Date: Thu, 1 Sep 2011 13:18:52 +0530 Subject: Constructors...BIIIIG PROBLEM! Message-ID: Hey guys... I think we have a problem with my _init_ method and the constructor When I create a class and its _init_ method and try to create an object of it outside the class, Say, something like class S: def _init_(self, name=None): self.name = name s = S("MyName") It says that the constructor takes no arguments!! I have to explicitly call the _init_ method which, I think is not the right way of doing things... Could you tell me if that is what is supposed to happen or is something wrong with my code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 1 03:56:11 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 09:56:11 +0200 Subject: Constructors...BIIIIG PROBLEM! References: Message-ID: Amogh M S wrote: > Hey guys... > I think we have a problem with my _init_ method and the constructor > When I create a class and its _init_ method and try to create an object of > it outside the class, > Say, something like > > class S: > def _init_(self, name=None): Your __init__() method needs two leading and two trailing underscores. > self.name = name > s = S("MyName") > > It says that the constructor takes no arguments!! I have to explicitly > call the _init_ method which, I think is not the right way of doing > things... Could you tell me if that is what is supposed to happen or is > something wrong with my code? From motoom at xs4all.nl Thu Sep 1 04:00:27 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 10:00:27 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: References: Message-ID: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> On Sep 1, 2011, at 09:48, Amogh M S wrote: > Hey guys... > I think we have a problem with my _init_ method and the constructor > When I create a class and its _init_ method and try to create an object of it outside the class, > Say, something like > > class S: > def _init_(self, name=None): > self.name = name > s = S("MyName") Two things: Derive your class from object, and the constructor function should be '__init__', that is, with *two* underscores before and after it. Are you reading a book or tutorial which does use a badly chosen font which doesn't distinguish two consecutive underscores well? class S(object): def __init__(self, name=None): self.name = name s = S("MyName") print s.name Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand From airween at gmail.com Thu Sep 1 04:24:29 2011 From: airween at gmail.com (=?utf-8?Q?Heged=C3=BCs?= Ervin) Date: Thu, 1 Sep 2011 10:24:29 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> Message-ID: <20110901082427.GA18046@arxnet.hu> hello, On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: > On Sep 1, 2011, at 09:48, Amogh M S wrote: [...] > > class S: > > def _init_(self, name=None): > > self.name = name > > s = S("MyName") > > Two things: Derive your class from object, why's that better than just create a simple class, without derive? thanks: a. From motoom at xs4all.nl Thu Sep 1 05:04:18 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 11:04:18 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <20110901082427.GA18046@arxnet.hu> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> <20110901082427.GA18046@arxnet.hu> Message-ID: <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> On Sep 1, 2011, at 10:24, Heged?s Ervin wrote: > On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >> Derive your class from object, > > why's that better than just create a simple class, without > derive? Amongst other things, fixes to the type system and the method resolution order. http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html http://www.python.org/download/releases/2.2.3/descrintro/ Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand From dotancohen at gmail.com Thu Sep 1 05:42:04 2011 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 1 Sep 2011 12:42:04 +0300 Subject: Regex to match all trailing whitespace _and_ newlines. Message-ID: In the terrific Anki [1] application I am trying to remove trailing whitespace from form fields. This is my regex: [\n+\s+]$ Actually, even simplifying it to [\n] or [\r\n] is not matching any newlines! What might be the cause of this? Note that I am not entering the regex in Python code, I am entering it in a regex-supporting Find/Replace dialogue in Anki. Anki is written in Python. Thanks. [1] ankisrs.net -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From __peter__ at web.de Thu Sep 1 06:30:15 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 12:30:15 +0200 Subject: Regex to match all trailing whitespace _and_ newlines. References: Message-ID: Dotan Cohen wrote: > In the terrific Anki [1] application I am trying to remove trailing > whitespace from form fields. This is my regex: > [\n+\s+]$ My attempt: >>> sub = re.compile(r"\s*?(\n|$)").sub >>> sub("", "alpha \nbeta \r\n\ngamma\n") 'alphabetagamma' >>> sub("", "alpha \nbeta \r\n\ngamma") 'alphabetagamma' >>> sub("", "alpha \nbeta \r\n\ngamma\t") 'alphabetagamma' From fnautaNO at SPAMsolfon.nl Thu Sep 1 06:30:40 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 1 Sep 2011 12:30:40 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net> Message-ID: <9c9578F5eaU1@mid.individual.net> "Paul K?lle" wrote in message news:mailman.620.1314810894.27778.python-list at python.org... > Hi, answers below... > > Am 31.08.2011 14:18, schrieb Fokke Nauta: >> "Paul K?lle" wrote in message >> news:mailman.595.1314780791.27778.python-list at python.org... >>> Hi, >>> >>> Am 30.08.2011 22:00, schrieb Fokke Nauta: >>>> Hi all, >>>> >>>> I am completely new to Python, but I'm confronted with a problem I >>>> can't >>>> solve. >>> Welcome to python. >>> >>>> This is my question: >>> [snip] >>> >>>> I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. >>>> Now >>>> I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 >>>> and >>>> PyXML-0.8.4. In the PyWebDAV README it says: >>>> >>>> Installation and setup of server can be as easy as follows: >>>> >>>> $ easy_install PyWebDAV >>>> $ davserver -D /tmp -n -J >>>> >>>> But of course it doesn't work like that. When I start up Python GUI I >>>> see >>>> the ">>>" prompt instead of the "$" prompt. But where do I place the >>>> two >>>> directories? And there is no easy_install script in the PyXML-0.8.4 >>>> directory, only a setup.py and ez_setup.py script. I guess the latter >>>> is >>>> the >>>> one to use. But how? >>> You dont install from "Python GUI", use normal cmd, navigate to the >>> folder >>> you downloaded PyXML and PyWebDAV and run "python setup.py install" >>> (python.exe has to be in your PATH). Then you have to find the >>> startup-script "davserver". Find your python installation directory and >>> look into/Tools/Scripts, in my computer this is >>> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the >>> site-packages folder i.e. E:\python27\Lib/site-packages. You might have >>> to >>> look for "davserver" there... >>> >> >> Thanks, Paul. >> >> I ran "python setup.py install" in both the PyXML and PyWebDAV >> directories. >> A lot of things happened and are added into those directories and I guess >> it >> will be OK. >> Next step, the startup-script "davserver". There is no script as such, >> also >> not in \python27\tools\scripts. >> I found 2 similar scripts: >> 1. server.py in D:\Python27\WebDAV\PyWebDAV\DAVServer >> 2. WebDAVServer.py in D:\Python27\WebDAV\PyWebDAV\DAV >> >> Which one is the one to use? > Your install locations look odd, but it might work nevertheless. The > server is in DAVServer\server.py, you can look at the file and you will > see: > > if __name__ == '__main__': > run() > > at the bottom. This is the "entry point" of a python script if called from > the command line. Yes, it was server.py. > My install looks a bit different but I can start the server as follows: > python.exe > E:\Python27\Lib\site-packages\pywebdav-0.9.4.1-py2.7.egg\DAVServer\server.py > -D c:\home -n > WARNING:pywebdav:Authentication disabled! > Listening on localhost (8008) I used server.py e:/wwwroot -m -c config.ini >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer > I would use a config file outside the program directory and use the -c > or --config switch, run server.py without arguments to see possible > startup options. > >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? > Don't know if that's documented somewhere but you can just look at the > code in mysqlauth.py in the same directory as server.py. Seems it needs > three columns, (User,Pass,can_write<0|1>) but I haven't > tried. > I have understood that the database will be configured with the first run, but in my case it didn't. In my congig.ini there was # Create User Database Table and Insert system user # Disable after the Table is created; for performance reasons firstrun=1 Fokke From fnautaNO at SPAMsolfon.nl Thu Sep 1 06:30:43 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 1 Sep 2011 12:30:43 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net> Message-ID: <9c9578F5eaU2@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.643.1314851358.27778.python-list at python.org... > On Wed, 31 Aug 2011 14:18:00 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? >> > After looking at the config file. > > I presume you have specified the MySQL username/password Sure > (personally, and out of paranoia, I'd create a webDAV user/password that > only has access rights to the specified webDAV database). > > Next, if you'd read further and didn't take the comment as the > instruction. set > firstrun=1 I did > to tell the server this is the first time it is being run - IT WILL > create the database table (after the first start, reset the flag to 0 to > speed up later runs). It didn't create the table. The database kept empty. > Later in the config file set > mysql_auth=1 > to enable the use of MySQL, and set the admin user/password to what you > plan to have it use. I did > You probably want to set > daemonize=1 > (maybe after first run) I left this to 0. > Oh, and don't forget to set the main data directory and any > port/host changes. I left host and port as they were. The main directory is e:\wwwroot > Start the server - it should connect to MySQL, create the table, and > add the admin user to the table. I started the server with server.py (in D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini The seems to work as I get a login screen in the browser. Later on I changed the ini file: # disable auth noauth = 1 # Enable mysql auth mysql_auth=0 No login screen anymore but I got an error message "fshandler:get_data: e:\wwwroot not found" Fokke From martin.hellwig at gmail.com Thu Sep 1 06:32:35 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 01 Sep 2011 11:32:35 +0100 Subject: How to daemonize a HTTPServer In-Reply-To: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On 01/09/2011 04:16, babbu Pehlwan wrote: > I have written a http server using BaseHTTPServer module. Now I want > to instantiate it through another python script. The issue here is > after instantiate the control doesn't come back till the server is > running. Please suggest. Sounds like something you could use the multiprocessing module for, but then again my crystal ball is a bit fuzzy today. -- mph From andrei.lisnic at gmail.com Thu Sep 1 06:40:25 2011 From: andrei.lisnic at gmail.com (UncleLaz) Date: Thu, 1 Sep 2011 03:40:25 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> On Aug 31, 5:35?pm, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. > > For example, consider Python?s indent-sensitive syntax. ?Although > other languages didn?t use indentation to specify scope, programmers > always used indentation anyways. ?Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? ?It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. ?It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. It's required to make distinction between objects inside the calss and outside of it. Seems pretty logical to me. From yasar11732 at gmail.com Thu Sep 1 06:51:43 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 1 Sep 2011 13:51:43 +0300 Subject: Invoking profile from command line prevent my sys.path modification Message-ID: Hi, I am new to profile module, so I am sorry if this is an absolute beginner question. In order to my code to run, I need to add a directory to sys.path. When I invole python -m profile myfile.py, my code won't work, saying that the thing that is supposed to be in path, isn't. Code works fine without profiling. Profiling works if I write it into the file, but I don't prefer doing that, if that is possible. -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Thu Sep 1 07:23:54 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 13:23:54 +0200 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> Message-ID: <2B38B9D1-4DD5-4E88-B4DB-324A677C6BD1@xs4all.nl> > On Aug 31, 5:35 pm, "T. Goodchild" wrote: >> So why is 'self' necessary on class methods? >> >> Just curious about the rationale behind this part of the language. When instance variables are accessed with the 'self.varname' syntax, it is clear to the programmer that an instance variable is accessed, and not some global. Other languages have weird syntax conventions like that you have to prepend all instance attributes with an '@', and in languages like C++ where there is not necessarily such a syntactic requirement, many programmers use ad-hoc constructs like '_varname' or 'm_varname' to make the distinction clear. >> It seems to me that the >> most common practice is that class methods *almost always* operate on >> the instance that called them. It would make more sense to me if this >> was assumed by default, and for "static" methods (methods that are >> part of a class, but never associated with a specific instance) to be >> labelled instead. Yes, you have a point there. My personal preference would be to optimize for the most common case, while exceptions to the norm are still possible, but perhaps a bit more verbose. Greetings -- "Learn to value yourself, which means: fight for your happiness." - Ayn Rand From johnroth1 at gmail.com Thu Sep 1 08:45:36 2011 From: johnroth1 at gmail.com (John Roth) Date: Thu, 1 Sep 2011 05:45:36 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> On Aug 31, 8:35?am, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. > > For example, consider Python?s indent-sensitive syntax. ?Although > other languages didn?t use indentation to specify scope, programmers > always used indentation anyways. ?Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? ?It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. ?It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. I personally consider this to be a wart. Some time ago I did an implementation analysis. The gist is that, if self and cls were made special variables that returned the current instance and class respectively, then the compiler could determine whether a function was an instance or class method. If it then marked the code object appropriately you could get rid of all of the wrappers and the attendant run-time overhead. I've never published the analysis because that train has already left the shed. The earliest it could be considered would be 4.0, which isn't even on the horizon. John Roth From lanyjie at yahoo.com Thu Sep 1 09:43:54 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 06:43:54 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> Message-ID: <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Hi Matt, ======================================================= From: Matt Joiner The "trailing \" workaround is nonobvious. Wrapping in () is noisy and already heavily used by other syntactical structures.? ======================================================= How about only require indentation to freely break lines? Here is an example: x = firstpart * secondpart #line breaks here + anotherpart #continue by indentation + stillanother #continue on. #until here, another line starts by dedentation? y = some_expression?- another_one All this would be completely compatible with former code, while having almost free line breaking! Plus, indentation makes it pretty. Really hope Python can have freedom in breaking lines. Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Sep 1 09:57:00 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 07:57:00 -0600 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> <20110901082427.GA18046@arxnet.hu> <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> Message-ID: On Thu, Sep 1, 2011 at 3:04 AM, Michiel Overtoom wrote: > > On Sep 1, 2011, at 10:24, Heged?s Ervin wrote: > >> On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >>> Derive your class from object, >> >> why's that better than just create a simple class, without >> derive? > > Amongst other things, fixes to the type system and the method resolution order. > > http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes > http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ > http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html > http://www.python.org/download/releases/2.2.3/descrintro/ That is for Python 2. For Python 3, old-style classes are gone, all classes derive from object by default, and writing it explicitly is merely good style for compatibility. From dalist0 at gmail.com Thu Sep 1 10:05:20 2011 From: dalist0 at gmail.com (Daniel) Date: Thu, 1 Sep 2011 07:05:20 -0700 (PDT) Subject: fun with nested loops References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steve, Thanks for your comments, I appreciate any input. > Do you think the software in the Apple iPod is "simple"? Or Microsoft No, that's much more complicated that what I am doing. But the iPod probably (?) doesn't get new algorithms based on a specification discussed with non-programmers once a month. I didn't explain enough of what I am doing. This is a fairly complex application that has been running for a few years now, I am just trying to improve it. The code runs a big test machine, that runs >100000 individual tests in one run on something like semiconductor chips. The specification of these tests is already very complex, it has the form of the nested loops, for all these configurations try these steps, if they fail try them again n times, if it still doesn't work give up this configuration, if it works continue on to the next steps etc. That's the form the specification is in, and it makes sense and is very readable. In pseudocode it looks like this, I am using @ to give loops a name: @loop1 for c in configurations: @loop2 while not_done: @loop3 while step1_did_not_work: @loop4 for substeps in step1 # loop 4a if hopeless(): continue loop1 # run next configuration if substepsFailed(): restart loop4 # try again if substepsWorked(): break loop3 # go on to next steps, like loop4 That format is fine, everyone involved can understand it, even the people in charge. I'd like to make this executable without changing too much of the form. It would be possible to do this as a FSM, but then you'd loose the line to line correspondence with the specification, and of course some errors always creep in. > non-CS people to be hacking the source code, they only interact with the This is a research setting, so the person running the machine will have to change the source from time to time if he gets a new specification. The specifications are far to complex to be entered into a user interface because of all the loops. > the code by splitting it into functions appropriately, instead of the > spaghetti code you have (apparently) written with jumps all over the place. I wouldn't call the example above spaghetti code in the sense of old Fortran or Basic full of gotos. In a language that can break out of nested loops this is highly structured code. I am not jumping forward to labels, not jumping into functions, not using jumps to replace loops etc. It is like the Fortran example (just to show the syntax, has an infinite loop), everyone can understand that right away, even non Fortran people: 10 loop1: do I=1,3 loop2: do J=1,4 print *,I,J goto 10 ! redo loop1 cycle loop1 exit loop1 enddo loop2 enddo loop1 There is no wild jumping her. The only problem is that Fortran does not allow to restart a loop, so instead of restart loop1 you have to do a goto 10. Otherwise you could do entirely without gotos (like in Ruby with the redo, which is of course much much better) > To take the most obvious, simple example: any time you have a loop that you > might want to redo, the right solution is to put the loop inside a > function, and then "redo the loop" becomes "call the function again". Doesn't work, because it can only redo one level, to break out of the next loop, I'd need exceptions anyway. And having all of these exceptions as gotos doesn't make it more readable. Replacing loop4 by a function makes it possible to replace the restart loop4 by a return, but then I still need an exception to continue loop1 and one to break out of loop4 to indicate that we can go on to the next step. > I suppose that, just possibly, your application really would benefit from > named labels to jump to. But if so, you've stumbled across something rarer > than iridium. Don't think so. I am doing that all of the time in other languages, and I am convinced the named loops (not raw labels+gotos, which are just a necessary evil) are beautiful and clean things. They have a lot of symmetry, break is always break, not sometimes break, sometimes return and sometimes raise breakSomeLoopExcept(). Rewriting the simple Fortran example above in Python would be much, much uglier and more difficult to comprehend. You always call break and continue with a label, searching for that label will tell you right away which loop the break breaks. I am always doing that, even if there is only one loop. break and continue (without label) are IMO (please no flame war about that) worse than goto, at least the goto tells you where it goes, with break/ continue you always have to scan the surroundings to find the right loop. I know I am not the only one who is trying to solve that problem, I was hoping someone has come up with a hack to solve it, like this goto Chis has come up with. I have to play with that a bit. Dan From ian.g.kelly at gmail.com Thu Sep 1 10:26:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 08:26:53 -0600 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> Message-ID: On Thu, Sep 1, 2011 at 6:45 AM, John Roth wrote: > I personally consider this to be a wart. Some time ago I did an > implementation analysis. The gist is that, if self and cls were made > special variables that returned the current instance and class > respectively, then the compiler could determine whether a function was > an instance or class method. If it then marked the code object > appropriately you could get rid of all of the wrappers and the > attendant run-time overhead. I don't see how you could get rid of the wrappers. Methods would still need to be bound, somehow, so that code like this will work: methods = {} for obj in objs: if obj.is_flagged: methods[obj.user_id] = obj.do_work else: methods[obj.user_id] = obj.do_other_work # ... methods[some_user_id]() Without method wrappers, how does the interpreter figure out which instance is bound to the method being called? Cheers, Ian From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 1 10:57:39 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 01 Sep 2011 16:57:39 +0200 Subject: fun with nested loops In-Reply-To: References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 01.09.2011 16:05 schrieb Daniel: > In pseudocode it looks like this, I am using @ to give loops a name: > > @loop1 > for c in configurations: > @loop2 > while not_done: > @loop3 > while step1_did_not_work: > @loop4 > for substeps in step1 # loop 4a > if hopeless(): continue loop1 # run next configuration > if substepsFailed(): restart loop4 # try again > if substepsWorked(): break loop3 # go on to next > steps, like loop4 let me have a try: def loop(f): def wrapper(*a, **k): while True: try: ret = f(*a, **k): return ret except wrapper.restart: continue # next try except wrapper.stop: return None return ret wrapper.restart = type('restart', (Exception,), {}) wrapper.stop = type('stop', (Exception,), {}) return wrapper @loop def level1(): for c in configurations: level2(c) @loop def level2(): while not_done: level3() @loop def level3(): while step1_did_not_work: level4() @loop def level4a(): for substeps in step1 if hopeless: raise level2.stop if substepsFailed: raise level4a.restart if substepsWorked: return ok I don't know if I have the levels right, but that should be a way which works, without too many indentations. Another approach could be a decorator which immediately runs the given functions, after adding the needed exception classes. Thomas From as at sci.fi Thu Sep 1 11:25:30 2011 From: as at sci.fi (Anssi Saari) Date: Thu, 01 Sep 2011 18:25:30 +0300 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: Message-ID: Sahil Tandon writes: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. If it's any help, I have usually done handling of standard input line by line with this kind of thing: for inputline in sys.stdin: From mukeshtiwari.iiitm at gmail.com Thu Sep 1 11:46:50 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Thu, 1 Sep 2011 08:46:50 -0700 (PDT) Subject: Listing HAL devices Message-ID: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Hello all I am trying to write a python script which detects usb pen drive and copy all the data into my home directory. After bit of searching , i found these two links 1] http://en.wikibooks.org/wiki/Python_Programming/Dbus and 2] http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-device-inserted-events-in-linux-in-python . I just copied the wiki program but after running it , i got error import dbus class BusListener: def __init__( self ): self.bus = dbus.SystemBus() self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/ Manager' ) print self.proxy if __name__ == "__main__": obj = BusListener() Traceback (most recent call last): File "Mount.py", line 13, in obj = BusListener() File "Mount.py", line 7, in __init__ self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/ freedesktop/Hal/Manager' ) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in get_object follow_name_owner_changes=follow_name_owner_changes) File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in __init__ self._named_service = conn.activate_name_owner(bus_name) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in activate_name_owner self.start_service_by_name(bus_name) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in start_service_by_name 'su', (bus_name, flags))) File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Hal was not provided by any .service files Kindly some one please tell me why i am getting this error . Thank you From patentsvnc at gmail.com Thu Sep 1 11:52:49 2011 From: patentsvnc at gmail.com (Den) Date: Thu, 1 Sep 2011 08:52:49 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows Message-ID: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Obviously, this is a windows-based question. I know that Ctrl-Alt-Del is handled deep inside the OS, and I'm not trying to interrupt that. But is there some way to detect that a C-A-D has been pressed? Also, is there a corresponding key-sequence in Mac and Linux? And how might one detect those too? Den From mukeshtiwari.iiitm at gmail.com Thu Sep 1 12:04:29 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Thu, 1 Sep 2011 09:04:29 -0700 (PDT) Subject: Listing HAL devices References: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Message-ID: On Sep 1, 8:46?pm, mukesh tiwari wrote: > Hello all > I am trying to write a python script which detects usb pen drive and > copy all the data into my home directory. After bit of searching , i > found these two links 1]http://en.wikibooks.org/wiki/Python_Programming/Dbus > and 2]http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-de... > . I just copied the wiki program but after running it , i got error > > import dbus > > class BusListener: > ? ? ? ? def __init__( self ): > ? ? ? ? ? ? ? ? self.bus = dbus.SystemBus() > ? ? ? ? ? ? ? ? self.hal_obj = > self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/ > Manager' ) > ? ? ? ? ? ? ? ? print self.proxy > > if __name__ == "__main__": > ? ? ? ? obj = BusListener() > > Traceback (most recent call last): > ? File "Mount.py", line 13, in > ? ? obj = BusListener() > ? File "Mount.py", line 7, in __init__ > ? ? self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/ > freedesktop/Hal/Manager' ) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in > get_object > ? ? follow_name_owner_changes=follow_name_owner_changes) > ? File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in > __init__ > ? ? self._named_service = conn.activate_name_owner(bus_name) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in > activate_name_owner > ? ? self.start_service_by_name(bus_name) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in > start_service_by_name > ? ? 'su', (bus_name, flags))) > ? File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in > call_blocking > ? ? message, timeout) > dbus.exceptions.DBusException: > org.freedesktop.DBus.Error.ServiceUnknown: The name > org.freedesktop.Hal was not provided by any .service files > > Kindly some one please tell me why i am getting this error . > Thank you I am using Ubuntu 11.04 . From ansuman.python at gmail.com Thu Sep 1 12:46:52 2011 From: ansuman.python at gmail.com (Ansuman Bebarta) Date: Thu, 1 Sep 2011 09:46:52 -0700 (PDT) Subject: Microphone Input Message-ID: <3a8e8ad0-5ff8-4236-88b6-73be500e1ad3@p25g2000pri.googlegroups.com> I want to have a microphone input in a python program on cross platform. I don't want to use any third party module rather I want to have a module of my own. Please guide me in this direction. From ian.g.kelly at gmail.com Thu Sep 1 13:19:33 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 11:19:33 -0600 Subject: Listing HAL devices In-Reply-To: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> References: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Message-ID: On Thu, Sep 1, 2011 at 9:46 AM, mukesh tiwari wrote: > dbus.exceptions.DBusException: > org.freedesktop.DBus.Error.ServiceUnknown: The name > org.freedesktop.Hal was not provided by any .service files > > Kindly some one please tell me why i am getting this error . > Thank you It looks like you don't have HAL installed. In any case, this is a Ubuntu / DBus issue, not really a Python issue, so you might find better support at those fora. By the way, HAL is deprecated. I believe current best practice is to interface with udev directly, but I don't know exactly what that entails. From james.thornton at gmail.com Thu Sep 1 13:58:54 2011 From: james.thornton at gmail.com (JT) Date: Thu, 1 Sep 2011 10:58:54 -0700 (PDT) Subject: Help parsing a text file In-Reply-To: References: Message-ID: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: > > I have a text file with XML like records that I need to parse. By XML > like I mean records have proper opening and closing tags. but fields > don't have closing tags (they rely on line ends). Not all fields appear > in all records, but they do adhere to a defined sequence. lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). - James -- Bulbflow: A Python framework for graph databases (http://bulbflow.com) From nospam at domain.invalid Thu Sep 1 14:38:09 2011 From: nospam at domain.invalid (William Gill) Date: Thu, 01 Sep 2011 14:38:09 -0400 Subject: Help parsing a text file In-Reply-To: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> References: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/1/2011 1:58 PM, JT wrote: > On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: >> >> I have a text file with XML like records that I need to parse. By XML >> like I mean records have proper opening and closing tags. but fields >> don't have closing tags (they rely on line ends). Not all fields appear >> in all records, but they do adhere to a defined sequence. > > lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). > > - James > Thanks to everyone. Though I didn't get what I expected, it made me think more about the reason I need to parse these files to begin with. So I'm going to do some more homework on the overall business application and work backward from there. Once I know how the data fits in the scheme of things, I will create an appropriate abstraction layer, either from scratch, or using one of the existing parsers mentioned, but I won't really know that until I have finished modeling. From tjreedy at udel.edu Thu Sep 1 14:40:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 14:40:28 -0400 Subject: fun with nested loops In-Reply-To: References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/1/2011 10:05 AM, Daniel wrote: You seems to be requesting one of the options in http://python.org/dev/peps/pep-3136/ Labeled break and continue (The 'Other languages' section omits Fortran.) The rejection post is at http://mail.python.org/pipermail/python-3000/2007-July/008663.html I basically agree with it. Your use case seems to be valid, extreme, and rare. You would probably use the proposed feature responsibly. But you are not everyone. I am not sure what Python-solution I would recommend. I might just stick with whatever you are doing that works for your group. However, I can also understand the desire to improve. -- Terry Jan Reedy From pavlovevidence at gmail.com Thu Sep 1 15:02:45 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 Sep 2011 12:02:45 -0700 (PDT) Subject: fun with nested loops In-Reply-To: References: Message-ID: <7f43d4ad-fbd7-45f0-bcf5-719e19813429@glegroupsg2000goo.googlegroups.com> On Wednesday, August 31, 2011 8:51:45 AM UTC-7, Daniel wrote: > Dear All, > > I have some complicated loops of the following form > > for c in configurations: # loop 1 > while nothing_bad_happened: # loop 2 > while step1_did_not_work: # loop 3 > for substeps in step1 # loop 4a > # at this point, we may have to > -leave loop 1 > -restart loop 4 > -skip a step in loop 4 > -continue on to loop 4b > > while step2_did_not_work: # loop 4b > for substeps in step2: > # at this point, we may have to > -leave loop 1 > -restart loop 2 > -restart loop 4b > ... > ...many more loops... > > > I don't see any way to reduce these nested loops logically, they > describe pretty well what the software has to do. > This is a data acquisition application, so on ever line there is > a lot of IO that might fail or make subsequent steps useless or > require a > retry. > > Now every step could need to break out of any of the enclosing loops. I feel your pain. Every language, even Python, has cases where the trade-offs made in the language design make some legitimate task very difficult. In such cases I typically throw out the guidebook and make use of whatever shameless Perlesque thing it takes to keep things manageable. In your example you seem like you're trying to maintain some semblance of structure and good habit; I'd it's probably no longer worth it. Just store the level to break to in a variable, and after every loop check the variable and break if you need to break further. Something like this, for example: break_level = 99 while loop1: while loop2: while loop3: if some_condition: break_level = (1, 2, or 3) break if break_level < 3: break break_level = 99 if break_level < 2: break break_level = 99 Carl Banks From woooee at gmail.com Thu Sep 1 15:17:37 2011 From: woooee at gmail.com (woooee) Date: Thu, 1 Sep 2011 12:17:37 -0700 (PDT) Subject: Text file with mixed end-of-line terminations References: <4e5e8d71$0$2554$e4fe514c@news2.news.xs4all.nl> Message-ID: <93d72f06-2e4d-4857-9d9a-f21473ef3267@x11g2000prb.googlegroups.com> You can use f.read() to read the entire file's contents into a string, providing the file isn't huge. Then, split on "\r" and replace "\n" when found. A simple test: input_data = "abc\rdef\rghi\r\njkl\r\nmno\r\n" first_split = input_data.split("\r") for rec in first_split: rec = rec.replace("\n", "") print rec From aaron.hildebrandt at gmail.com Thu Sep 1 15:54:02 2011 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 1 Sep 2011 12:54:02 -0700 (PDT) Subject: OSX application built with py2app can't see bundled PySide module? Message-ID: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> I'm trying to deploy a Python app on OSX that was built with PySide. py2app packages it without issue, copying and linking a lot of PySide and Qt files in the process. But then, when I try to run the built app, I get this error: Traceback (most recent call last): File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 31, in _run('dailies_v02.py') File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/dailies_v02.py", line 9, in from PySide.QtCore import * File "PySide/__init__.pyc", line 2, in File "PySide/private.pyc", line 2, in File "PySide/QtCore.pyc", line 18, in File "PySide/QtCore.pyc", line 15, in __load ImportError: '/usr/lib/python2.6/lib-dynload/PySide/QtCore.so' not found The weird thing is, QtCore.so IS included in the application bundle: py2app copied it to the build under Contents/Resources/lib/python2.6/lib-dynload/PySide/. Is there a reason the application isn't seeing this? From false at pp.jaring.my Thu Sep 1 17:12:44 2011 From: false at pp.jaring.my (Fulvio) Date: Fri, 02 Sep 2011 05:12:44 +0800 Subject: Optparse buggy? Message-ID: Hello, I'm on python3.2, trying some experiment with OptionParser but no success >>> from optparse import OptionParser as parser >>> parser.add_option('-n','--new', dest='new') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.2/optparse.py", line 1001, in add_option option = self.option_class(*args, **kwargs) AttributeError: 'str' object has no attribute 'option_class' >>> Any futher item in the option won't make any better. -- Archlinux on $(uname -a) :P From mydevgroup at gmail.com Thu Sep 1 17:14:23 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 22:14:23 +0100 Subject: Python thread Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George From ian.g.kelly at gmail.com Thu Sep 1 17:24:33 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 15:24:33 -0600 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 3:12 PM, Fulvio wrote: > Hello, > > I'm on python3.2, trying some experiment with OptionParser but no success > >>>> from optparse import OptionParser as parser >>>> parser.add_option('-n','--new', dest='new') > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python3.2/optparse.py", line 1001, in add_option > ? ?option = self.option_class(*args, **kwargs) > AttributeError: 'str' object has no attribute 'option_class' >>>> > > Any futher item in the option won't make any better. You're trying to call the method from the OptionParser class -- you need to instantiate it first. from optparse import OptionParser parser = OptionParser() parser.add_option('-n', '--new', dest='new') ... Cheers, Ian From jason.swails at gmail.com Thu Sep 1 17:27:25 2011 From: jason.swails at gmail.com (Jason Swails) Date: Thu, 1 Sep 2011 17:27:25 -0400 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 5:12 PM, Fulvio wrote: > Hello, > > I'm on python3.2, trying some experiment with OptionParser but no success > > >>> from optparse import OptionParser as parser > >>> parser.add_option('-n','--new', dest='new') > Here you've imported parser as an alias to the OptionParser class. You can only use add_option() on an instance of that class. Try this: from optparse import OptionParser parser = OptionParser() parser.add_option('-n','--new',dest='new') However, I think argparse has replaced optparse since Python 2.7 and higher... HTH, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From mydevgroup at gmail.com Thu Sep 1 17:41:13 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 22:41:13 +0100 Subject: PythonThreading Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George From mydevgroup at gmail.com Thu Sep 1 17:45:11 2011 From: mydevgroup at gmail.com (George Kovoor) Date: Thu, 1 Sep 2011 22:45:11 +0100 Subject: Threads in Python Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Sep 1 17:51:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 17:51:32 -0400 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On 9/1/2011 5:12 PM, Fulvio wrote: > I'm on python3.2, trying some experiment with OptionParser but no success Do note "The optparse module is deprecated and will not be developed further; development will continue with the argparse module." -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 1 17:54:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 17:54:37 -0400 Subject: Python thread In-Reply-To: References: Message-ID: On 9/1/2011 5:14 PM, George wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. Perhaps because threads are not subprocesses? > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. > > Does it mean that python threads are not mapped to the core in the system. They all run on the same core. > On using multiprocessing module, separate processes are created with unique > PID. That is why multiprocessing was added. -- Terry Jan Reedy From mydevgroup at gmail.com Thu Sep 1 18:08:01 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 23:08:01 +0100 Subject: Python thread In-Reply-To: Message-ID: So what exactly does threading module do, if it doesn't create a subprocess. Does each thread have its own stack and PC. What advantage would a threading module provide over sequential execution. On 01/09/2011 22:54, "Terry Reedy" wrote: > On 9/1/2011 5:14 PM, George wrote: >> Hi, >> Why doesn't python threads show an associated PID? On spawning python >> threads using the threading module I can only see the main thread's pid on >> using top or ps unix command, no subprocesses are displayed. In otherwords >> top or ps in not aware of any subprocesses created using threading module in >> python. > > Perhaps because threads are not subprocesses? > >> Whereas in Java , creating threads will result in separate pid , these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. >> >> Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > >> On using multiprocessing module, separate processes are created with unique >> PID. > > That is why multiprocessing was added. > From ramit.prasad at jpmorgan.com Thu Sep 1 18:21:37 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 1 Sep 2011 18:21:37 -0400 Subject: Python thread In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> >So what exactly does threading module do, if it doesn't create a subprocess. >Does each thread have its own stack and PC. >What advantage would a threading module provide over sequential execution. I believe it merely simulates multiple processes through scheduling (like the CPU). From http://docs.python.org/library/threading.html: CPython implementation detail: Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From me+list/python at ixokai.io Thu Sep 1 18:27:32 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Thu, 01 Sep 2011 15:27:32 -0700 Subject: Threads in Python In-Reply-To: References: Message-ID: <4E6006D4.9080106@ixokai.io> On 9/1/11 2:45 PM, George Kovoor wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. I think you're confused about what threads and subprocesses are. They are completely different mechanisms for concurrent code. Threads never show up on top or ps, in any language ... or the language isn't offering threads. I don't know Java, so I can't really comment on it much, but it may be misusing the 'thread' word, but I somehow doubt it. I suspect you're just mistaken about what Java is offering. Threads are separate operating ..er, chains-of-instructions within a single process... Notably with threads, they share the same address space so you can easily share objects amongst threads, without any copying and with no overhead ... Also notably with threads, this can be dangerous, so you often end up wrapping lots of locks around those shared objects and have to take extreme care to make sure nothing goes haywire. Subprocesses are different; they are a whole, separate process with its own address space and no shared memory (unless you go out of your way to do it manually). Heck, each subprocess can have any number of threads. Anything you want to share between them you have to take special care to set up and do -- multiprocessing exists to make this easier and make subprocesses easier to use, like threads are. They're very distinct. Threads are a lot more lightweight and start up a lot faster, but doing multithreaded programming right with any sort of shared objects is really, really, really hard to get right. Some say you can't. But, in Python, only one thread actually ever executes actual Python code at any given time. This does not actually make threading useless as some people claim; if you're making a lot of calls into C-code, for instance, the lock gets released while said C-code runs and other Python code can continue along. Its just not useful if your program is CPU-bound and wants to take advantage of multiple cores. But there's lots of other reasons to go concurrent. But if you do need lots of CPU power, multiprocessing lets you chew up multiple cores and does so /fairly/ easily. Communication between the processes can be expensive depending on the types of objects you need to pass back and forth, but it depends on how you're designing your app. They're just different ways of achieving concurrency, and the two primary ways Python provides. (Greenlets is another, available as a third-party module; Twisted's asynch dispatching isn't really exactly concurrency, but it does a better job then concurrency does for some operations; someone's always working on coroutines in some fashion or another, which is another kind of concurrency.) Lots of different ways to go concurrent, depending on your needs. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From cs at zip.com.au Thu Sep 1 18:43:01 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 2 Sep 2011 08:43:01 +1000 Subject: Threads in Python In-Reply-To: <4E6006D4.9080106@ixokai.io> References: <4E6006D4.9080106@ixokai.io> Message-ID: <20110901224301.GA8878@cskk.homeip.net> On 01Sep2011 15:27, Stephen Hansen wrote: | On 9/1/11 2:45 PM, George Kovoor wrote: | > Why doesn't python threads show an associated PID? On spawning python | > threads using the threading module I can only see the main thread's pid on | > using top or ps unix command, no subprocesses are displayed. In otherwords | > top or ps in not aware of any subprocesses created using threading module in | > python. | > | > Whereas in Java , creating threads will result in separate pid , these | > subprocesses can be listed using top or ps. Java threads get mapped to the | > cores in the system. | | I think you're confused about what threads and subprocesses are. They | are completely different mechanisms for concurrent code. Threads never | show up on top or ps, in any language ... or the language isn't offering | threads. I don't know Java, so I can't really comment on it much, but it | may be misusing the 'thread' word, but I somehow doubt it. I suspect | you're just mistaken about what Java is offering. No, you're mistaken about the threading models on offer. Some systems offer a threading model where threads can have distinct process ids; the only real criterion is that they share the same address space. The advantages of separate process ids for threads include letting the OS arrange their scheduling, delivery of signals (on UNIX systems) to a particular thread, ability to use multiple cores. On the flipside, threads with distinct process ids tend to be more expensive to set up and may be more expensive in thread switching. Java has long shipped with multiple threading implementations; IIRC "green threads" is an "all in one process id" model that can be used on any platform. Some use a mix of heavyweight (threads with distinct pids) and lightweight threads. | But, in Python, only one thread actually ever executes actual Python | code at any given time. In CPython this is true. Other implementations like Jython can use other threading models; I'd expect Jython to take a lot of advantage of Java's native threads. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Seeing my great fault Through darkening blue windows I begin again - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From benjamin.kaplan at case.edu Thu Sep 1 18:46:32 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 1 Sep 2011 18:46:32 -0400 Subject: Python thread In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Sep 1, 2011 at 6:21 PM, Prasad, Ramit wrote: >>So what exactly does threading module do, if it doesn't create a subprocess. >>Does each thread have its own stack and PC. >>What advantage would a threading module provide over sequential execution. > > I believe it merely simulates multiple processes through scheduling (like the CPU). > > >From http://docs.python.org/library/threading.html: CPython implementation detail: Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously. > > Ramit Threading is an OS-level construct to allow concurrency within a single process (and address space). Threads are never supposed to be separate processes (they aren't at the C-level, so I don't know what Java is doing here). CPython code has a global interpreter lock which prevents two threads from running Python code at the same time, but they're still useful for asynchronous operations. For example, one thread can be waiting for user input while another thread continues to process data. Other Python implementations such as Jython and IronPython don't have a global interpreter lock so threads can run concurrently (and on different cores in a multi-core machine). > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Thu Sep 1 19:02:17 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 19:02:17 -0400 Subject: Python thread In-Reply-To: References: Message-ID: On 9/1/2011 6:08 PM, George wrote: > So what exactly does threading module do, if it doesn't create a subprocess. > Does each thread have its own stack and PC. > What advantage would a threading module provide over sequential execution. https://secure.wikimedia.org/wikipedia/en/wiki/Thread_%28computer_science%29 -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 1 19:06:16 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 19:06:16 -0400 Subject: PythonThreading In-Reply-To: References: Message-ID: Please do not repeatedly post the same thing. Doing so, with different titles, will only annoy people. It takes awhile for a post to show up with whatever news or mail reader you are using. -- Terry Jan Reedy From lists at cheimes.de Thu Sep 1 19:09:51 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 Sep 2011 01:09:51 +0200 Subject: Python thread In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> Message-ID: Am 02.09.2011 00:46, schrieb Benjamin Kaplan: > Threading is an OS-level construct to allow concurrency within a > single process (and address space). Threads are never supposed to be > separate processes (they aren't at the C-level, so I don't know what > Java is doing here). CPython code has a global interpreter lock which > prevents two threads from running Python code at the same time, but > they're still useful for asynchronous operations. For example, one > thread can be waiting for user input while another thread continues to > process data. Other Python implementations such as Jython and > IronPython don't have a global interpreter lock so threads can run > concurrently (and on different cores in a multi-core machine). On Linux threading is implemented with multiple processes. A Linux pthread is a clone of the process created with the clone(2) syscall. [1] Each thread has a PID and an entry in the kernel's process table. Tools like htop can show user land threads as different processes. This may explain the confusion of the OP. He may have seen multiple Java threads as different processes. psutil can list all threads with PIDs. The getpid(2) syscall returns always the PID of the main process, gettid (only available through syscall(SYS_gettid)) returns the PID of the current thread. Christian [1] http://linux.die.net/man/2/clone From nobody at nowhere.com Thu Sep 1 20:10:14 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 02 Sep 2011 01:10:14 +0100 Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? Not reliably. You might infer that Ctrl-Alt-Del has been used by the way that certain operations behave, but that's fairly error-prone. > Also, is there a corresponding key-sequence in Mac and Linux? And how > might one detect those too? I don't know about Mac. Linux has some support for Ctrl-Alt-Del on the console, and the optional "Magic SysRq" feature. But there's no easy way to detect these (if the sequence is recognised by the kernel, it's not reported by the usual mechanisms). From dalist0 at gmail.com Thu Sep 1 20:21:33 2011 From: dalist0 at gmail.com (Daniel) Date: Thu, 1 Sep 2011 17:21:33 -0700 (PDT) Subject: fun with nested loops References: <7f43d4ad-fbd7-45f0-bcf5-719e19813429@glegroupsg2000goo.googlegroups.com> Message-ID: I thought a bit about Carl's and Thomas' proposals, and it gave me an idea how this problem could be approached: Break is relatively easy to implement with a context manager that returns an iterable that throws an exception specific to that context manager: with named_loop(i for i in range(10)) as loop1: for i in loop1: with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._break() # this is easy loop1._continue() # this is difficult # if we _continue here, we need to do a continue right after the with loop2a: if loop1.cont: continue # context manager does not create new scope with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() this throws an exception that propagates through all the context managers till it hits the one that made loop1 at that point the exception is caught. Now using the idea of break_levels, something like loop1._continue() should work. It is more difficult, because it should be caught in the last loop before the one that is targeted, loop1._continue throws an exception that is caught in loop2. Then loop1 just continues with the next value. I don't know how loop2 can learn that it is enclosed in loop1. Maybe loop1 could add itself to a global stack on enter and delete itself on exit, or maybe inspect could help? The big problem is that loop1._continue breaks out of loop2a, but then starts to execute loop2b, which we don't want. If loop1 is _continued inside of loop2a, a continue needs to directly follow the loop2a with block. An alternative would be to wrap each sequence of statements in another with statement, I think this is better: for i in loop1: with sequenced_stuff(): with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._continue() # this is caught in sequenced_stuff() with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() Loops can even be restarted with a small modification: In a loop like "for i in loop1:" the __iter__ method of loop1 is called. If __iter__ returns a smart iterator that keeps a reference to loop1, then it can be restarted, advanced etc. loop1.restart() would throw an exception that __exits__ all the inner loops and gets caught in the loop just before loop1. Then it resets the iterable that the iterator returned by __iter__ links to, i.e. loop1 restarts. Nice side benefit: loops can have a method peek(n) to look ahead. Thanks for all your input, Dan From bkasterm at gmail.com Thu Sep 1 20:35:10 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 01 Sep 2011 18:35:10 -0600 Subject: List comprehension timing difference. Message-ID: <87zkinkcht.fsf@gmail.com> In the following code I create the graph with vertices sgb-words.txt (the file of 5 letter words from the stanford graphbase), and an edge if two words differ by one letter. The two methods I wrote seem to me to likely perform the same computations, the list comprehension is faster though (281 seconds VS 305 seconds on my dell mini). Is the right interpretation of this timing difference that the comprehension is performed in the lower level C code? As this time I have no other conjecture about the cause. --------------------------------------------------------- import time import copy data = map (lambda x: x.strip(), open('sgb-words.txt').readlines()) def d (w1, w2): count = 0 for idx in range(0,5): if w1[idx] != w2[idx]: count += 1 return count print "creating graph" t0 = time.clock () graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a < b] t1 = time.clock () print "took " + str (t1 - t0) + " seconds." t0 = time.clock () graph2 = [] for i in range (0, len(data)): for j in range(0,len(data)): if d(data[i],data[j]) == 1 and i < j: graph2.append ([i,j]) t1 = time.clock () print "took " + str (t1 - t0) + " seconds." From steve+comp.lang.python at pearwood.info Thu Sep 1 21:04:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 11:04:01 +1000 Subject: fun with nested loops References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e602b81$0$29985$c3e8da3$5496439d@news.astraweb.com> Daniel wrote: > That's the form the specification is in, and it makes sense and is > very readable. > In pseudocode it looks like this, I am using @ to give loops a name: > > @loop1 > for c in configurations: > @loop2 > while not_done: > @loop3 > while step1_did_not_work: > @loop4 > for substeps in step1 # loop 4a > if hopeless(): continue loop1 # run next configuration > if substepsFailed(): restart loop4 # try again > if substepsWorked(): break loop3 # go on to next > steps, like loop4 > > That format is fine, everyone involved can understand it, even the > people in charge. Well good for them, because I sure as hell don't understand it. To me, that's exactly the sort of thing that Guido was worried about when he rejected the idea of named labels. I'd need to sit down and trace a few loops by hand to grasp it. I wonder how new people coming into the project find it? Personally, I consider two nested loops right on the boundary of my "magic number seven, plus or minus two" short term memory[1]. I prefer to chunk code into functions so that I can ignore details of the inner loops while reasoning about the outer loops, and vice versa. If you feel different, then I'm not being sarcastic when I say "good for you". If you require a 1:1 correspondence between your code and your pseudo-code specification, then maybe Python isn't the right language for this task. Ruby is very Python-like, and has labelled loops. Perl and PHP less so, but can also be quite readable with some discipline. You could also check out Cobra -- their website is down just at the moment, so I can't check whether it has labelled loops. http://cobra-language.com/ [1] Not really magic, and probably more like 4?2. -- Steven From python at mrabarnett.plus.com Thu Sep 1 21:12:47 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 02 Sep 2011 02:12:47 +0100 Subject: List comprehension timing difference. In-Reply-To: <87zkinkcht.fsf@gmail.com> References: <87zkinkcht.fsf@gmail.com> Message-ID: <4E602D8F.4090408@mrabarnett.plus.com> On 02/09/2011 01:35, Bart Kastermans wrote: > > In the following code I create the graph with vertices > sgb-words.txt (the file of 5 letter words from the > stanford graphbase), and an edge if two words differ > by one letter. The two methods I wrote seem to me to > likely perform the same computations, the list comprehension > is faster though (281 seconds VS 305 seconds on my dell mini). > > Is the right interpretation of this timing difference > that the comprehension is performed in the lower level > C code? > > As this time I have no other conjecture about the cause. > > --------------------------------------------------------- > import time > import copy > > data = map (lambda x: x.strip(), open('sgb-words.txt').readlines()) > > def d (w1, w2): > count = 0 > for idx in range(0,5): > if w1[idx] != w2[idx]: > count += 1 > return count > > print "creating graph" > t0 = time.clock () > graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a< b] > t1 = time.clock () > print "took " + str (t1 - t0) + " seconds." > > t0 = time.clock () > graph2 = [] > for i in range (0, len(data)): > for j in range(0,len(data)): > if d(data[i],data[j]) == 1 and i< j: > graph2.append ([i,j]) > t1 = time.clock () > print "took " + str (t1 - t0) + " seconds." Are they actually equivalent? Does graph == graph2? The first version (list comprehension) creates a list of pairs of values: [a, b] whereas the second version (for loops) creates a list of pairs of indexes: [i, j] The second version has subscripting ("data[i]" and "data[j]"), which will slow it down. From rtomek at ceti.com.pl Thu Sep 1 21:53:07 2011 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Fri, 2 Sep 2011 03:53:07 +0200 (CEST) Subject: slightly OT -- LaTeX In-Reply-To: <4E60379F.4000702@stoneleaf.us> References: <4E60379F.4000702@stoneleaf.us> Message-ID: On Thu, 1 Sep 2011, Ethan Furman wrote: > I asked a question a couple weeks ago about scripting WordPerfect with Python, > and a couple respondents suggested LaTeX was very good. Where would I start > if I wanted to learn about it? > > ~Ethan~ 1. Leslie Lamport, "LaTeX: A Document Preparation System" - I have used it, learning LaTeX in front of a computer, as I wrote my first document in it. I guess this is a very good book on the subject but I have never tried anything else. 2. http://www.latex-project.org/ http://www.latex-project.org/guides/ http://www.ctan.org/ Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From ethan at stoneleaf.us Thu Sep 1 21:55:43 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 01 Sep 2011 18:55:43 -0700 Subject: slightly OT -- LaTeX Message-ID: <4E60379F.4000702@stoneleaf.us> I asked a question a couple weeks ago about scripting WordPerfect with Python, and a couple respondents suggested LaTeX was very good. Where would I start if I wanted to learn about it? ~Ethan~ From sahil at FreeBSD.org Thu Sep 1 22:02:54 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 01 Sep 2011 22:02:54 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E60394E.2080708@FreeBSD.org> [Thanks to everyone who responded] Steven D'Aprano wrote: > On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: >> %% >> # unbuffer STDOUT >> sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) > > I've never bothered with unbuffered stdout, but that looks fine to me. > > I'm not sure if it is necessary though, because print seems to automatically > flush the buffer after each line in my testing. Unless you're printing > repeatedly to the same line, I'm not sure unbuffered stdout is helpful. I found it necessary because without reopening sys.stdout with buffering explicitly turned off, I would have to manually flush the buffer after each print. This is because the program must reply (via writing to STDOUT) after parsing each line read via STDIN. If I neither disable buffering nor manually flush after each print, the program just hangs instead of printing right away. >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: >> print('foo') >> else: >> print('bar') >> %% > > "while True" is considered slightly more idiomatic (readable), but > otherwise, that seems fine. Ah, thanks -- I've changed '1' to 'True'. >> This works, but while reading the documentation, I thought of using 'for >> line in fileinput.input()' in lieu of 'while 1:' construct. This does >> not work when debugging the program on the command line -- the script >> appears to just hang no matter what is typed into STDIN. I believe this >> is because of some internal buffering when using fileinput. Is there a >> recommended way to disable such buffering? Am I taking a totally wrong >> approach? > > I'm not sure anything about fileinput is exactly *recommended*, it's kinda > discouraged on account of being a bit slow. See help(fileinput) at the > interactive prompt. > > For what it's worth, the default buffersize for fileinput.input is 0, so if > that doesn't do what you want, I don't think fileinput is the right > solution. Got it. Based on your and others' response, I will stick with my existing approach. -- Sahil Tandon From ben+python at benfinney.id.au Thu Sep 1 22:11:23 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 02 Sep 2011 12:11:23 +1000 Subject: slightly OT -- LaTeX References: Message-ID: <8762lbsng4.fsf@benfinney.id.au> Ethan Furman writes: > I asked a question a couple weeks ago about scripting WordPerfect with > Python, and a couple respondents suggested LaTeX was very good. Someone (you, or the respondents, or some combination of those) has omitted a few steps there, and what you've said here has become a non sequitur: I can't see the path you've taken from ?scripting WordPerfect with Python? to ?LaTeX?. How does this relate to Python? (If it relates only to WordPerfect or LaTeX, you're in the wrong forum, so I assume there must be some particular relevance to Python.) > Where would I start if I wanted to learn about it? About LaTeX? seems the obvious answer. If you want something more specific, please be more specific with the question. -- \ ?Now Maggie, I?ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.? ?Homer, _The Simpsons_ | _o__) | Ben Finney From false at pp.jaring.my Thu Sep 1 22:11:55 2011 From: false at pp.jaring.my (Fulvio) Date: Fri, 02 Sep 2011 10:11:55 +0800 Subject: Optparse buggy? References: Message-ID: Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." Then,do you propose me to opt to argparse? -- Archlinux on $(uname -a) :P F From roy at panix.com Thu Sep 1 22:16:13 2011 From: roy at panix.com (Roy Smith) Date: Thu, 01 Sep 2011 22:16:13 -0400 Subject: Optparse buggy? References: Message-ID: In article , Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." One of the unfortunate things about optparse and argparse is the names. I can never remember which is the new one and which is the old one. It would have been a lot simpler if the new one had been named optparse2 (in the style of unittest2 and urllib2). From ben+python at benfinney.id.au Thu Sep 1 22:18:19 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 02 Sep 2011 12:18:19 +1000 Subject: Optparse buggy? References: Message-ID: <871uvzsn4k.fsf@benfinney.id.au> Fulvio writes: > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > Then,do you propose me to opt to argparse? Without argument, yes; though for now it is opt-in. -- \ ?We are no more free to believe whatever we want about God than | `\ we are free to adopt unjustified beliefs about science or | _o__) history [?].? ?Sam Harris, _The End of Faith_, 2004 | Ben Finney From askutt at gmail.com Thu Sep 1 22:25:22 2011 From: askutt at gmail.com (Adam Skutt) Date: Thu, 1 Sep 2011 19:25:22 -0700 (PDT) Subject: Python thread References: Message-ID: On Sep 1, 5:14?pm, George wrote: > Hi, > Why doesn't python threads show an associated PID? ?On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no ?subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. You probably need to run 'ps axm' or something similar to see to threads associated with a processes on your system. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. No. It depends on your runtime, but if Java uses native threads, it will have the same behavior as Python here. It also doesn't mean they get mapped to cores in the system. All it means is the operating system is responsible for scheduling the threads and managing their lifecycle. Adam From gagsl-py2 at yahoo.com.ar Thu Sep 1 22:26:54 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Sep 2011 23:26:54 -0300 Subject: Calling Script from Command line not working References: Message-ID: En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S escribi?: > We created a DLL using cygwin and have written a class based python > module > for the same. We have created a sample script for the class based python > module, that creates an object of the class and calls various methods in > the > class. This Test script works fine while I run it from IDLE. However > when I > run it from command prompt it either hangs or just returns without > executing > the functions. When it returns I do not get a error trace. > > When I tried to findout where exactly the issue is happening. the issue > occurs when I try to call the *cygwin_dll_init* method of the > cygwin1.dll . > This cygwin1.dll is actualy a dependency to the DLL we have built. So we > have to load this DLL and call this *cygwin_dll_init* method before > loading > my DLL. > > > cyg = cdll.LoadLibrary("cygwin1.dll") > cyg.cygwin_dll_init() #hangs or returns here > mydll=cdll.LoadLibrary("my.dll") >mydll.func1() >I'm trying to understand what exactly is the difference, when we call it > IDLE and when we call it from command prompt using the python command. I > will have to get the script working from command prompt as well. A few comments: * why do you initialize cygwin1.dll in Python? If it's a dependency of my.dll, it might be better to load and initialize it there. * for this function prototype: void cygwin_dll_init(void); you should declare it using: cyg = cdll.LoadLibrary("cygwin1.dll") cyg.restype = None cyg.cygwin_dll_init() #hangs or returns here ... Anyway, I don't see why a console application would fail but not inside IDLE. -- Gabriel Genellina From askutt at gmail.com Thu Sep 1 22:28:58 2011 From: askutt at gmail.com (Adam Skutt) Date: Thu, 1 Sep 2011 19:28:58 -0700 (PDT) Subject: Python thread References: Message-ID: On Sep 1, 5:54?pm, Terry Reedy wrote: > > Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > No, CPython is a native thread implementation, so they'll be scheduled however the kernel sees fit. Only allowing one thread to run at a time doesn't mean they'll always run on the same core. Adam From dan at tombstonezero.net Thu Sep 1 22:32:17 2011 From: dan at tombstonezero.net (Dan Sommers) Date: Fri, 2 Sep 2011 02:32:17 +0000 (UTC) Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 01 Sep 2011 16:02:54 +1000, Steven D'Aprano wrote: > On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: >> print('foo') >> else: >> print('bar') >> %% > "while True" is considered slightly more idiomatic (readable), but > otherwise, that seems fine. Arguably more readable, but arguably less idomatic, is to describe the actual condition that controls the loop in a string (non-empty strings are equivalent to True in this context): while "there is more input": rval = parse(raw_input()) if real is None: print('foo') else: print('bar') (Although now that I've said that, this looks like an infinite loop unless parse, raw_input, or print raises an exception.) Dan From miki.tebeka at gmail.com Fri Sep 2 00:01:56 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 1 Sep 2011 21:01:56 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <0d3e6227-9435-4103-b810-ae3b6e58c04f@glegroupsg2000goo.googlegroups.com> I found http://tobi.oetiker.ch/lshort/lshort.pdf very useful. From miki.tebeka at gmail.com Fri Sep 2 00:01:56 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 1 Sep 2011 21:01:56 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <0d3e6227-9435-4103-b810-ae3b6e58c04f@glegroupsg2000goo.googlegroups.com> I found http://tobi.oetiker.ch/lshort/lshort.pdf very useful. From invalid at invalid.invalid Fri Sep 2 00:32:48 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 2 Sep 2011 04:32:48 +0000 (UTC) Subject: Threads in Python References: Message-ID: On 2011-09-01, Stephen Hansen wrote: > On 9/1/11 2:45 PM, George Kovoor wrote: >> Why doesn't python threads show an associated PID? On spawning >> python threads using the threading module I can only see the main >> thread's pid on using top or ps unix command, no subprocesses are >> displayed. In otherwords top or ps in not aware of any subprocesses >> created using threading module in python. That's because threads are displayed by top/ps in most Linux systems. >> Whereas in Java , creating threads will result in separate pid, these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. If that's on the same system, then those aren't threads. > I think you're confused about what threads and subprocesses are. They > are completely different mechanisms for concurrent code. Threads never > show up on top or ps, in any language... That depends on your threading model. Some versions of Linux using LinuxThreads rather than NPTL will show each thread in top or ps. > or the language isn't offering threads. The difference between threads and processes isn't whether they show up in top or ps. For many years threads showed up in top and ps. They were still threads. But, you're right that on most modern, non-embedded, Linux systems threads don't show up in top or ps. > I don't know Java, so I can't really comment on it much, but it may > be misusing the 'thread' word, but I somehow doubt it. I suspect > you're just mistaken about what Java is offering. Sure sounds like it. -- Grant From cs at zip.com.au Fri Sep 2 01:01:59 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 2 Sep 2011 15:01:59 +1000 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: <4E60394E.2080708@FreeBSD.org> References: <4E60394E.2080708@FreeBSD.org> Message-ID: <20110902050158.GA20589@cskk.homeip.net> On 01Sep2011 22:02, Sahil Tandon wrote: | [Thanks to everyone who responded] | | Steven D'Aprano wrote: | >On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: | >>%% | >># unbuffer STDOUT | >>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) | > | >I've never bothered with unbuffered stdout, but that looks fine to me. | > | >I'm not sure if it is necessary though, because print seems to automatically | >flush the buffer after each line in my testing. Unless you're printing | >repeatedly to the same line, I'm not sure unbuffered stdout is helpful. | | I found it necessary because without reopening sys.stdout with | buffering explicitly turned off, I would have to manually flush the | buffer after each print. This is because the program must reply | (via writing to STDOUT) after parsing each line read via STDIN. If | I neither disable buffering nor manually flush after each print, the | program just hangs instead of printing right away. Yes. Steven was probably testing on a terminal. UNIX stdio buffering is line buffered on a terminal and block buffered otherwise (except for stderr, which is normally unbuffered regardless). So Steven saw stuff flushed on newlines and you would see stuff flushed when you explicitly flush or when the buffer fills (probably doesn't happen for your use because you need a response, and never write enough to fill the buffer). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Gentle suggestions being those which are written on rocks of less than 5lbs. - Tracy Nelson in comp.lang.c From anacrolix at gmail.com Fri Sep 2 01:33:01 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Fri, 2 Sep 2011 15:33:01 +1000 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > ======================================================= > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > ======================================================= > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression?- another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie From pavlovevidence at gmail.com Fri Sep 2 01:42:08 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 Sep 2011 22:42:08 -0700 (PDT) Subject: Optparse buggy? In-Reply-To: References: Message-ID: <058eeca4-6892-4075-abab-3ddcf6773692@glegroupsg2000goo.googlegroups.com> On Thursday, September 1, 2011 7:16:13 PM UTC-7, Roy Smith wrote: > In article , > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > One of the unfortunate things about optparse and argparse is the names. > I can never remember which is the new one and which is the old one. It > would have been a lot simpler if the new one had been named optparse2 > (in the style of unittest2 and urllib2). It's easy: "opt"parse parses only "opt"ions (-d and the like), whereas "arg"parse parses all "arg"uments. argparse is the more recent version since it does more. optparse2 would have been a bad name for something that parses more than options. (In fact, although I have some minor philosophical disagreements with optparse's design decisions, the main reason I always recommended using argparse instead was that optparse didn't handle positional arguments. optparse has all these spiffy features with type checking and defaults, but it never occurred to the optparse developers that this stuff would be useful for positional arugments, too. They just dropped the ball there.) Carl Banks From gahtune at gmail.com Fri Sep 2 02:14:12 2011 From: gahtune at gmail.com (Gabriel AHTUNE) Date: Fri, 2 Sep 2011 14:14:12 +0800 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: So can be done with this syntax: > x = firstpart * secondpart + #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE 2011/9/2 Matt Joiner > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. > > On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > > Hi Matt, > > ======================================================= > > From: Matt Joiner > > > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > > already heavily used by other syntactical structures. > > ======================================================= > > How about only require indentation > > to freely break lines? Here is an example: > > x = firstpart * secondpart #line breaks here > > + anotherpart #continue by indentation > > + stillanother #continue on. > > #until here, another line starts by dedentation > > y = some_expression - another_one > > All this would be completely compatible with former code, while > > having almost free line breaking! Plus, indentation makes it pretty. > > Really hope Python can have freedom in breaking lines. > > Yingjie > _______________________________________________ > Python-ideas mailing list > Python-ideas at python.org > http://mail.python.org/mailman/listinfo/python-ideas > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sathish at solitontech.com Fri Sep 2 02:17:18 2011 From: sathish at solitontech.com (Sathish S) Date: Fri, 2 Sep 2011 11:47:18 +0530 Subject: Calling Script from Command line not working In-Reply-To: References: Message-ID: Hey Gabriel, Thanks a lot for replying. I was able to run this python script from console/command prompt using cygwin python. I'm not sure whats the difference between these two versions of python. But it seems to be working. Searching theough the web i found that having cygwin1.dll could be causing this issue. So I'm trying to build my DLL using MinGW which will not create an dependecy DLL's. But I'm stuck up with few more issue in porting few functions to MinGW. I'm using Python2.7 and Cygwin Python 2.6.5 *Reply to your comments:* ** why do you initialize cygwin1.dll in Python? If it's a dependency of my.dll, it might be better to load and initialize it there.* Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it and initializing it ** for this function prototype: void cygwin_dll_init(void);* *you should declare it using:* I'm doing this as you said. But didn't mention it in my mail hCyg = cdll.LoadLibrary(CygWinDLL_Name) hCyg = CDLL(CygWinDLL_Name) Prototype_Cyg = CFUNCTYPE(c_void_p) Init = Prototype_Cyg (("cygwin_dll_init", hCyg)) Init.restype = c_void_p Init() Thanks, Sathish On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina wrote: > En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S > escribi?: > > > We created a DLL using cygwin and have written a class based python module >> for the same. We have created a sample script for the class based python >> module, that creates an object of the class and calls various methods in >> the >> class. This Test script works fine while I run it from IDLE. However when >> I >> run it from command prompt it either hangs or just returns without >> executing >> the functions. When it returns I do not get a error trace. >> >> When I tried to findout where exactly the issue is happening. the issue >> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll >> . >> This cygwin1.dll is actualy a dependency to the DLL we have built. So we >> have to load this DLL and call this *cygwin_dll_init* method before >> loading >> my DLL. >> >> >> cyg = cdll.LoadLibrary("cygwin1.dll"**) >> cyg.cygwin_dll_init() #hangs or returns here >> mydll=cdll.LoadLibrary("my.**dll") >> mydll.func1() >> I'm trying to understand what exactly is the difference, when we call it >> IDLE and when we call it from command prompt using the python command. I >> will have to get the script working from command prompt as well. >> > > A few comments: > > * why do you initialize cygwin1.dll in Python? If it's a dependency of > my.dll, it might be better to load and initialize it there. > > * for this function prototype: void cygwin_dll_init(void); > you should declare it using: > > > cyg = cdll.LoadLibrary("cygwin1.dll"**) > cyg.restype = None > > cyg.cygwin_dll_init() #hangs or returns here > ... > > Anyway, I don't see why a console application would fail but not inside > IDLE. > > -- > Gabriel Genellina > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Fri Sep 2 02:19:58 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 02 Sep 2011 18:19:58 +1200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <9cbashF8buU1@mid.individual.net> > On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: > >>Also, is there a corresponding key-sequence in Mac and Linux? The nearest equivalent in MacOSX is Command-Option-Escape, which brings up the force-quit dialog. I don't know how deep down in the system it's implemented. It's possible to use SetSystemUIMode to put an app into a "kiosk mode" where force-quitting is disabled, but I don't know whether the app can intercept Command-Option-Escape in that situation and do something else with it. -- Greg From sathish at solitontech.com Fri Sep 2 02:21:52 2011 From: sathish at solitontech.com (Sathish S) Date: Fri, 2 Sep 2011 11:51:52 +0530 Subject: Calling Script from Command line not working In-Reply-To: References: Message-ID: One more thing I observed is, while running the script from IDLE it launches a seperate process of pythonw.exe and I could see this console window poping up. However while running it from command prompt this does not happens. I was wondering if the command prompt way of calling the script is not able to launch this new process, that why it could be hanging. BTW I'm still trying to get the script running using Python 2.7 from the command prompt. Thanks, Sathish On Fri, Sep 2, 2011 at 11:47 AM, Sathish S wrote: > Hey Gabriel, > Thanks a lot for replying. I was able to run this python script from > console/command prompt using cygwin python. I'm not sure whats the > difference between these two versions of python. But it seems to be working. > Searching theough the web i found that having cygwin1.dll could be causing > this issue. So I'm trying to build my DLL using MinGW which will not create > an dependecy DLL's. But I'm stuck up with few more issue in porting few > functions to MinGW. > > I'm using Python2.7 and Cygwin Python 2.6.5 > > *Reply to your comments:* > > > ** why do you initialize cygwin1.dll in Python? If it's a dependency of > my.dll, it might be better to load and initialize it there.* > Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it > and initializing it > > ** for this function prototype: void cygwin_dll_init(void);* > *you should declare it using:* > I'm doing this as you said. But didn't mention it in my mail > > hCyg = cdll.LoadLibrary(CygWinDLL_Name) > hCyg = CDLL(CygWinDLL_Name) > Prototype_Cyg = CFUNCTYPE(c_void_p) > Init = Prototype_Cyg (("cygwin_dll_init", hCyg)) > Init.restype = c_void_p > Init() > > Thanks, > Sathish > > > > On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina wrote: > >> En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S >> escribi?: >> >> >> We created a DLL using cygwin and have written a class based python >>> module >>> for the same. We have created a sample script for the class based python >>> module, that creates an object of the class and calls various methods in >>> the >>> class. This Test script works fine while I run it from IDLE. However when >>> I >>> run it from command prompt it either hangs or just returns without >>> executing >>> the functions. When it returns I do not get a error trace. >>> >>> When I tried to findout where exactly the issue is happening. the issue >>> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll >>> . >>> This cygwin1.dll is actualy a dependency to the DLL we have built. So we >>> have to load this DLL and call this *cygwin_dll_init* method before >>> loading >>> my DLL. >>> >>> >>> cyg = cdll.LoadLibrary("cygwin1.dll"**) >>> cyg.cygwin_dll_init() #hangs or returns here >>> mydll=cdll.LoadLibrary("my.**dll") >>> mydll.func1() >>> I'm trying to understand what exactly is the difference, when we call it >>> IDLE and when we call it from command prompt using the python command. I >>> will have to get the script working from command prompt as well. >>> >> >> A few comments: >> >> * why do you initialize cygwin1.dll in Python? If it's a dependency of >> my.dll, it might be better to load and initialize it there. >> >> * for this function prototype: void cygwin_dll_init(void); >> you should declare it using: >> >> >> cyg = cdll.LoadLibrary("cygwin1.dll"**) >> cyg.restype = None >> >> cyg.cygwin_dll_init() #hangs or returns here >> ... >> >> Anyway, I don't see why a console application would fail but not inside >> IDLE. >> >> -- >> Gabriel Genellina >> >> -- >> http://mail.python.org/**mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Fri Sep 2 02:38:01 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 23:38:01 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <1314945481.74495.YahooMailNeo@web121517.mail.ne1.yahoo.com> Hi Gabriel, ================================================== From: Gabriel AHTUNE Subject: Re: [Python-ideas] allow line break at operators So can be done with this syntax: > x = firstpart * secondpart? +? #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE ================================================== That's good to me too, which I proposed early in this thread. Then somebody would like to have the operator in the beginning of the next line so that it would stand out.Then still another one said that indentation is good here. So I finally proposed line continuation with indentation. Since this is Python, we will live with indentation. Currently indentation in Python starts a new block, but if you view it from the perspective of line breaking, it also function as if the line is continued. The line if condition: do_a(); do_b() can be ?written as: if condition: #line breaks do_a(); # ';' is optional here? do_b() # continue Sounds a pretty natural way to allow free line breaking. Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Fri Sep 2 02:45:07 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 23:45:07 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <1314945907.94847.YahooMailNeo@web121513.mail.ne1.yahoo.com> Yeah, that might be a challenge for the Python?interpreter, for it has to check if the next line is indented or not. But it might be worthwhile to take this trouble, so that the coder has more freedom, and the code is hopefully better to read. ________________________________ From: Matt Joiner To: Yingjie Lan Cc: "python-list at python.org" ; python-ideas Sent: Friday, September 2, 2011 1:33 PM Subject: Re: [Python-ideas] allow line break at operators I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > ======================================================= > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > ======================================================= > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression?- another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From me+list/python at ixokai.io Fri Sep 2 03:06:12 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 02 Sep 2011 00:06:12 -0700 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4E608064.9030005@ixokai.io> On 9/1/11 8:52 AM, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? IIUC, by definition, Ctrl-Alt-Delete can't be responded to in any way. Its the entire point of the sequence: when you type it you can be entirely, totally, 100% certain that what happens next is the true OS and not any app faking things. That's why you have to hit CAD to get to the login form in some versions of Windows. The whole point of that secure sequence is that the OS and only the OS responds. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From tavares at fe.up.pt Fri Sep 2 03:08:14 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Fri, 2 Sep 2011 00:08:14 -0700 (PDT) Subject: CompIMAGE 2012: Call for Thematic Sessions and Papers Message-ID: Dear Colleague, We would like to call your attention to the International Symposium CompIMAGE 2012 ? Computational Modeling of Objects Presented in Images: Fundamentals, Methods and Applications (www.dis.uniroma1.it/ compimage2012), that will be held in Rome, Italy, in September 5-7, 2012. MAIN TOPICS - image processing and analysis - image segmentation - 2D and 3D reconstruction - data interpolation - registration and acquisition - objects tracking - scientific data visualization - satellite data - shape modeling - simulation - biometric person identification - medical imaging - motion and deformation analysis - material science - large set data visualization - vision in robotics and automation INVITED LECTURERS - Lorenzo Bruzzone, University of Trento, Italy - Jorge Marques, Instituto Superior T?cnico, Lisboa, Portugal - Fiorella Sgallari, University of Bologna, Italy - Bertrand Thirion, INRIA, France - Luminita Vese, UCLA, USA THEMATIC SESSIONS Proposals to organize Thematic Session within CompIMAGE2012 are welcome and should be submitted by email to: compimage2012 at dis.uniroma1.it. PUBLICATIONS - The proceedings book will be published by Taylor & Francis Group and indexed by Thomson Reuters Conference Proceedings Citation Index, IET Inspect and Elsevier Scopus. - A book with 20 invited works from the best ones presented in CompIMAGE 2012 (extended versions) will be published by Springer. - The organizers will encourage the submission of extended versions of the accepted papers to related International Journals; in particular, for special issues dedicated to CompIMAGE 2012. IMPORTANT DATES - Deadline for Thematic Sessions proposals: November 1, 2011 - Deadline for Full Paper Submission: December 31, 2011 - Authors Notification: March 16, 2012 - Final camera-ready papers: April 20, 2012 - Early Symposium registration (mandatory for Authors): April 20, 2012 - Symposium dates: September 5-7, 2012 AWARDS "Best paper award" and "Best student paper award" are going to be given to the author(s) of two papers presented at CompIMAGE 2012, selected by the Organizing Committee based on the best combined marks from the Scientific Committee and Session Chairs. Kind regards, Paolo Di Giamberardino Daniela Iacoviello Renato M. Natal Jorge Jo?o Manuel R. S. Tavares PS. For further details, please, visit CompIMAGE 2012 website at: www.dis.uniroma1.it/compimage2012. From nemjain at gmail.com Fri Sep 2 03:12:18 2011 From: nemjain at gmail.com (nemi) Date: Fri, 2 Sep 2011 00:12:18 -0700 (PDT) Subject: How to daemonize a HTTPServer References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On Sep 1, 6:32?am, "Martin P. Hellwig" wrote: > On 01/09/2011 04:16, babbu Pehlwan wrote: > > > I have written a http server using BaseHTTPServer module. Now I want > > to instantiate it through another python script. The issue here is > > after instantiate the control doesn't come back till the server is > > running. Please suggest. > > Sounds like something you could use the multiprocessing module for, but > then again my crystal ball is a bit fuzzy today. > > -- > mph Thanks dear, the issue get solved now. You are absolutely right, actually I was daemonising the same thread. Now I have created a seperate thread for the server. From stephen at xemacs.org Fri Sep 2 03:28:16 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Fri, 02 Sep 2011 16:28:16 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Gabriel AHTUNE writes: > So can be done with this syntax: > > > x = firstpart * secondpart + #line breaks here > > anotherpart + #continue > > stillanother #continue on. > > after a "+" operator the line is clearly not finished yet. Sure, but IIRC one design principle of Python is that the keyword that denotes the syntax should be the first thing on the line, making it easy to scan down the left side of the code to see the syntactic structure. The required indentation of the controlled suite also helps emphasize that keyword. Analogously, if operators are going to denote continuation, they should come first on the line. I just don't think this idea is going anywhere. Explicit continuation with backslash or implicit continuation of parenthesized expressions is just not that heavy a price to pay. Perhaps historically some of these ideas could have been implemented, but now they're just going to confuse a host of editors and code analysis tools. From rosuav at gmail.com Fri Sep 2 03:55:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 2 Sep 2011 17:55:41 +1000 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <4E608064.9030005@ixokai.io> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: On Fri, Sep 2, 2011 at 5:06 PM, Stephen Hansen wrote: > That's why you have to hit CAD to get to the login form in some versions > of Windows. The whole point of that secure sequence is that the OS and > only the OS responds. > Although I heard somewhere that that's more gimmick than guarantee, and that it IS possible for an app to hook CAD - just that it's a lot harder than building a simple window that looks like the login... but it's pretty easy to fool a lot of people. Just look at the emails in your spam box one day, find the ones spoofing a bank, and see what a poor job they do. And yet they work. ChrisA From vinay_sajip at yahoo.co.uk Fri Sep 2 05:56:29 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 02:56:29 -0700 (PDT) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From vinay_sajip at yahoo.co.uk Fri Sep 2 05:58:29 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 09:58:29 +0000 (UTC) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From vinay_sajip at yahoo.co.uk Fri Sep 2 06:00:30 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 03:00:30 -0700 (PDT) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From t at jollybox.de Fri Sep 2 06:01:34 2011 From: t at jollybox.de (Thomas Jollans) Date: Fri, 02 Sep 2011 12:01:34 +0200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4E60A97E.2080506@jollybox.de> On 01/09/11 17:52, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? > > Also, is there a corresponding key-sequence in Mac and Linux? And how > might one detect those too? On Linux Ctrl+Alt+Delete is typically configured to reboot the machine when in console mode. In X11 (graphical), as far as I know, it's no different than other keys. To catch it globally, you'd probably have to go through the individual window manager. As m'colleague Nobody mentions, there's also the SysRq feature, but that always goes straight to the kernel and is, like Ctrl+Alt+Delete on Windows, impossible to handle in userspace code. Thomas From fnautaNO at SPAMsolfon.nl Fri Sep 2 08:04:55 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 14:04:55 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><6545843.yvFAXZvWTv@PointedEars.de><9c528rFi5aU1@mid.individual.net><4761603.ypaU67uLZW@PointedEars.de><9c6d4cFa54U1@mid.individual.net> Message-ID: <9cbvupFjr3U2@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.622.1314812583.27778.python-list at python.org... > On Wed, 31 Aug 2011 11:27:36 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> >> Ofcourse I realized it was Unix/Linux. I already could tell that as the >> packages I downloaded were tar.gz files. >> So I unpacked them and expected to run a Python installer script from the >> Python command line. >> Hence my question "How do I do that", but perhaps I did not make myself >> clear enough. >> > NO Python package installer runs "from the Python command line" (ie; > from a Python interactive session prompt). > > Typically you run them from the OS command interpreter. If the > installer is a .py file and the associations are correct, the Python > interpreter will be started to process the installer script. If the > associations aren't set, you may have to enter > > python installer.py > > at the system prompt instead of > > installer.py > >> Tried to run the Python installer script from the DOS command line but >> that >> resulted in an error. >> > Okay -- so what was the error? > -- Sorry - I didn't come back on your question. In the mean time I forgot what the error message was. But I installed it the way Paul K?lle mentioned: "You dont install from "Python GUI", use normal cmd, navigate to the folder you downloaded PyXML and PyWebDAV and run "python setup.py install" (python.exe has to be in your PATH)." Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 08:19:32 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 14:19:32 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> Message-ID: <9cbvupFjr3U3@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.687.1314941410.27778.python-list at python.org... > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> "Dennis Lee Bieber" wrote in message >> news:mailman.643.1314851358.27778.python-list at python.org... > >> > Next, if you'd read further and didn't take the comment as the >> > instruction. set >> > firstrun=1 >> >> I did >> >> > to tell the server this is the first time it is being run - IT WILL >> > create the database table (after the first start, reset the flag to 0 >> > to >> > speed up later runs). >> >> It didn't create the table. The database kept empty. > > Odd -- but then, I'm not running it myself, and wasn't up to reading > all the code to see what path it takes. It's only for experimenting with calendar software, so authorization is not a point. So I forget about MySQL. >> >> > Later in the config file set >> > mysql_auth=1 >> > to enable the use of MySQL, and set the admin user/password to what you >> > plan to have it use. >> >> I did >> >> > You probably want to set >> > daemonize=1 >> > (maybe after first run) >> >> I left this to 0. >> >> > Oh, and don't forget to set the main data directory and any >> > port/host changes. >> >> I left host and port as they were. The main directory is e:\wwwroot >> >> > Start the server - it should connect to MySQL, create the table, and >> > add the admin user to the table. >> >> I started the server with server.py (in >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini >> > If the main directory is already in the config file, you probably > don't need to specify it on the command line... OK > And... could there be > something in the code where overriding the directory by command line > changes where it looks for the config file? (Just guessing at this > point). > Possibly. I tried this: server.py -n -c config.ini Once again, the server is up and running and when I am logging in with my browser (10.0.0.140:8081) I can see information showing up at the command prompt, showing somebody is logging is, but the same error: "fshandler:get_data: \Webdav not found". During starting up the server mentioned: "pywebdav:Serving data from \Webdav". In the config file it says: "# main directory directory = \Webdav" Perhaps my Python configuration is at fault. Fokke From msamogh at gmail.com Fri Sep 2 08:25:28 2011 From: msamogh at gmail.com (Amogh M S) Date: Fri, 2 Sep 2011 17:55:28 +0530 Subject: Python-list Digest, Vol 96, Issue 4 In-Reply-To: References: Message-ID: Thank you very much And no, no, I have not been reading a book with bad font =D haha!! The problem was that I did not inherit from Object... Since I am from a JAVA background, I assumed that Python would inherit implicitly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmsoft at gmail.com Fri Sep 2 08:27:50 2011 From: sjmsoft at gmail.com (sjm) Date: Fri, 2 Sep 2011 05:27:50 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sep 1, 12:52?pm, Den wrote: > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? If you manage to write a program that can detect CTRL-ALT-DEL, please report it as a bug in Windows! CTRL-ALT-DEL is Windows' "secure attention sequence" which must only be handled by the OS. -- Steve From msamogh at gmail.com Fri Sep 2 08:29:17 2011 From: msamogh at gmail.com (Amogh M S) Date: Fri, 2 Sep 2011 17:59:17 +0530 Subject: Python-list Digest, Vol 96, Issue 4 In-Reply-To: References: Message-ID: Two underscores??!!! OH!!! I thank thee! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Sep 2 08:45:39 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 02 Sep 2011 13:45:39 +0100 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <4e60ce59$0$18107$426a74cc@news.free.fr> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4e60ce59$0$18107$426a74cc@news.free.fr> Message-ID: <4E60CFF3.6080006@timgolden.me.uk> >> Obviously, this is a windows-based question. I know that Ctrl-Alt-Del >> is handled deep inside the OS, and I'm not trying to interrupt that. >> But is there some way to detect that a C-A-D has been pressed? Others have pointed out that this shouldn't really be possible for reasons of security. (And I agree). However, if what you're really after is to detect a session switch or a logon then this might be of some use: http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html TJG From bex.lewis at gmail.com Fri Sep 2 09:09:06 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Fri, 2 Sep 2011 06:09:06 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> Message-ID: <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> On Sep 2, 1:19?pm, "Fokke Nauta" wrote: > "Dennis Lee Bieber" wrote in messagenews:mailman.687.1314941410.27778.python-list at python.org... > > > > > > > > > > > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > > declaimed the following in > > gmane.comp.python.general: > > >> "Dennis Lee Bieber" wrote in message > >>news:mailman.643.1314851358.27778.python-list at python.org... > > >> > Next, if you'd read further and didn't take the comment as the > >> > instruction. set > >> > firstrun=1 > > >> I did > > >> > to tell the server this is the first time it is being run - IT WILL > >> > create the database table (after the first start, reset the flag to 0 > >> > to > >> > speed up later runs). > > >> It didn't create the table. The database kept empty. > > > Odd -- but then, I'm not running it myself, and wasn't up to reading > > all the code to see what path it takes. > > It's only for experimenting with calendar software, so authorization is not > a point. > So I forget about MySQL. > > > > > > > > > > > > >> > Later in the config file set > >> > mysql_auth=1 > >> > to enable the use of MySQL, and set the admin user/password to what you > >> > plan to have it use. > > >> I did > > >> > You probably want to set > >> > daemonize=1 > >> > (maybe after first run) > > >> I left this to 0. > > >> > Oh, and don't forget to set the main data directory and any > >> > port/host changes. > > >> I left host and port as they were. The main directory is e:\wwwroot > > >> > Start the server - it should connect to MySQL, create the table, and > >> > add the admin user to the table. > > >> I started the server with server.py (in > >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini > > > If the main directory is already in the config file, you probably > > don't need to specify it on the command line... > > OK > > > And... could there be > > something in the code where overriding the directory by command line > > changes where it looks for the config file? (Just guessing at this > > point). > > Possibly. > I tried this: > server.py -n -c config.ini > Once again, the server is up and running and when I am logging in with my > browser (10.0.0.140:8081) I can see information showing up at the command > prompt, showing somebody is logging is, but the same error: > "fshandler:get_data: \Webdav not found". During starting up the server > mentioned: "pywebdav:Serving data from \Webdav". > > In the config file it says: > "# main directory > directory = \Webdav" > > Perhaps my Python configuration is at fault. > > Fokke Is the path supposed to be absolute? In which case you'd need to have: directory=C:\path\to\Webdav instead of just directory=\Webdav Becky Lewis From python at bdurham.com Fri Sep 2 09:11:13 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 02 Sep 2011 09:11:13 -0400 Subject: Installing WebDAV server In-Reply-To: <9cbvupFjr3U3@mid.individual.net> References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> Message-ID: <1314969073.6889.140258136595213@webmail.messagingengine.com> Hi Fokke, Disclaimer: I have no experience with the Python WebDAV package you're using. But a thought: > In the config file it says: > "# main directory > directory = \Webdav" Perhaps you should qualify your directory path with a drive letter? I would try this 2 ways: directory = E:\Webdav And if that doesn't work: directory = E:/Webdav My thinking about the 2nd example is that perhaps the \W is getting interpreted as a control character vs. "backslash" "W". Malcolm From alan.isaac at gmail.com Fri Sep 2 09:12:37 2011 From: alan.isaac at gmail.com (Alan) Date: Fri, 2 Sep 2011 06:12:37 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> http://www.pytex.org/ hth, Alan Isaac From alan.isaac at gmail.com Fri Sep 2 09:12:37 2011 From: alan.isaac at gmail.com (Alan) Date: Fri, 2 Sep 2011 06:12:37 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> http://www.pytex.org/ hth, Alan Isaac From kw at codebykevin.com Fri Sep 2 09:21:43 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 02 Sep 2011 09:21:43 -0400 Subject: OSX application built with py2app can't see bundled PySide module? In-Reply-To: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> References: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/1/11 3:54 PM, Aaron Scott wrote: > I'm trying to deploy a Python app on OSX that was built with PySide. py2app packages it without issue, copying and linking a lot of PySide and Qt files in the process. But then, when I try to run the built app, I get this error: > > Traceback (most recent call last): > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 31, in > _run('dailies_v02.py') > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 28, in _run > execfile(path, globals(), globals()) > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/dailies_v02.py", line 9, in > from PySide.QtCore import * > File "PySide/__init__.pyc", line 2, in > File "PySide/private.pyc", line 2, in > File "PySide/QtCore.pyc", line 18, in > File "PySide/QtCore.pyc", line 15, in __load > ImportError: '/usr/lib/python2.6/lib-dynload/PySide/QtCore.so' not found > > The weird thing is, QtCore.so IS included in the application bundle: py2app copied it to the build under Contents/Resources/lib/python2.6/lib-dynload/PySide/. Is there a reason the application isn't seeing this? You might want to post this question to the MacPython list--that's where the py2app experts are found. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From python at bdurham.com Fri Sep 2 09:49:30 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 02 Sep 2011 09:49:30 -0400 Subject: slightly OT -- LaTeX In-Reply-To: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> References: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> Message-ID: <1314971370.18457.140258136609677@webmail.messagingengine.com> Hi Alan, Thanks for sharing that link - very interesting! http://www.pytex.org/ Malcolm (former LaTeX/TeX user from early 90's) From bkasterm at gmail.com Fri Sep 2 09:54:50 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 02 Sep 2011 07:54:50 -0600 Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> Message-ID: <87sjofjbh1.fsf@gmail.com> MRAB writes: > On 02/09/2011 01:35, Bart Kastermans wrote: >> graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a< b] >> graph2 = [] >> for i in range (0, len(data)): >> for j in range(0,len(data)): >> if d(data[i],data[j]) == 1 and i< j: >> graph2.append ([i,j]) > > Are they actually equivalent? Does graph == graph2? > > The first version (list comprehension) creates a list of pairs of > values: > > [a, b] > > whereas the second version (for loops) creates a list of pairs of > indexes: > > [i, j] > > The second version has subscripting ("data[i]" and "data[j]"), which > will slow it down. You are absolutely right. I had changed the code from the equivalent: graph2 = [] for i in range (0, len(data)): for j in range(0,len(data)): if d(data[i],data[j]) == 1 and i < j: graph2.append ([data[i],data[j]]) But then also tried the equivalent for a in data: for b in data: if d(a,b) == 1 and a < b: graph2.append([a,b]) Which does away with the indexing, and is just about exactly as fast as the list comprehension. That'll teach me; I almost didn't ask the question thinking it might be silly. And it was, but I thought it for the wrong reason. I tell my students there are no stupid questions, I should listen to myself more when I do. Thanks! From ting at thsu.org Fri Sep 2 10:50:24 2011 From: ting at thsu.org (ting at thsu.org) Date: Fri, 2 Sep 2011 07:50:24 -0700 (PDT) Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> <87sjofjbh1.fsf@gmail.com> Message-ID: <07906043-d732-43ca-8313-bee4746eca75@fi7g2000vbb.googlegroups.com> On Sep 2, 9:54?am, Bart Kastermans wrote: > if d(a,b) == 1 and a < b: It will probably be faster if you reverse the evaluation order of that expression. if a I have a function I want to run in a thread and return a value. It seems like the most obvious way to do this is to have my target function return the value, the Thread object stash that someplace, and return it as the return value for join(). Yes, I know there's other ways for a thread to return values (pass the target a queue, for example), but making the return value of the target function available would have been the most convenient. I'm curious why threading wasn't implemented this way. From d_vineet at yahoo.com Fri Sep 2 11:34:25 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Fri, 2 Sep 2011 08:34:25 -0700 (PDT) Subject: convert python List to javascript array Message-ID: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Hi ! Within a web framework, I want want to pass a python sequence (list or tuple) to client-side javascript function as an array (javascript compatible) e.g., I have this list: L = ['spam', 'ham', 'eggs', 12, (13.63)] What is the correct way to convert L to?javascript array format? 1) jsonify the list and pass it to javascript (whether json format & javascript array are similar?) OR 2) >> import array >> y = array.array(i, L) ?then return y to javascript function But the problem with this method is, it will give an array of basic values only. OR 3) Any other alternative? Thanks, Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 2 11:45:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 03 Sep 2011 01:45:22 +1000 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> Message-ID: <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: > I have a function I want to run in a thread and return a value. It > seems like the most obvious way to do this is to have my target > function return the value, the Thread object stash that someplace, and > return it as the return value for join(). > > Yes, I know there's other ways for a thread to return values (pass the > target a queue, for example), but making the return value of the > target function available would have been the most convenient. I'm > curious why threading wasn't implemented this way. Because then the code launching the thread would have to block, waiting until the thread is completed, so it will have a result to return. -- Steven From benjamin.kaplan at case.edu Fri Sep 2 11:50:12 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 2 Sep 2011 11:50:12 -0400 Subject: convert python List to javascript array In-Reply-To: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 11:34 AM, Vineet Deodhar wrote: > Hi ! > Within a web framework, I want want to pass a python sequence (list or > tuple) to client-side javascript function as an array (javascript > compatible) > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to?javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) > > OR > 2) >>> import array >>> y = array.array(i, L) > ?then return y to javascript function > But the problem with this method is, it will give an array of basic values > only. > > OR > 3) Any other alternative? > > Thanks, > Vineet > -- The JavaScript Object Notation (JSON) is meant exactly for this purpose. From patentsvnc at gmail.com Fri Sep 2 12:19:35 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:19:35 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4310f6ad-8aab-481b-9e68-3931f67b49b6@m4g2000pri.googlegroups.com> On Sep 2, 5:27?am, sjm wrote: > On Sep 1, 12:52?pm, Den wrote: > > > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > > is handled deep inside the OS, and I'm not trying to interrupt that. > > But is there some way to detect that a C-A-D has been pressed? > > If you manage to write a program that can detect CTRL-ALT-DEL, please > report it as a bug in Windows! ?CTRL-ALT-DEL is Windows' "secure > attention sequence" which must only be handled by the OS. > > -- Steve I have already done that, in AutoHotKey ... or at least it used to work. AHK can detect when a window opened. And when CAD was pressed the ... well, I've forgotten what it was called ... but a window opened asking if you wanted to open the task manager, or quit or log off or what. Then you would know that CAD was pressed. There was nothing you could do to stop it, but you could at least detect that it had been pressed. That's why I was wondering if there was a similar technique which could be used in Python. Den From patentsvnc at gmail.com Fri Sep 2 12:20:23 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:20:23 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <2ab915f4-a0cb-42ed-8d4b-5bd16a9ee9ca@x21g2000prd.googlegroups.com> On Sep 2, 5:27?am, sjm wrote: > On Sep 1, 12:52?pm, Den wrote: > > > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > > is handled deep inside the OS, and I'm not trying to interrupt that. > > But is there some way to detect that a C-A-D has been pressed? > > If you manage to write a program that can detect CTRL-ALT-DEL, please > report it as a bug in Windows! ?CTRL-ALT-DEL is Windows' "secure > attention sequence" which must only be handled by the OS. > > -- Steve I'm not trying to hook it or stop it, just detect it. Den From patentsvnc at gmail.com Fri Sep 2 12:26:12 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:26:12 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sep 1, 8:52?am, Den wrote: > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? > > Also, is there a corresponding key-sequence in Mac and Linux? ?And how > might one detect those too? > > Den I've been doing some more thinking on what I want. This may be a better explanation. Is there a way of detecting if my program has lost "focus" (I'm not sure the correct term)? For example, if someone is typing in my program, but some other program takes control (or CAD has been pressed) I would like simply to log that. I have no interest in trying to hijack or interfere with anything, simply log it. Den From gagsl-py2 at yahoo.com.ar Fri Sep 2 12:36:17 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 13:36:17 -0300 Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> Message-ID: En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks escribi?: > On Aug 31, 7:37 pm, Gregory Ewing wrote: >> Ian Kelly wrote: >> > if sys.version_info < (3,): >> > getDictValues = dict.itervalues >> > else: >> > getDictValues = dict.values >> >> > (which is basically what the OP was doing in the first place). >> > My problem was that I didn't understand the scoping rules. It is still > strange to me that the getValues variable is still in scope outside > the if/else branches. Those if/else are at global scope. An 'if' statement does not introduce a new scope; so getDictValues, despite being "indented", is defined at global scope, and may be used anywhere in the module. -- Gabriel Genellina From usenet-nospam at seebs.net Fri Sep 2 12:42:34 2011 From: usenet-nospam at seebs.net (Seebs) Date: 02 Sep 2011 16:42:34 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-09-02, Steven D'Aprano wrote: > Roy Smith wrote: >> I have a function I want to run in a thread and return a value. It >> seems like the most obvious way to do this is to have my target >> function return the value, the Thread object stash that someplace, and >> return it as the return value for join(). >> Yes, I know there's other ways for a thread to return values (pass the >> target a queue, for example), but making the return value of the >> target function available would have been the most convenient. I'm >> curious why threading wasn't implemented this way. > Because then the code launching the thread would have to block, waiting > until the thread is completed, so it will have a result to return. Isn't "waiting until the thread is completed" sort of the point of join()? -s -- Copyright 2011, all wrongs reversed. Peter Seebach / usenet-nospam at seebs.net http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. From jehugaleahsa at gmail.com Fri Sep 2 12:53:37 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 09:53:37 -0700 (PDT) Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> Message-ID: <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> On Sep 2, 12:36?pm, "Gabriel Genellina" wrote: > En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks ? > escribi : > > > On Aug 31, 7:37 pm, Gregory Ewing wrote: > >> Ian Kelly wrote: > >> > if sys.version_info < (3,): > >> > ? ? getDictValues = dict.itervalues > >> > else: > >> > ? ? getDictValues = dict.values > > >> > (which is basically what the OP was doing in the first place). > > > My problem was that I didn't understand the scoping rules. It is still > > strange to me that the getValues variable is still in scope outside > > the if/else branches. > > Those if/else are at global scope. An 'if' statement does not introduce a ? > new scope; so getDictValues, despite being "indented", is defined at ? > global scope, and may be used anywhere in the module. > > -- > Gabriel Genellina > > Does that mean the rules would be different inside a function? From jehugaleahsa at gmail.com Fri Sep 2 12:59:03 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 09:59:03 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers Message-ID: Hello: I am working on an algorithms library. It provides LINQ like functionality to Python iterators. Eventually, I plan on having feaures that work against sequences and mappings. I have the code up at http://code.google.com/p/py-compass. This is my first project in Python, so I'd like some feedback. I want to know if I am following conventions (overall style and quality of code). Thanks, Travis Parks From clp2 at rebertia.com Fri Sep 2 13:26:15 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 10:26:15 -0700 Subject: convert python List to javascript array In-Reply-To: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 8:34 AM, Vineet Deodhar wrote: > Hi ! > Within a web framework, I want want to pass a python sequence (list or > tuple) to client-side javascript function as an array (javascript > compatible) > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to?javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) JSON is in fact a subset of JavaScript, and modern browsers now include a specific API for parsing and generating it (https://developer.mozilla.org/En/Using_native_JSON ). Python likewise has a JSON module in the std lib: http://docs.python.org/library/json.html > OR > 2) >>> import array >>> y = array.array(i, L) > ?then return y to javascript function > But the problem with this method is, it will give an array of basic values > only. The word "array" gets tossed around a lot by programmers. The `array` module is not at all what you want in this case. Cheers, Chris -- http://rebertia.com From norrisd at bellsouth.net Fri Sep 2 13:41:32 2011 From: norrisd at bellsouth.net (aMereCat) Date: Fri, 2 Sep 2011 10:41:32 -0700 (PDT) Subject: Tenjin and External CSS Message-ID: I'm new at Python, Cherrypy and Tenjin and I can't get tenjin to recognize external css file. Does anyone have an example showing how it's done? Thanks. From johnroth1 at gmail.com Fri Sep 2 13:51:14 2011 From: johnroth1 at gmail.com (John Roth) Date: Fri, 2 Sep 2011 10:51:14 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> Message-ID: <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> On Sep 1, 8:26?am, Ian Kelly wrote: > On Thu, Sep 1, 2011 at 6:45 AM, John Roth wrote: > > I personally consider this to be a wart. Some time ago I did an > > implementation analysis. The gist is that, if self and cls were made > > special variables that returned the current instance and class > > respectively, then the compiler could determine whether a function was > > an instance or class method. If it then marked the code object > > appropriately you could get rid of all of the wrappers and the > > attendant run-time overhead. > > I don't see how you could get rid of the wrappers. ?Methods would > still need to be bound, somehow, so that code like this will work: > > methods = {} > for obj in objs: > ? ? if obj.is_flagged: > ? ? ? ? methods[obj.user_id] = obj.do_work > ? ? else: > ? ? ? ? methods[obj.user_id] = obj.do_other_work > # ... > methods[some_user_id]() > > Without method wrappers, how does the interpreter figure out which > instance is bound to the method being called? > > Cheers, > Ian Good question. Currently the instance wrapper is created during method instantiation, so the instance is obviously available at that point. There are two rather obvious ways of remembering it. One is to use the invocation stack, which has the instance. Another would be for the compiler to create a local variable for the instance and possibly the class and fill them in at instantiation time. Both of these require fixing the names "self" and "cls" so the compiler knows what to do with them. The first would require giving these two names their own bytecodes, the second makes them simple local variables the same as the ones in the method headers. The latter also allows them to be changed by the method, which is probably not the world's best programming practice although it's possible now. John Roth From askutt at gmail.com Fri Sep 2 14:01:17 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 11:01:17 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> Message-ID: <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> On Sep 2, 10:53?am, Roy Smith wrote: > I have a function I want to run in a thread and return a value. ?It > seems like the most obvious way to do this is to have my target > function return the value, the Thread object stash that someplace, and > return it as the return value for join(). > > Yes, I know there's other ways for a thread to return values (pass the > target a queue, for example), but making the return value of the > target function available would have been the most convenient. ?I'm > curious why threading wasn't implemented this way. I assume it is because the underlying operating system APIs do not support it. Windows and POSIX threads only support returning an integer when a thread exits, similar to the exit code of a process. More importantly, there's no way to tell whether the exit code of a thread was set by user code or by the system. Even worse, some of those integer values are reserved by some operating systems. If your thread died via an exception, it still has an error code set by the operating system. How would you going to distinguish those codes from your own? Adam From alain at dpt-info.u-strasbg.fr Fri Sep 2 14:23:28 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Fri, 02 Sep 2011 20:23:28 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Adam Skutt writes: > On Sep 2, 10:53?am, Roy Smith wrote: >> I have a function I want to run in a thread and return a value. ?It >> seems like the most obvious way to do this is to have my target >> function return the value, the Thread object stash that someplace, and >> return it as the return value for join(). >> > Yes, I know there's other ways for a thread to return values (pass the >> target a queue, for example), but making the return value of the >> target function available would have been the most convenient. ?I'm >> curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Windows and POSIX threads only support returning an > integer when a thread exits, similar to the exit code of a process. Sorry, you're wrong, at least for POSIX threads: void pthread_exit(void *value_ptr); int pthread_join(pthread_t thread, void **value_ptr); pthread_exit can pass anything, and that value will be retrieved with pthread_join. Threads of a process share their address space, there is no reason to restrict their return value to an int. > More importantly, there's no way to tell whether the exit code of a > thread was set by user code or by the system. Even worse, some of > those integer values are reserved by some operating systems. I'm not sure what you are talking about here. Maybe you confuse threads with processes? Re. the original question: since you can define your own Thread subclass, with wathever attribute you want, I guess there was no need to use join() to communicate the result. The Thread's run() can store its result in an attribute, and the "client" can get it from the same attribute after a successful call to join(). -- Alain. From Tim.Arnold at sas.com Fri Sep 2 14:43:53 2011 From: Tim.Arnold at sas.com (Tim Arnold) Date: Fri, 02 Sep 2011 14:43:53 -0400 Subject: sqlite3 with context manager Message-ID: Hi, I'm using the 'with' context manager for a sqlite3 connection: with sqlite3.connect(my.database,timeout=10) as conn: conn.execute('update config_build set datetime=?,result=? where id=?', (datetime.datetime.now(), success, self.b['id'])) my question is what happens if the update fails? Shouldn't it throw an exception? I ask because apparently something went wrong yesterday and the code never updated but I never got any warning. I rebooted the machine and everything is okay now, but I'd like to understand what happened. thanks, --Tim From vinay_sajip at yahoo.co.uk Fri Sep 2 14:47:33 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 11:47:33 -0700 (PDT) Subject: ANN: A new version (0.2.8) of the Python module which wraps GnuPG has been released. Message-ID: A new version of the Python module which wraps GnuPG has been released. What Changed? ============= This is a minor enhancement and bug-fix release. See the project website ( http://code.google.com/p/python-gnupg/ ) for more information. Summary: Better support for status messages from GnuPG. The fixing of some Unicode encoding problems. Quoted some command-line arguments to gpg for increased safety. The current version passes all tests on Windows (CPython 2.4, 2.5, 2.6, 3.1, 2.7 and Jython 2.5.1) and Ubuntu (CPython 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2). On Windows, GnuPG 1.4.11 has been used for the tests. What Does It Do? ================ The gnupg module allows Python programs to make use of the functionality provided by the Gnu Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP. This module is expected to be used with Python versions >= 2.4, as it makes use of the subprocess module which appeared in that version of Python. This module is a newer version derived from earlier work by Andrew Kuchling, Richard Jones and Steve Traugott. A test suite using unittest is included with the source distribution. Simple usage: >>> import gnupg >>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') >>> gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) ']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) ']}] >>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A']) >>> str(encrypted) '-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -----END PGP MESSAGE-----\n' >>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret') >>> str(decrypted) 'Hello, world!' >>> signed = gpg.sign("Goodbye, world!", passphrase='secret') >>> verified = gpg.verify(str(signed)) >>> print "Verified" if verified else "Not verified" 'Verified' For more information, visit http://code.google.com/p/python-gnupg/ - as always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. From askutt at gmail.com Fri Sep 2 14:53:43 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 11:53:43 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: On Sep 2, 2:23?pm, Alain Ketterlin wrote: > Sorry, you're wrong, at least for POSIX threads: > > void pthread_exit(void *value_ptr); > int pthread_join(pthread_t thread, void **value_ptr); > > pthread_exit can pass anything, and that value will be retrieved with > pthread_join. No, it can only pass a void*, which isn't much better than passing an int. Passing a void* is not equivalent to passing anything, not even in C. Moreover, specific values are still reserved, like PTHREAD_CANCELLED. Yes, it was strictly inappropriate for me to say both return solely integers, but my error doesn't meaningful alter my description of the situation. The interface provided by the underlying APIs is not especially usable for arbitrary data transfer. Doubly so when we're discussing something like Python's threading module. > I'm not sure what you are talking about here. Maybe you confuse threads > with processes? Windows threads have exit codes, just like processes. At least one code is reserved and cannot be used by the programmer. Adam From gagsl-py2 at yahoo.com.ar Fri Sep 2 15:10:41 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 16:10:41 -0300 Subject: Help required accessing dictionary References: <54e7c93d35c11cdf72cee56a8a1c5abc@edss.co.in> Message-ID: En Wed, 31 Aug 2011 22:46:54 -0300, escribi?: > I need to access the dictionary of the script that I am running through > my vc++ application by embedding python. > I am linking to python dynamically. I want to obtain the dictionary of > the script and access the variables declared in the script. > However, with the PyObject * that I get from the dictionary, I am not > able to find the type of the object. The reason being that > GetProcAddress to PyInt_Check returns a NULL. The same thing with > PyFloat_Check and so on. I think this is because they are macros and > not > exported functions. > > What can be done to be able to perform these checks without statically > linking to the pyhon lib ? Just include python.h PyInt_Check is completely implemented as a macro, it doesn't call any function. /* from intobject.h */ #define PyInt_Check(op) \ PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_INT_SUBCLASS) /* from object.h */ #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) -- Gabriel Genellina From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:12:36 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:12:36 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net> Message-ID: <9cco6uFvh4U1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.711.1314983727.27778.python-list at python.org... > On Fri, 2 Sep 2011 14:19:32 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > > >> >> In the config file it says: >> "# main directory >> directory = \Webdav" >> > I think that's the line that should have your e:/wwwroot > specification > -- Sorry! It used to have. But as it did not work, with the same error message, it could not find E:\wwwroot, I changed it into \Webdav. Ofcourse, in the command line as well. Later on I left the D specification out in the command line. Perhaps another drive letter might cause the problem, so in this case I kept it on the same partition. But I still got the same error. Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:21:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:21:03 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> Message-ID: <9ccoqkF5efU1@mid.individual.net> "becky_lewis" wrote in message news:86b084e0-09a8-4997-9e0c-4526d7851e1d at s2g2000vby.googlegroups.com... On Sep 2, 1:19 pm, "Fokke Nauta" wrote: > "Dennis Lee Bieber" wrote in > messagenews:mailman.687.1314941410.27778.python-list at python.org... > > > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > > declaimed the following in > > gmane.comp.python.general: > > >> "Dennis Lee Bieber" wrote in message > >>news:mailman.643.1314851358.27778.python-list at python.org... > > >> > Next, if you'd read further and didn't take the comment as the > >> > instruction. set > >> > firstrun=1 > > >> I did > > >> > to tell the server this is the first time it is being run - IT WILL > >> > create the database table (after the first start, reset the flag to 0 > >> > to > >> > speed up later runs). > > >> It didn't create the table. The database kept empty. > > > Odd -- but then, I'm not running it myself, and wasn't up to reading > > all the code to see what path it takes. > > It's only for experimenting with calendar software, so authorization is > not > a point. > So I forget about MySQL. > >> > Later in the config file set > >> > mysql_auth=1 > >> > to enable the use of MySQL, and set the admin user/password to what > >> > you > >> > plan to have it use. > > >> I did > > >> > You probably want to set > >> > daemonize=1 > >> > (maybe after first run) > > >> I left this to 0. > > >> > Oh, and don't forget to set the main data directory and any > >> > port/host changes. > > >> I left host and port as they were. The main directory is e:\wwwroot > > >> > Start the server - it should connect to MySQL, create the table, and > >> > add the admin user to the table. > > >> I started the server with server.py (in > >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini > > > If the main directory is already in the config file, you probably > > don't need to specify it on the command line... > > OK > > > And... could there be > > something in the code where overriding the directory by command line > > changes where it looks for the config file? (Just guessing at this > > point). > > Possibly. > I tried this: > server.py -n -c config.ini > Once again, the server is up and running and when I am logging in with my > browser (10.0.0.140:8081) I can see information showing up at the command > prompt, showing somebody is logging is, but the same error: > "fshandler:get_data: \Webdav not found". During starting up the server > mentioned: "pywebdav:Serving data from \Webdav". > > In the config file it says: > "# main directory > directory = \Webdav" > > Perhaps my Python configuration is at fault. > > Fokke Is the path supposed to be absolute? In which case you'd need to have: directory=C:\path\to\Webdav instead of just directory=\Webdav I tried: directory=D:\Webdav directory=D:/Webdav To no avail. It didn.t make any difference. I surely believe my WebDAV installation is at fault. Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:24:02 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:24:02 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net> Message-ID: <9ccoqkF5efU2@mid.individual.net> wrote in message news:mailman.703.1314969082.27778.python-list at python.org... > Hi Fokke, > > Disclaimer: I have no experience with the Python WebDAV package you're > using. > > But a thought: > >> In the config file it says: >> "# main directory >> directory = \Webdav" > > Perhaps you should qualify your directory path with a drive letter? > > I would try this 2 ways: > > directory = E:\Webdav > > And if that doesn't work: > > directory = E:/Webdav > > My thinking about the 2nd example is that perhaps the \W is getting > interpreted as a control character vs. "backslash" "W". > I tried: directory=D:\Webdav directory=D:/Webdav To no avail. It didn't make any difference. I surely believe my WebDAV installation is at fault. And D: is the same partition as where Python is, D:\Python27 Fokke From guido at python.org Fri Sep 2 15:30:34 2011 From: guido at python.org (Guido van Rossum) Date: Fri, 2 Sep 2011 12:30:34 -0700 Subject: [Python-ideas] allow line break at operators In-Reply-To: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > Gabriel AHTUNE writes: > ?> So can be done with this syntax: > ?> > ?> > x = firstpart * secondpart ?+ ?#line breaks here > ?> > anotherpart + #continue > ?> > stillanother #continue on. > ?> > ?> after a "+" operator the line is clearly not finished yet. > > Sure, but IIRC one design principle of Python is that the keyword that > denotes the syntax should be the first thing on the line, making it > easy to scan down the left side of the code to see the syntactic > structure. ?The required indentation of the controlled suite also > helps emphasize that keyword. That's true for *statements* (except assignments and calls). > Analogously, if operators are going to denote continuation, they > should come first on the line. That doesn't follow. My preferred style is actually to put the binary operator at the end of the line. This also matches the prevailing style for breaking lines after commas (a comma can be seen as a kind of binary operator). > I just don't think this idea is going anywhere. ?Explicit continuation > with backslash or implicit continuation of parenthesized expressions > is just not that heavy a price to pay. ?Perhaps historically some of > these ideas could have been implemented, but now they're just going to > confuse a host of editors and code analysis tools. Totally agreed that this isn't going to happen. -- --Guido van Rossum (python.org/~guido) From sahil at FreeBSD.org Fri Sep 2 15:56:46 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Fri, 02 Sep 2011 15:56:46 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: References: <20110901045650.GA3466@magic.hamla.org> Message-ID: <4E6134FE.9060309@FreeBSD.org> Dennis Lee Bieber wrote: > On Thu, 1 Sep 2011 00:56:50 -0400, Sahil Tandon >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: > > There is only ONE "None" object so the preferred method is > > if rval is None: Understood; thanks for that enlightenment. > Note: I don't see any exit handler/condition... Indeed. I excluded such things in the interest of brevity, to focus the discussion on my question. :) -- Sahil Tandon From gagsl-py2 at yahoo.com.ar Fri Sep 2 16:06:57 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 17:06:57 -0300 Subject: Invoking profile from command line prevent my sys.path modification References: Message-ID: En Thu, 01 Sep 2011 07:51:43 -0300, Ya?ar Arabac? escribi?: > I am new to profile module, so I am sorry if this is an absolute beginner > question. In order to my code to run, I need to add a directory to > sys.path. > When I invole python -m profile myfile.py, my code won't work, saying > that > the thing that is supposed to be in path, isn't. Code works fine without > profiling. Profiling works if I write it into the file, but I don't > prefer > doing that, if that is possible. You may set the PYTHONPATH environment variable, just for the profiling session. http://docs.python.org/install/index.html#modifying-python-s-search-path -- Gabriel Genellina From ian.g.kelly at gmail.com Fri Sep 2 16:09:26 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 14:09:26 -0600 Subject: Algorithms Library - Asking for Pointers In-Reply-To: References: Message-ID: On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > Hello: > > I am working on an algorithms library. It provides LINQ like > functionality to Python iterators. Eventually, I plan on having > feaures that work against sequences and mappings. > > I have the code up at http://code.google.com/p/py-compass. > > This is my first project in Python, so I'd like some feedback. I want > to know if I am following conventions (overall style and quality of > code). Sure, here are my comments. In the "forever" and "__forever" functions, your use of the term "generator" is confusing. "__forever" is a generator function, because it has a yield statement. Its argument, called "generator", appears to be a callable, not a generator or even necessarily a generator function. Also, note that __forever(lambda: value) is functionally equivalent to the more efficient itertools.repeat(value). The staticmethod __next(iterator) accesses the class it is defined in, which suggests that it might be better written as a classmethod __next(cls, iterator). Each of the LINQ-style methods is divided into two parts: the public method that contains the docstring and some argument checks, and a private staticmethod that contains the implementation. I'm not certain what the purpose of that is. If it's to facilitate overriding the implementation in subclasses, then you need to change the names of the private methods to start with only one _ character so that they won't be mangled by the compiler. The comments before each method that only contain the name of the immediately following method are redundant. aggregate: the default aggregator is unintuitive to me. I would make it a required field and add a separate method called sum that calls aggregate with the operator.add aggregator. Also, the implementation doesn't look correct. Instead of passing in each item to the aggregator, you're passing in the number of items seen so far? The LINQ Aggregate method is basically reduce, so rather than reinvent the wheel I would suggest this: # MISSING is a unique object solely defined to represent missing arguments. # Unlike None we can safely assume it will never be passed as actual data. MISSING = object() def aggregate(self, aggregator, seed=MISSING): if seed is self.MISSING: return reduce(aggregator, self._iterable) else: return reduce(aggregator, self._iterable, seed) Note for compatibility that in Python 3 the reduce function has been demoted from a builtin to a member of the functools module. any: the name of this method could cause some confusion with the "any" builtin that does something a bit different. compare: the loop would more DRY as a for loop: def __compare(first, second, comparison): for firstval, secondval in itertools.izip_longest(first, second, fillvalue=self.MISSING): if firstval is self.MISSING: return -1 elif secondval is self.MISSING: return 1 else: result = comparison(firstval, secondval) if result != 0: return result return 0 concatenate: again, no need to reinvent the wheel. This should be more efficient: def concatenate(self, other): return extend(itertools.chain(self.__iterable, other)) equals: could be just "return self.compare(other, comparison) == 0" __last: the loop could be a for loop: # assume we're looking at the last item and try moving to the next item = result.Value for item in iterator: pass return item lastOrDefault: there's a lot of repeated logic here. This could just be: def lastOrDefault(self, default=None): try: return self.last() except ValueError: return default map / forEach: .NET has to separate these into separate methods due to static typing. It seems a bit silly to have both of them in Python. Also, map would be more efficient as "return itertools.imap(mapper, self.__iterable)" max / min: it would be more efficient to use the builtin: def max(self, key): return max(self.__iterable, key=key) If somebody really needs to pass a comparison function instead of a key function, they can use functools.cmp_to_key. randomSamples: a more canonical way to pass the RNG would be to pass an instance of random.Random rather than an arbitrary function. Then to get a random integer you can just call generator.randrange(total). Note that for the default you can just use the random module itself, which provides default implementations of all the Random methods. Also, for loops: def __randomSamples(iterable, sampleCount, generator): samples = [] iterator = iter(iterable) # fill up the samples with the items from the beginning of the iterable for i, value in zip(xrange(sampleCount), iterator): samples.append(value) # replace items if the generated number is less than the total total = len(samples) for value in iterator: total += 1 index = generator.randrange(total) if index < len(samples): samples[index] = result return samples __reverse: you could just "return reversed(list(iterable))" __rotateLeft: def __rotateLeft(iterable, shift): iterator = iter(iterable) front = list(itertools.islice(iterator, shift)) return itertools.chain(iterator, front) skipWhile: suggest using itertools.dropwhile take: suggest using itertools.islice takeWhile: suggest using itertools.takewhile __toList: "return list(iterable)" __toSet: "return set(iterable)" __toTuple: "return tuple(iterable)". Note that as currently written this actually returns a generator, not a tuple. __where: suggest using itertools.ifilter __zip: suggest using a for loop over itertools.izip(first, second) Lookup: is inconsistent. The overridden __iter__ method returns an iterator over the values of the groups, but all the inherited methods are going to iterate over the keys. Probably you want to pass groups.values() to the superclass __init__ method. Cheers, Ian From nospam at torek.net Fri Sep 2 16:14:56 2011 From: nospam at torek.net (Chris Torek) Date: 2 Sep 2011 20:14:56 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: >On Sep 2, 2:23?pm, Alain Ketterlin >wrote: >> Sorry, you're wrong, at least for POSIX threads: >> >> void pthread_exit(void *value_ptr); >> int pthread_join(pthread_t thread, void **value_ptr); >> >> pthread_exit can pass anything, and that value will be retrieved with >> pthread_join. In article Adam Skutt wrote: >No, it can only pass a void*, which isn't much better than passing an >int. It is far better than passing an int, although it leaves you with an annoying storage-management issue, and sidesteps any reasonable attempts at type-checking (both of which are of course "par for the course" in C). For instance: struct some_big_value { ... lots of stuff ... }; struct some_big_value storage_management_problem[SIZE]; ... void *func(void *initial_args) { ... #ifdef ONE_WAY_TO_DO_IT pthread_exit(&storage_management_problem[index]); /* NOTREACHED */ #else /* the other way */ return &storage_management_problem[index]; #endif } ... int error; pthread_t threadinfo; pthread_attr_t attr; ... pthread_attr_init(&attr); /* set attributes if desired */ error = pthread_create(&threadinfo, &attr, func, &args_to_func); if (error) { ... handle error ... } else { ... void *rv; result = pthread_join(&threadinfo, &rv); if (rv == PTHREAD_CANCELED) { ... the thread was canceled ... } else { struct some_big_value *ret = rv; ... work with ret->field ... } } (Or, do dynamic allocation, and have a struct with a distinguishing ID followed by a union of multiple possible values, or a flexible array member, or whatever. This means you can pass any arbitrary data structure back, provided you can manage the storage somehow.) >Passing a void* is not equivalent to passing anything, not even >in C. Moreover, specific values are still reserved, like >PTHREAD_CANCELLED. Some manual pages are clearer about this than others. Here is one that I think is not bad: The symbolic constant PTHREAD_CANCELED expands to a constant expression of type (void *), whose value matches no pointer to an object in memory nor the value NULL. So, provided you use pthread_exit() "correctly" (always pass either NULL or the address of some actual object in memory), the special reserved value is different from all of "your" values. (POSIX threads are certainly klunky, but not all *that* badly designed given the constraints.) >>Re. the original question: since you can define your own Thread >>subclass, with wathever attribute you want, I guess there was no need to >>use join() to communicate the result. The Thread's run() can store its >>result in an attribute, and the "client" can get it from the same >>attribute after a successful call to join(). For that matter, you can use the following to get what the OP asked for. (Change all the instance variables to __-prefixed versions if you want them to be Mostly Private.) import threading class ValThread(threading.Thread): "like threading.Thread, but the target function's return val is captured" def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(ValThread, self).__init__(group, None, name, None, None, verbose) self.value = None self.target = target self.args = args self.kwargs = {} if kwargs is None else kwargs def run(self): "run the thread" if self.target: self.value = self.target(*self.args, **self.kwargs) def join(self, timeout = None): "join, then return value set by target function" super(ValThread, self).join(timeout) return self.value -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From tjreedy at udel.edu Fri Sep 2 16:22:35 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 02 Sep 2011 16:22:35 -0400 Subject: Handling 2.7 and 3.0 Versions of Dict In-Reply-To: <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> Message-ID: On 9/2/2011 12:53 PM, Travis Parks wrote: > On Sep 2, 12:36 pm, "Gabriel Genellina" >> Those if/else are at global scope. An 'if' statement does not introduce a >> new scope; so getDictValues, despite being "indented", is defined at >> global scope, and may be used anywhere in the module. > Does that mean the rules would be different inside a function? Yes. Inside a function, you would have to add global getDictValues before the if statement in order for the assignments to have global effect. -- Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Fri Sep 2 16:29:59 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 17:29:59 -0300 Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> Message-ID: En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks escribi?: > On Sep 2, 12:36 pm, "Gabriel Genellina" > wrote: >> En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks >> escribi : >> >> > On Aug 31, 7:37 pm, Gregory Ewing wrote: >> >> Ian Kelly wrote: >> >> > if sys.version_info < (3,): >> >> > getDictValues = dict.itervalues >> >> > else: >> >> > getDictValues = dict.values >> >> >> > (which is basically what the OP was doing in the first place). >> >> > My problem was that I didn't understand the scoping rules. It is still >> > strange to me that the getValues variable is still in scope outside >> > the if/else branches. >> >> Those if/else are at global scope. An 'if' statement does not introduce >> a new scope; so getDictValues, despite being "indented", is defined at >> global scope, and may be used anywhere in the module. > > Does that mean the rules would be different inside a function? Yes: a function body *does* create a new scope, as well as the class statement. See http://docs.python.org/reference/executionmodel.html -- Gabriel Genellina From ian.g.kelly at gmail.com Fri Sep 2 16:30:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 14:30:14 -0600 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> Message-ID: On Fri, Sep 2, 2011 at 11:51 AM, John Roth wrote: >> I don't see how you could get rid of the wrappers. ?Methods would >> still need to be bound, somehow, so that code like this will work: >> >> methods = {} >> for obj in objs: >> ? ? if obj.is_flagged: >> ? ? ? ? methods[obj.user_id] = obj.do_work >> ? ? else: >> ? ? ? ? methods[obj.user_id] = obj.do_other_work >> # ... >> methods[some_user_id]() >> >> Without method wrappers, how does the interpreter figure out which >> instance is bound to the method being called? >> >> Cheers, >> Ian > > Good question. > > Currently the instance wrapper is created during method instantiation, > so the instance is obviously available at that point. There are two > rather obvious ways of remembering it. One is to use the invocation > stack, which has the instance. Another would be for the compiler to > create a local variable for the instance and possibly the class and > fill them in at instantiation time. Both of these require fixing the > names "self" and "cls" so the compiler knows what to do with them. The > first would require giving these two names their own bytecodes, the > second makes them simple local variables the same as the ones in the > method headers. The latter also allows them to be changed by the > method, which is probably not the world's best programming practice > although it's possible now. That's not what I asked. Both of those options are storing the instance within a stack frame, once it's been called. I'm asking how you would remember the instance during the interval from the time when the method is accessed until when it has been called. In the code above, the method is accessed just before it is stored in the dictionary. That is when the method wrapper is currently created, and the instance is available. It is not called until much later, possibly not even within the same function. How would you remember the instance over that period without wrapping the function? Cheers, Ian From steve+comp.lang.python at pearwood.info Fri Sep 2 16:49:17 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 03 Sep 2011 06:49:17 +1000 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e61414e$0$29994$c3e8da3$5496439d@news.astraweb.com> Seebs wrote: > On 2011-09-02, Steven D'Aprano > wrote: [...] >> Because then the code launching the thread would have to block, waiting >> until the thread is completed, so it will have a result to return. > > Isn't "waiting until the thread is completed" sort of the point of join()? Doh! I mean, well done, you have passed my little test! -- Steven From rosuav at gmail.com Fri Sep 2 17:47:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 3 Sep 2011 07:47:54 +1000 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sat, Sep 3, 2011 at 2:26 AM, Den wrote: > I've been doing some more thinking on what I want. ?This may be a > better explanation. ?Is there a way of detecting if my program has > lost "focus" (I'm not sure the correct term)? ?For example, if someone > is typing in my program, but some other program takes control (or CAD > has been pressed) I would like simply to log that. ?I have no interest > in trying to hijack or interfere with anything, simply log it. Ah, then yes most definitely! If you're writing a GUI program, a LostFocus event is a normal thing to be able to catch. Now, if you're writing a console program, that mightn't be so easy. But certainly you can detect loss of focus to any window that you control. ChrisA From askutt at gmail.com Fri Sep 2 18:02:08 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 15:02:08 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <2c0123f1-f776-45af-b39e-a802f2009e7d@y21g2000yqy.googlegroups.com> On Sep 2, 4:14?pm, Chris Torek wrote: > In article > Adam Skutt ? wrote: > > >No, it can only pass a void*, which isn't much better than passing an > >int. > > It is far better than passing an int, although it leaves you with > an annoying storage-management issue, and sidesteps any reasonable > attempts at type-checking (both of which are of course "par for > the course" in C). And when written out, makes it sound distinctly worse than passing an int :p. And let's not kid ourselves, unless you're a C programmer, it is distinctly worse than passing an int. Heck, your example (snipped) goes out of your way to unnecessarily leverage the functionality provided by pthreads. > Some manual pages are clearer about this than others. ?Here is one > that I think is not bad: > > ? ? The symbolic constant PTHREAD_CANCELED expands to a constant > ? ? expression of type (void *), whose value matches no pointer to > ? ? an object in memory nor the value NULL. > > So, provided you use pthread_exit() "correctly" (always pass either > NULL or the address of some actual object in memory), the special > reserved value is different from all of "your" values. Unfortunately, I'm not sure all implementations behave that way. Not that cancellation is really worth bothering with anyway, but it's a pretty nasty corner case. Adam From johnroth1 at gmail.com Fri Sep 2 18:30:35 2011 From: johnroth1 at gmail.com (John Roth) Date: Fri, 2 Sep 2011 15:30:35 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> Message-ID: On Sep 2, 2:30?pm, Ian Kelly wrote: > On Fri, Sep 2, 2011 at 11:51 AM, John Roth wrote: > >> I don't see how you could get rid of the wrappers. ?Methods would > >> still need to be bound, somehow, so that code like this will work: > > >> methods = {} > >> for obj in objs: > >> ? ? if obj.is_flagged: > >> ? ? ? ? methods[obj.user_id] = obj.do_work > >> ? ? else: > >> ? ? ? ? methods[obj.user_id] = obj.do_other_work > >> # ... > >> methods[some_user_id]() > > >> Without method wrappers, how does the interpreter figure out which > >> instance is bound to the method being called? > > >> Cheers, > >> Ian > > > Good question. > > > Currently the instance wrapper is created during method instantiation, > > so the instance is obviously available at that point. There are two > > rather obvious ways of remembering it. One is to use the invocation > > stack, which has the instance. Another would be for the compiler to > > create a local variable for the instance and possibly the class and > > fill them in at instantiation time. Both of these require fixing the > > names "self" and "cls" so the compiler knows what to do with them. The > > first would require giving these two names their own bytecodes, the > > second makes them simple local variables the same as the ones in the > > method headers. The latter also allows them to be changed by the > > method, which is probably not the world's best programming practice > > although it's possible now. > > That's not what I asked. ?Both of those options are storing the > instance within a stack frame, once it's been called. ?I'm asking how > you would remember the instance during the interval from the time when > the method > is accessed until when it has been called. > > In the code above, the method is accessed just before it is stored in > the dictionary. ?That is when the method wrapper is currently created, > and the instance is available. ?It is not called until much later, > possibly not even within the same function. ?How would you remember > the instance over that period without wrapping the function? > > Cheers, > Ian I see what you're saying now - I didn't get your example the first time. So the optimization of eliminating the instance wrapper is only possible if it's retrieved via the instance and then called immediately. That would seem to be a useful optimization if it was possible - I wonder if PyPy is doing it since they've got that fancy JIT, and it would seem that an immediate call after retrieving the method is overwhelmingly more frequent than saving it for later. I think it's still true that calling the underlying function object through the instance wrapper requires remaking the parameter list, which seems to be another piece of unnecessary overhead, unless there's a fast path through the call machinery that treats the instance specially. It does, however, decouple the two issues so I can't claim the optimization as a benefit. Drat. John Roth From jehugaleahsa at gmail.com Fri Sep 2 18:49:03 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 15:49:03 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: Message-ID: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> On Sep 2, 4:09?pm, Ian Kelly wrote: > On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > > Hello: > > > I am working on an algorithms library. It provides LINQ like > > functionality to Python iterators. Eventually, I plan on having > > feaures that work against sequences and mappings. > > > I have the code up athttp://code.google.com/p/py-compass. > > > This is my first project in Python, so I'd like some feedback. I want > > to know if I am following conventions (overall style and quality of > > code). > > Sure, here are my comments. > > In the "forever" and "__forever" functions, your use of the term > "generator" is confusing. ?"__forever" is a generator function, > because it has a yield statement. ?Its argument, called "generator", > appears to be a callable, not a generator or even necessarily a > generator function. ?Also, note that __forever(lambda: value) is > functionally equivalent to the more efficient itertools.repeat(value). > > The staticmethod __next(iterator) accesses the class it is defined in, > which suggests that it might be better written as a classmethod > __next(cls, iterator). > > Each of the LINQ-style methods is divided into two parts: the public > method that contains the docstring and some argument checks, and a > private staticmethod that contains the implementation. ?I'm not > certain what the purpose of that is. ?If it's to facilitate overriding > the implementation in subclasses, then you need to change the names of > the private methods to start with only one _ character so that they > won't be mangled by the compiler. > > The comments before each method that only contain the name of the > immediately following method are redundant. > > aggregate: the default aggregator is unintuitive to me. ?I would make > it a required field and add a separate method called sum that calls > aggregate with the operator.add aggregator. > Also, the implementation doesn't look correct. ?Instead of passing in > each item to the aggregator, you're passing in the number of items > seen so far? ?The LINQ Aggregate method is basically reduce, so rather > than reinvent the wheel I would suggest this: > > # MISSING is a unique object solely defined to represent missing arguments. > # Unlike None we can safely assume it will never be passed as actual data. > MISSING = object() > > def aggregate(self, aggregator, seed=MISSING): > ? ? if seed is self.MISSING: > ? ? ? ? return reduce(aggregator, self._iterable) > ? ? else: > ? ? ? ? return reduce(aggregator, self._iterable, seed) > > Note for compatibility that in Python 3 the reduce function has been > demoted from a builtin to a member of the functools module. > > any: the name of this method could cause some confusion with the "any" > builtin that does something a bit different. > > compare: the loop would more DRY as a for loop: > > def __compare(first, second, comparison): > ? ? for firstval, secondval in itertools.izip_longest(first, second, > fillvalue=self.MISSING): > ? ? ? ? if firstval is self.MISSING: > ? ? ? ? ? ? return -1 > ? ? ? ? elif secondval is self.MISSING: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? result = comparison(firstval, secondval) > ? ? ? ? ? ? if result != 0: > ? ? ? ? ? ? ? ? return result > ? ? return 0 > > concatenate: again, no need to reinvent the wheel. ?This should be > more efficient: > > def concatenate(self, other): > ? ? return extend(itertools.chain(self.__iterable, other)) > > equals: could be just "return self.compare(other, comparison) == 0" > > __last: the loop could be a for loop: > > ? ? ? ? # assume we're looking at the last item and try moving to the next > ? ? ? ? item = result.Value > ? ? ? ? for item in iterator: pass > ? ? ? ? return item > > lastOrDefault: there's a lot of repeated logic here. ?This could just be: > > def lastOrDefault(self, default=None): > ? ? try: > ? ? ? ? return self.last() > ? ? except ValueError: > ? ? ? ? return default > > map / forEach: .NET has to separate these into separate methods due to > static typing. ?It seems a bit silly to have both of them in Python. > Also, map would be more efficient as "return itertools.imap(mapper, > self.__iterable)" > > max / min: it would be more efficient to use the builtin: > def max(self, key): > ? ? return max(self.__iterable, key=key) > If somebody really needs to pass a comparison function instead of a > key function, they can use functools.cmp_to_key. > > randomSamples: a more canonical way to pass the RNG would be to pass > an instance of random.Random rather than an arbitrary function. Then > to get a random integer you can just call generator.randrange(total). > Note that for the default you can just use the random module itself, > which provides default implementations of all the Random methods. > Also, for loops: > > ? ? def __randomSamples(iterable, sampleCount, generator): > ? ? ? ? samples = [] > ? ? ? ? iterator = iter(iterable) > ? ? ? ? # fill up the samples with the items from the beginning of the iterable > ? ? ? ? for i, value in zip(xrange(sampleCount), iterator): > ? ? ? ? ? ? samples.append(value) > ? ? ? ? # replace items if the generated number is less than the total > ? ? ? ? total = len(samples) > ? ? ? ? for value in iterator: > ? ? ? ? ? ? total += 1 > ? ? ? ? ? ? index = generator.randrange(total) > ? ? ? ? ? ? if index < len(samples): > ? ? ? ? ? ? ? ? samples[index] = result > ? ? ? ? return samples > > __reverse: you could just "return reversed(list(iterable))" > > __rotateLeft: > def __rotateLeft(iterable, shift): > ? ? iterator = iter(iterable) > ? ? front = list(itertools.islice(iterator, shift)) > ? ? return itertools.chain(iterator, front) > > skipWhile: suggest using itertools.dropwhile > take: suggest using itertools.islice > takeWhile: suggest using itertools.takewhile > __toList: "return list(iterable)" > __toSet: "return set(iterable)" > __toTuple: "return tuple(iterable)". ?Note that as currently written > this actually returns a generator, not a tuple. > __where: suggest using itertools.ifilter > __zip: suggest using a for loop over itertools.izip(first, second) > > Lookup: is inconsistent. ?The overridden __iter__ method returns an > iterator over the values of the groups, but all the inherited methods > are going to iterate over the keys. ?Probably you want to pass > groups.values() to the superclass __init__ method. > > Cheers, > Ian Awesome tips. I appreciate the time you spent commenting on just about every function. I really like your suggestions about using itertools more, and for loops. I was feeling like some things were becoming way too complicated. I also noted the bugs you discovered. I will incorporate your suggestions. Thanks again! From vinay_sajip at yahoo.co.uk Fri Sep 2 18:59:31 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 15:59:31 -0700 (PDT) Subject: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`? References: <7f46ab8f-710c-4463-a072-fa80c49f90de@ea4g2000vbb.googlegroups.com> Message-ID: <34939e5a-19ba-4cc5-b10b-36f8b2e42830@h9g2000vbr.googlegroups.com> On Aug 30, 9:53?am, Michel Albert wrote: > Unfortunately this setup makes `logging.basicConfig` pretty useless. > However, I believe that this is something that more people could > benefit from. I also believe, that it just "makes sense" to send > warnings (and above) to `stderr`, the rest to `stdout`. > > So I was thinking: "Why does `logging.basicConfig` not behave that > way". Because what seems entirely natural and obvious to you might not seem so for someone else. The API in the stdlib tries to provide baseline functionality which others can build on. For example, if you always have a particular pattern which you use, you can always write a utility function to set things up exactly how you like, and others who want to set things up differently (for whatever reason) can do the same thing, without having to come into conflict (if that's not too strong a word) with views different from their own. > Naturally, I was thinking of writing a patch against the python > codebase and submit it as a suggestion. But before doing so, I would > like to hear your thoughts on this. Does it make sense to you too or > am I on the wrong track? Are there any downsides I am missing? Python 2.x is closed to feature changes, and Python 2.7 and Python 3.2 already support flexible configuration using dictConfig() - see http://docs.python.org/library/logging.config.html#logging.config.dictConfig Also, Python 3.3 will support passing a list of handlers to basicConfig(): see http://plumberjack.blogspot.com/2011/04/added-functionality-for-basicconfig-in.html which will allow you to do what you want quite easily. Regards, Vinay Sajip From roy at panix.com Fri Sep 2 19:16:29 2011 From: roy at panix.com (Roy Smith) Date: Fri, 02 Sep 2011 19:16:29 -0400 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: In article <5da6bf87-9412-46c4-ad32-f8337d56b2c3 at o15g2000vbe.googlegroups.com>, Adam Skutt wrote: > On Sep 2, 10:53?am, Roy Smith wrote: > > I have a function I want to run in a thread and return a value. ?It > > seems like the most obvious way to do this is to have my target > > function return the value, the Thread object stash that someplace, and > > return it as the return value for join(). > > > Yes, I know there's other ways for a thread to return values (pass the > > target a queue, for example), but making the return value of the > > target function available would have been the most convenient. ?I'm > > curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Windows and POSIX threads only support returning an > integer when a thread exits, similar to the exit code of a process. But the whole point of higher level languages is to hide the warts of the lower-level APIs they are built on top of. Just because a POSIX thread can only return an int (actually, a void *) doesn't mean that level of detail needed to be exposed at the Python threading library level. > More importantly, there's no way to tell whether the exit code of a > thread was set by user code or by the system. Even worse, some of > those integer values are reserved by some operating systems. If your > thread died via an exception, it still has an error code set by the > operating system. How would you going to distinguish those codes from > your own? I think you're talking about processes, not threads, but in any case, it's a non-sequitur. Thread.join() currently returns None, so there's no chance for confusion. From greg.ewing at canterbury.ac.nz Fri Sep 2 20:51:11 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 03 Sep 2011 12:51:11 +1200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: <9cdc00Fnq3U1@mid.individual.net> Chris Angelico wrote: > Although I heard somewhere that that's more gimmick than guarantee, > and that it IS possible for an app to hook CAD - just that it's a lot > harder than building a simple window that looks like the login... And of course it's possible that someone has snuck in during the night and installed Linux on the machine, with a program that fakes a Windows login screen, with Ctrl-Alt-Delete and everything... -- Greg From nospam at torek.net Fri Sep 2 21:04:16 2011 From: nospam at torek.net (Chris Torek) Date: 3 Sep 2011 01:04:16 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: In article Roy Smith wrote: >Thread.join() currently returns None, so there's >no chance for [return value] confusion. Well, still some actually. If you use my example code (posted elsethread), you need to know: - that there was a target function (my default return value if there is none is None); and - that the joined thread really did finish (if you pass a timeout value, rather than None, and the join times out, the return value is again None). Of course, if your target function always exists and never returns None, *then* there's no chance for confusion. :-) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From jehugaleahsa at gmail.com Fri Sep 2 21:39:21 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 18:39:21 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> Message-ID: <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> On Sep 2, 6:49?pm, Travis Parks wrote: > On Sep 2, 4:09?pm, Ian Kelly wrote: > > > > > > > On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > > > Hello: > > > > I am working on an algorithms library. It provides LINQ like > > > functionality to Python iterators. Eventually, I plan on having > > > feaures that work against sequences and mappings. > > > > I have the code up athttp://code.google.com/p/py-compass. > > > > This is my first project in Python, so I'd like some feedback. I want > > > to know if I am following conventions (overall style and quality of > > > code). > > > Sure, here are my comments. > > > In the "forever" and "__forever" functions, your use of the term > > "generator" is confusing. ?"__forever" is a generator function, > > because it has a yield statement. ?Its argument, called "generator", > > appears to be a callable, not a generator or even necessarily a > > generator function. ?Also, note that __forever(lambda: value) is > > functionally equivalent to the more efficient itertools.repeat(value). > > > The staticmethod __next(iterator) accesses the class it is defined in, > > which suggests that it might be better written as a classmethod > > __next(cls, iterator). > > > Each of the LINQ-style methods is divided into two parts: the public > > method that contains the docstring and some argument checks, and a > > private staticmethod that contains the implementation. ?I'm not > > certain what the purpose of that is. ?If it's to facilitate overriding > > the implementation in subclasses, then you need to change the names of > > the private methods to start with only one _ character so that they > > won't be mangled by the compiler. > > > The comments before each method that only contain the name of the > > immediately following method are redundant. > > > aggregate: the default aggregator is unintuitive to me. ?I would make > > it a required field and add a separate method called sum that calls > > aggregate with the operator.add aggregator. > > Also, the implementation doesn't look correct. ?Instead of passing in > > each item to the aggregator, you're passing in the number of items > > seen so far? ?The LINQ Aggregate method is basically reduce, so rather > > than reinvent the wheel I would suggest this: > > > # MISSING is a unique object solely defined to represent missing arguments. > > # Unlike None we can safely assume it will never be passed as actual data. > > MISSING = object() > > > def aggregate(self, aggregator, seed=MISSING): > > ? ? if seed is self.MISSING: > > ? ? ? ? return reduce(aggregator, self._iterable) > > ? ? else: > > ? ? ? ? return reduce(aggregator, self._iterable, seed) > > > Note for compatibility that in Python 3 the reduce function has been > > demoted from a builtin to a member of the functools module. > > > any: the name of this method could cause some confusion with the "any" > > builtin that does something a bit different. > > > compare: the loop would more DRY as a for loop: > > > def __compare(first, second, comparison): > > ? ? for firstval, secondval in itertools.izip_longest(first, second, > > fillvalue=self.MISSING): > > ? ? ? ? if firstval is self.MISSING: > > ? ? ? ? ? ? return -1 > > ? ? ? ? elif secondval is self.MISSING: > > ? ? ? ? ? ? return 1 > > ? ? ? ? else: > > ? ? ? ? ? ? result = comparison(firstval, secondval) > > ? ? ? ? ? ? if result != 0: > > ? ? ? ? ? ? ? ? return result > > ? ? return 0 > > > concatenate: again, no need to reinvent the wheel. ?This should be > > more efficient: > > > def concatenate(self, other): > > ? ? return extend(itertools.chain(self.__iterable, other)) > > > equals: could be just "return self.compare(other, comparison) == 0" > > > __last: the loop could be a for loop: > > > ? ? ? ? # assume we're looking at the last item and try moving to the next > > ? ? ? ? item = result.Value > > ? ? ? ? for item in iterator: pass > > ? ? ? ? return item > > > lastOrDefault: there's a lot of repeated logic here. ?This could just be: > > > def lastOrDefault(self, default=None): > > ? ? try: > > ? ? ? ? return self.last() > > ? ? except ValueError: > > ? ? ? ? return default > > > map / forEach: .NET has to separate these into separate methods due to > > static typing. ?It seems a bit silly to have both of them in Python. > > Also, map would be more efficient as "return itertools.imap(mapper, > > self.__iterable)" > > > max / min: it would be more efficient to use the builtin: > > def max(self, key): > > ? ? return max(self.__iterable, key=key) > > If somebody really needs to pass a comparison function instead of a > > key function, they can use functools.cmp_to_key. > > > randomSamples: a more canonical way to pass the RNG would be to pass > > an instance of random.Random rather than an arbitrary function. Then > > to get a random integer you can just call generator.randrange(total). > > Note that for the default you can just use the random module itself, > > which provides default implementations of all the Random methods. > > Also, for loops: > > > ? ? def __randomSamples(iterable, sampleCount, generator): > > ? ? ? ? samples = [] > > ? ? ? ? iterator = iter(iterable) > > ? ? ? ? # fill up the samples with the items from the beginning of the iterable > > ? ? ? ? for i, value in zip(xrange(sampleCount), iterator): > > ? ? ? ? ? ? samples.append(value) > > ? ? ? ? # replace items if the generated number is less than the total > > ? ? ? ? total = len(samples) > > ? ? ? ? for value in iterator: > > ? ? ? ? ? ? total += 1 > > ? ? ? ? ? ? index = generator.randrange(total) > > ? ? ? ? ? ? if index < len(samples): > > ? ? ? ? ? ? ? ? samples[index] = result > > ? ? ? ? return samples > > > __reverse: you could just "return reversed(list(iterable))" > > > __rotateLeft: > > def __rotateLeft(iterable, shift): > > ? ? iterator = iter(iterable) > > ? ? front = list(itertools.islice(iterator, shift)) > > ? ? return itertools.chain(iterator, front) > > > skipWhile: suggest using itertools.dropwhile > > take: suggest using itertools.islice > > takeWhile: suggest using itertools.takewhile > > __toList: "return list(iterable)" > > __toSet: "return set(iterable)" > > __toTuple: "return tuple(iterable)". ?Note that as currently written > > this actually returns a generator, not a tuple. > > __where: suggest using itertools.ifilter > > __zip: suggest using a for loop over itertools.izip(first, second) > > > Lookup: is inconsistent. ?The overridden __iter__ method returns an > > iterator over the values of the groups, but all the inherited methods > > are going to iterate over the keys. ?Probably you want to pass > > groups.values() to the superclass __init__ method. > > > Cheers, > > Ian > > Awesome tips. I appreciate the time you spent commenting on just about > every function. I really like your suggestions about using itertools > more, and for loops. I was feeling like some things were becoming way >too complicated. > > I also noted the bugs you discovered. I will incorporate your > suggestions. > > Thanks again!- Hide quoted text - > > - Show quoted text - You commented that the itertools algorithms will perform faster than the hand-written ones. Are these algorithms optimized internally? From bkasterm at gmail.com Fri Sep 2 22:15:11 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 02 Sep 2011 20:15:11 -0600 Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> <87sjofjbh1.fsf@gmail.com> <07906043-d732-43ca-8313-bee4746eca75@fi7g2000vbb.googlegroups.com> Message-ID: <87bov29xsg.fsf@gmail.com> ting at thsu.org writes: > On Sep 2, 9:54?am, Bart Kastermans wrote: >> if d(a,b) == 1 and a < b: > > It will probably be faster if you reverse the evaluation order of that > expression. > > if a > That way the d() function is called less than half the time. Of course > this assumes that a that's true for your example. > -- > // T.Hsu Indeed makes quite a difference, goes from 275 seconds down to 153 seconds. From clp2 at rebertia.com Fri Sep 2 22:23:11 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 19:23:11 -0700 Subject: Algorithms Library - Asking for Pointers In-Reply-To: <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: On Fri, Sep 2, 2011 at 6:39 PM, Travis Parks wrote: > You commented that the itertools algorithms will perform faster than > the hand-written ones. Are these algorithms optimized internally? For one thing, they are written in C. Cheers, Chris From lanyjie at yahoo.com Sat Sep 3 00:18:21 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 2 Sep 2011 21:18:21 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> Have you considered line continuation by indentation? It seems to meet the design principle. I think it is the most natural way to allow free line breaking in Python. (Sorry, the yahoo web email interface is so weird that I don't know how to format comments between the quoted message below.) >________________________________ >From: Stephen J. Turnbull >To: Gabriel AHTUNE >Cc: Matt Joiner ; "python-list at python.org" ; python-ideas ; Yingjie Lan >Sent: Friday, September 2, 2011 3:28 PM >Subject: Re: [Python-ideas] allow line break at operators > >Gabriel AHTUNE writes: >> So can be done with this syntax: >> >> > x = firstpart * secondpart? +? #line breaks here >> > anotherpart + #continue >> > stillanother #continue on. >> >> after a "+" operator the line is clearly not finished yet. > >Sure, but IIRC one design principle of Python is that the keyword that >denotes the syntax should be the first thing on the line, making it >easy to scan down the left side of the code to see the syntactic >structure.? The required indentation of the controlled suite also >helps emphasize that keyword. > >Analogously, if operators are going to denote continuation, they >should come first on the line. > > > >I just don't think this idea is going anywhere.? Explicit continuation >with backslash or implicit continuation of parenthesized expressions >is just not that heavy a price to pay.? Perhaps historically some of >these ideas could have been implemented, but now they're just going to >confuse a host of editors and code analysis tools. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at torek.net Sat Sep 3 00:35:05 2011 From: nospam at torek.net (Chris Torek) Date: 3 Sep 2011 04:35:05 GMT Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: In article <18fe4afd-569b-4580-a629-50f6c74829e8 at c29g2000yqd.googlegroups.com> Travis Parks wrote: >[Someone] commented that the itertools algorithms will perform >faster than the hand-written ones. Are these algorithms optimized >internally? They are written in C, so avoid a lot of CPython interpreter overhead. Mileage in Jython, etc., may vary... -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From stephen at xemacs.org Sat Sep 3 00:38:15 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Sat, 03 Sep 2011 13:38:15 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Guido van Rossum writes: > On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > > Sure, but IIRC one design principle of Python is that the keyword that > > denotes the syntax should be the first thing on the line, [...] > That's true for *statements* (except assignments and calls). > > > Analogously, if operators are going to denote continuation, they > > should come first on the line. > That doesn't follow. Agreed, it's not a logical implication. The analogy is only an analogy, but my eyes do work that way. My conclusion is that we shouldn't try to encourage either style, because people "see" continuation differently. Legislating a style isn't going to change that, I think. From ian.g.kelly at gmail.com Sat Sep 3 00:38:22 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 22:38:22 -0600 Subject: sqlite3 with context manager In-Reply-To: References: Message-ID: On Fri, Sep 2, 2011 at 12:43 PM, Tim Arnold wrote: > Hi, > I'm using the 'with' context manager for a sqlite3 connection: > > with sqlite3.connect(my.database,timeout=10) as conn: > ? ? ? ? ? ?conn.execute('update config_build set datetime=?,result=? > where id=?', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(datetime.datetime.now(), success, > self.b['id'])) > > my question is what happens if the update fails? Shouldn't it throw an > exception? That depends on why it fails. If you pass in an id that doesn't exist in the database, it "successfully" updates 0 rows. I would guess that's what happened here. You should check cursor.rowcount after running the update query to make sure it actually did something. Cheers, Ian From d_vineet at yahoo.com Sat Sep 3 01:36:56 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Fri, 2 Sep 2011 22:36:56 -0700 (PDT) Subject: json in python 2.5 References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) JSON is in fact a subset of JavaScript, and modern browsers now include a specific API for parsing and generating it (https://developer.mozilla.org/En/Using_native_JSON ). ============= @Chris, thanks for the pointer on parsing json. ============= Python likewise has a JSON module in the std lib: http://docs.python.org/library/json.html ======== I tried with json in std lib. But it is included in python 2.6 onwards. For my current proj, I need to use python 2.5. Hence can't use json from the std lib. Any idea on converting list to json in python 2.5? ========= Thanks, Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Sep 3 01:50:36 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 22:50:36 -0700 Subject: json in python 2.5 In-Reply-To: <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 10:36 PM, Vineet Deodhar wrote: >> e.g., I have this list: >> L = ['spam', 'ham', 'eggs', 12, (13.63)] >> What is the correct way to convert L to javascript array format? > Python likewise has a JSON module in the std lib: > http://docs.python.org/library/json.html > ======== > I tried with json in std lib. > But it is included in python 2.6 onwards. > For my current proj, I need to use python 2.5. > Hence can't use json from the std lib. > Any idea on converting list to json in python 2.5? http://pypi.python.org/pypi/simplejson/ Cheers, Chris From stephen at xemacs.org Sat Sep 3 02:10:26 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Sat, 03 Sep 2011 15:10:26 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> Message-ID: <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> Yingjie Lan writes: > Have you considered line continuation by indentation? It seems to > meet the design principle. I think it is the most natural way to > allow free line breaking in Python. Briefly, yes, and I think it would need a lot of tuning and probably complex rules. Unlike statements, where everybody (except the judges of the Obfuscated C Contest) agrees on a simple rule: "In a control structure, the controlled suite should be uniformly indented one level", line breaking and indentation of long expressions is an art, and people have different opinions on "readability" and "beauty." Achieving a compromise that is workable even for a few major styles is likely to be annoying and bug-prone. Pretty much every program I write seems to have a continued list of data or a multi-line dictionary display as data. It's not unusual for me to comment the formal arguments in a function definition, or the parent classes of a class definition. The exception for parenthesized objects is something I depend on for what I consider good style. Of course I could use explicit continuation, but in a long table that's ugly and error-prone. Long expressions that need to be broken across lines, on the other hand, often indication that I haven't thought carefully enough about that component of the program, and an extra pair of parentheses or a terminal backslash just isn't that "heavy" or ugly in the context of such long expressions. For me, they're also pretty rare; many programs I write have no explicit continuations in them at all. YMMV, of course, but I find the compromise that Python arrived at to be very useful, and I must suppose that it was substantially easier to implement than "fully free" line breaking (whatever that means to you). From pavlovevidence at gmail.com Sat Sep 3 03:03:22 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 00:03:22 -0700 (PDT) Subject: sqlite3 with context manager In-Reply-To: References: Message-ID: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote: > Hi, > I'm using the 'with' context manager for a sqlite3 connection: > > with sqlite3.connect(my.database,timeout=10) as conn: > conn.execute('update config_build set datetime=?,result=? > where id=?', > (datetime.datetime.now(), success, > self.b['id'])) > > my question is what happens if the update fails? Shouldn't it throw an > exception? If you look at the sqlite3 syntax documentation, you'll see it has a SQL extension that allows you to specify error semantics. It looks something like this: UPDATE OR IGNORE UPDATE OR FAIL UPDATE OR ROLLBACK I'm not sure exactly how this interacts with pysqlite3, but using one of these might help it throw exceptions when you want it to. Carl Banks From nobody at nowhere.com Sat Sep 3 03:49:49 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 03 Sep 2011 08:49:49 +0100 Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: On Fri, 02 Sep 2011 17:55:41 +1000, Chris Angelico wrote: >> That's why you have to hit CAD to get to the login form in some versions >> of Windows. The whole point of that secure sequence is that the OS and >> only the OS responds. > > Although I heard somewhere that that's more gimmick than guarantee, > and that it IS possible for an app to hook CAD It's possible to configure how CAD is handled, but this requires Administrator privilege, so it's not exploitable (i.e. it doesn't gain you anything you can't obtain by other means). From lanyjie at yahoo.com Sat Sep 3 03:51:11 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 00:51:11 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> I agree that long lines of code are not very common in many projects, though it might be the case with some heavily involved in math. For some reason, when the feature of free line breaking came about in computer languages, it is welcomed and generally well accepted. Python uses indentation for blocks, and by the same mechanism, line breaking can be?accommodated without requiring parenthesis or ending backslashes. For the tuning, yes, people would disagree on how to split expressions/code. The continue-by-indentation would allow people to break a line in whatever way that pleases their aesthetic taste, as long as there is an indentation. Most people seems to like an indentation on the continuing lines, probably for a visual indication of a continuation line. Some general guidelines may be provided, but there is no need for other hard rules on breaking lines, except that an identifier should never be split apart. For the implementation, I don't have much clue. At least on the parser, it needs to look beyond the linefeed to determine if a line is completed. If the indentation is defined as a single symbol, then it would only require a one-step look-ahead, and that should not be hard. Again, my?apology?for top posting. >________________________________ >From: Stephen J. Turnbull >To: Yingjie Lan >Cc: Gabriel AHTUNE ; Matt Joiner ; "python-list at python.org" ; python-ideas >Sent: Saturday, September 3, 2011 2:10 PM >Subject: Re: [Python-ideas] allow line break at operators > >Yingjie Lan writes: > >> Have you considered line continuation by indentation? It seems to >> meet the design principle. I think it is the most natural way to >> allow free line breaking in Python. > >Briefly, yes, and I think it would need a lot of tuning and probably >complex rules.? Unlike statements, where everybody (except the judges >of the Obfuscated C Contest) agrees on a simple rule: "In a control >structure, the controlled suite should be uniformly indented one >level", line breaking and indentation of long expressions is an art, >and people have different opinions on "readability" and "beauty." >Achieving a compromise that is workable even for a few major styles is >likely to be annoying and bug-prone. > >Pretty much every program I write seems to have a continued list of >data or a multi-line dictionary display as data.? It's not unusual for >me to comment the formal arguments in a function definition, or the >parent classes of a class definition.? The exception for parenthesized >objects is something I depend on for what I consider good style.? Of >course I could use explicit continuation, but in a long table that's >ugly and error-prone. > >Long expressions that need to be broken across lines, on the other >hand, often indication that I haven't thought carefully enough about >that component of the program, and an extra pair of parentheses or a >terminal backslash just isn't that "heavy" or ugly in the context of >such long expressions.? For me, they're also pretty rare; many >programs I write have no explicit continuations in them at all. > >YMMV, of course, but I find the compromise that Python arrived at to >be very useful, and I must suppose that it was substantially easier to >implement than "fully free" line breaking (whatever that means to you). > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kissgoodbye5204 at yahoo.com.cn Sat Sep 3 04:28:12 2011 From: kissgoodbye5204 at yahoo.com.cn (www.brandtrade10.com) Date: Sat, 3 Sep 2011 01:28:12 -0700 (PDT) Subject: Nike Air Max LeBron VIII Message-ID: <89bd2be6-2cea-4c1a-8491-769fca930562@w22g2000prj.googlegroups.com> Published late last year for the first time Nike Air Max LeBron VIII that caused a large response, follow-up and then released LeBron VIII P2 and LeBron 8PS versions, LeBron is so loyal fans surprises. Back to {1}{/1}Nike for the first time this exposure will open the second half of LeBron 9 flagship shoe figure. Mystery photo from the body of the shoe can be seen a lot of reference material of carbon fiber, and also impressively hidden Hyperfuse material which is easy to understand Nike LeBron on the court to strong demand torque and light weighthttp://www.cheap-nbabasketballshoes.com/ under the foot pains. Wei is currently not yet fully revealed Nike LeBron 9 picture, ladies shoes andgentlemens, friends, fans, please wait.it will come update in http://www.cheap-nbabasketballshoes.com/ From alain at dpt-info.u-strasbg.fr Sat Sep 3 04:33:10 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 03 Sep 2011 10:33:10 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <878vq62fg9.fsf@dpt-info.u-strasbg.fr> Adam Skutt writes: > On Sep 2, 2:23?pm, Alain Ketterlin > wrote: >> Sorry, you're wrong, at least for POSIX threads: >> >> void pthread_exit(void *value_ptr); >> int pthread_join(pthread_t thread, void **value_ptr); >> >> pthread_exit can pass anything, and that value will be retrieved with >> pthread_join. > > No, it can only pass a void*, which isn't much better than passing an > int. We'll have to disagree. A void* simply can point to anything you want. Since thread stacks disappear at end of thread, only dynamically allocated memory can be used to store the result. That's why you get a pointer. There is no restriction on that pointer provided it doesn't point to memory that has been deallocated. > Passing a void* is not equivalent to passing anything, not even in C. > Moreover, specific values are still reserved, like PTHREAD_CANCELLED. Thread cancellation is program logic (pthread_cancel), it doesn't mean you thread crashed, it means your program decided to cancel the thread. If you still care about the return value after having called pthread_cancel(), > Yes, it was strictly inappropriate for me to say both return solely > integers, but my error doesn't meaningful alter my description of the > situation. The interface provided by the underlying APIs is not > especially usable for arbitrary data transfer. Again, I may misunderstand your wording, but there is no "data transfer" at all, since memory is shared between threads. > Doubly so when we're discussing something like Python's threading > module. The OP was clearly discussing the case where a thread has a result, and how to get it back. POSIX threads let you do that. There are of course tons of other ways to do the same thing. Win32 will force you to use some other way. >> I'm not sure what you are talking about here. Maybe you confuse threads >> with processes? > > Windows threads have exit codes, just like processes. At least one > code is reserved and cannot be used by the programmer. Is that STILL_ACTIVE that we are talking about? That's an artefact of the design of GetExitCodeThread, which will return either the thread exit code or its own error code. The python lib could easily hide this, and use run()'s return value to store the (python) result somewhere. -- Alain. From d_vineet at yahoo.com Sat Sep 3 04:58:44 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 01:58:44 -0700 (PDT) Subject: json: python 2.5: error in browser In-Reply-To: References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> Message-ID: <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> > Any idea on converting list to json in python 2.5? http://pypi.python.org/pypi/simplejson/ Cheers, Chris ============= Now I built json from simplejson. While trying to render the same in browser, nothing is displayed. Opera Dragonfly shows this error:-- ? Uncaught exception: SyntaxError: JSON.parse: Unable to parse value: A,B,C Error thrown at line 3, column 0 in http://127.0.0.1:8000/mywheels/test/cat: ??? var ctg = JSON.parse(["A", "B", "C"]); ~~~~~~~~~~~~~~~~ I validated this json --? ["A", "B", "C"]?? in jsonlint.com It is valid json. ? Why the?method "JSON.parse" is unable to parse JSON? ? --Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From alain at dpt-info.u-strasbg.fr Sat Sep 3 05:00:22 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 03 Sep 2011 11:00:22 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> <878vq62fg9.fsf@dpt-info.u-strasbg.fr> Message-ID: <874o0u2e6x.fsf@dpt-info.u-strasbg.fr> Alain Ketterlin writes: >> Passing a void* is not equivalent to passing anything, not even in C. >> Moreover, specific values are still reserved, like PTHREAD_CANCELLED. > > Thread cancellation is program logic (pthread_cancel), it doesn't mean > you thread crashed, it means your program decided to cancel the thread. > If you still care about the return value after having called > pthread_cancel(), Sotry, forgot to end this sentence... What I mean is: If you still care about the return value after having called pthread_cancel(), your program logic is unnecessarily complex, and you should find some other way to handle this case. -- Alain. From clp2 at rebertia.com Sat Sep 3 05:21:44 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 3 Sep 2011 02:21:44 -0700 Subject: json: python 2.5: error in browser In-Reply-To: <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> Message-ID: On Sat, Sep 3, 2011 at 1:58 AM, Vineet Deodhar wrote: > Opera Dragonfly shows this error:-- > > Uncaught exception: SyntaxError: JSON.parse: Unable to parse value: A,B,C > Error thrown at line 3, column 0 in http://127.0.0.1:8000/mywheels/test/cat: > ??? var ctg = JSON.parse(["A", "B", "C"]); > ~~~~~~~~~~~~~~~~ > I validated this json --? ["A", "B", "C"]?? in jsonlint.com > It is valid json. > > Why the?method "JSON.parse" is unable to parse JSON? It takes a *string* containing JSON. You want: var ctg = JSON.parse('["A", "B", "C"]');// note outer quotes! Think about it: If you already had ["A", "B", "C"] in the first place, then you could just do: var ctg = ["A", "B", "C"]; And JSON would never enter into the discussion. Your issue is akin to confusing the following two outputs: Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 'foo' # expression resulting in the string 'foo' >>> print 'foo' # contents of the string foo Regards, Chris From lanyjie at yahoo.com Sat Sep 3 06:33:48 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 03:33:48 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Ambiguity: yes, when the last line of a suite is a continued line, it would require double dedentations to end the line and the suite. I noticed a similar case in current Python language as well: ================================== #BEGIN CODE 1 if condition: for i in range(5): triangulate(i) else: #double dedentations for body in space: triangulate(body) #double dedentations again log('triangulation done') #END CODE 1 ================================== If lines can be continued by indentation, similar situation would rise: ================================== #BEGIN CODE 2 if condition: result = [sin(i) for i in range(5)] + [cos(i) for i in range(5)] else: result = [cos(i) for i in range(5)] + [sin(i) for i in range(5)] log('triangulation done') #END CODE 2 ================================== Generating text example: right, this is a case that can't be handled by standard indentation, unless we only consider full dedentation (dedentation to the exact level of the initial indentation) as the signal of ending the line. Whether to?accommodate?for such a case might be an issue of debate, but at least we can have such 'freedom' :) >________________________________ >From: Stephen J. Turnbull >To: Yingjie Lan >Cc: Gabriel AHTUNE ; Matt Joiner ; python-ideas >Sent: Saturday, September 3, 2011 5:29 PM >Subject: Re: [Python-ideas] allow line break at operators > >Yingjie Lan writes: > >> Python uses indentation for blocks, and by the same mechanism, line >> breaking can be?accommodated without requiring parenthesis or >> ending backslashes. > >Possibly, but now you have a problem that a dedent has ambiguous >meaning.? It might mean that you're ending a suite, or it might mean >you're ending a continued expression.? This probably can be >disambiguated, but I don't know how easy that will be to do perfectly, >including in reporting ill-formed programs. > >> Most people seems to like an indentation on the continuing lines, > >Most of the time, yes, but sometimes not.? For example, in generating >text, it's often useful to dedent substantially so you can have a >nearly normal length line in the literal strings being concatenated. >Or you might have a pattern like this: > >? ? x = long_named_variable_a >? ? ? ? ? ? - long_named_variable_a_base >? ? ? ? + long_named_variable_b >? ? ? ? ? ? - long_named_variable_b_base > >which your parser would raise an error on, I presume.? That's not >freedom! > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Sat Sep 3 06:50:30 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 03:50:30 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <1315047030.94472.YahooMailNeo@web121507.mail.ne1.yahoo.com> Oops, the generating text part of my reply is referring to your last code example. For literal texts, it is is not governed by this proposal, nor are expressions within brackets and backslash continued lines. In a word, this proposal is fully backward compatible. >________________________________ >From: Yingjie Lan >To: Stephen J. Turnbull >Cc: python list ; Gabriel AHTUNE ; python-ideas ; Matt Joiner >Sent: Saturday, September 3, 2011 6:33 PM >Subject: Re: [Python-ideas] allow line break at operators > > >Ambiguity: yes, when the last line of a suite is a continued line, it would require double dedentations to end the line and the suite. I noticed a similar case in current Python language as well: > > >================================== >#BEGIN CODE 1 >if condition: >for i in range(5): >triangulate(i) >else: #double dedentations >for body in space: >triangulate(body) >#double dedentations again >log('triangulation done') >#END CODE 1 >================================== > > > >If lines can be continued by indentation, similar situation would rise: > > >================================== >#BEGIN CODE 2 >if condition: >result = [sin(i) for i in range(5)] >+ [cos(i) for i in range(5)] >else: > >result = [cos(i) for i in range(5)] >+ [sin(i) for i in range(5)] > > >log('triangulation done') >#END CODE 2 >================================== > > > >Generating text example: right, this is a case that can't be handled by standard indentation, unless we only consider full dedentation (dedentation to the exact level of the initial indentation) as the signal of ending the line. Whether to?accommodate?for such a case might be an issue of debate, but at least we can have such 'freedom' :) > > > > > >>________________________________ >>From: Stephen J. Turnbull >>To: Yingjie Lan >>Cc: Gabriel AHTUNE ; Matt Joiner ; python-ideas >>Sent: Saturday, September 3, 2011 5:29 PM >>Subject: Re: [Python-ideas] allow line break at operators >> >>Yingjie Lan writes: >> >>> Python uses indentation for blocks, and by the same mechanism, line >>> breaking can be?accommodated without requiring parenthesis or >>> ending backslashes. >> >>Possibly, but now you have a problem that a dedent has ambiguous >>meaning.? It might mean that you're ending a suite, or it might mean >>you're ending a continued expression.? This probably can be >>disambiguated, but I don't know how easy that will be to do perfectly, >>including in reporting ill-formed programs. >> >>> Most people seems to like an indentation on the continuing lines, >> >>Most of the time, yes, but sometimes not.? For example, in generating >>text, it's often useful to dedent substantially so you can have a >>nearly normal length line in the literal strings being concatenated. >>Or you might have a pattern like this: >> >>? ? x = long_named_variable_a >>? ? ? ? ? ? - long_named_variable_a_base >>? ? ? ? + long_named_variable_b >>? ? ? ? ? ? - long_named_variable_b_base >> >>which your parser would raise an error on, I presume.? That's not >>freedom! >> >> >> >> >-- >http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Sep 3 08:04:42 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 05:04:42 -0700 (PDT) Subject: Why doesn't threading.join() return a value? In-Reply-To: <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: <6a30f0e6-cd0b-4ae2-9a0a-067411bc184f@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:01:17 AM UTC-7, Adam Skutt wrote: > On Sep 2, 10:53?am, Roy Smith wrote: > > I have a function I want to run in a thread and return a value. ?It > > seems like the most obvious way to do this is to have my target > > function return the value, the Thread object stash that someplace, and > > return it as the return value for join(). > > > Yes, I know there's other ways for a thread to return values (pass the > > target a queue, for example), but making the return value of the > > target function available would have been the most convenient. ?I'm > > curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Nope. This could easily be implemented by storing the return value in the Thread object. It's not done that way probably because no one thought of doing it. Carl Bannks From pavlovevidence at gmail.com Sat Sep 3 08:27:51 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 05:27:51 -0700 (PDT) Subject: Why doesn't threading.join() return a value? In-Reply-To: References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <7ea98c63-e045-45f2-9602-0c3b4495d141@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:53:43 AM UTC-7, Adam Skutt wrote: > On Sep 2, 2:23?pm, Alain Ketterlin > wrote: > > Sorry, you're wrong, at least for POSIX threads: > > > > void pthread_exit(void *value_ptr); > > int pthread_join(pthread_t thread, void **value_ptr); > > > > pthread_exit can pass anything, and that value will be retrieved with > > pthread_join. > > No, it can only pass a void*, which isn't much better than passing an > int. Passing a void* is not equivalent to passing anything, not even > in C. Moreover, specific values are still reserved, like > PTHREAD_CANCELLED. Yes, it was strictly inappropriate for me to say > both return solely integers, but my error doesn't meaningful alter my > description of the situation. The interface provided by the > underlying APIs is not especially usable for arbitrary data transfer. I'm sorry, but your claim is flat out wrong. It's very common in C programming to use a void* to give a programmer ability to pass arbitrary data through some third-party code. The Python API itself uses void* in this way in several different places. For instance, ake a look at the Capsule API (http://docs.python.org/c-api/capsule.html). You'll notice it uses a void* to let a user pass in opaque data. Another case is when declaring properties in C: it's common to define a single get or set function, and only vary some piece of data for the different properties. The API provides a void* so that the extension writer can pass arbitrary data to the get and set functions. Carl Banks From benjamin at schollnick.net Sat Sep 3 10:11:17 2011 From: benjamin at schollnick.net (Benjamin Schollnick) Date: Sat, 3 Sep 2011 10:11:17 -0400 Subject: Need advice on Web / Database framework... Message-ID: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Folks, I need some advice on a python web & database framework to use...? I have handcrafted a sqllite3 python script, that is a basic web application, interfacing with a sqlite3 database... But I am concerned at the thought of handcrafting a administration interface, and so forth. Are there any recommendations on a python toolkit / framework that could help deal with the realities of this? The main issue is hand crafting all the forms and html web pages... I have done a little cheetah templating... So that might be a partial solution, but I'm concerned with someone trying to craft a malicious payload in the fields, and so forth... I have thought about an out of the box solution, for example, using a wordpress install for the front-end, but I haven't been able to think of a good way to bridge this gap. Would Zope be a good solution possibly? Any suggestions would be appreciated... - Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From mukeshtiwari.iiitm at gmail.com Sat Sep 3 10:40:03 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Sat, 3 Sep 2011 07:40:03 -0700 (PDT) Subject: Reading pen drive data Message-ID: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> Hello all I am trying to write a python script which can mount a pen drive and read the data from pen drive. I am using pyudev [ http://packages.python.org/pyudev/api/index.html ] and wrote a small python code import pyudev, sys if __name__ =="__main__": context = pyudev.Context() devices = context.list_devices(subsystem ="usb") for device in devices : print device which prints Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') My problem is, how to know out of these usb which one to read . The other solution I got is whenever I insert the pen drive , my system mounts it in /media directory so I can read the /media directory to check if its empty or not but this does not seems promising to me because it may be possible that my system is not able to mount the pen drive so I have to manually do it . Kindly some one please tell me how to solve this problem. From noreply at domain.invalid Sat Sep 3 12:15:12 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 12:15:12 -0400 Subject: Functions vs OOP Message-ID: During some recent research, and re-familiarization with Python, I came across documentation that suggests that programming using functions, and programming using objects were somehow opposing techniques. It seems to me that they are complimentary. It makes sense to create objects and have some functions that take those objects as arguments. Are they suggesting that any function that takes an object as an argument should always be a method of that object? Conversely I can see creating functions that take raw input (e.g. strings) and return it in a format compatible with an object's constructor, rather than have objects accept any conceivable format for its constructor. Am I missing something, or am I taking things too literally? From mukeshtiwari.iiitm at gmail.com Sat Sep 3 12:21:57 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Sat, 3 Sep 2011 09:21:57 -0700 (PDT) Subject: Reading pen drive data References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> Message-ID: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> On Sep 3, 7:40?pm, mukesh tiwari wrote: > Hello all > I am trying to write a python script which can mount a pen drive and > read the data from pen drive. I am using pyudev [http://packages.python.org/pyudev/api/index.html] and wrote a small > python code > > import pyudev, sys > if __name__ =="__main__": > ? ? ? ? context = pyudev.Context() > ? ? ? ? devices = context.list_devices(subsystem ? ? ? ?="usb") > ? ? ? ? for device in devices : > ? ? ? ? ? ? ? ? print device > > which prints > > Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') > Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') > Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') > Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') > Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') > Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') > Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') > Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') > > My problem is, ?how to know ?out of these usb which one to read . The > other solution I got is whenever I insert the pen drive , my system > mounts ?it in /media ?directory so I can read the /media directory ?to > check if its empty or not but this does not seems promising to me > because it may be possible that my system is not able to mount the pen > drive so I have to manually do it . ?Kindly some one please tell me > how to solve this problem. I got this link and its working fine [ http://packages.python.org/pyudev/api/monitor.html ] >>> context = pyudev.Context() >>> monitor = pyudev.Monitor.from_netlink(context) >>> monitor.filter_by(subsystem='input') >>> for action, device in monitor: ... print('{0}: {1}'.format(action, device)) but when I am trying to execute code [ http://packages.python.org/pyudev/api/toolkit.html ] import pyudev, sys context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') observer = QUDevMonitorObserver(monitor) def device_connected(device): print('{0!r} added'.format(device)) observer.deviceAdded.connect(device_connected) monitor.start() I am getting Traceback (most recent call last): File "Mount.py", line 7, in observer = QUDevMonitorObserver(monitor) NameError: name 'QUDevMonitorObserver' is not defined Could any one please tell me how to avoid this error . Thank you From steve+comp.lang.python at pearwood.info Sat Sep 3 12:25:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 04 Sep 2011 02:25:43 +1000 Subject: Functions vs OOP References: Message-ID: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. > > It seems to me that they are complimentary. It makes sense to create > objects and have some functions that take those objects as arguments. Python is a mixed paradigm language, with object, functional and imperative paradigms. > Are they suggesting that any function that takes an object as an > argument should always be a method of that object? Yes. http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html [...] > Am I missing something, or am I taking things too literally? No, it is the OO purists who are missing something. -- Steven From python at mrabarnett.plus.com Sat Sep 3 12:29:11 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Sep 2011 17:29:11 +0100 Subject: Functions vs OOP In-Reply-To: References: Message-ID: <4E6255D7.2070005@mrabarnett.plus.com> On 03/09/2011 17:15, William Gill wrote: > During some recent research, and re-familiarization with Python, I > came across documentation that suggests that programming using > functions, and programming using objects were somehow opposing > techniques. > > It seems to me that they are complimentary. I think you mean "complementary". :-) > It makes sense to create objects and have some functions that take > those objects as arguments. Are they suggesting that any function > that takes an object as an argument should always be a method of that > object? Conversely I can see creating functions that take raw input > (e.g. strings) and return it in a format compatible with an object's > constructor, rather than have objects accept any conceivable format > for its constructor. > > Am I missing something, or am I taking things too literally? I think that it's all about "state". In functional programming, there's no state; a function's result depends solely on its arguments, so it will always return the same result for the same given arguments. In OOP, on the other hand, an object often has a state; a method may return a different result each time it's called, even for the same given arguments. From me+list/python at ixokai.io Sat Sep 3 12:50:25 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 03 Sep 2011 09:50:25 -0700 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <4E625AD1.6060103@ixokai.io> On 9/3/11 3:33 AM, Yingjie Lan wrote: > but at least we can have such 'freedom' :) Freedom is not and never has been, IMHO, a virtue or goal or even desire in Python. Where it occurs, it is at best a happy coincidence, and even if that happy coincidence happens often, it is not a design feature, IMHO. Simplicity and readability are virtues in Python. Freedom is even declared a vice to be avoided by the Zen, that holy document which defines all things Pythonic in clear and unambiguously absolute terms*. Looking over this whole thread at the various examples -- they add complication (a vice!). Complication to the parser, complication to the language itself and worse, understanding of code (as your head has to parse things too), all for what? So you don't have to use parens, which quite explicitly (another virtue!) do the job, to wrap around a long expression? Escaping newlines is arguably a bit on the ugly side (a vice!), so maybe the proposal has a little weight there, but since you can just avoid that by using parens, that's pretty much nullified. (Since it is also a virtue to offer only the Dutch way of doing things -- at least without hiding the alternatives in modules with a little bit of shame -- and this is clearly a case of the Dutch liking limited use of grouping parens). There just isn't even vaguely enough justification based on Python-virtues (readability, simplicity, explicitness, things like that) to even kind of make it worth the complication. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ * Obvious exaggeration :P -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From roy at panix.com Sat Sep 3 12:51:03 2011 From: roy at panix.com (Roy Smith) Date: Sat, 03 Sep 2011 12:51:03 -0400 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: In article , Chris Torek wrote: > For that matter, you can use the following to get what the OP asked > for. (Change all the instance variables to __-prefixed versions > if you want them to be Mostly Private.) > > import threading > > class ValThread(threading.Thread): > "like threading.Thread, but the target function's return val is captured" > def __init__(self, group=None, target=None, name=None, > args=(), kwargs=None, verbose=None): > super(ValThread, self).__init__(group, None, name, None, None, > verbose) > self.value = None > self.target = target > self.args = args > self.kwargs = {} if kwargs is None else kwargs > > def run(self): > "run the thread" > if self.target: > self.value = self.target(*self.args, **self.kwargs) > > def join(self, timeout = None): > "join, then return value set by target function" > super(ValThread, self).join(timeout) > return self.value Yeah, that's pretty much what I had in mind. I'm inclined to write up a PEP proposing that this become the standard behavior of threading.Thread. It seems useful, and I can't see any way it would break any existing code. From roy at panix.com Sat Sep 3 12:59:59 2011 From: roy at panix.com (Roy Smith) Date: Sat, 03 Sep 2011 12:59:59 -0400 Subject: [Python-ideas] allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: In article , Matt Joiner wrote: > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. I wrote a weird bug the other day. I had a function that returned a 4-tuple and wanted to unpack it, so I wrote: var1, var2, var3, var4 = my_function() which isn't a syntax error, but also isn't what I meant. Depending on whether var[123] have pre-existing values, this doesn't even produce a run-time error. Emacs encouraged me in this crime by merrily auto-indenting the code the way I expected :-) From malaclypse2 at gmail.com Sat Sep 3 13:08:26 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sat, 3 Sep 2011 13:08:26 -0400 Subject: Reading pen drive data In-Reply-To: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> Message-ID: On Sat, Sep 3, 2011 at 12:21 PM, mukesh tiwari wrote: > I am getting > Traceback (most recent call last): > File "Mount.py", line 7, in > observer = QUDevMonitorObserver(monitor) > NameError: name 'QUDevMonitorObserver' is not defined > > Could any one please tell me how to avoid this error . > It looks to me like that should be pyudev.QUDevMonitorObserver, shouldn't it? -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Sep 3 13:16:01 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Sep 2011 18:16:01 +0100 Subject: Reading pen drive data In-Reply-To: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> Message-ID: <4E6260D1.4010905@mrabarnett.plus.com> On 03/09/2011 17:21, mukesh tiwari wrote: > On Sep 3, 7:40 pm, mukesh tiwari wrote: >> Hello all >> I am trying to write a python script which can mount a pen drive and >> read the data from pen drive. I am using pyudev [http://packages.python.org/pyudev/api/index.html] and wrote a small >> python code >> >> import pyudev, sys >> if __name__ =="__main__": >> context = pyudev.Context() >> devices = context.list_devices(subsystem ="usb") >> for device in devices : >> print device >> >> which prints >> >> Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') >> >> My problem is, how to know out of these usb which one to read . The >> other solution I got is whenever I insert the pen drive , my system >> mounts it in /media directory so I can read the /media directory to >> check if its empty or not but this does not seems promising to me >> because it may be possible that my system is not able to mount the pen >> drive so I have to manually do it . Kindly some one please tell me >> how to solve this problem. > > I got this link and its working fine [ http://packages.python.org/pyudev/api/monitor.html > ] >>>> context = pyudev.Context() >>>> monitor = pyudev.Monitor.from_netlink(context) >>>> monitor.filter_by(subsystem='input') >>>> for action, device in monitor: > ... print('{0}: {1}'.format(action, device)) > > but when I am trying to execute code [ http://packages.python.org/pyudev/api/toolkit.html > ] > > import pyudev, sys > > context = pyudev.Context() > monitor = pyudev.Monitor.from_netlink(context) > monitor.filter_by(subsystem='usb') > observer = QUDevMonitorObserver(monitor) > def device_connected(device): > print('{0!r} added'.format(device)) > observer.deviceAdded.connect(device_connected) > monitor.start() > > I am getting > Traceback (most recent call last): > File "Mount.py", line 7, in > observer = QUDevMonitorObserver(monitor) > NameError: name 'QUDevMonitorObserver' is not defined > > Could any one please tell me how to avoid this error . > Thank you I think you need to import it from pyudev.pyqt4. From d_vineet at yahoo.com Sat Sep 3 13:23:17 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 10:23:17 -0700 (PDT) Subject: framework suggestions for Ben Message-ID: <1315070597.66606.YahooMailNeo@web160520.mail.bf1.yahoo.com> >Folks, >I need some advice on a python web & database framework to use...? >I have handcrafted a sqllite3 python script, that is a basic web application, interfacing with a >sqlite3 database... It depends on whether you want to develop?desktop apps or browser-based apps. I will suggest 2 frameworks with their urls. I will not enumerate the features?here,?because their?websites?contain loads of advocacy about them. ? ========= For desktop apps, my STRONG advise to you is DABO. http://dabodev.com/ It is developed by the experts in data-centric business apps. It contains the features which I haven't seen in any other framework except MS VFP & cursor adapter?(if at all you are familiar with them). ======== For browser based apps, I found web2py very simple yet powerful. http://web2py.com/ ? It requires no installation (not even python). Everything works out of the box. No dependencies. ========= ? Hope this helps. :) Vineet ...... >- Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From mithrandi at mithrandi.net Sat Sep 3 13:26:22 2011 From: mithrandi at mithrandi.net (Tristan Seligmann) Date: Sat, 3 Sep 2011 19:26:22 +0200 Subject: [ANN] Pyflakes 0.5.0 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 It is my unexpected pleasure to announce the release of Pyflakes 0.5.0, the first release in several years, and available now from PyPI[1]. Highlights of this release include the use of the built-in AST instead of the compiler module, and support for various new syntax constructs in Python 2.7. Note that development of Pyflakes (as well as the other divmod.org projects) has moved to Launchpad[2] since the last release. [1] http://pypi.python.org/packages/source/p/pyflakes/pyflakes-0.5.0.tar.gz#md5=568dab27c42e5822787aa8a603898672 [2] https://launchpad.net/pyflakes -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.18 (GNU/Linux) iQIcBAEBCgAGBQJOYmL+AAoJEFjA+xzeO3YAme4P/AxLuy0WJN2zG97my1oEwky9 VT79BwnxOqR4NB7I1dRKE3PG4Llgl6frAa0SouM12Dr0QZj9Ug3qHAmmf+TZFrF6 OIQcBUGkZW7EanBhCbjmfqo+0atJ8toAcj9uyF7Db/0A7gCDw160JIMnmTmxu8z6 3r5xRLNSnxs4jj6OSViv9oHNs2r2lpU/RObkGXy6EHxMgezYqw84FbA61fxquK4p +J1n++vzfiasqgcQFFU3R67T0P2gWUe0C6pv/D+CurSCOdgQJv4LeRtNeYgKhw/W rN0/3cERXGyRMa4JYDbFyP2G8lrpOuWo2F+jFtEGAxgziK8EqCK58ZSeqMBsodJ9 slAZobSQkrUj6GfpNKdW5mjYRqymBmUhPFc+sUI2poGb3zvMnWmUa2tiSfwl9uxO 9Di82XXAztKba8++cGJQCbuONiLRPgW5kArz5dRz3jFVdAZYL7xUvah4uznwfazc CA8Q0tiXXoL7X1sT6heNu4VRtnJfEh5LojFdizA4nJEpNssZrPFkSZMv+eSR4Sow 8u2n4f07od6EBzHMhEyqFN7goaniW05VL+EvMdC5px+brnyKOIoLSAGWptBL5EYL aaAb2zRrebyr/u5vGa+sKEXcoW2TEsc9qO8p/nNSetcoIcNfDwnd3cdyJPU+lYbn Wctc68Y+xNWChiuTYa3e =kKgi -----END PGP SIGNATURE----- From milleja46 at gmail.com Sat Sep 3 13:54:15 2011 From: milleja46 at gmail.com (Joshua Miller) Date: Sat, 3 Sep 2011 13:54:15 -0400 Subject: IDLE from python 3.2 constantly crashes Message-ID: Ok i've been using IDLE on my home computer and everytime i try and open a file that i saved to my hdd instead of my flashdrive(because it's a school project) by accident, it opens for a second and i try to do something else like open another file and it crashes. Is there anyway to remedy this error? By the way i'm running python 3.2 on windows 7 if it makes a difference From nagle at animats.com Sat Sep 3 14:10:06 2011 From: nagle at animats.com (John Nagle) Date: Sat, 03 Sep 2011 11:10:06 -0700 Subject: SSL module needs issuer information Message-ID: <4e626d97$0$1665$742ec2ed@news.sonic.net> The SSL module still doesn't return much information from the certificate. SSLSocket.getpeercert only returns a few basic items about the certificate subject. You can't retrieve issuer information, and you can't get the extensions needed to check if a cert is an EV cert. With the latest flaps about phony cert issuers, it's worth having issuer info available. It was available in the old M2Crypto module, but not in the current Python SSL module. John Nagle From ian.g.kelly at gmail.com Sat Sep 3 14:50:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 3 Sep 2011 12:50:14 -0600 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On Sat, Sep 3, 2011 at 10:15 AM, William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. > > It seems to me that they are complimentary. ?It makes sense to create > objects and have some functions that take those objects as arguments. Are > they suggesting that any function that takes an object as an argument should > always be a method of that object? ?Conversely I can see creating functions > that take raw input (e.g. strings) and return it in a format compatible with > an object's constructor, rather than have objects accept any conceivable > format for its constructor. > > Am I missing something, or am I taking things too literally? I think you may be confusing "functional programming" and "programming using functions". These are not the same thing. Functional programming is about using functions in the *mathematical* sense. A mathematical function maps one value (or tuple of values) to another value. The mapped value never varies; if it did, it would be a different function. So functional programming eschews the use of functions where the results depend on any internal or external state beyond the values of the passed-in arguments, such as the variable state of the object the method is being called on. Functional programming and OOP are not entirely opposed -- for example, string methods in Python such as str.upper are perfectly functional, since strings are immutable. Many functional languages such as Common LISP also have powerful OOP facilities. Still, functional programming does not fit well with the traditional OOP model of objects passing messages to other objects, which generally implies statefulness. Cheers, Ian From paul at subsignal.org Sat Sep 3 14:59:27 2011 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Sat, 03 Sep 2011 20:59:27 +0200 Subject: Need advice on Web / Database framework... In-Reply-To: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: Hi, Am 03.09.2011 16:11, schrieb Benjamin Schollnick: > Folks, > > I need some advice on a python web& database framework to use...? Hardest question ever ;) > > I have handcrafted a sqllite3 python script, that is a basic web > application, interfacing with a sqlite3 database... > > But I am concerned at the thought of handcrafting a administration > interface, and so forth. If you are not familiar with the various pitfalls of web security I'd recomment a framework which has all the layers already integrated. Take a look at http://www.web2py.com, I think it's quite powerful and has good documentation. If you want to get your hands dirty you can compose your own "framework" cherrypy+sqlalchemy+cheetah might be a good combination. hth Paul From tjreedy at udel.edu Sat Sep 3 15:01:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:01:31 -0400 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: On 9/3/2011 3:51 AM, Yingjie Lan wrote: > I agree that long lines of code are not very common in many projects, > though it might be the case with some heavily involved in math. For some > reason, when the feature of free line breaking came about in computer > languages, it is welcomed and generally well accepted. Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance. > Python uses indentation for blocks, and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. > and by the same mechanism, line breaking can be > accommodated without requiring parenthesis or ending backslashes. You need proof for your claim that indentation can be used for both jobs in the form of a grammar that works with Python's parser. I am dubious that you can do that with an indents *after* the newline. Even if you could, it would be confusing for human readers. There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:15:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:15:28 -0400 Subject: Functions vs OOP In-Reply-To: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 12:25 PM, Steven D'Aprano wrote: > William Gill wrote: > >> During some recent research, and re-familiarization with Python, I came >> across documentation Ours, or someone else's? >> that suggests that programming using functions, and >> programming using objects were somehow opposing techniques. >> >> It seems to me that they are complimentary. It makes sense to create >> objects and have some functions that take those objects as arguments. > > Python is a mixed paradigm language, with object, functional and imperative > paradigms. > >> Are they suggesting that any function that takes an object as an >> argument should always be a method of that object? Or of the class of the object. > Yes. > http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html Since in Python, everything is an object, that would mean that every function has to be a method, which would mean creating classes just to have a class to attach functions to. How awful. (Oh, right, I believe I just described Java.) >> Am I missing something, or am I taking things too literally? > > No, it is the OO purists who are missing something. Yes, Python. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:20:52 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:20:52 -0400 Subject: IDLE from python 3.2 constantly crashes In-Reply-To: References: Message-ID: On 9/3/2011 1:54 PM, Joshua Miller wrote: > Ok i've been using IDLE on my home computer and everytime i try and > open a file that i saved to my hdd instead of my flashdrive(because > it's a school project) by accident, it opens for a second and i try to > do something else like open another file and it crashes. Is there > anyway to remedy this error? > > By the way i'm running python 3.2 on windows 7 if it makes a difference Since I and others am using the same (3.2 on Win 7) quite successfully, it is hard to know what the problem is with your setup. Start with more details of exactly what you do and what 'it crashes' means. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:23:13 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:23:13 -0400 Subject: SSL module needs issuer information In-Reply-To: <4e626d97$0$1665$742ec2ed@news.sonic.net> References: <4e626d97$0$1665$742ec2ed@news.sonic.net> Message-ID: On 9/3/2011 2:10 PM, John Nagle wrote: > The SSL module still doesn't return much information from the > certificate. SSLSocket.getpeercert only returns a few basic items > about the certificate subject. You can't retrieve issuer information, > and you can't get the extensions needed to check if a cert is an EV cert. > > With the latest flaps about phony cert issuers, it's worth > having issuer info available. It was available in the old M2Crypto > module, but not in the current Python SSL module. Check the tracker to see if there is an issue about this already. If not, open one with a specific feature request. -- Terry Jan Reedy From noreply at domain.invalid Sat Sep 3 17:09:03 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:09:03 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/3/2011 12:29 PM, MRAB wrote: > I think you mean "complementary". :-) How polite of you to point out my spelling deficiency. I guess shouldn't be watching football while typing (I'm sure the beer didn't help either). > I think that it's all about "state". > > In functional programming, there's no state; a function's result > depends solely on its arguments, so it will always return the same > result for the same given arguments. > > In OOP, on the other hand, an object often has a state; a method may > return a different result each time it's called, even for the same > given arguments. I think you mean "it [sic, a function] will "return the same result for the same given values..." x=1 y= myFn(x) will return the same result as y= myFn(1) A method may use an attribute as an implicit argument, and that attribute's value change, just like the value of x (above) may change. It may or may not return anything (it may just modify an attribute). The question wasn't about encapsulation, it was about programming paradigms, and if they conflict. As was pointed out elsewhere, I may have just confused "functional programming" with "programming using functions". From noreply at domain.invalid Sat Sep 3 17:13:06 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:13:06 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/3/2011 2:50 PM, Ian Kelly wrote: > I think you may be confusing "functional programming" and "programming > using functions". These are not the same thing. > I think you may be right, Ian. It didn't make much sense From noreply at domain.invalid Sat Sep 3 17:34:05 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:34:05 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 3:15 PM, Terry Reedy wrote: >> William Gill wrote: >> >>> During some recent research, and re-familiarization with Python, I came >>> across documentation > > Ours, or someone else's? Python. > > Since in Python, everything is an object, that would mean that every > function has to be a method, which would mean creating classes just to > have a class to attach functions to. How awful. Exactly why I asked, but I realize the the mistake was mine. I think they were talking about "functional programming" not "using functions in an OO program." From ben+python at benfinney.id.au Sat Sep 3 17:39:30 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 04 Sep 2011 07:39:30 +1000 Subject: Functions vs OOP References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87bov1qp9p.fsf@benfinney.id.au> William Gill writes: > On 9/3/2011 3:15 PM, Terry Reedy wrote: > >> William Gill wrote: > >> > >>> During some recent research, and re-familiarization with Python, I > >>> came across documentation > > > > Ours, or someone else's? > > Python. Can you show exactly where in the Python documentation you found the passage which confused you? -- \ ?If you're a cowboy and you're dragging a guy behind your | `\ horse, I bet it would really make you mad if you looked back | _o__) and the guy was reading a magazine.? ?Jack Handey | Ben Finney From nospam at domain.invalid Sat Sep 3 17:58:01 2011 From: nospam at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:58:01 -0400 Subject: Functions vs OOP In-Reply-To: <87bov1qp9p.fsf@benfinney.id.au> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> <87bov1qp9p.fsf@benfinney.id.au> Message-ID: On 9/3/2011 5:39 PM, Ben Finney wrote: > William Gill writes: > >> On 9/3/2011 3:15 PM, Terry Reedy wrote: >>>> William Gill wrote: >>>> >>>>> During some recent research, and re-familiarization with Python, I >>>>> came across documentation >>> >>> Ours, or someone else's? >> >> Python. > > Can you show exactly where in the Python documentation you found the > passage which confused you? > Sorry, no. I tried to locate the exact reference again, and couldn't remember where I read it (short term memory problems). From bkasterm at gmail.com Sat Sep 3 18:15:18 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Sat, 03 Sep 2011 16:15:18 -0600 Subject: Tkinter label height to fit content Message-ID: <87mxelgtmx.fsf@gmail.com> I have a label into which I am going to put content of different sizes. I would like to know how high I need to make the label so that I can size the window so it can stay the same for the different content sizes. I have a strategy, but it seems more complicated then it should be. I want to set a label to a given width and wraplength: l = Label(root) l['width'] = 30 l['wraplength'] = 244 l['text'] = "testing this" Now I want to query the label to find how many lines are used. l['height'] stays at 0, so the best I have been able to come up with is to use l.winfo_height() and convert the height given in pixels to the number of lines used. Nothing in dir(l) seems to give me the information directly, but this strategy is fragile to font changes and other changes. Any suggestions? From PointedEars at web.de Sat Sep 3 18:58:15 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 04 Sep 2011 00:58:15 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> Message-ID: <109595831.VCN276Cjj6@PointedEars.de> Fokke Nauta wrote: > "Thomas 'PointedEars' Lahn" [?]: >> Fokke Nauta wrote: >>> "Thomas 'PointedEars' Lahn" [?] wrote: >>>> The Python shell executes Python code. The above obviously is not >>>> Python >>>> code, but *system* shell commands. So let the *system* command shell >>>> execute them (as indicated by the `$' prompt, which is customary for a >>>> sh-based UNIX/Linux shell prompt). >>> I know. I worked with SCO Unix and various sorts of Linux. >>> But never with Python, so I hadn't got a clue about the prompt. >> Come on, with that experience you see a `$' and those commands and don't >> realize it is (ba)sh? > > Ofcourse I realized it was Unix/Linux. I already could tell that as the > packages I downloaded were tar.gz files. For *Windows*? > So I unpacked them and expected to run a Python installer script from the > Python command line. Again, given all that experience you claim to have, how come it did not occur to you that the `$' was meant to be a *command* *shell* prompt? Other OSes have command shells, too, you know; they are just named and run differently. > Tried to run the Python installer script from the DOS command line but > that resulted in an error. "There was an error" is no error report at all. >>>> However, you appear to have found the *UNIX/Linux* README (and the >>>> corresponding version?) of that server: the second command is usually >>>> how you would run a program as daemon on Unices (run through an init >>>> script), while on Windows NT (like XP) you would have a setup program >>>> install a service for you (maybe to execute that command when the >>>> service is started). Look for the Windows version. >>> There is no other Windows version except the packages I mentioned, >>> PyWebDAV and PyXML. The only Windows thing I got was the Python >>> interpreter itself. >> Has it not occurred to you to STFW for "easy_install" first? > > What do you mean by STFW? Search The F****ing Web. > I wasn't aware that easy_install was a utility. Downloaded and installed > the Windows version and run easy_install pywebdav. > It downloaded something, installed something and finished something. > But, once again, don't know how to proceed. RTFM. >>>>> And there is no easy_install script in the PyXML-0.8.4 >>>>> directory, only a setup.py and ez_setup.py script. I guess the latter >>>>> is >>>>> the one to use. But how? >>>> RTFM. >>> Which fucking manual? >> That of the server, on Windows-related information. Or that of >> easy_install. Or Python. Whichever comes first. > > It's my own server and I didn't write a manual for it. No, the people providing it for you obviously did, but you do not seem to care to read it. > In the manual of Easy_install it says how to install packaged etc and I > did sucessfully. > There is no furter information as how to proceed. Either you are lying, or you are really forgetful, or you are simply not smart enough for this. You yourself told me/us before what the next step is: >>>>> How do I proceed next? >>>> Look for the Windows version. If there is none, get easy_install and >>>> use >>>> it as described. > > I did and it worked. What's next? Start the now-installed server, for goodness' sake! Observing this, be reminded that playing stupid does not work with me: And please get rid of that attribution novel and trim your quotes to the relevant minimum. I am asking you the last time here. If you cannot find it within you to think about your readers when you post, you are not worth my attention or (free) time. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From lanyjie at yahoo.com Sat Sep 3 19:22:57 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 16:22:57 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> >?Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance.? >?and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. Agreed.?Currently indentation in Python starts a new block,?but if you view it from the perspective of line breaking,?it also functions as if the line is continued. The line of code below if condition: do_a(); do_b() can be ?written as: if condition: #line breaks do_a(); # ';' is optional here? do_b() # continue That indentation can be also employed for line breaking is quite evident to me. During the open email correspondence with Stephen, it seems to be a tenable point.? >?There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. I believe the other two ways are not as good as this new way. As the proposal is fully backward compatible, people may choose whatever way they prefer.? >________________________________ >From: Terry Reedy >To: python-list at python.org >Cc: python-ideas at python.org >Sent: Sunday, September 4, 2011 3:01 AM >Subject: Re: [Python-ideas] allow line break at operators > >On 9/3/2011 3:51 AM, Yingjie Lan wrote: >> I agree that long lines of code are not very common in many projects, >> though it might be the case with some heavily involved in math. For some >> reason, when the feature of free line breaking came about in computer >> languages, it is welcomed and generally well accepted. > >Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance. > >> Python uses indentation for blocks, > >and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. > >> and by the same mechanism, line breaking can be >> accommodated without requiring parenthesis or ending backslashes. > >You need proof for your claim that indentation can be used for both jobs in the form of a grammar that works with Python's parser. I am dubious that you can do that with an indents *after* the newline. > >Even if you could, it would be confusing for human readers. There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. > >-- Terry Jan Reedy > >-- http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gelonida at gmail.com Sat Sep 3 20:15:32 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 04 Sep 2011 02:15:32 +0200 Subject: SSL module needs issuer information In-Reply-To: <4e626d97$0$1665$742ec2ed@news.sonic.net> References: <4e626d97$0$1665$742ec2ed@news.sonic.net> Message-ID: Hi John, On 09/03/2011 08:10 PM, John Nagle wrote: > The SSL module still doesn't return much information from the > certificate. SSLSocket.getpeercert only returns a few basic items > about the certificate subject. You can't retrieve issuer information, > and you can't get the extensions needed to check if a cert is an EV cert. > > With the latest flaps about phony cert issuers, it's worth > having issuer info available. It was available in the old M2Crypto > module, but not in the current Python SSL module. Your phrasing 'old M2Crypto' disturbs me slightly. I am using Python 2.6. Is M2Crypto also obsolete for python 2.6? Is there any serious alternative if I want to verify the server certificate in a safe way (and if I want to send a client certificate)?? I am in search for a set of libraries, which allows me to: - verify the server certificate (ideally via a custom call back, which can inspect the certificate data and then decide whether the certificate shall be accepted or not) - send a client certificate - use https with a cookie jar (ideally even persistent, but session cookies are enough) - do XMLRPC calls (but send cookies in the headers) Would m2crypto be the right choice? From gelonida at gmail.com Sat Sep 3 20:18:34 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 04 Sep 2011 02:18:34 +0200 Subject: Need advice on Web / Database framework... In-Reply-To: References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: Hi Paul, On 09/03/2011 08:59 PM, Paul K?lle wrote: > Am 03.09.2011 16:11, schrieb Benjamin Schollnick: >> Folks, >> >> I need some advice on a python web& database framework to use...? > Hardest question ever ;) . . . >> But I am concerned at the thought of handcrafting a administration >> interface, and so forth. > If you are not familiar with the various pitfalls of web security I'd > recomment a framework which has all the layers already integrated. Take > a look at http://www.web2py.com, I think it's quite powerful and has > good documentation. > If you want to get your hands dirty you can compose your own "framework" > cherrypy+sqlalchemy+cheetah might be a good combination. > How does web2py compare to django? I just started playing with django, but don't know web2py From rantingrick at gmail.com Sat Sep 3 21:15:52 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 3 Sep 2011 18:15:52 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> Message-ID: <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> On Sep 3, 5:15?pm, Bart Kastermans wrote: > Any suggestions? Yeah, have you considered using the "linespace()" method of tk.Font objects to calculate the height? Although i must say it "feels" as if your doing something you should not need to do, however i cannot be sure without knowing more about this GUI. Sounds a lot like trying to put socks on a rooster. http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#fonts From tjreedy at udel.edu Sat Sep 3 21:51:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 21:51:37 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 5:34 PM, William Gill wrote: > On 9/3/2011 3:15 PM, Terry Reedy wrote: >>> William Gill wrote: >>> >>>> During some recent research, and re-familiarization with Python, I came >>>> across documentation >> >> Ours, or someone else's? > > Python. > >> >> Since in Python, everything is an object, that would mean that every >> function has to be a method, which would mean creating classes just to >> have a class to attach functions to. How awful. > > Exactly why I asked, but I realize the the mistake was mine. I think > they were talking about "functional programming" not "using functions in > an OO program." It is possible that our doc was less than crystal clear. We are constantly improving it where we can see fixable faults. If you run across whatever it was and it still seems a bit muddy, post something again. -- Terry Jan Reedy From python at mrabarnett.plus.com Sat Sep 3 22:04:54 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 04 Sep 2011 03:04:54 +0100 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: <4E62DCC6.8000906@mrabarnett.plus.com> On 04/09/2011 00:22, Yingjie Lan wrote: >> Every language with blocks needs some mechanism to indicate the > beginning and ending of blocks and of statements within blocks. If > visible fences ('begin/end' or '{}') and statement terminators (';') are > used, then '\n' can be treated as merely a space, as it is in C, for > instance. >> and it uses unescaped '\n' (with two escapement options) to terminate > statements. This is fundamental to Python's design and goes along with > significant indents. > > Agreed. Currently indentation in Python starts a new block, but if you > view it from the perspective of line breaking, it also functions as if > the line is continued. The line of code below > > if condition: do_a(); do_b() > > can be written as: > > if condition: #line breaks > do_a(); # ';' is optional here > do_b() # continue > > That indentation can be also employed for line breaking is quite evident > to me. During the open email correspondence with Stephen, it seems to be > a tenable point. > > > There would then be three ways to escape newline, with one doing > double duty. And for what? Merely to avoid using either of the two > methods already available. > > I believe the other two ways are not as good as this new way. As the > proposal is fully backward compatible, people may choose whatever way > they prefer. > I think that the rules would be: If a line ends with a colon and the next line is indented, then it's the start of a block, and the following lines which belong to that block have the same indent. If a line doesn't end with a colon but the next line is indented, then it's the start of a continuation, and the following lines which belong to that continuation have the same indent. In both cases there could be blocks nested in blocks and possibly continuations nested in continuations, as well as blocks nested in continuations and continuations nested in blocks. I'm not sure what the effect would be if you had mis-indented lines. For example, if a line was accidentally indented after a comment, then it would be treated as part of the comment. It's in cases like those that syntax colouring would be helpful. It would be a good idea to use an editor which could indicate in some way when a line is a continuation. > ------------------------------------------------------------------------ > *From:* Terry Reedy > *To:* python-list at python.org > *Cc:* python-ideas at python.org > *Sent:* Sunday, September 4, 2011 3:01 AM > *Subject:* Re: [Python-ideas] allow line break at operators > > On 9/3/2011 3:51 AM, Yingjie Lan wrote: > > I agree that long lines of code are not very common in many projects, > > though it might be the case with some heavily involved in math. > For some > > reason, when the feature of free line breaking came about in computer > > languages, it is welcomed and generally well accepted. > > Every language with blocks needs some mechanism to indicate the > beginning and ending of blocks and of statements within blocks. If > visible fences ('begin/end' or '{}') and statement terminators (';') > are used, then '\n' can be treated as merely a space, as it is in C, > for instance. > > > Python uses indentation for blocks, > > and it uses unescaped '\n' (with two escapement options) to > terminate statements. This is fundamental to Python's design and > goes along with significant indents. > > > and by the same mechanism, line breaking can be > > accommodated without requiring parenthesis or ending backslashes. > > You need proof for your claim that indentation can be used for both > jobs in the form of a grammar that works with Python's parser. I am > dubious that you can do that with an indents *after* the newline. > > Even if you could, it would be confusing for human readers. There > would then be three ways to escape newline, with one doing double > duty. And for what? Merely to avoid using either of the two methods > already available. > From noreply at domain.invalid Sat Sep 3 22:18:19 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 22:18:19 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 9:51 PM, Terry Reedy wrote: > > It is possible that our doc was less than crystal clear. We are > constantly improving it where we can see fixable faults. If you run > across whatever it was and it still seems a bit muddy, post something > again. > Will do. Thanks. From shilparani9030 at gmail.com Sat Sep 3 23:14:29 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Sat, 3 Sep 2011 20:14:29 -0700 (PDT) Subject: KATRINA KAIF RARE PHOTOS Message-ID: <66624c9c-94ca-44a1-a6f1-fc67871b334b@r40g2000prf.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html KAJAL AGARWAL LATEST HOT http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From jehugaleahsa at gmail.com Sat Sep 3 23:35:24 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Sat, 3 Sep 2011 20:35:24 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: <112f5d1d-fbf7-44da-a0dd-cbbeb3a59c6d@dq7g2000vbb.googlegroups.com> On Sep 3, 12:35?am, Chris Torek wrote: > In article <18fe4afd-569b-4580-a629-50f6c7482... at c29g2000yqd.googlegroups.com> > Travis Parks ? wrote: > > >[Someone] commented that the itertools algorithms will perform > >faster than the hand-written ones. Are these algorithms optimized > >internally? > > They are written in C, so avoid a lot of CPython interpreter > overhead. ?Mileage in Jython, etc., may vary... > -- > In-Real-Life: Chris Torek, Wind River Systems > Intel require I note that my opinions are not those of WRS or Intel > Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) ?+1 801 277 2603 > email: gmail (figure it out) ? ? ?http://web.torek.net/torek/index.html I thought I would point out that many of the itertools functions change between 2.x and 3.x versions. Since 2.7 is supposed to be the last 2.x language, I suppose I will wait until 3.2 becomes the norm before I incorporate some of these changes. In the mean time, I will starting working on algorithms that work against Sequences. I think a really important lesson is that Python really doesn't need an algorithms library, like many others do. A lot of the common algorithms are supported by the syntax itself. All my library did was allow for easier function composition. From d_vineet at yahoo.com Sun Sep 4 01:03:08 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 22:03:08 -0700 (PDT) Subject: my suggestions for framework Message-ID: <1315112588.16268.YahooMailNeo@web160517.mail.bf1.yahoo.com> > recomment a framework which has all the layers already integrated. Take > a look at http://www.web2py.com, I think it's quite powerful and has > good documentation. > If you want to get your hands dirty you can compose your own "framework" > cherrypy+sqlalchemy+cheetah might be a good combination. > How does web2py compare to django? I just started playing with django, but don't know web2py ---- IMHO, django is suitable for CMS kind of apps. AFAIK, originally it was written for a newspaper website, subsequently it has grown over the time. I have tried turbogears(TG), django & web2py. TG is like picking all good eggs from different open source projects. It integrates sqlalchemy, genshi, cheetah, pylons, for sql abstraction layer, templating system, web server respectively. One can choose other options also, if desired. -1 for TG is its complexity and not-so-good docs, too many dependencies. ? django has very good docs & active community. It is better in terms of simplicity & dependency?as compared to TG. ? web2py is vastly flexible, no dependencies, no installation required, just plug & play, very good community & docs. Honestly, I did not find any -1 for web2py. ? Of course, one has to form his/her own opinion. On stackoverflow.com, there are plenty of threads which compare the python frameworks. ? :-) ---Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From tinnews at isbd.co.uk Sun Sep 4 04:13:49 2011 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Sun, 4 Sep 2011 09:13:49 +0100 Subject: Functions vs OOP References: Message-ID: Ian Kelly wrote: > On Sat, Sep 3, 2011 at 10:15 AM, William Gill wrote: > > During some recent research, and re-familiarization with Python, I came > > across documentation that suggests that programming using functions, and > > programming using objects were somehow opposing techniques. > > > > It seems to me that they are complimentary. ?It makes sense to create > > objects and have some functions that take those objects as arguments. Are > > they suggesting that any function that takes an object as an argument should > > always be a method of that object? ?Conversely I can see creating functions > > that take raw input (e.g. strings) and return it in a format compatible with > > an object's constructor, rather than have objects accept any conceivable > > format for its constructor. > > > > Am I missing something, or am I taking things too literally? > > I think you may be confusing "functional programming" and "programming > using functions". These are not the same thing. > > Functional programming is about using functions in the *mathematical* > sense. A mathematical function maps one value (or tuple of values) to > another value. The mapped value never varies; if it did, it would be > a different function. So functional programming eschews the use of > functions where the results depend on any internal or external state > beyond the values of the passed-in arguments, such as the variable > state of the object the method is being called on. > I think there may be another issue here. If someone says "functional programming" to me then I would generally assume that they *do* mean "programming using functions". While your distinction of the two may be strictly correct I don't think it's the generally accepted meaning. -- Chris Green From fnautaNO at SPAMsolfon.nl Sun Sep 4 04:59:41 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Sun, 4 Sep 2011 10:59:41 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> <109595831.VCN276Cjj6@PointedEars.de> Message-ID: <9cgsvvFdhuU1@mid.individual.net> "Thomas 'PointedEars' Lahn" wrote in message news:109595831.VCN276Cjj6 at PointedEars.de... If you don't have anything better to contribute, please stop answering. Es gen?gt schon. Fokke From adam.jorgensen.za at gmail.com Sun Sep 4 05:05:32 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Sun, 4 Sep 2011 11:05:32 +0200 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Progranming with functions vs Progranming with objects sounds like C vs. C++ more than functional programming vs. OO programming On 4 September 2011 04:18, William Gill wrote: > On 9/3/2011 9:51 PM, Terry Reedy wrote: > >> >> It is possible that our doc was less than crystal clear. We are >> constantly improving it where we can see fixable faults. If you run >> across whatever it was and it still seems a bit muddy, post something >> again. >> >> Will do. > > Thanks. > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Sun Sep 4 05:58:08 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 4 Sep 2011 02:58:08 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <4E62DCC6.8000906@mrabarnett.plus.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> <4E62DCC6.8000906@mrabarnett.plus.com> Message-ID: <1315130288.86666.YahooMailNeo@web121515.mail.ne1.yahoo.com> > Thanks, I think that's the rule described in its full glory. Currently I am not ?quite sure of the use case for continuation nested in continuation -- it seems to be still a single continuation, but it allows for some additional freedom in formatting the continued line. Do you have other use cases for that? For the case of mis-indentation, as demonstrated in your scenario,?I think it is better that the rule is not applied to a comment?continued onto the next line. The effect of a '#' only carries to the end of a line, if one would like the next line to be a comment, just use another '#'. It remains to consider a mis-indentation that only involves code lines. However, that is not a new problem, so we should not worry (it is like a sunken cost).? Sorry for top posting. It seems yahoo web email is not designed with such a use case in mind. >________________________________ >From: MRAB >To: python-list at python.org >Sent: Sunday, September 4, 2011 10:04 AM >Subject: Re: [Python-ideas] allow line break at operators > >On 04/09/2011 00:22, Yingjie Lan wrote: >>>? Every language with blocks needs some mechanism to indicate the >> beginning and ending of blocks and of statements within blocks. If >> visible fences ('begin/end' or '{}') and statement terminators (';') are >> used, then '\n' can be treated as merely a space, as it is in C, for >> instance. >>>? and it uses unescaped '\n' (with two escapement options) to terminate >> statements. This is fundamental to Python's design and goes along with >> significant indents. >> >> Agreed. Currently indentation in Python starts a new block, but if you >> view it from the perspective of line breaking, it also functions as if >> the line is continued. The line of code below >> >> if condition: do_a(); do_b() >> >> can be written as: >> >> if condition: #line breaks >> do_a(); # ';' is optional here >> do_b() # continue >> >> That indentation can be also employed for line breaking is quite evident >> to me. During the open email correspondence with Stephen, it seems to be >> a tenable point. >> >>? > There would then be three ways to escape newline, with one doing >> double duty. And for what? Merely to avoid using either of the two >> methods already available. >> >> I believe the other two ways are not as good as this new way. As the >> proposal is fully backward compatible, people may choose whatever way >> they prefer. >> >I think that the rules would be: > >If a line ends with a colon and the next line is indented, then it's >the start of a block, and the following lines which belong to that >block have the same indent. > >If a line doesn't end with a colon but the next line is indented, then >it's the start of a continuation, and the following lines which belong >to that continuation have the same indent. > >In both cases there could be blocks nested in blocks and possibly >continuations nested in continuations, as well as blocks nested in >continuations and continuations nested in blocks. > >I'm not sure what the effect would be if you had mis-indented lines. >For example, if a line was accidentally indented after a comment, then >it would be treated as part of the comment. It's in cases like those >that syntax colouring would be helpful. It would be a good idea to use >an editor which could indicate in some way when a line is a >continuation. > >>? ? ------------------------------------------------------------------------ >>? ? *From:* Terry Reedy >>? ? *To:* python-list at python.org >>? ? *Cc:* python-ideas at python.org >>? ? *Sent:* Sunday, September 4, 2011 3:01 AM >>? ? *Subject:* Re: [Python-ideas] allow line break at operators >> >>? ? On 9/3/2011 3:51 AM, Yingjie Lan wrote: >>? ? ? > I agree that long lines of code are not very common in many projects, >>? ? ? > though it might be the case with some heavily involved in math. >>? ? For some >>? ? ? > reason, when the feature of free line breaking came about in computer >>? ? ? > languages, it is welcomed and generally well accepted. >> >>? ? Every language with blocks needs some mechanism to indicate the >>? ? beginning and ending of blocks and of statements within blocks. If >>? ? visible fences ('begin/end' or '{}') and statement terminators (';') >>? ? are used, then '\n' can be treated as merely a space, as it is in C, >>? ? for instance. >> >>? ? ? > Python uses indentation for blocks, >> >>? ? and it uses unescaped '\n' (with two escapement options) to >>? ? terminate statements. This is fundamental to Python's design and >>? ? goes along with significant indents. >> >>? ? ? > and by the same mechanism, line breaking can be >>? ? ? > accommodated without requiring parenthesis or ending backslashes. >> >>? ? You need proof for your claim that indentation can be used for both >>? ? jobs in the form of a grammar that works with Python's parser. I am >>? ? dubious that you can do that with an indents *after* the newline. >> >>? ? Even if you could, it would be confusing for human readers. There >>? ? would then be three ways to escape newline, with one doing double >>? ? duty. And for what? Merely to avoid using either of the two methods >>? ? already available. >> > >-- >http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandru at bastilla.coruscant.org.invalid Sun Sep 4 06:07:26 2011 From: alexandru at bastilla.coruscant.org.invalid (Alexandru Lazar) Date: Sun, 4 Sep 2011 10:07:26 +0000 (UTC) Subject: Need advice on Web / Database framework... References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: > How does web2py compare to django? I just started playing with django, > but don't know web2py I haven't used Django, but I did use web2py for a project that fell on my head just before leaving my old workplace. I just wanted it to end quickly so I took web2py as a shortcut. It's a great framework -- there seems to be an abstraction layer for anything, so you can write a fairly pythonic web app with it. The app I had to write was fairly trivial to be sure, and I barely had to write any code at all. What I didn't quite like about it was the documentation, that felt rather sketchy. There's the Official Web2py Book, but that has more of a tutorial structure. The API reference feels a tad sketchy and I sometimes had to guess my way around. But there's a good chance that this is just my bad impression, as I am not a web developer. Alex From steve+comp.lang.python at pearwood.info Sun Sep 4 07:18:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 04 Sep 2011 21:18:53 +1000 Subject: Functions vs OOP References: Message-ID: <4e635e9e$0$29984$c3e8da3$5496439d@news.astraweb.com> tinnews at isbd.co.uk wrote: > I think there may be another issue here. If someone says "functional > programming" to me then I would generally assume that they *do* mean > "programming using functions". Strictly speaking you are correct, "functional programming" does mean "programming using functions", the usual name for which is "procedural programming". But it means more than that: functions in the sense of mathematical functions, not merely sub-routines. http://en.wikipedia.org/wiki/Functional_programming Merely using functions is not the same as functional programming. > While your distinction of the two may > be strictly correct I don't think it's the generally accepted meaning. On the contrary, "functional programming" specifically refers to languages derived from, based on, or at least inspired by, the ideas of Alonzo Church's lambda calculus. It should be understood as somewhat in opposition to the idea of imperative programming, where the programmer gives instructions for changing program state. http://en.wikipedia.org/wiki/Programming_paradigm In practice, there are degrees of purity: strictly speaking, a purely functional language would be impractical, because it would have no I/O and therefore not be very useful. But generally, functional programming implies: - all coding is done using functions - functions are first-class data values - higher-order functions are used (functions which take functions as arguments) - no global variables - all data is immutable (cannot be modified) - functions should always return the same result each time they are called with the same arguments (so-called "referential transparency") - computations should be performed lazily as needed - no side-effects other than those caused by hardware limitations (e.g. there is only a finite amount of memory available), usually with an exemption made for I/O - use of recursion instead of imperative features such as iteration (for loops, while loops, etc.) Pure functional programming languages enforce those conventions as design features, rather than just leaving it up to the coder to apply them as a convention. Impure functional languages, such as Python, don't enforce all (or even any) of those conditions, although they may provide certain functional features. -- Steven From rustompmody at gmail.com Sun Sep 4 09:13:58 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 4 Sep 2011 06:13:58 -0700 (PDT) Subject: Functions vs OOP References: Message-ID: On Sep 3, 9:15?pm, William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. Staying with (for the moment) the suggestion that OO-P and F-P are complementary, I believe it is worthwhile to distinguish syntactic OO- P vs F-P from semantic OO-P vs F-P. Syntactically: f(x) is functional x.f() is object oriented. Semantically if f's return value depends only on x ie does not depend on state it is functional (in the math sense) -- the jargon is that f is referentially transparent. Referential opaqueness is usually such a source of problems that it turns out good to contain the problem somewhat -- hence the wish for encapsulation. One can find in the python library itself all 4 combinations: syntactically and semantically OO : sort syntactically and semantically FP: sorted syntactically OO semantically FP: join From erik.williamson at gmail.com Sun Sep 4 10:22:07 2011 From: erik.williamson at gmail.com (Erik) Date: Sun, 4 Sep 2011 07:22:07 -0700 (PDT) Subject: Can't use subprocess.Popen() after os.chroot() - why? Message-ID: Hi All, I'm trying to do the following: import os from subprocess import Popen, PIPE os.chroot("/tmp/my_chroot") p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_val, stderr_val = p.communicate() print stdout_val but the Popen call is dying with the following exception: Traceback (most recent call last): File "./test.py", line 7, in p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads File "/home/erik/lib/python2.7/pickle.py", line 858, in load File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string LookupError: unknown encoding: string-escape Am I missing something here? does the chroot environment need to be populated with more than just the date executable in this case? I can't seem to find any examples of this & would appreciate any insight. Thanks, Erik. From ron3200 at gmail.com Sun Sep 4 11:22:32 2011 From: ron3200 at gmail.com (ron3200) Date: Sun, 04 Sep 2011 10:22:32 -0500 Subject: [Python-ideas] allow line break at operators In-Reply-To: <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315149752.24283.18.camel@Gutsy> On Sat, 2011-09-03 at 13:38 +0900, Stephen J. Turnbull wrote: > Guido van Rossum writes: > > On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > > > > Sure, but IIRC one design principle of Python is that the keyword that > > > denotes the syntax should be the first thing on the line, > [...] > > That's true for *statements* (except assignments and calls). > > > > > Analogously, if operators are going to denote continuation, they > > > should come first on the line. > > > That doesn't follow. > > Agreed, it's not a logical implication. The analogy is only an > analogy, but my eyes do work that way. > > My conclusion is that we shouldn't try to encourage either style, > because people "see" continuation differently. Legislating a style > isn't going to change that, I think. I like to start continued lines with an operator as well. I also think it helps me keep it in my head a bit easier when I do that. I think this is one of those areas where computers and people differ, but it may also depend on the persons native language as to what works better for them. Ron From alain at dpt-info.u-strasbg.fr Sun Sep 4 11:25:48 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 04 Sep 2011 17:25:48 +0200 Subject: Can't use subprocess.Popen() after os.chroot() - why? References: Message-ID: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> Erik writes: > import os > from subprocess import Popen, PIPE > > os.chroot("/tmp/my_chroot") > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > stdout_val, stderr_val = p.communicate() > print stdout_val > > but the Popen call is dying with the following exception: > > Traceback (most recent call last): > File "./test.py", line 7, in > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ > File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child > File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads > File "/home/erik/lib/python2.7/pickle.py", line 858, in load > File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string > LookupError: unknown encoding: string-escape > > Am I missing something here? does the chroot environment need to be > populated with more than just the date executable in this case? Yes, because /bin/date is probably dynamically linked: you need the libs as well. (Try first with a statically linked executable, e.g., /bin/busybox, and everything should be ok). I agree the message is strange. For some reason, subprocess is calling pickle.loads, which calls rep.decode("string-escape"), which probably needs to access some file and fails because of the chroot(). I woud advise to use the chroot command instead of chrooting your python process, if that's possible for you. -- Alain. From rantingrick at gmail.com Sun Sep 4 12:37:00 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 09:37:00 -0700 (PDT) Subject: allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On Sep 3, 11:50?am, Stephen Hansen wrote: > Freedom is not and never has been, IMHO, a virtue or goal or even desire > in Python. Exactly! > Where it occurs, it is at best a happy coincidence, Exactly! > and even > if that happy coincidence happens often, it is not a design feature, IMHO. Exactly! Actually i believe Python allows TOO many freedoms and indulges TOO many excesses to the detriment of our code bases. Take the fact that both tabs AND spaces are legal in Python source. We should have choose one over the other! From hansmu at xs4all.nl Sun Sep 4 13:36:28 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 04 Sep 2011 19:36:28 +0200 Subject: Can't use subprocess.Popen() after os.chroot() - why? In-Reply-To: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> References: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e63b71c$0$2421$e4fe514c@news2.news.xs4all.nl> On 4/09/11 17:25:48, Alain Ketterlin wrote: > Erik writes: > >> import os >> from subprocess import Popen, PIPE >> >> os.chroot("/tmp/my_chroot") >> p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) >> stdout_val, stderr_val = p.communicate() >> print stdout_val >> >> but the Popen call is dying with the following exception: >> >> Traceback (most recent call last): >> File "./test.py", line 7, in >> p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) >> File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ >> File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child >> File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads >> File "/home/erik/lib/python2.7/pickle.py", line 858, in load >> File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string >> LookupError: unknown encoding: string-escape >> >> Am I missing something here? does the chroot environment need to be >> populated with more than just the date executable in this case? > > Yes, because /bin/date is probably dynamically linked: you need the libs > as well. (Try first with a statically linked executable, e.g., > /bin/busybox, and everything should be ok). /bin/date also needs timezone information from either /etc/localtime or /usr/share/zoneinfo/ (depends on whether the environment variable TZ is set). It may need other data files as well (e.g. for localization). > I agree the message is strange. For some reason, subprocess is calling > pickle.loads, which calls rep.decode("string-escape"), which probably > needs to access some file and fails because of the chroot(). The child process tries to exec /bin/date and fails. The child process then pickles the resulting exception and sends it to the parent via a pipe that the parent has created for this purpose. The parent then tries to unpickle the exception and fails to find the string-escape decoder in its usual place, due to the chroot. If you fix that, then the parent process will be able to re-raise the exception from the child process (which may or may not confuse you). > I woud advise to use the chroot command instead of chrooting your python > process, if that's possible for you. You'll find you need to copy a lot of dynamic libraries and several data files to your chroot box, before the normal commands in /bin work. Keep in mind that the more features you copy to the chroot jail, the easier it becomes to escape from it. Hope this helps, -- HansM From rantingrick at gmail.com Sun Sep 4 14:08:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 11:08:36 -0700 (PDT) Subject: allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: On Sep 4, 10:22?am, ron3200 wrote: > I think this is one of those areas where computers and people differ, > but it may also depend on the persons native language as to what works > better for them. Yes but what works better for "them" is not always a better way of doing things! People do foolish things all the time just from pure habit. A foolish consistency is a foolish consistency my friend. I mean, look at the folks who popped their cherry writing Basic code; talk about dysfunctional! From tjreedy at udel.edu Sun Sep 4 14:32:07 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 04 Sep 2011 14:32:07 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 4:13 AM, tinnews at isbd.co.uk wrote: > Ian Kelly wrote: >> Functional programming is about using functions in the *mathematical* >> sense. A mathematical function maps one value (or tuple of values) to >> another value. The mapped value never varies; if it did, it would be >> a different function. So functional programming eschews the use of >> functions where the results depend on any internal or external state >> beyond the values of the passed-in arguments, such as the variable >> state of the object the method is being called on. >> > I think there may be another issue here. If someone says "functional > programming" to me then I would generally assume that they *do* mean > "programming using functions". While your distinction of the two may > be strictly correct I don't think it's the generally accepted meaning. The distintion drawn by Ian *is* generally accepted in computer science. See https://secure.wikimedia.org/wikipedia/en/wiki/Functional_programming For instance, programming is C is imperative programming with functions but it generally is not 'functional programming' in the sense referred to by Ian and the Wikipedia article. Given that our docs are written by people who do understand the technical distinction, you are probably wrong to assume otherwise. However, as I said to William, it is possible that our docs could be improved so as to not depend on all readers having prior knowledge of the intended meaning of 'functional programming'. As the use of Python has expanded, so has the variety of backgrounds of Python programmers. -- Terry Jan Reedy From PointedEars at web.de Sun Sep 4 14:35:02 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 04 Sep 2011 20:35:02 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> <109595831.VCN276Cjj6@PointedEars.de> <9cgsvvFdhuU1@mid.individual.net> Message-ID: <1536106.qVoOGUtdWV@PointedEars.de> Fokke Nauta wrote: > "Thomas 'PointedEars' Lahn" wrote in message > news:109595831.VCN276Cjj6 at PointedEars.de... > > > > If you don't have anything better to contribute, please stop answering. > > Es gen?gt schon. I should have expected as much from an address munger. *plonk* -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From bkasterm at gmail.com Sun Sep 4 15:39:49 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Sun, 04 Sep 2011 13:39:49 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> Message-ID: <87obz0w0ze.fsf@gmail.com> rantingrick writes: > On Sep 3, 5:15?pm, Bart Kastermans wrote: > >> Any suggestions? > > Yeah, have you considered using the "linespace()" method of tk.Font > objects to calculate the height? Although i must say it "feels" as if > your doing something you should not need to do, however i cannot be > sure without knowing more about this GUI. Sounds a lot like trying to > put socks on a rooster. > > http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#fonts Thx. That function should allow for a bit of robustness. I get bits of information over RSS, these are of varying length. I want to show 10 at a time, and scroll through them. Now when I scroll the window grows and shrinks depending on their size, I want to right from the start make it high enough to contain even the biggest that will have to be shown. So the question is determining the height parameter for the labels ahead of time. My strategy has been to put all in labels and then try to get the information from the label of how high it needs to be made at a certain width. From nospam at domain.invalid Sun Sep 4 15:43:31 2011 From: nospam at domain.invalid (William Gill) Date: Sun, 04 Sep 2011 15:43:31 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 2:32 PM, Terry Reedy wrote: > On 9/4/2011 4:13 AM, tinnews at isbd.co.uk wrote: >> Ian Kelly wrote: > >>> Functional programming is about using functions in the *mathematical* >>> sense. A mathematical function maps one value (or tuple of values) to >>> another value. The mapped value never varies; if it did, it would be >>> a different function. So functional programming eschews the use of >>> functions where the results depend on any internal or external state >>> beyond the values of the passed-in arguments, such as the variable >>> state of the object the method is being called on. >>> >> I think there may be another issue here. If someone says "functional >> programming" to me then I would generally assume that they *do* mean >> "programming using functions". While your distinction of the two may >> be strictly correct I don't think it's the generally accepted meaning. > > The distintion drawn by Ian *is* generally accepted in computer science. > See > https://secure.wikimedia.org/wikipedia/en/wiki/Functional_programming > For instance, programming is C is imperative programming with functions > but it generally is not 'functional programming' in the sense referred > to by Ian and the Wikipedia article. Given that our docs are written by > people who do understand the technical distinction, you are probably > wrong to assume otherwise. > > However, as I said to William, it is possible that our docs could be > improved so as to not depend on all readers having prior knowledge of > the intended meaning of 'functional programming'. As the use of Python > has expanded, so has the variety of backgrounds of Python programmers. > Since I am the one who opened this can of worms, and since I believe I have relocated the document that I misinterpreted, I feel compelled to jump in here. The source of my error is "Functional Programming HOWTO (/python-3.1.3-docs-html/howto/functional.html)" Having arrived at this page indirectly (searching for and skimming other information regarding functions and methods) I was only half paying attention. As a result I made the same mistake Chris did. As a point of reference, I would not call myself a programmer, and any formal exposure was many, many years ago. I am familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional. At least not in this context. Having done a little more digging I now understand the difference. "Functional programming" is the proper terminology, and had I come across it from another direction, or with a more deliberate focus I probably wouldn't have made the initial mistake. If you read the material with even a nominal understanding of the functional paradigm (functional relationships in a mathematical sense, not functions in the procedural sense), it is clear. If you read it without consciously recognizing this difference, the material does nothing to alert you to the initial error. From georg at python.org Sun Sep 4 16:21:50 2011 From: georg at python.org (Georg Brandl) Date: Sun, 04 Sep 2011 22:21:50 +0200 Subject: [RELEASED] Python 3.2.2 Message-ID: <4E63DDDE.2040108@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the Python 3.2.2 maintenance release. Python 3.2.2 mainly fixes `a regression `_ in the ``urllib.request`` module that prevented opening many HTTP resources correctly with Python 3.2.1. Python 3.2 is a continuation of the efforts to improve and stabilize the Python 3.x line. Since the final release of Python 2.7, the 2.x line will only receive bugfixes, and new features are developed for 3.x only. Since PEP 3003, the Moratorium on Language Changes, is in effect, there are no changes in Python's syntax and built-in types in Python 3.2. Development efforts concentrated on the standard library and support for porting code to Python 3. Highlights are: * numerous improvements to the unittest module * PEP 3147, support for .pyc repository directories * PEP 3149, support for version tagged dynamic libraries * PEP 3148, a new futures library for concurrent programming * PEP 384, a stable ABI for extension modules * PEP 391, dictionary-based logging configuration * an overhauled GIL implementation that reduces contention * an extended email package that handles bytes messages * a much improved ssl module with support for SSL contexts and certificate hostname matching * a sysconfig module to access configuration information * additions to the shutil module, among them archive file support * many enhancements to configparser, among them mapping protocol support * improvements to pdb, the Python debugger * countless fixes regarding bytes/string issues; among them full support for a bytes environment (filenames, environment variables) * many consistency and behavior fixes for numeric operations For a more extensive list of changes in 3.2, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2 visit: http://www.python.org/download/releases/3.2/ Please consider trying Python 3.2 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.18 (GNU/Linux) iEYEARECAAYFAk5j3d4ACgkQN9GcIYhpnLA2BACeLZ8nSdVOoxlJw4DnbM42neeA fwAAoKTHetXsVxrEfvCWSorUhoJ083kZ =5Wm1 -----END PGP SIGNATURE----- From rantingrick at gmail.com Sun Sep 4 17:10:59 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 14:10:59 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> Message-ID: <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> On Sep 4, 2:39?pm, Bart Kastermans wrote: > I get bits of information over RSS, these are of varying length. ?I > want to show 10 at a time, and scroll through them. ?Now when I > scroll the window grows and shrinks depending on their size, I want > to right from the start make it high enough to contain even the > biggest that will have to be shown. ?So the question is determining > the height parameter for the labels ahead of time. ?My strategy has > been to put all in labels and then try to get the information from > the label of how high it needs to be made at a certain width. I see. However i might opt instead for a text widget with columns of wrapped text. You could use the textwrap.py module to help (although you'll have to work around it's shortcomings for paragraphs and such). In any event it's difficult to offer good advice without seeing the code directly. From rantingrick at gmail.com Sun Sep 4 17:15:07 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 14:15:07 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> Message-ID: On Sep 4, 2:39?pm, Bart Kastermans wrote: > Thx. ?That function should allow for a bit of robustness. Correction. The function is actually "tkFont.metrics(arg)" which takes "linespace" as an optional argument. From exarkun at twistedmatrix.com Sun Sep 4 17:26:01 2011 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sun, 04 Sep 2011 21:26:01 -0000 Subject: pyOpenSSL 0.13 release Message-ID: <20110904212601.1808.1179874796.divmod.xquotient.244@localhost.localdomain> Hello all, I'm happy to announce the release of pyOpenSSL 0.13. With this release, pyOpenSSL now supports OpenSSL 1.0. Additionally, pyOpenSSL now works with PyPy. Apart from those two major developments, the following interesting changes have been made since the last release: * (S)erver (N)ame (I)ndication is now supported. * There are now APIs with which the underlying OpenSSL version can be queried. * The peer's certificate chain for a connection can now be inspected. * New methods have been added to PKey and X509 objects exposing more OpenSSL functionality. Release files are available on PyPI. The latest development version and the issue tracker can be found on Launchpad. Jean-Paul From steve+comp.lang.python at pearwood.info Sun Sep 4 19:41:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 05 Sep 2011 09:41:42 +1000 Subject: Functions vs OOP References: Message-ID: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> William Gill wrote: > The source of my error is "Functional Programming HOWTO > (/python-3.1.3-docs-html/howto/functional.html)" For those who don't have access to William's local file system, I expect he's looking at this: http://docs.python.org/release/3.1.3/howto/functional.html or the most recent version: http://docs.python.org/dev/howto/functional.html [...] > If you read the material with even a nominal understanding of the > functional paradigm (functional relationships in a mathematical sense, > not functions in the procedural sense), it is clear. If you read it > without consciously recognizing this difference, the material does > nothing to alert you to the initial error. What about the entire "Introduction" section, which starts with this statement? "This section explains the basic concept of functional programming" If you would like to suggest improvements, please do so. -- Steven From nospam at domain.invalid Sun Sep 4 20:46:19 2011 From: nospam at domain.invalid (William Gill) Date: Sun, 04 Sep 2011 20:46:19 -0400 Subject: Functions vs OOP In-Reply-To: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> References: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/4/2011 7:41 PM, Steven D'Aprano wrote: > William Gill wrote: > >> The source of my error is "Functional Programming HOWTO >> (/python-3.1.3-docs-html/howto/functional.html)" > > For those who don't have access to William's local file system, I expect > he's looking at this: > > http://docs.python.org/release/3.1.3/howto/functional.html > > or the most recent version: > > http://docs.python.org/dev/howto/functional.html I didn't expect anyone to access my file system so I trimmed the path, but left enough for an industrious soul like yourself to figure it out. You did, so it seems I was correct, or do you think "functional.html" would have been sufficient? ;-) > > [...] >> If you read the material with even a nominal understanding of the >> functional paradigm (functional relationships in a mathematical sense, >> not functions in the procedural sense), it is clear. If you read it >> without consciously recognizing this difference, the material does >> nothing to alert you to the initial error. > > What about the entire "Introduction" section, which starts with this > statement? > > "This section explains the basic concept of functional programming" Which clears up the misunderstanding, how? Unless the target audience is people who already understands "the basic concept of functional programming." That seems like a circular reference. The article is introducing a concept. To assume any familiarity with that concept as a basis, is not an introduction. As previously stated; I was already familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional programming. Nothing I read (I'll be honest; scanned) did anything to contradict my incorrect point of reference. > If you would like to suggest improvements, please do so. How about a caveat stating something like "NOTE: functional as in mathematical functions, not to be confused with functions/procedures." From rosuav at gmail.com Sun Sep 4 20:59:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 5 Sep 2011 10:59:59 +1000 Subject: Functions vs OOP In-Reply-To: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> References: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Sep 5, 2011 at 9:41 AM, Steven D'Aprano wrote: > http://docs.python.org/dev/howto/functional.html > > What about the entire "Introduction" section, which starts with this > statement? > > "This section explains the basic concept of functional programming" > > If you would like to suggest improvements, please do so. Well, it does invite you to skip that whole section :) Since you asked, though, the copyeditor in me does want to suggest one small tweak: Second paragraph after the bullet list ends "Avoiding side effects means not using data structures that get updated as a program runs; every function?s output must only depend on its input." - I'd word it as "must depend only on". Pretty immaterial, but the formal style prefers correctness. Somewhat more significant: Under "Modularity", may be of value to add a paragraph about parallelism. With functional code, it's easy for an interpreter to ascertain which functions depend on each other (because one's return value is another's input). Independent functions can be run in parallel without affecting the result; the interpreter can therefore divide a complex task across multiple CPUs without any work from the programmer. Like I said, it's just "since you asked". :) The above paragraph is hereby given out as public domain, use it (edit it, whatever) under whatever license the Python docs require. ChrisA From simoncropper at fossworkflowguides.com Mon Sep 5 01:18:30 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 15:18:30 +1000 Subject: Hello, and request for help with 'dynamic grids' Message-ID: <4E645BA6.4070500@fossworkflowguides.com> Hi, I am a applications developer - originally from Windows using primarily Visual Foxpro, although I am familiar with a variety of other xbase derivatives. I now use Linux / Ubuntu, and have been actively teaching myself Python with the view to migrate most of my applications to sqlite-based database. I am looking for the ability to create dynamic grids in a window but can't for the life of me find how to do this. Here is the functionality that I desire... 1. Have a dialog appear that allows me to select a database, e.g. sqlite3 database. 2. Select table in the database and have all the records appear in a grid. Fields represented as column, width and order adjustable, rows representing records. Each cell can be edited directly. 3. I would like to create filters on this grid based on attributes in the table. So if the table is a list of names, filter and show only those people with a particular first name. For people familiar with xbase languages it equivalent to browsing a table and applying a filter. 4. Once the record is identified I would like to select the record or hit enter to have the data sent to the keyboard buffer or put into the clipboard. I have found most of these elements available. I can create dialogs, I can connect to a database, I can extract data from the tables using SQL but I can't find how to easily get these lists into a grid -- it appears to me you need to allocate list record 1 to grid row 1, list record 2 to grid row 2, etc and manage how many rows are displayed and 'page' through the table. Am I missing something? I presume that you could just supply a list or array selected using SQL from a table and just pass this data to a grid and have it manage all the basics like if the window is resized the number of rows and columns are adjusted accordingly, buffering records, etc. My investigations have generally found that windows/forms/data entry screen can be created for a specific table or view, but these are hard-wired during development. Is there anyway of rapidly defining the grid during runtime so any table can be viewed? -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From krille012 at gmail.com Mon Sep 5 02:47:42 2011 From: krille012 at gmail.com (=?ISO-8859-1?Q?Kristofer_Tengstr=F6m?=) Date: Sun, 4 Sep 2011 23:47:42 -0700 (PDT) Subject: Need help with simple OOP Python question Message-ID: Hi, I'm having trouble creating objects that in turn can have custom objects as variables. The code looks like this: --------------------------------------------- class A: sub = dict() def sub_add(self, cls): obj = cls() self.sub[obj.id] = obj class B(A): id = 'inst' base = A() base.sub_add(B) base.sub['inst'].sub_add(B) print # prints a blank line print base.sub['inst'] print base.sub['inst'].sub['inst'] ---------------------------------------------- Now, what I get from this is the following: <__main__.B instance at 0x01FC20A8> <__main__.B instance at 0x01FC20A8> Why is this? What I want is for them to be two separate objects, but it seems like they are the same one. I've tried very hard to get this to work, but as I've been unsuccessful I would really appreciate some comments on this. I'm sure it's something really easy that I just haven't thought of. Python version is 2.6.5 (I'm using Panda3D to create a 2?D game). From me+list/python at ixokai.io Mon Sep 5 03:07:45 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Mon, 05 Sep 2011 00:07:45 -0700 Subject: Need help with simple OOP Python question In-Reply-To: References: Message-ID: <4E647541.7080304@ixokai.io> On 9/4/11 11:47 PM, Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() You are sharing this single "sub" dictionary with all instances of your A class. If you want to define instance-specific attributes, define them in the __init__ method, like so: class A: def __init__(self): self.sub = dict() def sub_add(self, cls): obj = cls() self.sub[obj.id] = obj -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Mon Sep 5 03:10:14 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 09:10:14 +0200 Subject: Need help with simple OOP Python question References: Message-ID: Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() Putting it into the class like this means sub is shared by all instances. > def sub_add(self, cls): > obj = cls() > self.sub[obj.id] = obj > > class B(A): > id = 'inst' > > base = A() > base.sub_add(B) > base.sub['inst'].sub_add(B) > > print # prints a blank line > print base.sub['inst'] > print base.sub['inst'].sub['inst'] > > ---------------------------------------------- > > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? What I want is for them to be two separate objects, but > it seems like they are the same one. I've tried very hard to get this > to work, but as I've been unsuccessful I would really appreciate some > comments on this. I'm sure it's something really easy that I just > haven't thought of. Your class A needs an initialiser: class A: def __init__(self): self.sub = {} # one dict per instance # ... From steve+comp.lang.python at pearwood.info Mon Sep 5 03:19:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 05 Sep 2011 17:19:12 +1000 Subject: Hello, and request for help with 'dynamic grids' References: Message-ID: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote: > I am looking for the ability to create dynamic grids in a window but > can't for the life of me find how to do this. What GUI toolkit are you using? -- Steven From ben+python at benfinney.id.au Mon Sep 5 03:26:51 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 05 Sep 2011 17:26:51 +1000 Subject: Need help with simple OOP Python question References: Message-ID: <87sjobo3es.fsf@benfinney.id.au> Kristofer Tengstr?m writes: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. That terminology is rather confused. I think what you want is to have instances with their own attributes. > class A: > sub = dict() This binds a single object (a new empty dict) to the class attribute ?sub?. Every instance of class ?A? will share the same attribute, and hence that same dict. > def sub_add(self, cls): This defines a function which will be bound to the class attribute ?sub_add?. It will, when later called as a method, receive the instance as the first parameter, bound to the local name ?self?. > obj = cls() > self.sub[obj.id] = obj Here, ?self? will be an instance of the ?A? class. Each instance has no ?sub? attribute, so Python will find the class attribute ?A.sub?, shared by all ?A? instances. You're then modifying that class attribute ?A.sub?. [?] > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? I hope the above explains it. > What I want is for them to be two separate objects, but it seems like > they are the same one. Yes. Anything you talk about in the class definition scope cannot know about any instance of that class, since the instances don't exist yet. Instead, instance attributes need to be bound to a particular instance, which means you need to have a reference to the instance; that's what ?self? is for. The class initialiser is a method named ?__init__?, and is called on each newly-created instance before that instance is returned from the constructor. I advise you to work through the Python tutorial, beginning to end, which will give you a good grounding in these and other fundamental Python topics . Work through each example, understand it by experimenting, and then proceed to the next, until you've done the lot. -- \ ?If history and science have taught us anything, it is that | `\ passion and desire are not the same as truth.? ?E. O. Wilson, | _o__) _Consilience_, 1998 | Ben Finney From bex.lewis at gmail.com Mon Sep 5 05:01:05 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Mon, 5 Sep 2011 02:01:05 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> Message-ID: > > > Possibly. > > I tried this: > > server.py -n -c config.ini > > Once again, the server is up and running and when I am logging in with my > > browser (10.0.0.140:8081) I can see information showing up at the command > > prompt, showing somebody is logging is, but the same error: > > "fshandler:get_data: \Webdav not found". During starting up the server > > mentioned: "pywebdav:Serving data from \Webdav". > > > In the config file it says: > > "# main directory > > directory = \Webdav" > > > Perhaps my Python configuration is at fault. > > > Fokke > > Is the path supposed to be absolute? In which case you'd need to have: > directory=C:\path\to\Webdav > > instead of just > directory=\Webdav > > I tried: > directory=D:\Webdav > directory=D:/Webdav > > To no avail. > It didn.t make any difference. > > I surely believe my WebDAV installation is at fault. > > Fokke Interestingly, looking at the code that returns the "fshandler:get_data: \Webdav not found" message, it looks like it tests that the path given exists and then tries an os.path.isfile, then an os.path.isdir. If both fail you get the message that you see. This might be a bit of a shot in the dark but could you try the path with and without a trailing '/' or '\'? I don't currently have a windows box available to test on and figure out why it would be detected as existing but not test true for either a file or directory. Becky Lewis From hnsri49 at gmail.com Mon Sep 5 05:34:22 2011 From: hnsri49 at gmail.com (srinivas hn) Date: Mon, 5 Sep 2011 15:04:22 +0530 Subject: Need help with simple OOP Python question In-Reply-To: References: Message-ID: Hi, You are getting same object because you are overriding the dictionary update. Its printing the proper value with the last updated instance of B. If you want to see the two different instances of class B give print self.sub inside the sub_add method in class A. CHEERS CNA 9986229891 On Mon, Sep 5, 2011 at 12:17 PM, Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() > def sub_add(self, cls): > obj = cls() > self.sub[obj.id] = obj > > class B(A): > id = 'inst' > > base = A() > base.sub_add(B) > base.sub['inst'].sub_add(B) > > print # prints a blank line > print base.sub['inst'] > print base.sub['inst'].sub['inst'] > > ---------------------------------------------- > > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? What I want is for them to be two separate objects, but > it seems like they are the same one. I've tried very hard to get this > to work, but as I've been unsuccessful I would really appreciate some > comments on this. I'm sure it's something really easy that I just > haven't thought of. > > Python version is 2.6.5 (I'm using Panda3D to create a 2?D game). > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From simoncropper at fossworkflowguides.com Mon Sep 5 06:07:05 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 20:07:05 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E649F49.5050103@fossworkflowguides.com> On 05/09/11 17:19, Steven D'Aprano wrote: > On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote: > >> I am looking for the ability to create dynamic grids in a window but >> can't for the life of me find how to do this. > > What GUI toolkit are you using? > > I have looked at wxGlade, Boa Constructor, wxFormBuilder, tkinder, I have also looked through the Python website many times looking for commands that would allow me to create a GUI from scratch. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From t at jollybox.de Mon Sep 5 06:40:07 2011 From: t at jollybox.de (Thomas Jollans) Date: Mon, 05 Sep 2011 12:40:07 +0200 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E645BA6.4070500@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> Message-ID: <4E64A707.9090006@jollybox.de> On 05/09/11 07:18, Simon Cropper wrote: > I am looking for the ability to create dynamic grids in a window but > can't for the life of me find how to do this. It depends on which windowing toolkit you're planning to use. If you use PyGTK, you'd want a TreeView widget to display the list. Fill a ListStore instance with your data and give that to the TreeView. You can implement filtering and sorting on top of that using TreeModelFilter and TreeModelSort. LibreOffice and OpenOffice have database management components (I haven't used them, I assume they're somewhat similar to MS Access) - and they can be scripted using Python. Depending on what you're doing, and what you're planning to do in the future (re learning investment), that might be worth looking into. Thomas From simoncropper at fossworkflowguides.com Mon Sep 5 06:52:40 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 20:52:40 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E64A707.9090006@jollybox.de> References: <4E645BA6.4070500@fossworkflowguides.com> <4E64A707.9090006@jollybox.de> Message-ID: <4E64A9F8.3000501@fossworkflowguides.com> On 05/09/11 20:40, Thomas Jollans wrote: > It depends on which windowing toolkit you're planning to use. If you use > PyGTK, you'd want a TreeView widget to display the list. Fill a > ListStore instance with your data and give that to the TreeView. You can > implement filtering and sorting on top of that using TreeModelFilter and > TreeModelSort. I have look at most. I have no preference. Are you able to point me to some resource material explaining how this can be done - e.g. a tutorial or manual? > LibreOffice and OpenOffice have database management components (I > haven't used them, I assume they're somewhat similar to MS Access) - and > they can be scripted using Python. Depending on what you're doing, and > what you're planning to do in the future (re learning investment), that > might be worth looking into. 'Base' is of no value in this regard. It is not really designed for this and there is a raging debate at the moment whether it will be maintained in the future. It also fails in that it requires predefined connections and forms to be established. It would not be possible to dynamically link to a table in a database (I have established ODBC links to a SQLite database, but the driver is an un-maintained draft). I also believe that the 'base' component in libreoffice/openoffice is a java implementation not python. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From krille012 at gmail.com Mon Sep 5 09:15:40 2011 From: krille012 at gmail.com (=?ISO-8859-1?Q?Kristofer_Tengstr=F6m?=) Date: Mon, 5 Sep 2011 06:15:40 -0700 (PDT) Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> Message-ID: <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Thanks everyone, moving the declaration to the class's __init__ method did the trick. Now there's just one little problem left. I'm trying to create a list that holds the parents for each instance in the hierarchy. This is what my code looks like now: ----------------------------------------- class A: def __init__(self, parents=None): self.sub = dict() if parents: self.parents = parents else: self.parents = [] def sub_add(self, cls): hierarchy = self.parents hierarchy.append(self) obj = cls(hierarchy) self.sub[obj.id] = obj class B(A): id = 'inst' base = A() base.sub_add(B) base.sub['inst'].sub_add(B) print print vars(base) print print vars(base.sub['inst']) print print vars(base.sub['inst'].sub['inst']) --------------------------------------------- The output from this program is the following: {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794B8>}} {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794E0>}} {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {}} As you can see, the problem looks similar to the one before: All the instances have an identical parent list. However, I don't understand why as self.parents is declared in the __init__ method. Any ideas? What I want is for the first instance to have an empty list, the second to have one element in the list and the third to have two parent elements. From python at bdurham.com Mon Sep 5 09:23:51 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 05 Sep 2011 09:23:51 -0400 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E645BA6.4070500@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> Message-ID: <1315229031.32028.140258137504765@webmail.messagingengine.com> Hi Simon, > I am a applications developer - originally from Windows using primarily Visual Foxpro, although I am familiar with a variety of other xbase derivatives. Check out dabodev.com. Dabo is a Python framework created by former VFP developers. Highly recommended. Malcolm From simoncropper at fossworkflowguides.com Mon Sep 5 09:33:31 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 23:33:31 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <1315229031.32028.140258137504765@webmail.messagingengine.com> References: <4E645BA6.4070500@fossworkflowguides.com> <1315229031.32028.140258137504765@webmail.messagingengine.com> Message-ID: <4E64CFAB.70804@fossworkflowguides.com> On 05/09/11 23:23, python at bdurham.com wrote: > Check out dabodev.com. Dabo is a Python framework created by former VFP > developers. > Dabo is a great product. Spoke extensively with Ed Leafe and Paul McNett. Unfortunately the framework is not 'dynamic'. If you have an fixed database and tables it can quite quickly create a basic data entry setup and menu. Looks great when it runs. The problem is creating the window and grid on the fly. I want a program that can be used to open any database and 'data mine' and extract table content. Dabo allows RAD for an established relational databases not unknown ones. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From piet at vanoostrum.org Mon Sep 5 10:15:01 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Mon, 05 Sep 2011 16:15:01 +0200 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Torek writes: [snip] > Instead, we have a syntax where you, the programmer, write out the > name of the local variable that binds to the first parameter. This > means the first parameter is visible. Except, it is only visible > at the function definition -- when you have the instance and call > the instance or class method: > > black_knight = K() > black_knight.meth1('a', 1) > black_knight.meth2(2) > > the first parameters (black_knight, and black_knight.__class__, > respectively) are magic, and invisible. > > Thus, Python is using the "explicit is better than implicit" rule > in the definition, but not at the call site. I have no problem with > this. Sometimes I think implicit is better than explicit. In this > case, there is no need to distinguish, at the calls to meth1() and > meth2(), as to whether they are "class" or "instance" methods. At > the *calls* they would just be distractions. It *is* explicit also at the call site. It only is written at the left of the dot rather than at the right of the parenthesis. And that is necessary to locate which definition of the method applies. It would be silly to repeat this information after the parenthesis. Not only silly, it would be stupid as it would be a source of errors, and an example of DRY. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From piet at vanoostrum.org Mon Sep 5 10:23:24 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Mon, 05 Sep 2011 16:23:24 +0200 Subject: Closures and Partial Function Application References: <9cd48486-acd9-4888-9677-0e54fd1eedfd@k15g2000yqd.googlegroups.com> Message-ID: Travis Parks writes: > I also like partial function application. What is the easiest way of > achieving this in Python? Would it look something like this: > > def foo(x, y): > return x + y > > xFoo = lambda y: foo(10, y) from functools import partial xfoo = partial(foo, 10) -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From wuwei23 at gmail.com Mon Sep 5 10:40:15 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 5 Sep 2011 07:40:15 -0700 (PDT) Subject: Hello, and request for help with 'dynamic grids' References: Message-ID: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> On Sep 5, 3:18?pm, Simon Cropper wrote: > My investigations have generally found that windows/forms/data entry > screen can be created for a specific table or view, but these are > hard-wired during development. Is there anyway of rapidly defining the > grid during runtime so any table can be viewed? The commercial product Resolver One provides a grid/spreadsheet style interface with Python scripting capabilities. I'm not sure of its current licensing status but I believe it used to be free if used on open source projects. http://www.resolversystems.com/products/resolver-one/ Each spreadsheet itself is Python code; I think it should be quite do- able to take something with introspective SQL capabilities like SQLAlchemy and have it title columns and fill them with the correct fields accordingly. Hope this helps. From __peter__ at web.de Mon Sep 5 10:43:02 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 16:43:02 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: Kristofer Tengstr?m wrote: > Thanks everyone, moving the declaration to the class's __init__ method > did the trick. Now there's just one little problem left. I'm trying to > create a list that holds the parents for each instance in the > hierarchy. This is what my code looks like now: > > ----------------------------------------- > > class A: > def __init__(self, parents=None): > self.sub = dict() > if parents: You should explicitly test for None here; otherwise in a call like ancestors = [] a = A(anchestors) the list passed as an argument will not be used, which makes fore confusing behaviour. > self.parents = parents > else: > self.parents = [] > def sub_add(self, cls): > hierarchy = self.parents > hierarchy.append(self) Here you are adding self to the parents (that should be called ancestors) and pass it on to cls(...). Then -- because it's non-empty -- it will be used by the child, too, and you end up with a single parents list. > obj = cls(hierarchy) > self.sub[obj.id] = obj While the minimal fix is to pass a copy def sub_add(self, cls): obj = cls(self.parents + [self]) self.sub[obj.id] = obj I suggest that you modify your node class to keep track only of the direct parent instead of all ancestors. That makes the implementation more robust when you move a node to another parent. From fnautaNO at SPAMsolfon.nl Mon Sep 5 10:51:00 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Mon, 5 Sep 2011 16:51:00 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> Message-ID: <9ck5upFlpnU1@mid.individual.net> "becky_lewis" wrote in message news:a7cd34d7-ed2b-4449-8edc-a6a45b59ecde at hb5g2000vbb.googlegroups.com... > > >> > Possibly. >> > I tried this: >> > server.py -n -c config.ini >> > Once again, the server is up and running and when I am logging in with >> > my >> > browser (10.0.0.140:8081) I can see information showing up at the >> > command >> > prompt, showing somebody is logging is, but the same error: >> > "fshandler:get_data: \Webdav not found". During starting up the server >> > mentioned: "pywebdav:Serving data from \Webdav". >> >> > In the config file it says: >> > "# main directory >> > directory = \Webdav" >> >> > Perhaps my Python configuration is at fault. >> >> > Fokke >> >> Is the path supposed to be absolute? In which case you'd need to have: >> directory=C:\path\to\Webdav >> >> instead of just >> directory=\Webdav >> >> I tried: >> directory=D:\Webdav >> directory=D:/Webdav >> >> To no avail. >> It didn.t make any difference. >> >> I surely believe my WebDAV installation is at fault. >> >> Fokke > > Interestingly, looking at the code that returns the > "fshandler:get_data: \Webdav not found" message, it looks like it > tests that the path given exists and then tries an os.path.isfile, > then an os.path.isdir. If both fail you get the message that you see. > This might be a bit of a shot in the dark but could you try the path > with and without a trailing '/' or '\'? I don't currently have a > windows box available to test on and figure out why it would be > detected as existing but not test true for either a file or directory. > Hi Becky, I tried it straight away: directory=D:\Webdav\ directory=D:/Webdav/ Didn't work, in both cases the same error "fshandler:get_data: \Webdav not found". I have the opinion that my WebDAV installation is at fault. The database is not created either. To have set up Python, I used python-2.7.2.msi. To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both Unix/Linux. To install the, I used " >> You dont install from "Python GUI", use normal cmd, navigate to the >> folder >> you downloaded PyXML and PyWebDAV and run "python setup.py install" >> (python.exe has to be in your PATH). Then you have to find the >> startup-script "davserver". Find your python installation directory and >> look into/Tools/Scripts, in my computer this is >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have >> to >> look for "davserver" there..." Shall I re?nstall the whole lot? Would it make a difference if in that case I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi? Fokke From joncle at googlemail.com Mon Sep 5 10:59:31 2011 From: joncle at googlemail.com (Jon Clements) Date: Mon, 5 Sep 2011 07:59:31 -0700 (PDT) Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: <9bda87ee-ac0a-4b8f-b9a9-aa0cefd1bd04@k9g2000vbd.googlegroups.com> On Sep 5, 3:43?pm, Peter Otten <__pete... at web.de> wrote: > Kristofer Tengstr?m wrote: > > Thanks everyone, moving the declaration to the class's __init__ method > > did the trick. Now there's just one little problem left. I'm trying to > > create a list that holds the parents for each instance in the > > hierarchy. This is what my code looks like now: > > > ----------------------------------------- > > > class A: > > ? ? def __init__(self, parents=None): > > ? ? ? ? self.sub = dict() > > ? ? ? ? if parents: > > You should explicitly test for None here; otherwise in a call like > > ancestors = [] > a = A(anchestors) > > the list passed as an argument will not be used, which makes fore confusing > behaviour. > > > ? ? ? ? ? ? self.parents = parents > > ? ? ? ? else: > > ? ? ? ? ? ? self.parents = [] > > ? ? def sub_add(self, cls): > > ? ? ? ? hierarchy = self.parents > > ? ? ? ? hierarchy.append(self) > > Here you are adding self to the parents (that should be called ancestors) > and pass it on to cls(...). Then -- because it's non-empty -- it will be > used by the child, too, and you end up with a single parents list. > > > ? ? ? ? obj = cls(hierarchy) > > ? ? ? ? self.sub[obj.id] = obj > > While the minimal fix is to pass a copy > > def sub_add(self, cls): > ? ? obj = cls(self.parents + [self]) > ? ? self.sub[obj.id] = obj > > I suggest that you modify your node class to keep track only of the direct > parent instead of all ancestors. That makes the implementation more robust > when you move a node to another parent. I may not be understanding the OP correctly, but going by what you've put here, I might be tempted to take this kind of stuff out of the class's and using a graph library (such as networkx) - that way if traversal is necessary, it might be a lot easier. But once again, I must say I'm not 100% sure what the OP wants to achieve... Jon. From mdekauwe at gmail.com Mon Sep 5 11:06:10 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 08:06:10 -0700 (PDT) Subject: Best way to print a module? Message-ID: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Hi, If I wanted to print an entire module, skipping the attributes starting with "__" is there an *optimal* way? Currently I am doing something like this. Note I am just using sys here to make the point import sys data = [] for attr in sys.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(sys, attr) data.append((attr, attr_val)) data.sort() for i in data: print "%s = %s" % (i[0], i[1]) Clearly this would be quicker if I didn't store it and sort the output, i.e. for attr in sys.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(sys, attr) print "%s = %s" % (attr, attr_val) Anyway if there is a better way it would be useful to hear it... Many thanks, Martin From wolftracks at invalid.com Mon Sep 5 11:15:24 2011 From: wolftracks at invalid.com (W. eWatson) Date: Mon, 05 Sep 2011 08:15:24 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? Message-ID: See Subject. From rosuav at gmail.com Mon Sep 5 11:24:19 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 6 Sep 2011 01:24:19 +1000 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: > See Subject. > -- > http://mail.python.org/mailman/listinfo/python-list > To what extent "familiar"? I have it installed on several computers, but only because it comes with Open Wat C/C++. With something off-topic like this, it might be better to have a real email address, so the responses can be off-list. ChrisA From __peter__ at web.de Mon Sep 5 11:28:43 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 17:28:43 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> <9bda87ee-ac0a-4b8f-b9a9-aa0cefd1bd04@k9g2000vbd.googlegroups.com> Message-ID: Jon Clements wrote: > I > must say I'm not 100% sure what the OP wants to achieve... Learn Python? ;) From wolftracks at invalid.com Mon Sep 5 12:15:20 2011 From: wolftracks at invalid.com (W. eWatson) Date: Mon, 05 Sep 2011 09:15:20 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 9/5/2011 8:24 AM, Chris Angelico wrote: > On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: >> See Subject. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > To what extent "familiar"? I have it installed on several computers, > but only because it comes with Open Wat C/C++. > > With something off-topic like this, it might be better to have a real > email address, so the responses can be off-list. > > ChrisA sierra_mtnview @ sbcglobal.net Here's the story. As far as I can tell F77 1.8 is not available. I've Googled quite a bit for it. My source for 1.9 is . It gives me: open-watcom-f77-win32-1.9.exe. When I install, there are only choices: Custom, which presumably will ask a lot of questions, and some one shot do-it without any intervention. I took the latter. ..., XP, and no Win7? I use Win7. Trouble?? Something is amiss with my install. I downloaded 1.9. I did not use any customization. I can bring up the IDE easily. Using it is a different matter. The only Getting Started in F77 manual I can find is shown as v1.8. If 1.9 is needed, I can't find it. If I use the 1.8 manual, then the contents don't match up with what I find in the F77 IDE. For example, the manual talks about a Kitchen project on page 15. Not found anywhere in the install folder. From dannagle at verizon.net Mon Sep 5 12:22:51 2011 From: dannagle at verizon.net (Dan Nagle) Date: Mon, 5 Sep 2011 12:22:51 -0400 Subject: [OT] Anyone here familiar with installing Open Watcom F77? References: Message-ID: Hello, On 2011-09-05 16:15:20 +0000, W. eWatson said: > On 9/5/2011 8:24 AM, Chris Angelico wrote: >> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: >>> See Subject. >>> To what extent "familiar"? I have it installed on several computers, >> but only because it comes with Open Wat C/C++. >> >> With something off-topic like this, >> sierra_mtnview @ sbcglobal.net > Here's the story. > > As far as I can tell F77 1.8 is not available. I've Googled quite a > bit for it. My source for 1.9 is > . It gives me: > open-watcom-f77-win32-1.9.exe. On Usenet, comp.lang.fortran might be the best source of help for this. There's a good chance one of the regulars there can answer you within one or two posts. (I'll not cross-post, you can choose for yourself.) HTH -- Cheers! Dan Nagle From k.sahithi2862 at gmail.com Mon Sep 5 12:23:00 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Mon, 5 Sep 2011 09:23:00 -0700 (PDT) Subject: FOR FAST UPDATES IN TELUGU FILM INDUSTRY Message-ID: <9da5ae2b-4615-4bb6-bcd6-8b6ef68962bf@p37g2000prp.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From rantingrick at gmail.com Mon Sep 5 12:30:19 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 5 Sep 2011 09:30:19 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <0460d27a-ce73-40f5-a31a-6772eacb7784@l7g2000vbz.googlegroups.com> On Sep 5, 10:06?am, Martin De Kauwe wrote: > Hi, > > If I wanted to print an entire module, skipping the attributes > starting with "__" is there an *optimal* way? Currently I am doing > something like this. Note I am just using sys here to make the point > > import sys > > data = [] > for attr in sys.__dict__.keys(): > ? ? if not attr.startswith('__') and not attr.endswith('__'): > ? ? ? ? attr_val = getattr(sys, attr) > ? ? ? ? data.append((attr, attr_val)) > data.sort() > for i in data: > ? ? print "%s = %s" % (i[0], i[1]) > > Clearly this would be quicker if I didn't store it and sort the > output, i.e. > > for attr in sys.__dict__.keys(): > ? ? if not attr.startswith('__') and not attr.endswith('__'): > ? ? ? ? attr_val = getattr(sys, attr) > ? ? ? ? print "%s = %s" % (attr, attr_val) > > Anyway if there is a better way it would be useful to hear it... > > Many thanks, > > Martin Martin, have you considered that your custom function is just re- inventing the built-in dir() function? I would suggest using a list comprehension against the dir() function with a predicate to remove anything that startswith '_'. Here's some Ruby code to solve the problem. I'll let you figure out the Python equivalent. rb> ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'} ["whatsup"] From cjw at ncf.ca Mon Sep 5 12:36:59 2011 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 05 Sep 2011 12:36:59 -0400 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 05-Sep-11 12:22 PM, Dan Nagle wrote: > Hello, > > On 2011-09-05 16:15:20 +0000, W. eWatson said: > >> On 9/5/2011 8:24 AM, Chris Angelico wrote: >>> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson >>> wrote: >>>> See Subject. > > > >>>> To what extent "familiar"? I have it installed on several computers, >>> but only because it comes with Open Wat C/C++. >>> >>> With something off-topic like this, > > > >>> sierra_mtnview @ sbcglobal.net >> Here's the story. >> >> As far as I can tell F77 1.8 is not available. I've Googled quite a >> bit for it. My source for 1.9 is >> . It gives me: >> open-watcom-f77-win32-1.9.exe. > > On Usenet, comp.lang.fortran might be the best source of help for this. > There's a good chance one of the regulars there can answer you > within one or two posts. (I'll not cross-post, you can choose for > yourself.) > > HTH > You might get in touch with someone at Waterloo University, which is located in Kitchener/Waterloo. This could have come from the 60's or 70's. Good luck. Colin W. From tjreedy at udel.edu Mon Sep 5 13:38:08 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 13:38:08 -0400 Subject: Need help with simple OOP Python question In-Reply-To: <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: On 9/5/2011 9:15 AM, Kristofer Tengstr?m wrote: > Thanks everyone, moving the declaration to the class's __init__ method > did the trick. Now there's just one little problem left. I'm trying to > create a list that holds the parents for each instance in the > hierarchy. This is what my code looks like now: > > ----------------------------------------- > > class A: > def __init__(self, parents=None): > self.sub = dict() > if parents: > self.parents = parents > else: > self.parents = [] > def sub_add(self, cls): > hierarchy = self.parents > hierarchy.append(self) > obj = cls(hierarchy) > self.sub[obj.id] = obj Indexing objects by their internal id is usually useless. Considier whether you should be using sets rather than dicts. -- Terry Jan Reedy From noreply at domain.invalid Mon Sep 5 13:45:25 2011 From: noreply at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 13:45:25 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 9:13 AM, rusi wrote: > On Sep 3, 9:15 pm, William Gill wrote: >> During some recent research, and re-familiarization with Python, I came >> across documentation that suggests that programming using functions, and >> programming using objects were somehow opposing techniques. > > Staying with (for the moment) the suggestion that OO-P and F-P are > complementary, I believe it is worthwhile to distinguish syntactic OO- > P vs F-P from semantic OO-P vs F-P. > > Syntactically: f(x) is functional x.f() is object oriented. > Semantically if f's return value depends only on x ie does not depend > on state it is functional (in the math sense) -- the jargon is that f > is referentially transparent. Not to split hairs, but syntactically f(x) is a function in many programming paradigms. As I understand it functional programming places specific requirements on functions, i.e.referential transparency. So f(x) may or may not be "functional". x.f() is also a function, but it is a member of the object x, is referred to as a 'method' of x, and uses the syntactical "dot" notation object"dot"function for identification. > Referential opaqueness is usually such a source of problems that it > turns out good to contain the problem somewhat -- hence the wish for > encapsulation. > > One can find in the python library itself all 4 combinations: > syntactically and semantically OO : sort > syntactically and semantically FP: sorted > syntactically OO semantically FP: join From nospam at domain.invalid Mon Sep 5 14:58:29 2011 From: nospam at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 14:58:29 -0400 Subject: Functions vs OOP In-Reply-To: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 12:25 PM, Steven D'Aprano wrote: > William Gill wrote: > >> Are they suggesting that any function that takes an object as an >> argument should always be a method of that object? > > Yes. I can think of times when a special application, such as a converter, would take an object as an argument, but the somewhat unique nature of the application wouldn't justify changing the class to make the behavior into a method. I could extend the underlying class to include the new behavior (method), but that would mean existing instances of the base class would need conversion to the new class, requiring yet another method. Seems to me, that would be POOP (Puristic Object Oriented Programming) ;-) From jeanmichel at sequans.com Mon Sep 5 15:04:37 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 05 Sep 2011 21:04:37 +0200 Subject: Functions vs OOP In-Reply-To: References: Message-ID: <4E651D45.4020602@sequans.com> William Gill wrote: > > Not to split hairs, but syntactically f(x) is a function in many > programming paradigms. > > As I understand it functional programming places specific requirements > on functions, i.e.referential transparency. So f(x) may or may not be > "functional". > > x.f() is also a function, but it is a member of the object x, is > referred to as a 'method' of x, and uses the syntactical "dot" > notation object"dot"function for identification. > Functional programming is not about writing a programm with functions (google it for more info). This may cause some confusion. Your original post was about functions vs methods, which are identical except some syntax detail. FYI, in python x.f() is equivalent to f(x). In an OOP world one will prefer the x.f() form. JM From timr at probo.com Mon Sep 5 16:07:15 2011 From: timr at probo.com (Tim Roberts) Date: Mon, 05 Sep 2011 13:07:15 -0700 Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: Martin De Kauwe wrote: > >If I wanted to print an entire module, skipping the attributes >starting with "__" is there an *optimal* way? Your question is somewhat ambiguous. When I read "print an entire module", I assumed you were asking for a way to print the source code, perhaps with syntax coloring. Surely there is no reason to have an "optimal" method of doing this -- this is never going to be in an inner loop. If you have a method that works, there is little justification to optimize... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jredgrave at capisco.com Mon Sep 5 16:38:18 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Mon, 5 Sep 2011 13:38:18 -0700 (PDT) Subject: One line command line filter Message-ID: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> It seems unreasonably hard to write simple one-line unix command line filters in python: eg: ls | python -c " print x.upper()" to get at sys.stdin or similar needs an import, which makes a subsequent for-loop illegal. python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError Am I missing something obvious? The best I've come up with is to use sitecustomize.py to add to __builtin__ def stdin(): import sys for x in sys.stdin(): if not x: return yield x.strip() import __builtin__ __builtin__.stdin = stdin This allows ls | python -c "for x in stdin(): print x.upper()" Is there a better solution - if not is this worth a PEP? From t at jollybox.de Mon Sep 5 16:47:23 2011 From: t at jollybox.de (Thomas Jollans) Date: Mon, 05 Sep 2011 22:47:23 +0200 Subject: One line command line filter In-Reply-To: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4E65355B.8040503@jollybox.de> On 05/09/11 22:38, Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError > > Am I missing something obvious? ls | python -c "for line in __import__('sys').stdin: print (line.upper())" From jredgrave at capisco.com Mon Sep 5 17:32:08 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Mon, 5 Sep 2011 14:32:08 -0700 (PDT) Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> > > Am I missing something obvious? > > ls | python -c "for line in __import__('sys').stdin: print (line.upper())" Ah, so I am missing something - it is possible - but 'obvious'? Do people think it should be more accessible From pythonfiddle at gmail.com Mon Sep 5 18:00:36 2011 From: pythonfiddle at gmail.com (Python Fiddle Admin) Date: Mon, 5 Sep 2011 15:00:36 -0700 (PDT) Subject: Running Python Demo on the Web? Message-ID: Python has been ported to the web browser at pythonfiddle.com. Python Fiddle can import snippets of code that you are reading on a web page and run them in the browser. It supports a few popular libraries. Another common usage is to post code on the site to allow other people to play around with it. Also, it can be used to demonstrate a working program. From tjreedy at udel.edu Mon Sep 5 18:21:56 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 18:21:56 -0400 Subject: One line command line filter In-Reply-To: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: On 9/5/2011 4:38 PM, Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x"<<- SyntaxError > > Am I missing something obvious? The doc says "-c Execute the Python code in command. command can be one or more statements separated by newlines," However, I have no idea how to put newlines into a command-line string. Changing '; ' to '\n' does not work, at least not in Windows. The '\n' is passed on to Python as 2 chars, and the '\' is seen as the line-continuation char and the 'n' as illegal following it. Will a *nix shell 'cook' the string and convert '\n' to a literal newline before passing it to Python? For *nix, I would expect the <", line 1, in EOFError: EOF when reading a line Perhaps tolerable if Python is at the end of the pipe, not otherwise. > Is there a better solution - if not is this worth a PEP? PEPs have to propose a concrete solution, preferably with some previous discussion. I take is that your proposal would be to add another builtin means to access stdin. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 5 18:55:36 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 18:55:36 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/5/2011 1:45 PM, William Gill wrote: > On 9/4/2011 9:13 AM, rusi wrote: >> On Sep 3, 9:15 pm, William Gill wrote: >>> During some recent research, and re-familiarization with Python, I came >>> across documentation that suggests that programming using functions, and >>> programming using objects were somehow opposing techniques. >> >> Staying with (for the moment) the suggestion that OO-P and F-P are >> complementary, I believe it is worthwhile to distinguish syntactic OO- >> P vs F-P from semantic OO-P vs F-P. >> >> Syntactically: f(x) is functional x.f() is object oriented. >> Semantically if f's return value depends only on x ie does not depend >> on state it is functional (in the math sense) -- the jargon is that f >> is referentially transparent. > > Not to split hairs, but syntactically f(x) is a function in many > programming paradigms. > > As I understand it functional programming places specific requirements > on functions, i.e.referential transparency. So f(x) may or may not be > "functional". In Python, it may be a parameterized procedure. Some languages separate functions and procedures (also called subroutines). Python does not. (Or you could say that it makes procedures into functions with side-effects by returning None by default). > x.f() is also a function, but it is a member of the object x, is > referred to as a 'method' of x, and uses the syntactical "dot" notation > object"dot"function for identification. > >> Referential opaqueness is usually such a source of problems that it >> turns out good to contain the problem somewhat -- hence the wish for >> encapsulation. >> >> One can find in the python library itself all 4 combinations: >> syntactically and semantically OO : sort >> syntactically and semantically FP: sorted >> syntactically OO semantically FP: join > -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 5 19:02:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 19:02:04 -0400 Subject: One line command line filter In-Reply-To: <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> Message-ID: On 9/5/2011 5:32 PM, Jon Redgrave wrote: >>> Am I missing something obvious? >> >> ls | python -c "for line in __import__('sys').stdin: print (line.upper())" > > Ah, so I am missing something - it is possible - but 'obvious'? > Do people think it should be more accessible __import__ is well-documented and is listed in the index of the builtin functions chapter. "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime." could be explanded to include "or where you want to import as part of an expression" Every Python programmer should peruse that chapter to learn what is available for possible future use. -- Terry Jan Reedy From mdekauwe at gmail.com Mon Sep 5 19:02:41 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 16:02:41 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <9c0733c8-875b-425a-9021-5f22bf75d1a6@m4g2000pri.googlegroups.com> Hi, Tim yes I had a feeling my posting might be read as ambiguous! Sorry I was trying to quickly think of a good example. Essentially I have a set of .ini parameter files which I read into my program using configobj, I then replace the default module parameters if the user file is different (in my program). When it comes to writing the data back out I need to potentially loop over 5 module files and I need to ignore the superfluous information. My guess is that the way I am doing it might be a little on the slow side, hence the posting. Like you said it might be that the way I am doing it is "fine", I just wanted to see if there was a better way that is all. Rantingrick I did actually try the dir() to start with, I can't remember why I changed back. I will try your suggestion and see (thanks) So instead of sys as per my example my module more realistically looks like this: params.py apples = 12.0 cats = 14.0 dogs = 1.3 so my fuller example then import sys sys.path.append("/Users/mdekauwe/Desktop/") import params #params.py contains #apples = 12.0 #cats = 14.0 #dogs = 1.3 fname = "test.asc" try: ofile = open(fname, 'w') except IOError: raise IOError("Can't open %s file for write" % fname) data = [] for attr in params.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(params, attr) data.append((attr, attr_val)) data.sort() try: ofile.write("[params]\n") for i in data: ofile.write("%s = %s\n" % (i[0], i[1])) except IOError: raise IOError("Error writing params files, params section") etc, etc thanks From simoncropper at fossworkflowguides.com Mon Sep 5 19:09:17 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Tue, 06 Sep 2011 09:09:17 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> References: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> Message-ID: <4E65569D.9000603@fossworkflowguides.com> On 06/09/11 00:40, alex23 wrote: > On Sep 5, 3:18 pm, Simon Cropper > wrote: >> My investigations have generally found that windows/forms/data entry >> screen can be created for a specific table or view, but these are >> hard-wired during development. Is there anyway of rapidly defining the >> grid during runtime so any table can be viewed? > > The commercial product Resolver One provides a grid/spreadsheet style > interface with Python scripting capabilities. I'm not sure of its > current licensing status but I believe it used to be free if used on > open source projects. > > http://www.resolversystems.com/products/resolver-one/ > > Each spreadsheet itself is Python code; I think it should be quite do- > able to take something with introspective SQL capabilities like > SQLAlchemy and have it title columns and fill them with the correct > fields accordingly. > > Hope this helps. > > Alex, The Resolver Package looks good. Not exactly open source though. I equate it to a proprietary package that can at times be used for free by select groups. The product creates spreadsheets with python code in the background (instead of say VBA in Excel or Basic in Calc). Access to a database still needs to be hard-wired, so it does not act as a 'dynamic' viewer. The product works pretty much like Excel and Calc in this manner. Sheets can be shared, although the Resolver Exchange website does not clarify the licence under which samples are released (GPL, CC, etc), so it is debatable how any of this could reliably be used in creation of derivatives. From what I can glean from this page... http://www.resolversystems.com/opensource/ ... Resolver will allow you to use the package if you are an open source project to create spreadsheets that can be redistributed. For people to use these sheets they need to download the viewer or purchase the package. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From steve+comp.lang.python at pearwood.info Mon Sep 5 19:18:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:18:37 +1000 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > The doc says "-c > Execute the Python code in command. command can be one or more > statements separated by newlines," > > However, I have no idea how to put newlines into a command-line string. I imagine that it depends on the shell you are using, but bash on Linux makes it simple: double quotes "..." are like Python's triple-quoted strings in that they can include newlines. [steve at sylar python]$ ls f*.py | python -c "import sys > print sys.stdin.read()" factorial.py fetchqm.py fib.py fileutils.py findsingle.py fixascii.py fix.py frange.py frequencies.py Other shells may be different. -- Steven From mdekauwe at gmail.com Mon Sep 5 19:20:42 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 16:20:42 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> <9c0733c8-875b-425a-9021-5f22bf75d1a6@m4g2000pri.googlegroups.com> Message-ID: <5de6e076-f25a-4a44-ba9b-2c99ff006565@e20g2000prn.googlegroups.com> Trying to follow the suggestion this would be the alternate implementation. import sys sys.path.append("/Users/mdekauwe/Desktop/") import params #params.py contains #apples = 12.0 #cats = 14.0 #dogs = 1.3 fname = "test.asc" try: ofile = open(fname, 'w') except IOError: raise IOError("Can't open %s file for write" % fname) attributes = [attr for attr in dir(params) if not attr.startswith('__')] attributes.sort() try: ofile.write("[params]\n") for i in attributes: ofile.write("%s = %s\n" % (i, getattr(params, i))) except IOError: raise IOError("Error writing params files, params section") Is that a better version? I honestly don't know. thanks From steve+comp.lang.python at pearwood.info Mon Sep 5 19:29:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:29:00 +1000 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4e655b3e$0$29982$c3e8da3$5496439d@news.astraweb.com> Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" Python is neither bash nor Perl. It is not intended to compete in the "quick and dirty one-liner commands" stakes. However, you might like to consider ipython, which is intended as a complete Python shell, not just an interactive interpreter. http://ipython.org/ [...] > The best I've come up with is to use sitecustomize.py to add to > __builtin__ If you're a system administrator who wants to replace bash one-liners at the command line with Python one-liners, sure, why not? If you build up a useful collection of sys admin tools or recipes, you might like to consider sharing them. Perhaps if Python was used more by sys admins, there might be less resistance to making it easier to compete with bash one-liners. -- Steven From steve+comp.lang.python at pearwood.info Mon Sep 5 19:46:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:46:16 +1000 Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <4e655f4a$0$29965$c3e8da3$5496439d@news.astraweb.com> Tim Roberts wrote: > Martin De Kauwe wrote: >> >>If I wanted to print an entire module, skipping the attributes >>starting with "__" is there an *optimal* way? > > Your question is somewhat ambiguous. When I read "print an entire > module", I assumed you were asking for a way to print the source code, > perhaps with syntax coloring. > > Surely there is no reason to have an "optimal" method of doing this -- > this is never going to be in an inner loop. Regardless of an inner loop or not, the time required for IO (reading the file from disk, writing it to a printer) will be much larger than the time required to skip dunder (double-underscore) objects. > If you have a method that works, > there is little justification to optimize... Pretty much. HOWEVER, having agreed with you in general, in this specific case it is obvious to me from context that the OP doesn't want to print the source code of the module, but the module's names and their values. I'd try a couple of approaches: - use dir() or vars() to get the module's names, then loop and print each one; - make a shallow copy of the module __dict__, less dunder names, and pass it to the prettyprint module for printing. -- Steven From nospam at domain.invalid Mon Sep 5 20:30:47 2011 From: nospam at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 20:30:47 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/5/2011 3:04 PM, Jean-Michel Pichavant wrote: > William Gill wrote: >> >> Not to split hairs, but syntactically f(x) is a function in many >> programming paradigms. >> >> As I understand it functional programming places specific requirements >> on functions, i.e.referential transparency. So f(x) may or may not be >> "functional". >> >> x.f() is also a function, but it is a member of the object x, is >> referred to as a 'method' of x, and uses the syntactical "dot" >> notation object"dot"function for identification. >> > > Functional programming is not about writing a programm with functions > . This may cause some confusion. It can, and it did. That was the impression I (incorrectly) got from the documentation. Which didn't make sense to me. > (google it for more info). I can, and I did. That, and the answers I got in this ng are how I corrected my misconception. > > Your original post was about functions vs methods, which are identical > except some syntax detail. FYI, in python x.f() is equivalent to f(x). > In an OOP world one will prefer the x.f() form. > No, my original post was about how (based on the aforementioned misconception) the documentation seemed to suggest that OOP should never have free standing functions, only methods. From nospam at torek.net Mon Sep 5 21:10:40 2011 From: nospam at torek.net (Chris Torek) Date: 6 Sep 2011 01:10:40 GMT Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: >Chris Torek writes: >[snip] >> when you have [an] instance and call [an] instance or class method: [note: I have changed the names very slightly here, and removed additional arguments, on purpose] >> black_knight = K() >> black_knight.spam() >> black_knight.eggs() >> >> the first parameters ... are magic, and invisible. >> >> Thus, Python is using the "explicit is better than implicit" rule >> in the definition, but not at the call site. ... In article Piet van Oostrum wrote: >It *is* explicit also at the call site. It only is written at the left >of the dot rather than at the right of the parenthesis. It cannot possibly be explicit. The first parameter to one of the method functions is black_knight, but the first parameter to the other method is black_knight.__class__. Which one is which? Is spam() the instance method and eggs() the class method, or is spam() the class method and eggs the instance method? (One does not, and should not, have to *care*, which is kind of the point here. :-) ) >And that is necessary to locate which definition of the method >applies. By "that" I assume you mean the name "black_knight" here. But the name is not required to make the call; see the last line of the following code fragment: funclist = [] ... black_knight = K() funclist.append(black_knight.spam) funclist.append(black_knight.eggs) ... # At this point, let's say len(funclist) > 2, # and some number of funclist[i] entries are ordinary # functions that have no special first parameter. random.choice(funclist)() >It would be silly to repeat this information after the parenthesis. >Not only silly, it would be stupid as it would be a source of errors, >and an example of DRY. Indeed. But I believe the above is a demonstration of how the "self" or "cls" parameter is in fact implicit, not explicit. (I am using python 2.x, and doing this in the interpreter: random.choice(funclist) -- without the parentheses to call the function -- produces: > > The first is the instance method, whose name I am still keeping secret; the second is the class method; and the third is the ordinary function I added to the list. The actual functions print their own name and their parameters if any, and one can see that the class and instance methods get one parameter, and the ordinary function gets none.) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From tjreedy at udel.edu Mon Sep 5 21:25:44 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 21:25:44 -0400 Subject: One line command line filter In-Reply-To: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/5/2011 7:18 PM, Steven D'Aprano wrote: > Terry Reedy wrote: > >> The doc says "-c >> Execute the Python code in command. command can be one or more >> statements separated by newlines," >> >> However, I have no idea how to put newlines into a command-line string. > > I imagine that it depends on the shell you are using, but bash on Linux > makes it simple: double quotes "..." are like Python's triple-quoted > strings in that they can include newlines. > > [steve at sylar python]$ ls f*.py | python -c "import sys >> print sys.stdin.read()" > factorial.py > fetchqm.py I was guessing that whoever wrote the doc could do something like that. As far as I know, there is no way to escape a newline with Windows cmd.exe. (Someone please tell me if I am wrong!) An "unmatched" quote is either ignored or matched by the newline! C:\Programs\Python32> python -c "print('haha') haha -- Terry Jan Reedy From jabba.laci at gmail.com Mon Sep 5 21:36:46 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Mon, 5 Sep 2011 21:36:46 -0400 Subject: download pages using a cookies.txt file Message-ID: Hi, I would like to download a page that requires authentication with cookies. I've already figured out how to do it with wget (blog post here: http://bit.ly/pp25LP). In short: (1) extract cookies from Firefox's cookies.sqlite and store them in a text file (2) wget --cookies=on --load-cookies=cookies.txt --keep-session-cookies "http://..." My question is: how to do it from Python? If possible, I want to avoid making external calls to wget. Thanks, Laszlo From sahil at FreeBSD.org Mon Sep 5 21:45:02 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Mon, 5 Sep 2011 21:45:02 -0400 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: <20110906014502.GE254@magic.hamla.org> On Mon, 2011-09-05 at 21:36:46 -0400, Jabba Laci wrote: > I would like to download a page that requires authentication with > cookies. I've already figured out how to do it with wget (blog post > here: http://bit.ly/pp25LP). In short: > (1) extract cookies from Firefox's cookies.sqlite and store them in a text file > (2) wget --cookies=on --load-cookies=cookies.txt > --keep-session-cookies "http://..." > > My question is: how to do it from Python? If possible, I want to avoid > making external calls to wget. Have you already explored the cookielib (known as http.cookiejar in Python 3.0) module? -- Sahil Tandon From clp2 at rebertia.com Mon Sep 5 22:19:17 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 5 Sep 2011 19:19:17 -0700 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: On Mon, Sep 5, 2011 at 6:36 PM, Jabba Laci wrote: > Hi, > > I would like to download a page that requires authentication with > cookies. I've already figured out how to do it with wget (blog post > here: http://bit.ly/pp25LP). In short: > (1) extract cookies from Firefox's cookies.sqlite and store them in a text file > (2) wget --cookies=on --load-cookies=cookies.txt > --keep-session-cookies "http://..." > > My question is: how to do it from Python? http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar Cheers, Chris From rantingrick at gmail.com Mon Sep 5 23:58:30 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 5 Sep 2011 20:58:30 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <90128a68-1a3c-433a-8cf8-efa3b130d7ea@hb5g2000vbb.googlegroups.com> On Aug 31, 9:35?am, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. Welcome aboard mate! > But one of the things that bugs me Oh here we go! :-) > is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. It will will seem odd at first. I too hated typing all those "selfs" all the time. But believe me my new friend in no time those selfs will roll of your fingers with great ease. You'll forget how much you hate them and find much more to complain about. Like for instance: I really lament the missing redundancy of Explicit Lexical Scoping in python. For me global variables should have to be qualified. > For example, consider Python?s indent-sensitive syntax. ? > [...] > and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. Yes, forced indention is my favorite aspect of Python! > So why is 'self' necessary on class methods? It could be that Guido has a exaggerated self importance and just liked the sound of all those selfs whist reading source code. However i believe the real reason is really readability! It takes a while to understand this aspect because the natural human response is to be lazy (for instance i could have used "used to" in the previous sentence if i was slothful). We are all inherently lazy beings who need structure to keep us from spiraling out of control into the abyss of selfishness. GvR: Computer Scientist and Behavioral psychologist. From steve+comp.lang.python at pearwood.info Tue Sep 6 00:31:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 14:31:25 +1000 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e65a21e$0$29969$c3e8da3$5496439d@news.astraweb.com> On Tue, 6 Sep 2011 11:10 am Chris Torek wrote: >>> black_knight = K() >>> black_knight.spam() >>> black_knight.eggs() >>> >>> the first parameters ... are magic, and invisible. >>> >>> Thus, Python is using the "explicit is better than implicit" rule >>> in the definition, but not at the call site. ... > > In article > Piet van Oostrum wrote: >>It *is* explicit also at the call site. It only is written at the left >>of the dot rather than at the right of the parenthesis. > > It cannot possibly be explicit. The first parameter to one of the > method functions is black_knight, but the first parameter to the > other method is black_knight.__class__. I think you are expecting more explicitness than actually required. There are degrees of explicitness: - The current President of the United States is a black man. - On 6th September 2011, the duly constituted President of the United States of America is a black man. - On 6th September 2011, the duly constituted government official with the title of President of the nation known as the United States of America is an individual member of the species Homo sapiens with XY chromosomes and of recent African ancestry. As opposed to implicit: - He is a black guy. There is no requirement for every last gory detail to be overtly specified in full. I quote from WordNet: explicit adj 1: precisely and clearly expressed or readily observable; leaving nothing to implication; "explicit instructions"; "she made her wishes explicit"; "explicit sexual scenes" [syn: expressed] [ant: implicit] 2: in accordance with fact or the primary meaning of a term [syn: denotative] Note the second definition in particular: in accordance with the primary meaning of a term: the primary meaning of "class method" is that it receives the class rather than the instance as first argument. The "explicit is better than implicit" Zen should, in my opinion, be best understood as a recommendation that code should, in general, avoid getting input from context. In general, functions should avoid trying to decide which behaviour is wanted according to context or the environment: def func(x): if running_in_a_terminal(): print "The answer is", (x+1)/2 else: printer = find_a_printer() if printer is not None: printer.send((x+1)/2, header="func(%r)"%x, footer="Page 1") else: # Try sending email to the current user, the default user, # postmaster or root in that order. msg = make_email("The answer is", (x+1)/2) for user in [get_current_user(), DEFAULT_USER, "root at localhost.localdomain", ...]: result = send_mail(msg, to=user) if result == 0: break else: # Fall back on beeping the speakers in Morse code ... (what if I want to beep the speakers from the terminal?), but not as a prohibition against code like this: def factorial(x): # Return the factorial of the integer part of x. n = int(x) if n <= 1: return 1 return n*factorial(n-1) There's no need to require the user to explicitly call int(x) before calling factorial just to satisfy the Zen. A function is free to process arguments as required, even to throw out information (e.g. float -> int, instance -> class). What it shouldn't do is *add* information implied by context (or at least, it should be very cautious in doing so, and document it carefully, and preferably allow the caller to easily override such implied data). > Which one is which? Is spam() the instance method and eggs() the > class method, or is spam() the class method and eggs the instance > method? (One does not, and should not, have to *care*, which is > kind of the point here. :-) ) You can't tell just from the syntax used to call them: function(arg) bound_method(arg) builtin_function_or_method(arg) callable_instance(arg) type(arg) all use the same syntax. There is no requirement that you should be able to tell *everything* about a line of code just from the syntax used. If you want to know whether black_knight.spam is an instance method or a class method, or something else, use introspection to find out. > By "that" I assume you mean the name "black_knight" here. But the > name is not required to make the call; see the last line of the > following code fragment: > > funclist = [] > ... > black_knight = K() > funclist.append(black_knight.spam) > funclist.append(black_knight.eggs) > ... > # At this point, let's say len(funclist) > 2, > # and some number of funclist[i] entries are ordinary > # functions that have no special first parameter. > random.choice(funclist)() Irrelevant. The instance used for the bound method is explicitly specified when you create it. But there's no requirement that you need to explicitly specify the instance every single time you *use* the bound method. The instance is part of the bound method, it isn't implied by context or history or guessed from the environment. Contrast what Python actually does with a hypothetical language where bound methods' instances are implicitly assigned according to the most recent instance created: black_knight = Knight() funclist.append(spam) # refers to black_knight.spam white_knight = Knight() funclist.append(spam) # refers to white_knight.spam baldrick = Knave() funclist.append(eggs) # oops, Knaves don't have an eggs attribute -- Steven From haoxinfenshou98 at yahoo.com.cn Tue Sep 6 01:51:43 2011 From: haoxinfenshou98 at yahoo.com.cn (shoestrade) Date: Mon, 5 Sep 2011 22:51:43 -0700 (PDT) Subject: When it comes to the Air Force Message-ID: When it comes to the Air Force 1 {1}{/1}a lot of you might imagine that it would be quite hard to continue improving and innovating on the design of it, but leave it to Nike to surprise you at just about every turn. Those of you that know Nike?s reputation know that they always have new tricks hidden up their sleeves to keep t? We well know that the Nike Air Force 1{2}{/2} is one of the most versatile models that we have seen hosting a custom program called the Nike Bespoke. Since the last pair of Nike Harajuku customs plus a couple more designs done by different individuals, the AF1 has been off the scene. Yet no worries because it ishttp://www.jordanshoesoutletnet.com/ From xyzhtml at 163.com Tue Sep 6 01:57:31 2011 From: xyzhtml at 163.com (xyz) Date: Tue, 6 Sep 2011 13:57:31 +0800 Subject: Floating point multiplication in python Message-ID: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> hi all: As we know , 1.1 * 1.1 is 1.21 . But in python ,I got following : >>> 1.1 * 1.1 1.2100000000000002 why python get wrong result? Who can tell me where's the 0.0000000000000002 from? From clp2 at rebertia.com Tue Sep 6 02:18:30 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 5 Sep 2011 23:18:30 -0700 Subject: Floating point multiplication in python In-Reply-To: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: On Mon, Sep 5, 2011 at 10:57 PM, xyz wrote: > hi all: > > As we know , ?1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? It's not Python's fault per se, rather it's the inherent nature of binary floating-point arithmetic. Try the equivalent in most other languages and you'll get the same "error". Please read http://docs.python.org/tutorial/floatingpoint.html Cheers, Chris From jwiegley at gmail.com Tue Sep 6 02:51:17 2011 From: jwiegley at gmail.com (John Wiegley) Date: Tue, 06 Sep 2011 01:51:17 -0500 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: >>>>> Jon Redgrave writes: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > eg: ls | python -c " print x.upper()" [...] > Is there a better solution - if not is this worth a PEP? Have you looked at PyP (http://code.google.com/p/pyp)? John From gherron at islandtraining.com Tue Sep 6 03:00:39 2011 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 06 Sep 2011 00:00:39 -0700 Subject: Floating point multiplication in python In-Reply-To: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: <4E65C517.2080601@islandtraining.com> On 09/05/2011 10:57 PM, xyz wrote: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? Who can tell me where's the 0.0000000000000002 from? It's not a python error It's the nature of floating point arithmetic to be inaccurate on *ANY* computer. Python just allows you to see the inaccuracies. (But try: print 1.1*1.1 and see that the print statement does hide the roundoff error from you.) Read this for more info: http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate From steve+comp.lang.python at pearwood.info Tue Sep 6 03:11:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 17:11:10 +1000 Subject: Floating point multiplication in python References: Message-ID: <4e65c78f$0$29974$c3e8da3$5496439d@news.astraweb.com> On Tue, 6 Sep 2011 03:57 pm xyz wrote: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 The problem is that 1.1 is a *decimal* number, but computers use *binary*, and it is impossible to express 1.1 exactly as a binary number. So when you type 1.1 into nearly all computer languages, what you are actually getting is a tiny bit more than 1.1: >>> repr(1.1) '1.1000000000000001' which is the closest number to 1.1 that is possible using a C double floating point number. Normally you don't see it, because Python truncates the result when printing: >>> str(1.1) '1.1' but the difference is there. -- Steven From pierre.quentel at gmail.com Tue Sep 6 03:18:16 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Tue, 6 Sep 2011 00:18:16 -0700 (PDT) Subject: Relative seeks on string IO Message-ID: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Hi, I am wondering why relative seeks fail on string IO in Python 3.2 Example : from io import StringIO txt = StringIO('Favourite Worst Nightmare') txt.seek(8) # no problem with absolute seek but txt.seek(2,1) # 2 characters from current position raises "IOError: Can't do nonzero cur-relative seeks" (tested with Python3.2.2 on WindowsXP) A seek relative to the end of the string IO raises the same IOError However, it is not difficult to simulate a class that performs relative seeks on strings : ==================== class FakeIO: def __init__(self,value): self.value = value self.pos = 0 def read(self,nb=None): if nb is None: return self.value[self.pos:] else: return self.value[self.pos:self.pos+nb] def seek(self,offset,whence=0): if whence==0: self.pos = offset elif whence==1: # relative to current position self.pos += offset elif whence==2: # relative to end of string self.pos = len(self.value)+offset txt = FakeIO('Favourite Worst Nightmare') txt.seek(8) txt.seek(2,1) txt.seek(-8,2) ===================== Is there any reason why relative seeks on string IO are not allowed in Python3.2, or is it a bug that could be fixed in a next version ? - Pierre From __peter__ at web.de Tue Sep 6 03:53:07 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Sep 2011 09:53:07 +0200 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError > > Am I missing something obvious? > > The best I've come up with is to use sitecustomize.py to add to > __builtin__ > def stdin(): > import sys > for x in sys.stdin(): > if not x: return > yield x.strip() > import __builtin__ > __builtin__.stdin = stdin > > This allows > ls | python -c "for x in stdin(): print x.upper()" > > Is there a better solution - if not is this worth a PEP? $ touch alpha beta gamma omega $ ls | python -c 'import sys; sys.stdout.writelines(s.upper() for s in sys.stdin if s.startswith(("a", "o")))' ALPHA OMEGA If you are doing this a lot, why don't you write a helper script and invoke that? $ ls | pyfilter.py -f '"m" in line' -s 'lines = (line + line[::-1] for line in map(str.strip, lines))' -s'import re' -p 're.compile(r"(([a- z])\2)").sub(lambda m: m.group(1).upper(), line)' alphAAhpla betAAteb gaMMAAMMag omegAAgemo This relies on the convention that a single line of input is accessible as "line" and the complete input is called "lines". Of course the same can be done with python -c ..., -- and it is even more readable: $ ls | python -c 'import re, sys for line in sys.stdin: > line = line.strip() > line = line + line[::-1] > print re.compile(r"(([a-z])\2)").sub(lambda m: m.group(1).upper(), line) > ' alphAAhpla betAAteb gaMMAAMMag omegAAgemo > Is there a better solution - if not is this worth a PEP? The python interpreter could accept multiple -c arguments, but to see how this will be received a post on python-ideas should be sufficient. For the sake of completeness here's the script I used to produce the example above: $ cat pyfilter.py #!/usr/bin/env python import sys def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "-s", "--setup", action="append", default=[], dest="setups", metavar="SETUP") parser.add_argument( "-f", "--filter", action="append", default=[], dest="filters", metavar="FILTER") parser.add_argument("-p", "--print", dest="format") args = parser.parse_args() lines = sys.stdin for setup in args.setups: exec setup for line in lines: line = line.rstrip("\n") for filter in args.filters: if not eval(filter): continue if args.format: line = eval(args.format) try: print line except IOError as e: if e.errno == 32: # broken pipe break raise if __name__ == "__main__": main() From 1248283536 at qq.com Tue Sep 6 04:18:41 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 6 Sep 2011 16:18:41 +0800 Subject: strang thing: Message-ID: i found stange thing that i can't solve import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): print row[0], row[1], row[2], row[3],row[4], row[5], row[6] it's ok, when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) change the code into import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] the wrong output is : file = open(filename,'r') TypeError: 'str' object is not callable i don't know why?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Sep 6 04:22:37 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 6 Sep 2011 18:22:37 +1000 Subject: strang thing: In-Reply-To: References: Message-ID: 2011/9/6 ???? <1248283536 at qq.com>: > ??? file = open(filename,'r') > when i? add??? (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA From wolfgang at rohdewald.de Tue Sep 6 04:24:59 2011 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Tue, 6 Sep 2011 10:24:59 +0200 Subject: strang thing: In-Reply-To: References: Message-ID: <201109061024.59596.wolfgang@rohdewald.de> On Dienstag 06 September 2011, ???? wrote: > (date,open,high,low,close,vol,adjclose) = (row[0], > row[1], row[2], row[3],row[4], row[5], row[6]) print > row[0], row[1], row[2], row[3],row[4], row[5], row[6] > > > the wrong output is : > file = open(filename,'r') > TypeError: 'str' object is not callable you reassigned "open" to be a string -- Wolfgang From duncan.booth at invalid.invalid Tue Sep 6 04:30:53 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Sep 2011 08:30:53 GMT Subject: Floating point multiplication in python References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: Gary Herron wrote: > (But try: > print 1.1*1.1 > and see that the print statement does hide the roundoff error from you.) That varies according to the version of Python you are using. On my system: Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(1.1*1.1) 1.21 >>> ^Z C:\Python27>cd \python32 C:\Python32>python Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(1.1*1.1) 1.2100000000000002 -- Duncan Booth http://kupuguy.blogspot.com From k.sahithi2862 at gmail.com Tue Sep 6 05:20:38 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Tue, 6 Sep 2011 02:20:38 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From sinisa.segvic at fer.hr Tue Sep 6 05:59:07 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 02:59:07 -0700 (PDT) Subject: Portable locale usage Message-ID: Hi, I am musing on how to write portable Python3 code which would take advantage of the standard locale module. For instance, it would be very nice if we could say something like: # does not work! myISOCountryCode='hr' locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) Up to now, I have found ways to set locale on Linux and Windows: import locale locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # works on linux locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows I have noticed that locale defines a dictionary locale.locale_alias, and that it contains the following promising keys: 'hr_hr', 'hrvatski', 'hr'. Unfortunately, both on Windows and Linux all these keys are bound to the same outdated string 'hr_HR.ISO8859-2'. My questions are the following: 1. Is there a way for writing portable Python code dealing with locales (as sketched in the beginning)? 2. If not, is there anything wrong with that idea? 3. What is the status of locale.locale_alias (official documentation does not mention it)? Cheers, Sinisa http://www.zemris.fer.hr/~ssegvic/index_en.html From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Tue Sep 6 06:14:57 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Tue, 06 Sep 2011 12:14:57 +0200 Subject: Floating point multiplication in python In-Reply-To: References: Message-ID: Am 06.09.2011 07:57 schrieb xyz: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? Who can tell me where's the 0.0000000000000002 from? 1.1 does not fit in a binary floating point number. It is approximated - in binary! - as 1.000110011001100110011 ... (periodically). Note that, while in the decimal system we normally use, only numbers which have other components in the denominator than 2 or 5 are periodically, in the binary systems only components with 2 are allowed in order not to be periodically. Example: 3.453 is not periodically, because it is 3453/100 and 100 has only the factors 2 and 5, each twice. 1/3 = .3333333... is periodically, because it has the factor 3. The same applies to 1/6, which has 2 and 3 as factors. The latter destroys the non-periodical behaviour. As said, in the dual system, only the 2 is allowed. .5 (10) = 2** -1 = .1 (2). .25 (10) = 2 ** -2 = .01 (2). .75 (10) = their sum = .11 (2). But .1 (1/10) is more complicated, -2 would be as well. As the IEEE floating point representation is limited, there is a slight error value which makes the stored value differ from the intended one. Look here: >>> x=(1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1) >>> a=0 >>> for n,i in enumerate(x): a += i*2**-n; print a, a-1.1, i*2**-n, a-olda ... 1 -0.1 1 1 1.0 -0.1 0.0 0.0 1.0 -0.1 0.0 0.0 1.0 -0.1 0.0 0.0 1.0625 -0.0375 0.0625 0.0625 1.09375 -0.00625 0.03125 0.03125 1.09375 -0.00625 0.0 0.0 1.09375 -0.00625 0.0 0.0 1.09765625 -0.00234375 0.00390625 0.00390625 1.099609375 -0.000390625 0.001953125 0.001953125 1.099609375 -0.000390625 0.0 0.0 1.099609375 -0.000390625 0.0 0.0 1.09985351562 -0.000146484375 0.000244140625 0.000244140625 1.09997558594 -2.44140625001e-05 0.0001220703125 0.0001220703125 1.09997558594 -2.44140625001e-05 0.0 0.0 1.09997558594 -2.44140625001e-05 0.0 0.0 1.09999084473 -9.15527343759e-06 1.52587890625e-05 1.52587890625e-05 1.09999847412 -1.52587890634e-06 7.62939453125e-06 7.62939453125e-06 1.09999847412 -1.52587890634e-06 0.0 0.0 1.09999847412 -1.52587890634e-06 0.0 0.0 1.0999994278 -5.72204589933e-07 9.53674316406e-07 9.53674316406e-07 1.09999990463 -9.53674317294e-08 4.76837158203e-07 4.76837158203e-07 1.09999990463 -9.53674317294e-08 0.0 0.0 1.09999990463 -9.53674317294e-08 0.0 0.0 1.09999996424 -3.57627869541e-08 5.96046447754e-08 5.96046447754e-08 1.09999999404 -5.96046456636e-09 2.98023223877e-08 2.98023223877e-08 1.09999999404 -5.96046456636e-09 0.0 0.0 1.09999999404 -5.96046456636e-09 0.0 0.0 1.09999999776 -2.23517426789e-09 3.72529029846e-09 3.72529029846e-09 1.09999999963 -3.72529118664e-10 1.86264514923e-09 1.86264514923e-09 1.09999999963 -3.72529118664e-10 0.0 0.0 1.09999999963 -3.72529118664e-10 0.0 0.0 1.09999999986 -1.3969847501e-10 2.32830643654e-10 2.32830643654e-10 1.09999999998 -2.32831531832e-11 1.16415321827e-10 1.16415321827e-10 1.09999999998 -2.32831531832e-11 0.0 0.0 1.09999999998 -2.32831531832e-11 0.0 0.0 1.09999999999 -8.73123795486e-12 1.45519152284e-11 1.45519152284e-11 1.1 -1.45528034068e-12 7.27595761418e-12 7.27595761418e-12 1.1 -1.45528034068e-12 0.0 0.0 1.1 -1.45528034068e-12 0.0 0.0 1.1 -5.45785638906e-13 9.09494701773e-13 9.09494701773e-13 1.1 -9.10382880193e-14 4.54747350886e-13 4.54747350886e-13 1.1 -9.10382880193e-14 0.0 0.0 1.1 -9.10382880193e-14 0.0 0.0 1.1 -3.41948691585e-14 5.68434188608e-14 5.68434188608e-14 1.1 -5.77315972805e-15 2.84217094304e-14 2.84217094304e-14 1.1 -5.77315972805e-15 0.0 0.0 1.1 -5.77315972805e-15 0.0 0.0 1.1 -2.22044604925e-15 3.5527136788e-15 3.5527136788e-15 1.1 -4.4408920985e-16 1.7763568394e-15 1.7763568394e-15 1.1 -4.4408920985e-16 0.0 0.0 1.1 -4.4408920985e-16 0.0 0.0 1.1 -2.22044604925e-16 2.22044604925e-16 2.22044604925e-16 1.1 0.0 1.11022302463e-16 2.22044604925e-16 1.1 0.0 0.0 0.0 1.1 0.0 0.0 0.0 1.1 0.0 1.38777878078e-17 0.0 1.1 0.0 6.93889390391e-18 0.0 So here we have reached the point where the maximum precision is reached - a doesn't change anymore, although it should. The error is about 1E-16. Now if you multiply two values with an error, the error also propagates into the result - PLUs the result can have its own error source - in the same order of magnitude. (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e or (2*a + e) * e. From donstockbauer at hotmail.com Tue Sep 6 06:46:38 2011 From: donstockbauer at hotmail.com (Don Stockbauer) Date: Tue, 6 Sep 2011 03:46:38 -0700 (PDT) Subject: When it comes to the Air Force References: Message-ID: On Sep 6, 12:51?am, shoestrade wrote: > When it comes to the Air Force 1 {1}{/1}a lot of you might imagine > that it would be quite hard to continue improving and innovating on > the design of it, but leave it to Nike to surprise you at just about > every turn. Those of you that know Nike?s reputation know that they > always have new tricks hidden up their sleeves to keep t? > We well know that the Nike Air Force 1{2}{/2} is one of the most > versatile models that we have seen hosting a custom program called the > Nike Bespoke. Since the last pair of Nike Harajuku customs plus a > couple more designs done by different individuals, the AF1 has been > off the scene. Yet no worries because it ishttp://www.jordanshoesoutletnet.com/ But how does the Air Force relate to Skynet????? From hansmu at xs4all.nl Tue Sep 6 07:15:10 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 06 Sep 2011 13:15:10 +0200 Subject: One line command line filter In-Reply-To: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6600be$0$2480$e4fe514c@news2.news.xs4all.nl> On 6/09/11 01:18:37, Steven D'Aprano wrote: > Terry Reedy wrote: > >> The doc says "-c >> Execute the Python code in command. command can be one or more >> statements separated by newlines," >> >> However, I have no idea how to put newlines into a command-line string. > > I imagine that it depends on the shell you are using, but bash on Linux > makes it simple: double quotes "..." are like Python's triple-quoted > strings in that they can include newlines. Single quotes in bash are more similar to triple quotes in Python, in that some shell syntax is recognized within double quoted string, but not within single quoted strings: $ python -c 'import sys print `sys.version`' '2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. build 5664)]' $ python -c "import sys > print `sys.copyright`" -bash: sys.copyright: command not found When using single quotes, the `` are passed to Python, which interprets them as a call to repr(). With double quotes, the shell interprets `` as a sub-command. > Other shells may be different. Most *nix shells are similar to bash. The ones that are different are csh and tcsh: they require a backslash before each newline: $ tcsh % ls f*.py | python -c 'import sys \ ? print sys.stdin.read()' filecmp.py fileinput.py fnmatch.py formatter.py fpformat.py fractions.py ftplib.py functools.py % Sometimes you need two backslashes, one for csh and one for Python: % python -c 'print "spam spam spam spam spam spam spam spam " \\ ? "spam spam spam spam spam"' spam spam spam spam spam spam spam spam spam spam spam spam spam % Hope this helps, -- HansM From t at jollybox.de Tue Sep 6 07:16:50 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 06 Sep 2011 13:16:50 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: <4E660122.3000507@jollybox.de> On 06/09/11 11:59, ssegvic wrote: > Hi, > > I am musing on how to write portable Python3 code which would > take advantage of the standard locale module. > > For instance, it would be very nice if we could say something like: > > # does not work! Doesn't it? > myISOCountryCode='hr' This is a language code. (there also happens to be a country code 'hr', but you're referring to the Croatian language, 'hr') > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > locale.getpreferredencoding())) As far as I can tell, this does work. Can you show us a traceback? > Up to now, I have found ways to set locale on Linux and Windows: > > import locale > locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # works on linux > locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows > > I have noticed that locale defines a dictionary locale.locale_alias, > and that it contains the following promising keys: 'hr_hr', > 'hrvatski', 'hr'. > Unfortunately, both on Windows and Linux all these keys > are bound to the same outdated string 'hr_HR.ISO8859-2'. It looks like you don't actually care about the encoding: in your first example, you use the default system encoding, which you do not control, and in your second example, you're using two different encodings on the two platforms. So why do you care whether or not the default uses ISO 8859-2 ? > My questions are the following: > > 1. Is there a way for writing portable Python code dealing with > locales > (as sketched in the beginning)? > > 2. If not, is there anything wrong with that idea? As I said, I believe the above code should work. It works on my Linux system. What are you attempting to achieve with this setting of the locale, without even setting the encoding? Doesn't it make more sense to simply use the user's usual locale, and interact with them on their own terms? > 3. What is the status of locale.locale_alias (official documentation > does not mention it)? I don't know, but I'd assume it's not considered part of the public API, and you that shouldn't assume that it'll exist in future versions of Python. Thomas From bex.lewis at gmail.com Tue Sep 6 07:46:20 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 6 Sep 2011 04:46:20 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> Message-ID: On Sep 5, 3:51 pm, "Fokke Nauta" wrote: > > Hi Becky, > > I tried it straight away: > directory=D:\Webdav\ > directory=D:/Webdav/ > > Didn't work, in both cases the same error "fshandler:get_data: \Webdav not > found". > > I have the opinion that my WebDAV installation is at fault. The database is > not created either. > To have set up Python, I used python-2.7.2.msi. > To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both > Unix/Linux. > To install the, I used > " > > >> You dont install from "Python GUI", use normal cmd, navigate to the > >> folder > >> you downloaded PyXML and PyWebDAV and run "python setup.py install" > >> (python.exe has to be in your PATH). Then you have to find the > >> startup-script "davserver". Find your python installation directory and > >> look into/Tools/Scripts, in my computer this is > >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the > >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have > >> to > >> look for "davserver" there..." > > Shall I re?nstall the whole lot? Would it make a difference if in that case > I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi? > > Fokke You could try that but I'd imagine you'll end up with the same issue. My best guess is that something is preventing os.path.isdir from detecting the path as a directory under windows. I can't reproduce it on my Linux system but may have a working windows installation later. If I were you I'd fire up a python shell (execute python and get the >>> prompt), import os.path and manually try os.path.isdir(path_name) to try and find out what the actualy problem is. From santosh.dumbre at gmail.com Tue Sep 6 07:58:04 2011 From: santosh.dumbre at gmail.com (Santosh Dumbre) Date: Tue, 6 Sep 2011 17:28:04 +0530 Subject: Beginner's query - What is scope of Python for Embedded Programming(C, C++) ? Message-ID: Hi, Please consider a beginner's query - I am 9 -years experienced in C++. Currently working in Automation domain. Will Python help me to work in Automation/Embedded domain ? Your advice is highly appreciated. Please reply. Thanks a lot, Santosh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bex.lewis at gmail.com Tue Sep 6 08:01:33 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 6 Sep 2011 05:01:33 -0700 (PDT) Subject: Running Python Demo on the Web? References: Message-ID: On Sep 5, 11:00?pm, Python Fiddle Admin wrote: > Python has been ported to the web browser at pythonfiddle.com. Python > Fiddle can import snippets of code that you are reading on a web page > and run them in the browser. It supports a few popular libraries. > > Another common usage is to post code on the site to allow other people > to play around with it. Also, it can be used to demonstrate a working > program. Looks interesting but you don't appear to have support for most (any?) of the python core libs. Are you planning on adding more libraries? From cjw at ncf.ca Tue Sep 6 08:10:16 2011 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 06 Sep 2011 08:10:16 -0400 Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: On 05-Sep-11 18:00 PM, Python Fiddle Admin wrote: > Python has been ported to the web browser at pythonfiddle.com. Python > Fiddle can import snippets of code that you are reading on a web page > and run them in the browser. It supports a few popular libraries. > > Another common usage is to post code on the site to allow other people > to play around with it. Also, it can be used to demonstrate a working > program. A neat idea. import brian dir(brian) Responds "scipy not available" Colin W. From zdoor at xs4all.nl Tue Sep 6 08:42:39 2011 From: zdoor at xs4all.nl (Alex van der Spek) Date: Tue, 6 Sep 2011 08:42:39 -0400 Subject: HDF5 tree walker Message-ID: <4e661540$0$2439$e4fe514c@news2.news.xs4all.nl> Is there an equivalent to os.path.walk() for HDF5 file trees accessed through h5py? Thanks! Alex van der Spek From dreyemi at gmail.com Tue Sep 6 09:02:24 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 14:02:24 +0100 Subject: Python marks an instance of my class undefined Message-ID: Is there anything I need to do to create an instance of a class? I have this simple code(The class is in a package core.fleet): class Fleet(object): def __init__(self): """ no-arg constructor """ def fleet_file_upload(self, filename, type=None): if type == 'user': return 'photos/%Y/%m/%d' return 'images' def fleet_get_fleet(self): """ Get all fleet """ return db.db_get_fleet() def fleet_get_fleet_type(self): """ Get fleet by type or category """ For Python shell, I did this: >>> import core.fleet >>> f = Fleet() Traceback (most recent call last): File "", line 1, in NameError: name 'Fleet' is not defined What am I doing wrong? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Tue Sep 6 09:13:17 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 6 Sep 2011 15:13:17 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: 2011/9/6 ssegvic : > Hi, > > I am musing on how to write portable Python3 code which would > take advantage of the standard locale module. > > For instance, it would be very nice if we could say something like: > > # does not work! > myISOCountryCode='hr' > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > locale.getpreferredencoding())) > > Up to now, I have found ways to set locale on Linux and Windows: > > import locale > locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') ? ? ?# works on linux > locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows > > I have noticed that locale defines a dictionary locale.locale_alias, > and that it contains the following promising keys: 'hr_hr', > 'hrvatski', 'hr'. > Unfortunately, both on Windows and Linux all these keys > are bound to the same outdated string 'hr_HR.ISO8859-2'. > > My questions are the following: > > 1. Is there a way for writing portable Python code dealing with > locales > ? ?(as sketched in the beginning)? > > 2. If not, is there anything wrong with that idea? > > 3. What is the status of locale.locale_alias (official documentation > does not mention it)? > > > Cheers, > > Sinisa > > http://www.zemris.fer.hr/~ssegvic/index_en.html > -- > http://mail.python.org/mailman/listinfo/python-list > There may be some differences btween OSes end the versions, but using python 2.7 and 3.2 on Win XP and Win7 (Czech) I get the following results for setlocale: >>> locale.setlocale(locale.LC_ALL,'Croatian') 'Croatian_Croatia.1250' >>> locale.getlocale() ('Croatian_Croatia', '1250') >>> locale.getpreferredencoding(do_setlocale=False) 'cp1250' >>> However, "hr" is not recognised on this systems: >>> locale.setlocale(locale.LC_ALL, "hr") Traceback (most recent call last): File "", line 1, in File "locale.pyc", line 531, in setlocale Error: unsupported locale setting >>> regards, vbr From wxjmfauth at gmail.com Tue Sep 6 09:37:51 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 6 Sep 2011 06:37:51 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) Message-ID: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> This is just an attempt to put the http://groups.google.com/group/comp.lang.python/browse_thread/thread/a008af1ac2968833# discussion at a correct level. With Python 2.7 a new float number representation (the David Gay's algorithm) has been introduced. If this is well honored in Python 2.7, it seems to me, there are some missmatches in the Py3 series. >>> sys.version '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]' >>> 0.1 0.10000000000000001 >>> print 0.1 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> >>> sys.version 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] >>> >>> 0.1 0.1 >>> print 0.1 0.1 >>> 1.1 * 1.1 1.21 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> >>> sys.version '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]' >>> 0.1 0.1 >>> print(0.1) 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print(1.1 * 1.1) 1.21 >>> print(repr(1.1 * 1.1)) 1.2100000000000002 >>> '{:g}'.format(1.1 * 1.1) '1.21' >>> sys.version '3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' >>> 0.1 0.1 >>> print(0.1) 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print (1.1 * 1.1) 1.2100000000000002 >>> print(repr((1.1 * 1.1))) 1.2100000000000002 >>> >>> '{:g}'.format(1.1 * 1.1) '1.21' >>> jmf From dreyemi at gmail.com Tue Sep 6 09:42:54 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 14:42:54 +0100 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: I was able to get this solved by calling class like this: >>> from core.fleet import Fleet >>> f = Fleet() Thanks to a thread from the list titled "TypeError: 'module' object is not callable" On Tue, Sep 6, 2011 at 2:02 PM, Kayode Odeyemi wrote: > Is there anything I need to do to create an instance of a class? > > I have this simple code(The class is in a package core.fleet): > > class Fleet(object): > def __init__(self): > """ no-arg constructor """ > def fleet_file_upload(self, filename, type=None): > if type == 'user': > return 'photos/%Y/%m/%d' > return 'images' > > def fleet_get_fleet(self): > """ Get all fleet """ > return db.db_get_fleet() > > def fleet_get_fleet_type(self): > """ Get fleet by type or category """ > > For Python shell, I did this: > > >>> import core.fleet > >>> f = Fleet() > Traceback (most recent call last): > File "", line 1, in > NameError: name 'Fleet' is not defined > > What am I doing wrong? > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Tue Sep 6 10:18:32 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 06 Sep 2011 16:18:32 +0200 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: <4E662BB8.6050102@shopzeus.com> On 2011-09-06 15:42, Kayode Odeyemi wrote: > I was able to get this solved by calling class like this: > > >>> from core.fleet import Fleet > >>> f = Fleet() > > Thanks to a thread from the list titled "TypeError: 'module' object is > not callable" Or you can also do this: import core.fleet # import module core.fleet under the name core.fleet f = core.fleet.Fleet() Please note that the import statement imports the module with the given name. So for example import x.y.z will import the name "x.y.z". Anything that is in module "z" will be available through its module, that is "x.y.z". Whenever you use "import ", you have to access module contents through "". You can change the name: import core.fleet as c # import module core.fleet under the name c f = c.Fleet() From dreyemi at gmail.com Tue Sep 6 10:32:19 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 15:32:19 +0100 Subject: Python marks an instance of my class undefined In-Reply-To: <4E662BB8.6050102@shopzeus.com> References: <4E662BB8.6050102@shopzeus.com> Message-ID: On Tue, Sep 6, 2011 at 3:18 PM, Laszlo Nagy wrote: > On 2011-09-06 15:42, Kayode Odeyemi wrote: > >> I was able to get this solved by calling class like this: >> >> >>> from core.fleet import Fleet >> >>> f = Fleet() >> >> Thanks to a thread from the list titled "TypeError: 'module' object is not >> callable" >> > Or you can also do this: > > import core.fleet # import module core.fleet under the name core.fleet > f = core.fleet.Fleet() > > Please note that the import statement imports the module with the given > name. > > So for example > > import x.y.z > > will import the name "x.y.z". Anything that is in module "z" will be > available through its module, that is "x.y.z". > Whenever you use "import ", you have to access module contents > through "". > > You can change the name: > > import core.fleet as c # import module core.fleet under the name c > f = c.Fleet() > > That is, import [package-name] .[class-name] If using from, that can take the form of [package-name].[pymodule] import [pymodule] or [class-name] I just got to understand it. Thanks. This explanation really simplifies it further. Can I do: from [pymodule] import [class-name], assuming the pymodule as a class instance? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From fnautaNO at SPAMsolfon.nl Tue Sep 6 10:46:17 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Tue, 6 Sep 2011 16:46:17 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> Message-ID: <9cmq1vFk6fU1@mid.individual.net> "becky_lewis" wrote in message news:f5b9ec16-de9a-4365-81a8-860dc27a985e at d25g2000yqh.googlegroups.com... On Sep 5, 3:51 pm, "Fokke Nauta" wrote: > > Hi Becky, > > I tried it straight away: > directory=D:\Webdav\ > directory=D:/Webdav/ > > Didn't work, in both cases the same error "fshandler:get_data: \Webdav not > found". > > I have the opinion that my WebDAV installation is at fault. The database > is > not created either. > To have set up Python, I used python-2.7.2.msi. > To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both > Unix/Linux. > To install the, I used > " > > >> You dont install from "Python GUI", use normal cmd, navigate to the > >> folder > >> you downloaded PyXML and PyWebDAV and run "python setup.py install" > >> (python.exe has to be in your PATH). Then you have to find the > >> startup-script "davserver". Find your python installation directory and > >> look into/Tools/Scripts, in my computer this is > >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the > >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have > >> to > >> look for "davserver" there..." > > Shall I re?nstall the whole lot? Would it make a difference if in that > case > I would use ActivePython-2.7.2.5-win32-x86.msi instead of > python-2.7.2.msi? > > Fokke You could try that but I'd imagine you'll end up with the same issue. My best guess is that something is preventing os.path.isdir from detecting the path as a directory under windows. I can't reproduce it on my Linux system but may have a working windows installation later. If I were you I'd fire up a python shell (execute python and get the >>> prompt), import os.path and manually try os.path.isdir(path_name) to try and find out what the actualy problem is. I'm not familiar with Python, but I entered "import os.path " (nothing happened) and "os.path.isdir(path_name) " in the shell. I guess what I did was not correct. Underneath I copied what showed up in the shell. ------------------------------------------- Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import os.path >>> os.path.isdir(path_name) Traceback (most recent call last): File "", line 1, in os.path.isdir(path_name) NameError: name 'path_name' is not defined >>> ------------------------------------------- Fokke From sinisa.segvic at fer.hr Tue Sep 6 10:46:46 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 07:46:46 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> On 6 ruj, 13:16, Thomas Jollans wrote: > > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > > locale.getpreferredencoding())) > > As far as I can tell, this does work. Can you show us a traceback? Sorry, I was imprecise. I wanted to say that the above snippet does not work both on Windows and Linux. This is what I get on Windows: >>> import sys >>> sys.version '3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]' >>> myISOCountryCode='hr' >>> locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) Traceback (most recent call last): File "", line 1, in locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) File "C:\apps\Python32\lib\locale.py", line 538, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting The snippet actually works on Linux, as you note. > It looks like you don't actually care about the encoding: in your first > example, you use the default system encoding, which you do not control, > and in your second example, you're using two different encodings on the > two platforms. That's true. That's because currently I care most about lists of strings being sorted properly (see below). Nevertheless, it *appears* to me that, in the Unicode era, the locales could well be decoupled from particular encodings. But this is another topic. > So why do you care whether or not the default uses ISO 8859-2 ? It's not that I care about encoding, it's that Windows throws locale.Error at me :-) > > My questions are the following: > > > 1. Is there a way for writing portable Python code dealing with > > locales > > ? ? (as sketched in the beginning)? > > > 2. If not, is there anything wrong with that idea? > > As I said, I believe the above code should work. It works on my Linux > system. > > What are you attempting to achieve with this setting of the locale, > without even setting the encoding? Doesn't it make more sense to simply > use the user's usual locale, and interact with them on their own terms? For the moment, I only wish to properly sort a Croatian text file both on Windows and Linux (I am a cautious guy, I like reachable goals). When the locale is properly set, sorting works like a charm with mylist.sort(key=locale.strxfrm). My current solution to the portability problem is: import locale try: locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # linux except locale.Error: locale.setlocale(locale.LC_ALL, 'Croatian_Croatia.1250') # windows Thanks for your feedback! Sinisa From hansmu at xs4all.nl Tue Sep 6 11:12:59 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 06 Sep 2011 17:12:59 +0200 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: <4e66387b$0$2499$e4fe514c@news2.news.xs4all.nl> On 6/09/11 16:18:32, Laszlo Nagy wrote: > On 2011-09-06 15:42, Kayode Odeyemi wrote: >> I was able to get this solved by calling class like this: >> >> >>> from core.fleet import Fleet >> >>> f = Fleet() >> >> Thanks to a thread from the list titled "TypeError: 'module' object is >> not callable" > Or you can also do this: > > import core.fleet # import module core.fleet under the name core.fleet > f = core.fleet.Fleet() > > Please note that the import statement imports the module with the given > name. > > So for example > > import x.y.z > > will import the name "x.y.z". Anything that is in module "z" will be > available through its module, that is "x.y.z". > Whenever you use "import ", you have to access module contents > through "". > > You can change the name: > > import core.fleet as c # import module core.fleet under the name c > f = c.Fleet() An import statement always imports a module, but Python also has the from...import statement to import one item from a module: from core.fleet import Fleet f = Fleet() The convention is to use the name "Fleet" (with an initial capital) for the class and "fleet" (all lower case) for the module. This makes it easier to not confuse the class and the module. Hope this helps, -- HansM From sinisa.segvic at fer.hr Tue Sep 6 11:31:59 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 08:31:59 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <13b9a70f-9e40-43a3-8198-0d84c8484fb8@z18g2000yqb.googlegroups.com> On 6 ruj, 15:13, Vlastimil Brom wrote: > There may be some differences btween OSes end the versions, but using > python 2.7 and 3.2 on Win XP and Win7 (Czech) > I get the following results for setlocale: > > >>> locale.setlocale(locale.LC_ALL,'Croatian') > > 'Croatian_Croatia.1250'>>> locale.getlocale() > > ('Croatian_Croatia', '1250') > > >>> locale.getpreferredencoding(do_setlocale=False) > 'cp1250' > > However, "hr" is not recognised on this systems: > > >>> locale.setlocale(locale.LC_ALL, "hr") > > Traceback (most recent call last): > ? File "", line 1, in > ? File "locale.pyc", line 531, in setlocale > Error: unsupported locale setting Thanks for your feedback! So this works only on Linux (in concordance with the documentation): locale.setlocale(locale.LC_ALL, ('croatian', locale.getpreferredencoding())) And this works only on Windows (incomplete locale spec probably filled in by Windows API): locale.setlocale(locale.LC_ALL, 'croatian') Obviously, there is a misunderstanding between Python which uses standard (IANA) language codes and Windows which, as usual, have their own ways :-( One possible solution would be to change locale.locale_alias on Windows so that it honors the custom Windows conventions: 'hr' -> 'Croatian_Croatia.1250' instead of 'hr' -> 'hr_HR.ISO8859-2' In addition, locale.getpreferredencoding() should probably be changed in order to return valid Windows encodings ('1250' instead of 'cp1250'). Cheers, Sinisa From t at jollybox.de Tue Sep 6 11:53:37 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 06 Sep 2011 17:53:37 +0200 Subject: Portable locale usage In-Reply-To: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <4E664201.1010806@jollybox.de> On 06/09/11 16:46, ssegvic wrote: > For the moment, I only wish to properly sort a Croatian text file > both on Windows and Linux (I am a cautious guy, I like reachable > goals). > When the locale is properly set, sorting works like a charm > with mylist.sort(key=locale.strxfrm). The problem with that is of course that a Croatian locale has to be installed. Many Linux systems don't have locales that aren't used. From PointedEars at web.de Tue Sep 6 12:07:42 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 06 Sep 2011 18:07:42 +0200 Subject: Floating point multiplication in python References: Message-ID: <2204592.egLE2XKegd@PointedEars.de> Thomas Rachel wrote: > Now if you multiply two values with an error, the error also propagates > into the result - PLUs the result can have its own error source - in the > same order of magnitude. > > (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e > or (2*a + e) * e. Your explanation about floating-point precision, which I already knew about but have only scanned here ? so it might be flawed as well ?, notwithstanding, it is not clear to me at all what you are trying to prove there. Computers (well, perhaps outside of mathematical software) do NOT compute an equation as humans would do, so the binomial theorem does NOT apply. In an algorithm of the real implementation, (a + e) * (a + e) would be computed as follows: b := a + e c := b * b or c := b + ? + b [add the value of `b' to the value of `b' (b?1) times, since binary logic does not support multiplication] IOW, the error does propagate into the result indeed, but not as you described. Indeed, thanks to rounding on assignment and multiplication (i. e., setting register values or IEEE-754 floating-point mantissa and exponent), the error will be different, probably greater than you compute here. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From josepharmbruster at gmail.com Tue Sep 6 12:17:19 2011 From: josepharmbruster at gmail.com (Joseph Armbruster) Date: Tue, 6 Sep 2011 12:17:19 -0400 Subject: PEP 20 - Silly Question? Message-ID: I have used Python for some time and ran a windows build-bot for a bit. This morning, I told a fellow developer "There should be only one obvious way to do it." and then I proceeded to forward him to the Zen of Python and sent him a link to: http://www.python.org/dev/peps/pep-0020/ I noticed that it says only 19 of 20 have been written down. Which one was not written down? Thank You, Joseph Armbruster -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericsnowcurrently at gmail.com Tue Sep 6 12:26:05 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Tue, 6 Sep 2011 10:26:05 -0600 Subject: PEP 20 - Silly Question? In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 10:17 AM, Joseph Armbruster wrote: > I have used Python for some time and ran a windows build-bot for a bit. > ?This morning, I told a fellow developer "There should be only one obvious > way to do it." and then I proceeded to forward him to the Zen of Python and > sent him a link to: > http://www.python.org/dev/peps/pep-0020/ > I noticed that it says only 19 of 20 have been written down. ?Which one was > not written down? I'm not sure there ever was a 20th. Apparently Tim Peters was going to leave the last one for Guido to fill in: http://mail.python.org/pipermail/python-list/1999-June/616160.html (from http://www.wefearchange.org/2010/06/import-this-and-zen-of-python.html) -eric > Thank You, > Joseph Armbruster > > -- > http://mail.python.org/mailman/listinfo/python-list > > From schesis at gmail.com Tue Sep 6 12:27:27 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 6 Sep 2011 12:27:27 -0400 Subject: PEP 20 - Silly Question? In-Reply-To: References: Message-ID: : On 6 September 2011 12:17, Joseph Armbruster wrote: > I noticed that it says only 19 of 20 have been written down. ?Which one was > not written down? The last one. -[]z. From __peter__ at web.de Tue Sep 6 12:54:42 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Sep 2011 18:54:42 +0200 Subject: PEP 20 - Silly Question? References: Message-ID: Joseph Armbruster wrote: > I have used Python for some time and ran a windows build-bot for a bit. > This morning, I told a fellow developer "There should be only one obvious > way to do it." and then I proceeded to forward him to the Zen of Python > and sent him a link to: > http://www.python.org/dev/peps/pep-0020/ > > I noticed that it says only 19 of 20 have been written down. Which one > was not written down? Whoever offers a $1 billion sponsorship to the PSF gets to decide that one. Expect something like "Keep your baby real dry with black whole diapers". From Tim.Arnold at sas.com Tue Sep 6 13:18:07 2011 From: Tim.Arnold at sas.com (Tim Arnold) Date: Tue, 06 Sep 2011 13:18:07 -0400 Subject: sqlite3 with context manager In-Reply-To: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> References: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/3/2011 3:03 AM, Carl Banks wrote: > On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote: >> Hi, >> I'm using the 'with' context manager for a sqlite3 connection: >> >> with sqlite3.connect(my.database,timeout=10) as conn: >> conn.execute('update config_build set datetime=?,result=? >> where id=?', >> (datetime.datetime.now(), success, >> self.b['id'])) >> >> my question is what happens if the update fails? Shouldn't it throw an >> exception? > > If you look at the sqlite3 syntax documentation, you'll see it has a SQL extension that allows you to specify error semantics. It looks something like this: > > UPDATE OR IGNORE > UPDATE OR FAIL > UPDATE OR ROLLBACK > > I'm not sure exactly how this interacts with pysqlite3, but using one of these might help it throw exceptions when you want it to. > > > Carl Banks I see now. You can use 'update or fail' if you have the extensions built in: http://docs.python.org/library/sqlite3.html#f1 example of use, line 76: http://projects.developer.nokia.com/TECwidget/browser/data/montreal/updsqlite.py?rev=7ca2ebd301ed1eff0e2c28283470db060b872cd6 For my case, however, I'll follow Ian's advice and check on the rowcount after the update. thanks for the explanation and advice, --Tim From xnews2 at fredp.lautre.net Tue Sep 6 14:27:41 2011 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 06 Sep 2011 18:27:41 GMT Subject: Advice on how to get started with 2D-plotting ? Message-ID: Hi, I'm a Python long-timer, but I've never had to use tools like Matplotlib & others before. Now, for my work, I would need to learn the basics fast, for a one-time quick-n-dirty job. This involves a graphic comparison of RFC1918 IP subnets allocation across several networks. The idea is to draw parallel lines, with segments (subnets) coloured green, yellow or red depending on the conflicts between the networks. What would be the simplest/fastest way of getting this done ? (the graphic parts, the IP stuff I know how to handle) Alternately, if someone knows of a ready-made and accessible tool that does just that, I'm all ears :-) TIA, fp From fnautaNO at SPAMsolfon.nl Tue Sep 6 15:26:12 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Tue, 6 Sep 2011 21:26:12 +0200 Subject: Installing WebDAV server References: <9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net> Message-ID: <9cnaekF5nfU1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.809.1315328739.27778.python-list at python.org... > On Tue, 6 Sep 2011 16:46:17 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > > >> ------------------------------------------- >> Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] >> on >> win32 >> Type "copyright", "credits" or "license()" for more information. >> >>> import os.path >> >>> os.path.isdir(path_name) >> >> Traceback (most recent call last): >> File "", line 1, in >> os.path.isdir(path_name) >> NameError: name 'path_name' is not defined >> >>> >> ------------------------------------------- >> > "path_name" is a placeholder -- you're supposed to put in the exact > string(s) you have been trying in the configuration file (wrap the > string in quotes). > >>>> import os.path >>>> os.path.isdir("e:\webdav") > False >>>> os.mkdir("e:\webdav") >>>> os.path.isdir("e:\webdav") > True >>>> os.path.isdir("e:\webdav\\") > Traceback ( File "", line 1 > os.path.isdir("e:\webdav\") > ^ > SyntaxError: EOL while scanning single-quoted string >>>> os.path.isdir("e:\webdav\\") > True >>>> os.path.isdir("e:\webdav/") > True >>>> os.path.isdir("e:/webdav/") > True >>>> os.path.isdir("e:/webdav") > True >>>> os.rmdir("e:/webdav") >>>> os.path.isdir("e:\webdav") > False >>>> > > Note that Python itself (and the C-runtime) doesn't care if the > separator is \ or / or even mixed; it is just the Windows command line > that uses \ for separator and / for options. (Python, however, uses \ as > an escape and \" is treated first, hence the need for \\" to escape the > \ itself) Thanks, this is clear. This is my Python shell: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import os.path >>> os.path.isdir("d:\webdav") True >>> So Python recognizes the directory d:\webdav This is the command shell: D:\Python27\WebDAV\PyWebDAV\DAVServer>server.py -n -c config.ini INFO:pywebdav:Starting up PyWebDAV server INFO:pywebdav:chunked_http_response feature ON INFO:pywebdav:http_request_use_iterator feature OFF INFO:pywebdav :http_response_use_iterator feature OFF INFO:fshandler:Initialized with D:/Webdav-http://10.0.0.140:8081/ WARNING:pywebdav:Authentication disabled! INFO:pywebdav:Serving data from D:/Webdav Listening on 10.0.0.140 <8081> (here I try to login the WebDAV server with the local IE browser) INFO:fshandler :get_data: D:\Webdav not found server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; Windows N T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; Windows N T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - So - I'm a bit lost now. Thinking seriously that my webdav installation is at fault. Fokke From bkasterm at gmail.com Tue Sep 6 16:15:03 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 14:15:03 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> Message-ID: <87obyx4ed4.fsf@gmail.com> I build on the suggestion by rantingrick, but took it in a bit different direction. I now have working code that performs reasonable. The reason for the class lines (as opposed to just a function) is b/c font.measure appears not that fast. So I want to remember between different calls to lines.count where the cutoff was, and then start looking from there. This one step of "optimization" was enough to make it run reasonable on my system. There are one important thing skipped, Tkinter.Label takes whitespace into account. This code does not yet. Also I just hacked this together as an example solution to work further from. import Tkinter as Tk import tkFont import random import sys def genstr (j): rno = random.randint(4,50) ret_val = str(j) + ":" for i in range (0, rno): ret_val += "hello" + str(i) return ret_val def gendata (lh): ret_val = [] for i in range(0,lh): ret_val.append (genstr (i)) return ret_val data = gendata (100) root = Tk.Tk() font = tkFont.Font(family='times', size=13) class lines: def __init__ (self): self.lastct = 1 # remember where the cutoff was last work from there def count (self, text, cutoff = 400): global font no_lines = 1 start_idx = 0 idx = self.lastct while True: if idx > len (text): idx = len (text) # shrink from guessed value while font.measure (text[start_idx:idx - 1]) > cutoff: if idx <= start_idx: print "error" sys.exit () else: idx -= 1 self.lastct = idx - start_idx # adjust since was too big # increase from guessed value (note: if first shrunk then done) while (idx < len (text) and font.measure (text[start_idx:idx]) < cutoff): idx += 1 self.lastct = idx - start_idx # adjust since was too small # next line has been determined print "*" + text[start_idx:idx-1] + "*" if idx == len(text) and font.measure (text[start_idx:]) < cutoff: return no_lines elif idx == len(text): return no_lines + 1 else: no_lines += 1 start_idx = idx - 1 idx = start_idx + self.lastct lin = lines() # for testing speed compute for all data for i in range(0,len(data)): lin.count(data[i], 450) # show only first 10 for i in range(0,min(len(data),10)): l = Tk.Label(root) l.pack() l['text'] = data[i] print i no = lin.count (data[i], 450) print "computed lines", no l['width'] = 50 l['justify'] = Tk.LEFT l['anchor'] = 'w' l['wraplength'] = 450 l['padx']=10 l['pady'] = 5 l['height'] = no l['font'] = font if i % 2 == 0: l['background'] = 'grey80' else: l['background'] = 'grey70' root.mainloop() From tjreedy at udel.edu Tue Sep 6 16:49:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 06 Sep 2011 16:49:19 -0400 Subject: Relative seeks on string IO In-Reply-To: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> References: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Message-ID: On 9/6/2011 3:18 AM, Pierre Quentel wrote: > I am wondering why relative seeks fail on string IO in Python 3.2 Good question. > from io import StringIO > txt = StringIO('Favourite Worst Nightmare') > txt.seek(8) # no problem with absolute seek Please post code without non-code indents, like so: from io import StringIO txt = StringIO('Favourite Worst Nightmare') txt.seek(8,0) # no problem with absolute seek txt.seek(0,1) # 0 characters from current position ok, and useless txt.seek(-2,2) # end-relative gives error message for cur-relative so someone can copy and paste without deleting indents. I verified with 3.2.2 on Win7. I am curious what 2.7 and 3.1 do. What system are you using? Does it have a narrow or wide unicode build? (IE, what is the value of sys.maxunicode?) > txt.seek(2,1) # 2 characters from current position > > raises "IOError: Can't do nonzero cur-relative seeks" (tested with > Python3.2.2 on WindowsXP) > > A seek relative to the end of the string IO raises the same IOError > Is there any reason why relative seeks on string IO are not allowed in > Python3.2, or is it a bug that could be fixed in a next version ? Since StringIO seeks by fixed-size code units (depending on the build), making seeking from the current position and end trivial, I consider this a behavior bug. At minimum, it is a doc bug. I opened http://bugs.python.org/issue12922 As noted there, I suspect the limitation in inherited from TextIOBase. But I challenge that it should be. I was somewhat surprised that seeking (from the start) is not limited to the existing text. Seeking past the end fills in with nulls. (They are typically a nuisance though.) from io import StringIO txt = StringIO('0123456789') txt.seek(15,0) # no problem with absolute seek txt.write('xxx') s = txt.getvalue() print(ord(s[12])) # 0 -- Terry Jan Reedy From garabik-news-2005-05 at kassiopeia.juls.savba.sk Tue Sep 6 16:58:09 2011 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Tue, 6 Sep 2011 20:58:09 +0000 (UTC) Subject: Portable locale usage References: Message-ID: Thomas Jollans wrote: > It looks like you don't actually care about the encoding: in your first > example, you use the default system encoding, which you do not control, > and in your second example, you're using two different encodings on the > two platforms. So why do you care whether or not the default uses ISO > 8859-2 ? > Maybe because using 8859-2 locale, (unicode) strings not representable in the encodings will be sorted - how? I would care, I prefer not to have undefined behaviour. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From rantingrick at gmail.com Tue Sep 6 16:59:41 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 13:59:41 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: <27d7b2a8-1a24-4066-b603-13c935c42af1@fd21g2000vbb.googlegroups.com> On Sep 6, 1:27?pm, Fred Pacquier wrote: > I'm a Python long-timer, but I've never had to use tools like Matplotlib & > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. ################## ## START SCRIPT ## ################## # # Easy_as.py # import Tkinter as tk # Create a main window and a canvas. app = tk.Tk() can = tk.Canvas( app, width=500, height=500, #bd=1, #relief=tk.SOLID, ) can.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) # Create some gridlines on the canvas. W,H = 500, 500 row, col = 0,0 for _ in range(10): can.create_line(0, row, W, row, fill='red') print 0, row, W, row can.create_line(col, 0, col, H, fill='green') row += 50 col += 50 can.create_line( 0,500,300,300, 350,200,400,450, fill='magenta', width=5, ) # Start the event loop. app.mainloop() ################ ## END SCRIPT ## ################ Any questions? From rantingrick at gmail.com Tue Sep 6 17:23:50 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 14:23:50 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> Message-ID: <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Hmm, i can replace all that code with this... # # Easy_as.py # import Tkinter as tk from ScrolledText import ScrolledText import tkFont import random # Create some puesdo data. data = [ '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) for x in range(100) ] ##print data # Create the main window and a scrolled text widget. root = tk.Tk() font = tkFont.Font(family='times', size=13) textbox = ScrolledText( root, width=60, height=20, font=('Times', 10), wrap=tk.WORD, ) textbox.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) textbox.insert(1.0, '\n\n'.join(data)) # Start the event loop. root.mainloop() # # End # From jabba.laci at gmail.com Tue Sep 6 17:25:32 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Tue, 6 Sep 2011 17:25:32 -0400 Subject: import os or import os.path Message-ID: Hi, If I want to use the 'os.path' module, it's enought to import 'os': import os if os.path.isfile('/usr/bin/bash'): print 'got it' In other source codes I noticed that people write 'import os.path' in this case. Which is better practice? Thanks, Laszlo From rantingrick at gmail.com Tue Sep 6 17:37:57 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 14:37:57 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Message-ID: Or if you prefer the alternating background approach... ################## # Easy_as.py ################## import Tkinter as tk from ScrolledText import ScrolledText import tkFont import random END = 'end' INSERT = 'insert' # # Create some puesdo data. data = [ '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) for x in range(100) ] ##print data # # Create the main window and a scrolled text widget. root = tk.Tk() font = tkFont.Font(family='times', size=13) textbox = ScrolledText( root, width=60, height=20, font=('Times', 10), wrap=tk.WORD, ) textbox.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) # # Add a tag to the very end of the widget and # configure the tag only once! textbox.tag_add('one', END) textbox.tag_config('one', background='gray') # # Iterate over the lines stuffing them into the textbox. idata = iter(data) sidx = 1.0 while True: try: textbox.insert(END, idata.next()+"\n") textbox.tag_add('one', sidx, INSERT) textbox.insert(END, idata.next()+"\n") print sidx, textbox.index(END) sidx = textbox.index(INSERT) except StopIteration: break # # Start the event loop. root.mainloop() ################## # End ################## From ian.g.kelly at gmail.com Tue Sep 6 17:47:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 6 Sep 2011 15:47:57 -0600 Subject: import os or import os.path In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci wrote: > Hi, > > If I want to use the 'os.path' module, it's enought to import 'os': > > import os > if os.path.isfile('/usr/bin/bash'): > ? ?print 'got it' > > In other source codes I noticed that people write 'import os.path' in > this case. Which is better practice? "import os.path" is better practice. There is no guarantee in general that the os module will automatically import os.path, and in future versions or different implementations it might not. Cheers, Ian From neubyr at gmail.com Tue Sep 6 17:52:52 2011 From: neubyr at gmail.com (neubyr) Date: Tue, 6 Sep 2011 16:52:52 -0500 Subject: MIMEText encode error - Python 2.6.6 Message-ID: I am trying to write a program which can email file's content using smtplib. I am getting following error while using Python 2.6.6 version. {{{ File "./killed_jobs.py", line 88, in sendmail msg = MIMEText(ipfile.read, 'plain') File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", line 30, in __init__ self.set_payload(_text, _charset) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", line 224, in set_payload self.set_charset(charset) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", line 266, in set_charset cte(self) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", line 73, in encode_7or8bit orig.encode('ascii') AttributeError: 'builtin_function_or_method' object has no attribute 'encode' }}} I am referring to email examples on the doc site http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples . Following is the msg object part in my code: {{{ ... ... def sendmail(inputfile): ipfile = open(inputfile, 'r') msg = MIMEText(ipfile.read, 'plain') ipfile.close() ... ... }}} I have tried setting subtype and chartype separately as mentioned here - http://docs.python.org/release/2.6.6/library/email.mime.html, but the error remains same. Any help on what might be wrong here? thanks, neuby.r From bkasterm at gmail.com Tue Sep 6 18:00:51 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 16:00:51 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Message-ID: <87k49l49gs.fsf@gmail.com> rantingrick writes: > Hmm, i can replace all that code with this... Because I stupidly forgot to repeat the original problem I had, and my code doesn't show it (and doesn't show the correct use of the function I wrote). The code shows that I now know how to compute the number of lines and item will have; in the actual program I am developing I will take the max of these numbers and make all items that height. This means the code I should have shown is as follows (here I first compute the maximum height needed for any item, and then show all items using this height). Also in the actual program there will be scrolling options to change the item shown by the different labels. import Tkinter as Tk import tkFont import random import sys def genstr (j): rno = random.randint(4,50) ret_val = str(j) + ":" for i in range (0, rno): ret_val += "hello" + str(i) return ret_val def gendata (lh): ret_val = [] for i in range(0,lh): ret_val.append (genstr (i)) return ret_val data = gendata (100) root = Tk.Tk() font = tkFont.Font(family='times', size=13) class lines: def __init__ (self): self.lastct = 1 # remember where the cutoff was last work from there def count (self, text, cutoff = 400): global font no_lines = 1 start_idx = 0 idx = self.lastct while True: if idx > len (text): idx = len (text) # shrink from guessed value while font.measure (text[start_idx:idx - 1]) > cutoff: if idx <= start_idx: print "error" sys.exit () else: idx -= 1 self.lastct = idx - start_idx # adjust since was too big # increase from guessed value (note: if first shrunk then done) while (idx < len (text) and font.measure (text[start_idx:idx]) < cutoff): idx += 1 self.lastct = idx - start_idx # adjust since was too small # next line has been determined print "*" + text[start_idx:idx-1] + "*" if idx == len(text) and font.measure (text[start_idx:]) < cutoff: return no_lines elif idx == len(text): return no_lines + 1 else: no_lines += 1 start_idx = idx - 1 idx = start_idx + self.lastct lin = lines() max_ht = 0 for i in range(0,len(data)): ct = lin.count(data[i], 450) if ct > max_ht: max_ht = ct for i in range(0,min(len(data),5)): l = Tk.Label(root) l.pack() l['text'] = data[i] l['width'] = 50 l['justify'] = Tk.LEFT l['anchor'] = 'w' l['wraplength'] = 450 l['padx']=10 l['pady'] = 5 l['height'] = max_ht l['font'] = font if i % 2 == 0: l['background'] = 'grey80' else: l['background'] = 'grey70' root.mainloop() > > # > # Easy_as.py > # > import Tkinter as tk > from ScrolledText import ScrolledText > import tkFont > import random > # Create some puesdo data. > data = [ > '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) > for x in range(100) > ] > ##print data > # Create the main window and a scrolled text widget. > root = tk.Tk() > font = tkFont.Font(family='times', size=13) > textbox = ScrolledText( > root, > width=60, > height=20, > font=('Times', 10), > wrap=tk.WORD, > ) > textbox.pack( > fill=tk.BOTH, > expand=True, > padx=5, > pady=5, > ) > textbox.insert(1.0, '\n\n'.join(data)) > # Start the event loop. > root.mainloop() > # > # End > # From python at mrabarnett.plus.com Tue Sep 6 18:05:20 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 06 Sep 2011 23:05:20 +0100 Subject: MIMEText encode error - Python 2.6.6 In-Reply-To: References: Message-ID: <4E669920.3010704@mrabarnett.plus.com> On 06/09/2011 22:52, neubyr wrote: > I am trying to write a program which can email file's content using > smtplib. I am getting following error while using Python 2.6.6 > version. > > {{{ > File "./killed_jobs.py", line 88, in sendmail > msg = MIMEText(ipfile.read, 'plain') > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", > line 30, in __init__ > self.set_payload(_text, _charset) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", > line 224, in set_payload > self.set_charset(charset) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", > line 266, in set_charset > cte(self) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", > line 73, in encode_7or8bit > orig.encode('ascii') > AttributeError: 'builtin_function_or_method' object has no attribute 'encode' > > }}} > > > I am referring to email examples on the doc site > http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples > . Following is the msg object part in my code: > > {{{ > ... > ... > def sendmail(inputfile): > ipfile = open(inputfile, 'r') > msg = MIMEText(ipfile.read, 'plain') > ipfile.close() > > ... > ... > }}} > > I have tried setting subtype and chartype separately as mentioned here > - http://docs.python.org/release/2.6.6/library/email.mime.html, but > the error remains same. Any help on what might be wrong here? > The docs say: MIMEText(_text[, _subtype[, _charset]]) ... _text is the string for the payload ... You're passing ipfile.read, which is the read method of the file. You should be passing the string returned by calling ipfile.read, ie ipfile.read(). From rantingrick at gmail.com Tue Sep 6 18:40:08 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 15:40:08 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: On Sep 6, 5:00?pm, Bart Kastermans wrote: > rantingrick writes: > > Hmm, i can replace all that code with this... > > Because I stupidly forgot to repeat the original problem I had, and my > code doesn't show it (and doesn't show the correct use of the function I > wrote). Oh NOW i see! This new code you posted is like night and day compared to the original :o) Anyway, i did not read the code to find the difference because i want to know why you insist on using multiple labels for this when a scrolled text will suffice. Are you trying to create some sort of textual "animation frames" that you can flip through on demand? If not i would use the scrolled text (and even the scrolled text can "feel" like animation frames whist scrolling). Take your input data and replace ALL single newlines with null strings (thereby preserving paragraphs) and let the textbox control the line wrapping. The benefits are enormous using my way; your way is limited and requires re-inventing the wheel. Tell me WHY the textbox approach is not a viable solution and THEN i'll listen to you. Until then; you can lead a horse to water... From rantingrick at gmail.com Tue Sep 6 18:43:58 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 15:43:58 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: <700374dd-49ff-4f0a-8c22-198bff6b7b42@k15g2000yqd.googlegroups.com> On Sep 6, 5:40?pm, rantingrick wrote: > On Sep 6, 5:00?pm, Bart Kastermans wrote: > Take your input data and replace ALL single newlines with null strings CORRECTION: Take your input data and replace ALL single newlines with A SINGLE SPACE From bkasterm at gmail.com Tue Sep 6 20:33:32 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 18:33:32 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: <8762l5jin7.fsf@gmail.com> rantingrick writes: > On Sep 6, 5:00?pm, Bart Kastermans wrote: >> rantingrick writes: >> > Hmm, i can replace all that code with this... >> >> Because I stupidly forgot to repeat the original problem I had, and my >> code doesn't show it (and doesn't show the correct use of the function I >> wrote). > > Oh NOW i see! This new code you posted is like night and day compared > to the original :o) Quite, I should know better (I deal with students thinking what is in their mind should be clear to me all the time): ############################################## # run through all the data we have, compute the maximum height max_ht = 0 for i in range(0,len(data)): # lin.count is the line counting function ct = lin.count(data[i], 450) if ct > max_ht: max_ht = ct for i in range(0,min(len(data),5)): # l is the Tkinter.Label with all formatting applied and data[i] # set for text l['height'] = max_ht # use this maximum height for all Labels. ############################################### Thinking on this some more, the first computation should surely be max_ht = max (map (lambda x: lin.count(x, 450), data)) The second one could then be labels = map (label_prepare_pack, data[:5]) where label_prepare_pack prepares (sets all attributes and data), packs, and returns the new label. The first (for max_ht) is a clear improvement to me, the second (for labels) uses too many side-effects to be very appealing to me. > Anyway, i did not read the code to find the difference because i want > to know why you insist on using multiple labels for this when a > scrolled text will suffice. Are you trying to create some sort of > textual "animation frames" that you can flip through on demand? I don't follow precisely, but I am indeed looking to flip through all of data while showing only 5 or 10 at a time. The problem I wanted to solve was that my window kept changing size while doing this. > If not > i would use the scrolled text (and even the scrolled text can "feel" > like animation frames whist scrolling). > > Take your input data and replace ALL single newlines with null strings > (thereby preserving paragraphs) and let the textbox control the line > wrapping. The benefits are enormous using my way; your way is limited > and requires re-inventing the wheel. Tell me WHY the textbox approach > is not a viable solution and THEN i'll listen to you. The reason I thought this, was that I didn't realize I could bind actions to tags (to get different actions for different bits of text). Now that I do know this I could use code like my lin.count to get the maximum height still (to get a constant location for the i-th item as the items are changed; more importantly to get a constant height for the whole list of items), and then use tags to bind the corresponding actions. > Until then; you can lead a horse to water... I certainly appreciate your trying. I might not see the fresh stream yet, but I do see liquid (possibly a shallow muddy pool, but big progress from the dry sandy dunes before). I will keep both approaches in mind as I further develop. Again, thanks for the help, greatly appreciated. From ben+python at benfinney.id.au Tue Sep 6 20:36:05 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 07 Sep 2011 10:36:05 +1000 Subject: PEP 20 - Silly Question? References: Message-ID: <877h5lnq8a.fsf@benfinney.id.au> Zero Piraeus writes: > On 6 September 2011 12:17, Joseph Armbruster wrote: > > I noticed that it says only 19 of 20 have been written down. ?Which > > one was not written down? > > The last one. I always thought it was the first one. Or the 6.25th one, I forget. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From nobody at nowhere.com Tue Sep 6 21:01:11 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 07 Sep 2011 02:01:11 +0100 Subject: Can't use subprocess.Popen() after os.chroot() - why? References: Message-ID: On Sun, 04 Sep 2011 07:22:07 -0700, Erik wrote: > I'm trying to do the following: > os.chroot("/tmp/my_chroot") > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > but the Popen call is dying with the following exception: > LookupError: unknown encoding: string-escape > > Am I missing something here? does the chroot environment need to be > populated with more than just the date executable in this case? Yes. It also needs to include any parts of the Python run-time which Python will try to load while executing subsequent code. In this case, the module which implements the string-escape encoding. But fixing that will probably show up yet more files which need to exist within the pseudo-root. E.g. any shared libraries which the executable needs (probably at least libc), and any data files which those libraries need (in the case of /bin/date, it may need /etc/timezone; many programs may require locale data if you aren't in the "C" locale, and so on). Whether from Python or from C, chroot() requires a good understanding of the low-level details of your operating system. If you don't know how to build a minimal Linux distribution from scratch, you're going to have to learn many of those details in order to use chroot(). For any non-trivial chroot() usage, it's often easier to install a small newlib+busybox-based Linux distribution under the pseudo-root than to try to re-use files from and existing (presumably glibc+coreutils-based) desktop/server distribution. From skippy.hammond at gmail.com Tue Sep 6 21:11:55 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 07 Sep 2011 11:11:55 +1000 Subject: import os or import os.path In-Reply-To: References: Message-ID: <4E66C4DB.7080008@gmail.com> On 7/09/2011 7:47 AM, Ian Kelly wrote: > On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci wrote: >> Hi, >> >> If I want to use the 'os.path' module, it's enought to import 'os': >> >> import os >> if os.path.isfile('/usr/bin/bash'): >> print 'got it' >> >> In other source codes I noticed that people write 'import os.path' in >> this case. Which is better practice? > > "import os.path" is better practice. There is no guarantee in general > that the os module will automatically import os.path, and in future > versions or different implementations it might not. That's probably a matter of opinion - eg, http://docs.python.org/tutorial/interpreter.html has an example of importing the os module then accessing os.path. Personally I think directly importing os.path is a waste of precious keystrokes ;) Cheers, Mark. From python at mrabarnett.plus.com Tue Sep 6 21:25:56 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 07 Sep 2011 02:25:56 +0100 Subject: PEP 20 - Silly Question? In-Reply-To: <877h5lnq8a.fsf@benfinney.id.au> References: <877h5lnq8a.fsf@benfinney.id.au> Message-ID: <4E66C824.6010008@mrabarnett.plus.com> On 07/09/2011 01:36, Ben Finney wrote: > Zero Piraeus writes: > >> On 6 September 2011 12:17, Joseph Armbruster wrote: >>> I noticed that it says only 19 of 20 have been written down. Which >>> one was not written down? >> >> The last one. > > I always thought it was the first one. Or the 6.25th one, I forget. > Or the zeroth one. From milleja46 at gmail.com Tue Sep 6 21:31:52 2011 From: milleja46 at gmail.com (Joshua Miller) Date: Tue, 6 Sep 2011 21:31:52 -0400 Subject: PEP 20 - Silly Question? In-Reply-To: <4E66C824.6010008@mrabarnett.plus.com> References: <877h5lnq8a.fsf@benfinney.id.au> <4E66C824.6010008@mrabarnett.plus.com> Message-ID: You sure it wasn't the invisible one? you know the one in the white text that blends into the background? On Tue, Sep 6, 2011 at 9:25 PM, MRAB wrote: > On 07/09/2011 01:36, Ben Finney wrote: >> >> Zero Piraeus ?writes: >> >>> On 6 September 2011 12:17, Joseph Armbruster >>> ?wrote: >>>> >>>> I noticed that it says only 19 of 20 have been written down. ?Which >>>> one was not written down? >>> >>> The last one. >> >> I always thought it was the first one. Or the 6.25th one, I forget. >> > Or the zeroth one. > -- > http://mail.python.org/mailman/listinfo/python-list > From tyler at tysdomain.com Tue Sep 6 22:19:37 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Tue, 06 Sep 2011 20:19:37 -0600 Subject: Looking for open-source Python projects to help out with Message-ID: <4E66D4B9.9050402@tysdomain.com> Hello: I've got a bit of time on my hands, so I'm curious what sorts of projects there are that people needs help with. I'd like to choose something that doesn't have a ton of red tape, but is stable, which is why I ask here instead of just Googling open source projects. My main interests lie in accessibility, Utilities and security. -- Take care, ~Ty Web: http://tds-solutions.net Sent from my toaster. From wolftracks at invalid.com Tue Sep 6 22:43:23 2011 From: wolftracks at invalid.com (W. eWatson) Date: Tue, 06 Sep 2011 19:43:23 -0700 Subject: strange thing: In-Reply-To: References: Message-ID: CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in my spam on the net. From rosuav at gmail.com Tue Sep 6 22:48:21 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 7 Sep 2011 12:48:21 +1000 Subject: strange thing: In-Reply-To: References: Message-ID: On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson wrote: > CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in > my spam on the net. No, I didn't; as someone else pointed out, you'll get better results asking on a dedicated Fortran list. ChrisA From goon12 at gmail.com Tue Sep 6 23:49:34 2011 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 6 Sep 2011 23:49:34 -0400 Subject: import os or import os.path In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 5:25 PM, Jabba Laci wrote: > Hi, > > If I want to use the 'os.path' module, it's enought to import 'os': > > import os > if os.path.isfile('/usr/bin/bash'): > ? ?print 'got it' > > In other source codes I noticed that people write 'import os.path' in > this case. Which is better practice? I just followed what the help said: "" DESCRIPTION Instead of importing this module directly, import os and refer to this module as os.path. "" From casevh at gmail.com Tue Sep 6 23:58:29 2011 From: casevh at gmail.com (casevh) Date: Tue, 6 Sep 2011 20:58:29 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> Message-ID: <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> On Sep 6, 6:37?am, jmfauth wrote: > This is just an attempt to put thehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > discussion at a correct level. > > With Python 2.7 a new float number representation (the David Gay's > algorithm) > has been introduced. If this is well honored in Python 2.7, it > seems to me, there are some missmatches in the Py3 series. > > >>> sys.version > > '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit > (Intel)]' > > >>> 0.1 > 0.10000000000000001 > >>> print 0.1 > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print 1.1 * 1.1 > 1.21 > >>> print repr(1.1 * 1.1) > 1.2100000000000002 > > >>> sys.version > > 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] > > > > >>> 0.1 > 0.1 > >>> print 0.1 > 0.1 > >>> 1.1 * 1.1 > 1.21 > >>> print 1.1 * 1.1 > 1.21 > >>> print repr(1.1 * 1.1) > 1.2100000000000002 > I tried this with the same version of Python and I get: >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> 1.1 * 1.1 1.2100000000000002 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> > >>> sys.version > > '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]'>>> 0.1 > 0.1 > >>> print(0.1) > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print(1.1 * 1.1) > 1.21 > >>> print(repr(1.1 * 1.1)) > 1.2100000000000002 > >>> '{:g}'.format(1.1 * 1.1) > > '1.21' > > >>> sys.version > > '3.2.2 (default, Sep ?4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' > > >>> 0.1 > 0.1 > >>> print(0.1) > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print (1.1 * 1.1) > 1.2100000000000002 > >>> print(repr((1.1 * 1.1))) > 1.2100000000000002 > > >>> '{:g}'.format(1.1 * 1.1) > '1.21' > I get same results as you do for Python 3.1.4 and 3.2.2. IIRC, Python 3.2 changed (for floats) __str__ to call __repr__. That should explain the difference between 3.1.4 and 3.2.2 Also note that 1.1 * 1.1 is not the same as 1.21. >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301, 4503599627370496) >>> (1.21).as_integer_ratio() (1362338887279575, 1125899906842624) This doesn't explain why 2.7.2 displayed a different result on your computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and (1.21)? casevh > jmf From steve+comp.lang.python at pearwood.info Wed Sep 7 00:51:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 07 Sep 2011 14:51:13 +1000 Subject: Floating point multiplication in python References: <2204592.egLE2XKegd@PointedEars.de> Message-ID: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> On Wed, 7 Sep 2011 02:07 am Thomas 'PointedEars' Lahn wrote: > Thomas Rachel wrote: > >> Now if you multiply two values with an error, the error also propagates >> into the result - PLUs the result can have its own error source - in the >> same order of magnitude. >> >> (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e >> or (2*a + e) * e. > > Your explanation about floating-point precision, which I already knew > about but have only scanned here ? so it might be flawed as well ?, > notwithstanding, it is not clear to me at all what you are trying to prove > there. > > Computers (well, perhaps outside of mathematical software) do NOT compute > an equation as humans would do, so the binomial theorem does NOT apply. I think you have misunderstood. The binomial theorem always applies. Any time you multiply two numbers, both numbers can always be re-written as a sum of two numbers: 10*5 = (6+4)*(2+3) So a perfect square can always be re-written in the form where the binomial theorem applies: 5*5 = (2+3)*(2+3) 25 = 2*2 + 2*3 + 3*2 + 3*3 25 = 4 + 6 + 6 + 9 25 = 25 The binomial theorem is not a part of the algorithm for performing multiplication. It is part of the analysis of the errors that occur during multiplication. The actual mechanics of how bits are flipped is irrelevant. Any floating point number x should be considered as equal to (a+e), where a is the number actually wanted by the user, and e the error term forced upon the user by the use of binary floats. (If you're lucky, e=0.) Generally, both a and e are unknown, but of course their sum is known -- it's just the float x. So given a float x, when you square it you get this: Exact values: a*a = a**2 Float values: x*x = (a+e)(a+e) = a**2 + 2*a*e + e**2 So the error term has increased from e to (2*a*e+e**2). It is usual to assume that e**2 is small enough that it underflows to zero, so we have the error term e increasing to 2*a*e as a fairly simple estimate of the new error. > In an algorithm of the real implementation, > > (a + e) * (a + e) > > would be computed as follows: > > b := a + e > c := b * b > or > c := b + ? + b > > [add the value of `b' to the value of `b' (b?1) times, since binary logic > does not support multiplication] What you probably mean to say is that binary hardware usually implements multiplication via repeated addition. http://en.wikipedia.org/wiki/Binary_multiplier If you don't mean that, I can't imagine what you are trying to say. Multiplication of numbers exists in any base, binary no less than decimal. > IOW, the error does propagate into the result indeed, but not as you > described. Indeed, thanks to rounding on assignment and multiplication > (i. e., setting register values or IEEE-754 floating-point mantissa and > exponent), the error will be different, probably greater than you compute > here. There may be other sources of error, particularly when multiplying two numbers of greatly different magnitudes, but that doesn't invalidate Thomas Rachel's point (which is only an estimate, of course). We can see how much error is actually there by using exact arithmetic: Error in float 1.1: >>> from fractions import Fraction as F >>> >>> a = F(11, 10) >>> x = F.from_float(1.1) >>> e = x - a >>> print e 1/11258999068426240 Error in float 1.1*1.1: >>> b = F(11, 10)**2 >>> y = F.from_float(1.1**2) >>> f = y - b >>> print f 21/112589990684262400 which is slightly more than double e above, and slightly less than our estimate of 2*a*e = 11/56294995342131200 So we can conclude that, at least for 1.1**2, Python floats are more accurate than we would expect from a simple application of the binomial theorem. (For implementations using IEEE doubles.) -- Steven From wolftracks at invalid.com Wed Sep 7 01:08:11 2011 From: wolftracks at invalid.com (W. eWatson) Date: Tue, 06 Sep 2011 22:08:11 -0700 Subject: strange thing: In-Reply-To: References: Message-ID: On 9/6/2011 7:48 PM, Chris Angelico wrote: > On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson wrote: >> CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in >> my spam on the net. > > No, I didn't; as someone else pointed out, you'll get better results > asking on a dedicated Fortran list. > > ChrisA OK. From cmpython at gmail.com Wed Sep 7 01:56:10 2011 From: cmpython at gmail.com (CM) Date: Tue, 6 Sep 2011 22:56:10 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) AFAIK, probably Matplotlib. I'm not sure what quite to imagine for your plot but below is code that makes an attempt at (maybe) something like you are describing, shown here: http://www.flickr.com/photos/67254913 at N07/6123112552/in/photostream#/ There are smarter ways to do this in matplotlib, but this is pretty quick and dirty. I'm just plotting lines over-top other lines. The pic I put is the plot as a .png, which matplotlib makes if you want, but you can also view it in a frame that matplotlib generates and then pan/zoom/etc... from pylab import * x = [1,2,3,4,5,6,7,8] y = [2 for num in x] #plot the parallel lines themselves in green for num in range(6): y = [num for item in x] plot(x,y,color='g',lw='4') #plot any conflict sections in red or yellow #some hard data to give the idea: x2 = [3,4] y2 = [2 for num in x2] x3 = [5,6,7] y3 = [4 for num in x3] x4 = [2,3] y4 = [3 for num in x4] #plot these three colored parts over the green lines plot(x2,y2,color='r',lw='12') plot(x3,y3,color='yellow',lw='12') plot(x4,y4,color='r',lw='12') pos = arange(6) yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6')) show() #------------------------- Che From cmpython at gmail.com Wed Sep 7 02:00:58 2011 From: cmpython at gmail.com (CM) Date: Tue, 6 Sep 2011 23:00:58 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: On Sep 6, 2:27?pm, Fred Pacquier wrote: > Hi, > > I'm a Python long-timer, but I've never had to use tools like Matplotlib & > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) One fairly simple way is with Matplotlib. Not sure what quite to imagine for your plot but below is code that makes an attempt at (maybe) something like you are describing, shown here: http://www.flickr.com/photos/67254913 at N07/6123112552/in/photostream#/ There are fancier ways to do this in Matplotlib, but this is pretty quick and dirty--I'm just plotting lines over-top other lines. The pic I put is the plot as a .png, which matplotlib makes if you want, but you can also view it in a frame that matplotlib generates and then pan/zoom/etc... This is using the pylab module, but you could also embed your plots in a GUI if you prefer. from pylab import * #plot the parallel lines in green x = [1,2,3,4,5,6,7,8] y = [2 for num in x] for num in range(6): y = [num for item in x] plot(x,y,color='g',lw='4') #plot any conflict sections in red or yellow #...some data to give the idea: x2 = [3,4] y2 = [2 for num in x2] x3 = [5,6,7] y3 = [4 for num in x3] x4 = [2,3] y4 = [3 for num in x4] #plot three colored parts over the green lines plot(x2,y2,color='r',lw='12') plot(x3,y3,color='yellow',lw='12') plot(x4,y4,color='r',lw='12') #change y labels to meaningful labels pos = arange(6) yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6')) show() #------------------------- Che From wxjmfauth at gmail.com Wed Sep 7 02:32:07 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 6 Sep 2011 23:32:07 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> Message-ID: <6091df75-58e4-4316-8f3c-957b53c24490@dq7g2000vbb.googlegroups.com> On 7 sep, 05:58, casevh wrote: > ... > > Also note that 1.1 * 1.1 is not the same as 1.21. > > >>> (1.1 * 1.1).as_integer_ratio() > > (5449355549118301, 4503599627370496)>>> (1.21).as_integer_ratio() > > (1362338887279575, 1125899906842624) > > This doesn't explain why 2.7.2 displayed a different result on your > computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and > (1.21)? > Sure. I just picked up these numbers/expressions by chance. They came to my mind following the previous discussion. Sticking with the latest versions: >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301L, 4503599627370496L) >>> (1.21).as_integer_ratio() (1362338887279575L, 1125899906842624L) >>> >>> sys.version '3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301, 4503599627370496) >>> (1.21).as_integer_ratio() (1362338887279575, 1125899906842624) >>> Has "long" not disappeared 2.7? I have not the skill to dive into the machinery. I have only some theroretical understanding and I'm a little bit confused and have to face "there something strange somewhere". Test on Windows 7, 32 bits. jmf From mdickinson at enthought.com Wed Sep 7 02:56:42 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Tue, 6 Sep 2011 23:56:42 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> Message-ID: <6aec0187-2fa1-49ae-b2c0-fb0a10ec443c@br5g2000vbb.googlegroups.com> On Sep 7, 4:58?am, casevh wrote: > IIRC, Python > 3.2 changed (for floats) __str__ to call __repr__. Yes, exactly: str and repr of a float are identical in Python 3.2 + I'm also puzzled by the 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] [...] >>> 1.1 * 1.1 1.21 in jmf's message. Cut-and-paste typo? -- Mark From pierre.quentel at gmail.com Wed Sep 7 03:00:24 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Wed, 7 Sep 2011 00:00:24 -0700 (PDT) Subject: Relative seeks on string IO References: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Message-ID: <30c6f7f0-b846-47a9-be49-e234a8bb8c16@e9g2000yqb.googlegroups.com> > > Please post code without non-code indents, like so: > Sorry about that. After the line "Example :" I indented the next block, out of habit ;-) > > What system are you using? Does it have a narrow or wide unicode build? > (IE, what is the value of sys.maxunicode?) > I use Windows XP Pro, version 2002, SP3. sys.maxunicode is 65535 I have the same behaviour with 3.1.1 and with 2.7 I don't understand why variable sized code units would cause problems. On text file objects, read(nb) reads nb characters, regardless of the number of bytes used to encode them, and tell() returns a position in the text stream just after the next (unicode) character read As for SringIO, a wrapper around file objects simulates a correct behaviour for relative seeks : ==================== txt = "abcdef" txt += "????? ??? ??????" txt += "?????" txt += "endof file" out = open("test.txt","w",encoding="utf-8") out.write(txt) out.close() fobj = open("test.txt",encoding="utf-8") fobj.seek(3) try: fobj.seek(2,1) except IOError: print('raises IOError') class _file: def __init__(self,file_obj): self.file_obj = file_obj def read(self,nb=None): if nb is None: return self.file_obj.read() else: return self.file_obj.read(nb) def seek(self,offset,whence=0): if whence==0: self.file_obj.seek(offset) else: if whence==2: # read till EOF while True: buf = self.file_obj.read() if not buf: break self.file_obj.seek(self.file_obj.tell()+offset) fobj = _file(open("test.txt",encoding="utf-8")) fobj.seek(3) fobj.seek(2,1) fobj.seek(-5,2) print(fobj.read(3)) ========================== - Pierre From herbert.weinhandl at oeaw.ac.at Wed Sep 7 03:14:57 2011 From: herbert.weinhandl at oeaw.ac.at (Weinhandl Herbert) Date: Wed, 07 Sep 2011 09:14:57 +0200 Subject: Advice on how to get started with 2D-plotting ? In-Reply-To: References: Message-ID: <4e6719f1$0$38260$3b214f66@aconews.univie.ac.at> Am 06.09.2011 20:27, schrieb Fred Pacquier: > Hi, > > I'm a Python long-timer, but I've never had to use tools like Matplotlib& > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > maybe networkx http://pypi.python.org/pypi/networkx/1.5 http://networkx.lanl.gov/ is a better solution for your problem or http://pypi.python.org/pypi/graphcanvas/4.0.0 > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) > > Alternately, if someone knows of a ready-made and accessible tool that does > just that, I'm all ears :-) > > TIA, > fp hth Herbert From Shambhu.Rajak at kpitcummins.com Wed Sep 7 03:25:28 2011 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Wed, 7 Sep 2011 07:25:28 +0000 Subject: Prequisites required to learn Django frame work Message-ID: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> Hi, I have been doing python development since last year, I think I should learn the famous Django frame work. Can any one suggest what are the perquisite required to setup django on my local home machine. Please suggest something that does not require a separate server, as this is a personal interest of mine. Thanks, Shambhu -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Wed Sep 7 03:39:51 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 7 Sep 2011 17:39:51 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: Hi Tyler, I'm currently working on building a new kind of social-network for Users-Groups, Game-Clans & Student-Groups. Building it using DJango with Pinax. Detailed Feature-Set (planned): ? Event management ? Conference management (including ticketing with payment-gateway integration) ? Video+Audio Conferencing of event, with online interaction possibilitiy (great for webinars) ? Join/create/delete/list groups ? Sitewide calendar ? Sitewide feed from non-private groups ? SSO integration (facebook, twitter & linkedin) ? Wall (+feed) for each group ? Listing of who's in which group ? PM group members I will probably be releasing it under the New BSD license, although I'm happy to consider others given a good argument. Interested? On Wed, Sep 7, 2011 at 12:19 PM, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of projects > there are that people needs help with. I'd like to choose something that > doesn't have a ton of red tape, but is stable, which is why I ask here > instead of just Googling open source projects. My main interests lie in > accessibility, Utilities and security. > > -- > > Take care, > ~Ty > Web: http://tds-solutions.net > > Sent from my toaster. > > -- > http://mail.python.org/mailman/listinfo/python-list > From wxjmfauth at gmail.com Wed Sep 7 04:21:20 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Wed, 7 Sep 2011 01:21:20 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> <6aec0187-2fa1-49ae-b2c0-fb0a10ec443c@br5g2000vbb.googlegroups.com> Message-ID: On 7 sep, 08:56, Mark Dickinson wrote: > On Sep 7, 4:58?am, casevh wrote: > > > IIRC, Python > > 3.2 changed (for floats) __str__ to call __repr__. > > Yes, exactly: ?str and repr of a float are identical in Python 3.2 + > > I'm also puzzled by the > > 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] > [...]>>> 1.1 * 1.1 > > 1.21 > > in jmf's message. ?Cut-and-paste typo? > > -- > Mark No. But, it's *my* mistake. I'm using a modified sys.displayhook which uses a print statement (mainly for language reason). If forgot to reset to the initial/default state for these tests when working with too many opened interactive interpreters. Sorry for the noise. >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> >>> 1.1 * 1.1 1.21 >>> '?l?phant' ?l?phant >>> >>> sys.displayhook = sys.__displayhook__ >>> 1.1 * 1.1 1.2100000000000002 >>> '?l?phant' '\xe9l\xe9phant' >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> jmf From fayaz.yusuf.khan at gmail.com Wed Sep 7 04:32:48 2011 From: fayaz.yusuf.khan at gmail.com (Fayaz Yusuf Khan) Date: Wed, 7 Sep 2011 14:02:48 +0530 Subject: Looking for open-source Python projects to help out with In-Reply-To: References: <4E66D4B9.9050402@tysdomain.com> Message-ID: <201109071403.00915.fayaz@dexetra.com> On Wednesday, September 07, 2011 01:09:51 PM Alec Taylor wrote: > Hi Tyler, > > I'm currently working on building a new kind of social-network for > Users-Groups, Game-Clans & Student-Groups. > > Building it using DJango with Pinax. > > Detailed Feature-Set (planned): > ? Event management > ? Conference management (including ticketing with payment-gateway > integration) ? Video+Audio Conferencing of event, with online interaction > possibilitiy (great for webinars) > ? Join/create/delete/list groups > ? Sitewide calendar > ? Sitewide feed from non-private groups > ? SSO integration (facebook, twitter & linkedin) > ? Wall (+feed) for each group > ? Listing of who's in which group > ? PM group members > > I will probably be releasing it under the New BSD license, although > I'm happy to consider others given a good argument. > > Interested? The project page and mailing list? -- Fayaz Yusuf Khan Cloud developer and designer Dexetra SS, Kochi, India fayaz.yusuf.khan_AT_gmail_DOT_com fayaz_AT_dexetra_DOT_com +91-9746-830-823 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 316 bytes Desc: This is a digitally signed message part. URL: From gelonida at gmail.com Wed Sep 7 04:57:53 2011 From: gelonida at gmail.com (Gelonida N) Date: Wed, 07 Sep 2011 10:57:53 +0200 Subject: Floating point multiplication in python In-Reply-To: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <2204592.egLE2XKegd@PointedEars.de> <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/07/2011 06:51 AM, Steven D'Aprano wrote: 11258999068426240 > > Error in float 1.1*1.1: > >>>> b = F(11, 10)**2 >>>> y = F.from_float(1.1**2) >>>> f = y - b >>>> print f > 21/112589990684262400 > > which is slightly more than double e above, and slightly less than our > estimate of 2*a*e = 11/56294995342131200 > > So we can conclude that, at least for 1.1**2, Python floats are more > accurate than we would expect from a simple application of the binomial > theorem. (For implementations using IEEE doubles.) The reason why the error is different from the 2*a*e is, that we encounter two problems. first problem is, that x = a + e e exists because a float does have a limited number (let's call it N) of digits and a has an infinite amount of non zero digits in the binary format. second problem is, that the result of the multiplication is not (a+e) * (a+e) but a 'rounded' version of it, because the floating point representation of the result would require about 2*N digits, whereas only N digits will be stored in the result. depending on the rounding which happened (up or down) the error will be bigger or smaller than the estimated one. From gelonida at gmail.com Wed Sep 7 05:06:25 2011 From: gelonida at gmail.com (Gelonida N) Date: Wed, 07 Sep 2011 11:06:25 +0200 Subject: Prequisites required to learn Django frame work In-Reply-To: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> References: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> Message-ID: Hi Shambhu, On 09/07/2011 09:25 AM, Shambhu Rajak wrote: > Hi, > > I have been doing python development since last year, I think I should > learn the famous Django frame work. > > > > Can any one suggest what are the perquisite required to setup django on > my local home machine. > Just easyinstall django This is enough for learning and midsize home grown projects not requiring a very secure setup. Django comes with a built in server, which is good enough for learning. However It should not be used for deployment. As database engine you can use sqlite3, which is also good enough for learning. My above mentioned setup will be working under windows and under linux. If you want to have something with a better performance, then you have two things to look at. Change the data base engine to mysql or postgres. mysql / postgres should be installable under Windows Use a real web server (apache / nginx with uwsgi plugins) As an intermediate step you could instead of installing a 'real' web server you could also use a python twisted server From alec.taylor6 at gmail.com Wed Sep 7 05:09:53 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 7 Sep 2011 19:09:53 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: <201109071403.00915.fayaz@dexetra.com> References: <4E66D4B9.9050402@tysdomain.com> <201109071403.00915.fayaz@dexetra.com> Message-ID: The project page is: http://SamuelMarks.GitHub.com/groupHub /me is thinking a rename to "groupSwitch", thoughts? The project is currently in planning stage. All help is appreciated. On Wed, Sep 7, 2011 at 6:32 PM, Fayaz Yusuf Khan wrote: > On Wednesday, September 07, 2011 01:09:51 PM Alec Taylor wrote: >> Hi Tyler, >> >> I'm currently working on building a new kind of social-network for >> Users-Groups, Game-Clans & Student-Groups. >> >> Building it using DJango with Pinax. >> >> Detailed Feature-Set (planned): >> ? Event management >> ? Conference management (including ticketing with payment-gateway >> integration) ? Video+Audio Conferencing of event, with online interaction >> possibilitiy (great for webinars) >> ? Join/create/delete/list groups >> ? Sitewide calendar >> ? Sitewide feed from non-private groups >> ? SSO integration (facebook, twitter & linkedin) >> ? Wall (+feed) for each group >> ? Listing of who's in which group >> ? PM group members >> >> I will probably be releasing it under the New BSD license, although >> I'm happy to consider others given a good argument. >> >> Interested? > The project page and mailing list? > > -- > Fayaz Yusuf Khan > Cloud developer and designer > Dexetra SS, Kochi, India > fayaz.yusuf.khan_AT_gmail_DOT_com > fayaz_AT_dexetra_DOT_com > +91-9746-830-823 > > -- > http://mail.python.org/mailman/listinfo/python-list > > From fnautaNO at SPAMsolfon.nl Wed Sep 7 05:17:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Wed, 7 Sep 2011 11:17:03 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> Message-ID: <9cor4gFk15U1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.823.1315377607.27778.python-list at python.org... > On Tue, 6 Sep 2011 21:26:12 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> (here I try to login the WebDAV server with the local IE browser) >> >> INFO:fshandler :get_data: D:\Webdav not found > > At this point my best suggestion is to study the source code of > fshandler to see what it is doing at this moment in time (offhand, is > there any content IN the directory to be "served"?) There is a file indeed, in d:\Webdav >> server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; >> Windows N >> T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - >> server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; >> Windows N >> T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - >> > That almost looks like something is trying to retrieve a default > page for 404 (not found) page. > > To save you some time: > > -=-=-=- > if os.path.exists(path): > if os.path.isfile(path): > file_size = os.path.getsize(path) > if range == None: > ## REST SNIPPED > else: > # also raise an error for collections > # don't know what should happen then.. > log.info('get_data: %s not found' % path) I have seen this part. Do I need to alter it? > Note that at this point in the system, it is looking for a FILE, not > a directory. > -- I have re-installed Python and the setuptool, and tried the Python version of Active, but it did not make a difference. So now I use the "old" Python 2.7 again. Used easy_install to install PyWebDAV. I now run davserver.exe from the Script directory. Still the same problem. What I found, however, was that if I specify the directory from the command line (like davserver -D d:\Webdav -n) there is no error message as "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still the 404 error. The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs when I specify the "-c config.ini" in the command line. I didn't expect it to be this so tricky. It looked easy to set up an experimental webdav server. Fokke From tjreedy at udel.edu Wed Sep 7 05:37:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 05:37:32 -0400 Subject: Floating point multiplication in python In-Reply-To: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <2204592.egLE2XKegd@PointedEars.de> <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/7/2011 12:51 AM, Steven D'Aprano wrote: > So given a float x, when you square it you get this: > > Exact values: a*a = a**2 > > Float values: x*x = (a+e)(a+e) > = a**2 + 2*a*e + e**2 > > So the error term has increased from e to (2*a*e+e**2). It is usual to > assume that e**2 is small enough that it underflows to zero, so we have the > error term e increasing to 2*a*e as a fairly simple estimate of the new > error. And the relative error, which is what is often important, increases from e/a to 2e/a. -- Terry Jan Reedy From bex.lewis at gmail.com Wed Sep 7 06:31:35 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Wed, 7 Sep 2011 03:31:35 -0700 (PDT) Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> Message-ID: > I have re-installed Python and the setuptool, and tried the Python version > of Active, but it did not make a difference. > So now I use the "old" Python 2.7 again. Used easy_install to install > PyWebDAV. I now run davserver.exe from the Script directory. Still the same > problem. > What I found, however, was that if I specify the directory from the command > line (like davserver -D d:\Webdav -n) there is no error message as > "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still the > 404 error. > The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs when I > specify the "-c config.ini" in the command line. > > I didn't expect it to be this so tricky. It looked easy to set up an > experimental webdav server. > > Fokke How are you trying to access the webdav server? I've been hacking on the server for several days now (unrelated reasons) and have found that it's a little unforgiving when it comes to configuration errors. You need to be accessing the webdav server via the correct port (I think it's 8008 by default). If you're not doing this and something else is running on port 80 (which is where a webdav client will go to by default) then this would explain the 404 errors. From sinisa.segvic at fer.hr Wed Sep 7 06:39:14 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 03:39:14 -0700 (PDT) Subject: Portable locale usage References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> On 6 ruj, 17:53, Thomas Jollans wrote: > On 06/09/11 16:46, ssegvic wrote: > > > For the moment, I only wish to properly sort a Croatian text file > > both on Windows and Linux (I am a cautious guy, I like reachable > > goals). > > When the locale is properly set, sorting works like a charm > > with mylist.sort(key=locale.strxfrm). > > The problem with that is of course that a Croatian locale has to be > installed. Many Linux systems don't have locales that aren't used. It appears we did not understand each other completely. Python locales on Linux work as advertised, I have no problems with locales on Linux whatsoever (yes, the Croatian locale had to be manually installed). On the other hand, it appears that Python locales on Windows do not work as advertised. Consider for instance my initial example: locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) The code above does not work on Windows even though the fine manual says: http://docs.python.org/py3k/library/locale.html ''' locale.setlocale(category, locale=None) ... If (the locale) is a tuple, it is converted to a string using the locale aliasing engine. ... ''' I do not believe my troubles could be solved by installing anything, since the OS support for Croatian apperas to be present: locale.setlocale(locale.LC_ALL, 'Croatian_Croatia.1250') To conclude, it seems to me that the Windows implementation of the locale aliasing engine has some space for improvement. All further comments shall be greatly appreciated :-) Cheers, Sinisa From sinisa.segvic at fer.hr Wed Sep 7 07:02:18 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 04:02:18 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <6b6671a8-8e92-4ace-a1ed-63e900246000@gz5g2000vbb.googlegroups.com> On 6 ruj, 22:58, garabik-news-2005... at kassiopeia.juls.savba.sk wrote: > Thomas Jollans wrote: > > It looks like you don't actually care about the encoding: in your first > > example, you use the default system encoding, which you do not control, > > and in your second example, you're using two different encodings on the > > two platforms. So why do you care whether or not the default uses ISO > > 8859-2 ? > > Maybe because using 8859-2 locale, (unicode) strings not representable in the > encodings will be sorted - how? Exactly. Additionally, fonts supporting 8859-2 are scarce. My favourite fonts were never available in 8859-2. Sinisa From sinisa.segvic at fer.hr Wed Sep 7 07:17:52 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 04:17:52 -0700 (PDT) Subject: Portable locale usage References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <16cabd28-d195-4689-9a28-374671a030ba@gz5g2000vbb.googlegroups.com> On 6 ruj, 17:53, Thomas Jollans wrote: > On 06/09/11 16:46, ssegvic wrote: > > > For the moment, I only wish to properly sort a Croatian text file > > both on Windows and Linux (I am a cautious guy, I like reachable > > goals). > > When the locale is properly set, sorting works like a charm > > with mylist.sort(key=locale.strxfrm). > > The problem with that is of course that a Croatian locale has to be > installed. Many Linux systems don't have locales that aren't used. I already concluded that on Linux there are no problems whatsoever (the Croatian locale was kindly installed by the distribution setup). Since my initial snippet does not work on Windows, I would conclude that the locale aliasing engine on Windows should be improved. Any opposing views will be appreciated :-) For convenience, I repeat the snippet here: import locale locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) Cheers, Sinisa From mohammedimran107 at gmail.com Wed Sep 7 08:49:57 2011 From: mohammedimran107 at gmail.com (mohammed imran) Date: Wed, 7 Sep 2011 05:49:57 -0700 (PDT) Subject: mohammedimran Message-ID: <7d838612-c5a0-43d7-b852-4a84c35b183f@l4g2000vbz.googlegroups.com> http://123maza.com/65/fun564/ From t at jollybox.de Wed Sep 7 09:15:53 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 15:15:53 +0200 Subject: Portable locale usage In-Reply-To: <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> Message-ID: <4E676E89.4010506@jollybox.de> On 07/09/11 12:39, ssegvic wrote: > On 6 ruj, 17:53, Thomas Jollans wrote: >> On 06/09/11 16:46, ssegvic wrote: >> >>> For the moment, I only wish to properly sort a Croatian text file >>> both on Windows and Linux (I am a cautious guy, I like reachable >>> goals). >>> When the locale is properly set, sorting works like a charm >>> with mylist.sort(key=locale.strxfrm). >> >> The problem with that is of course that a Croatian locale has to be >> installed. Many Linux systems don't have locales that aren't used. > > It appears we did not understand each other completely. Yes we did. I was just pointing out that your code wouldn't be portable to systems that don't have that specific locale. From mohammedimran107 at gmail.com Wed Sep 7 09:27:22 2011 From: mohammedimran107 at gmail.com (mohammed imran) Date: Wed, 7 Sep 2011 06:27:22 -0700 (PDT) Subject: mohammedimran Message-ID: <43cb58c7-1b7b-4e61-a53a-7eb5603396ff@et6g2000vbb.googlegroups.com> http://123maza.com/65/fun564/ From t at jollybox.de Wed Sep 7 09:45:30 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 15:45:30 +0200 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: <4E67757A.6070701@jollybox.de> On 07/09/11 04:19, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of > projects there are that people needs help with. I'd like to choose > something that doesn't have a ton of red tape, but is stable, which is > why I ask here instead of just Googling open source projects. My main > interests lie in accessibility, Utilities and security. > How about Python itself? Much of the standard library is written in Python, and there are almost certainly bugs that need fixing. From fnautaNO at SPAMsolfon.nl Wed Sep 7 09:52:20 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Wed, 7 Sep 2011 15:52:20 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> Message-ID: <9cpbddFtidU1@mid.individual.net> "becky_lewis" wrote in message news:d26f81b2-f87e-46f1-bb4e-8ef1943dfe7f at c29g2000yqd.googlegroups.com... >> I have re-installed Python and the setuptool, and tried the Python >> version >> of Active, but it did not make a difference. >> So now I use the "old" Python 2.7 again. Used easy_install to install >> PyWebDAV. I now run davserver.exe from the Script directory. Still the >> same >> problem. >> What I found, however, was that if I specify the directory from the >> command >> line (like davserver -D d:\Webdav -n) there is no error message as >> "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still >> the >> 404 error. >> The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs >> when I >> specify the "-c config.ini" in the command line. >> >> I didn't expect it to be this so tricky. It looked easy to set up an >> experimental webdav server. >> >> Fokke > > How are you trying to access the webdav server? By IE 8 and Firefox, on the same system as well as on another system. Firefox doesn't show the 404 error but shows a blank screen. I bound the davserver to the local adress of the system where it's on (10.0.0.140). The port was 8081 but I changed it to 8008 as you said it's the default. No difference. > I've been hacking on > the server for several days now (unrelated reasons) and have found > that it's a little unforgiving when it comes to configuration errors. > You need to be accessing the webdav server via the correct port (I > think it's 8008 by default). If you're not doing this and something > else is running on port 80 (which is where a webdav client will go to > by default) then this would explain the 404 errors. I certainly use the correct IP address and port number. Underneath is my command shell. The 1st time I specified the config file (davserver.ini), the 2nd time I specified on the command line. Here I logged in with Firefox from system XXX (replaced the name by XXX). (Here I started the server with the the config file (davserver.ini) D:Python27\Scripts>davserver -m -c davserver.ini INFO:pywebdav:Starting up PyWebDAV server INFO:pywebdav:chunked_http_response feature ON INFO:pywebdav:http_request_use_iterator feature OFF INFO:pywebdav:http_response_use_iterator feature OFF INFO:DAVServer.fshandler:Initialized with d:\webdav-http://10.0.0.140:8081/ WARNING:pywebdav:Authentication disabled! INFO:pywebdav:Serving data from d:\webdav Listening on 10.0.0.140 <8081> (browser logging in) INFO:DAVServer.fshandler:get_data: d:\webdav not found XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - ^C D:\Python27\Scripts>INFO:pywebdav:Killed by user (Here I started the server with command line options) davserver -D d:\webdav -H 10.0.0.140 -P 8081 -n WARNING:pywebdav:Authentication disabled! Listening on 10.0.0.140 <8081> XXX --- [07/Sep/2011 11:58:49] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - XXX --- [07/Sep/2011 11:58:54] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - ^C D:\Python27\Scripts>INFO:pywebdav:Killed by user From d_vineet at yahoo.com Wed Sep 7 09:58:26 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Wed, 7 Sep 2011 06:58:26 -0700 (PDT) Subject: web2py In-Reply-To: References: Message-ID: <1315403906.49408.YahooMailNeo@web160511.mail.bf1.yahoo.com> >>>------------------------------------------ Hi, I have been doing python development since last year, I think I should learn the famous Django frame work. Can any one suggest what are the perquisite required to setup django on my local home machine. Please suggest something that does not require a separate server, as this is a personal interest of mine. Thanks, Shambhu I'm currently working on building a new kind of social-network for Users-Groups, Game-Clans & Student-Groups. Building it using DJango with Pinax. Detailed Feature-Set (planned): ? Event management ? Conference management (including ticketing with payment-gateway integration) ? Video+Audio Conferencing of event, with online interaction possibilitiy (great for webinars) ? Join/create/delete/list groups ? Sitewide calendar ? Sitewide feed from non-private groups ? SSO integration (facebook, twitter & linkedin) ? Wall (+feed) for each group ? Listing of who's in which group ? PM group members >>>------------------------------------------ I don't want to undermine django. It is a good framework. But still, my advise would be to go for 'web2py'. http://web2py.com/ It is simple yet powerful. Full stack MVC framework. Low learning curve; simple syntax. Good docs & community. Everything works out of the box (including web-server, DAL, sqlite, etc) No dependencies; plug&play. etc. etc. ---Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Wed Sep 7 10:51:20 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 07 Sep 2011 16:51:20 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: <4E6784E8.2040206@shopzeus.com> > 1. Is there a way for writing portable Python code dealing with > locales > (as sketched in the beginning)? I usually do this at the top of my main program, before importing other modules: import locale locale.setlocale(locale.LC_ALL, '') This is absolutely portable. The above snippet works for different operating systems with different default encodings. You can always setup some environment variable before starting up the program if you really have to. And yes, that setting will be OS dependent, but your program will still be portable. I have no access to Croatian Windows, but I bet that the above code would set the locale to the correct thing on both Linux and Windows. It would be a bad idea to set the locale from anywhere else than your main program anyway. There are also some notes in the docs about this ( http://docs.python.org/library/locale.html#locale.setlocale ): > setlocale() > is not > thread-safe on most systems. Applications typically start with a call of > > import locale > locale.setlocale(locale.LC_ALL, '') > > This sets the locale for all categories to the user's default setting > (typically specified in the *LANG* environment variable). If the > locale is not changed thereafter, using multithreading should not > cause problems. > Why are you trying to force a specific locale to your program anyway? L -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericsnowcurrently at gmail.com Wed Sep 7 11:12:20 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 7 Sep 2011 09:12:20 -0600 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: On Tue, Sep 6, 2011 at 8:19 PM, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of projects > there are that people needs help with. I'd like to choose something that > doesn't have a ton of red tape, but is stable, which is why I ask here > instead of just Googling open source projects. My main interests lie in > accessibility, Utilities and security. An interesting one that I haven't had time to help on yet is the "extensions for unittest" project: https://code.google.com/p/unittest-ext/issues/list Basically it's adding an extensions framework to the stdlib unittest module. I'm sure Michael Foord wouldn't mind the help. Like I said, a very interesting project, though not directly related to accessibility or security. -eric > > -- > > Take care, > ~Ty > Web: http://tds-solutions.net > > Sent from my toaster. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bclark76 at gmail.com Wed Sep 7 11:56:32 2011 From: bclark76 at gmail.com (bclark76) Date: Wed, 7 Sep 2011 08:56:32 -0700 (PDT) Subject: How to structure packages Message-ID: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> I'm learning python, and was playing with structuring packages. Basically I want to have a package called mypackage that defines a number of classes and functions. so I create: mypackage __init__.py myfunc.py MyClass.py my __init__.py is blank. my MyClass.py looks like: import blah class MyClass(blahblah): blah blah blah then I have a run.py that looks like from mypackage import MyClass x = MyClass() This doesn't work because MyClass is mypackage.MyClass.MyClass. There's this MyClass module 'in the way'. I'm trying to follow the rule that every file defines only one class. I could define MyClass in __init__.py, but then what if I wanted to define more classes in the mypackage package? My one class per file rule goes out the window. Is this rule wrongheaded, or is there another way to do this? Thanks. From alec.taylor6 at gmail.com Wed Sep 7 12:09:41 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 8 Sep 2011 02:09:41 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: References: <4E66D4B9.9050402@tysdomain.com> Message-ID: Accessibility? Hmm, you could look at http://groups.google.com/group/django-users/browse_thread/thread/44a4dbf8771e0f4f (https://groups.google.com/forum/#!topic/django-users/RKTb-HceD08) On Thu, Sep 8, 2011 at 1:12 AM, Eric Snow wrote: > On Tue, Sep 6, 2011 at 8:19 PM, Littlefield, Tyler wrote: >> Hello: >> I've got a bit of time on my hands, so I'm curious what sorts of projects >> there are that people needs help with. I'd like to choose something that >> doesn't have a ton of red tape, but is stable, which is why I ask here >> instead of just Googling open source projects. My main interests lie in >> accessibility, Utilities and security. > > An interesting one that I haven't had time to help on yet is the > "extensions for unittest" project: > > https://code.google.com/p/unittest-ext/issues/list > > Basically it's adding an extensions framework to the stdlib unittest > module. ?I'm sure Michael Foord wouldn't mind the help. ?Like I said, > a very interesting project, though not directly related to > accessibility or security. > > -eric > >> >> -- >> >> Take care, >> ~Ty >> Web: http://tds-solutions.net >> >> Sent from my toaster. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From gordon at panix.com Wed Sep 7 12:11:11 2011 From: gordon at panix.com (John Gordon) Date: Wed, 7 Sep 2011 16:11:11 +0000 (UTC) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: In <2a4f542c-a8c1-46c7-9899-a3fad0940cf6 at x11g2000yqc.googlegroups.com> bclark76 writes: > mypackage > __init__.py > myfunc.py > MyClass.py > from mypackage import MyClass Try this instead: from mypackage.MyClass import MyClass -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rafadurancastaneda at gmail.com Wed Sep 7 13:18:43 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Wed, 07 Sep 2011 19:18:43 +0200 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4E67A773.6070304@gmail.com> Check python pep8: http://www.python.org/dev/peps/pep-0008/ And you will see than you shouldn't named modules as you did, so you should do something like: mypackage __init__.py mymodule ... mypackage.mymodule.MyClass On 07/09/11 18:11, John Gordon wrote: > In<2a4f542c-a8c1-46c7-9899-a3fad0940cf6 at x11g2000yqc.googlegroups.com> bclark76 writes: > >> mypackage >> __init__.py >> myfunc.py >> MyClass.py >> from mypackage import MyClass > Try this instead: > > from mypackage.MyClass import MyClass > From __peter__ at web.de Wed Sep 7 13:30:34 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Sep 2011 19:30:34 +0200 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: bclark76 wrote: > I'm learning python, and was playing with structuring packages. If you are coming from Jave you have to unlearn a thing or two. > Basically I want to have a package called mypackage that defines a > number of classes and functions. > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, Yes. > or is there another way to do this? I recommend that you always start out with a module. Once that becomes unwieldy you can convert it into a package. Let's assume that mystuff.py contains a MyClass that you want to move into a separate file. You get the following files: mystuff __init__.py descriptivename.py # MyClass here Note that all filenames are lowercase. If you add the line from .descriptivename import MyClass to __init__.py you can continue to import and use MyClass with the statement from mystuff import MyClass m = MyClass() or import mystuff m = mystuff.MyClass() The disadvantage is of course that mystuff.descriptivename will always be imported, even if you don't need the part of the mystuff package defined there. You may also have a look into unittest as an example of a module that was recently converted into a package. Classes and functions are grouped into submodules by their functionality rather than employing Java's mechanical one-class-per-file pattern. From rantingrick at gmail.com Wed Sep 7 13:56:53 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 7 Sep 2011 10:56:53 -0700 (PDT) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: On Sep 7, 10:56?am, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > so I create: > > mypackage > ? ? __init__.py > ? ? myfunc.py > ? ? MyClass.py Don't tell me you create a module called myfunc.py??? Stuff that function in __init__! Also don't name modules MyClass either. Both the spelling and grammar is incorrect. ALL modules use lowercase (and only integrate underscores in the most dire of need!) geom __init__.py vector3d.py point3d.py transformation.py from geom.transformation import Transformation from geom.vector3d import Vector3d from geom.point3d import Point3d or alternatively: geom __init__.py from __vector3d import Vector3d from __point3d import Point3d from __transformation import Transformation __vector3d.py __point3d.py __transformation.py from geom import Transformation from geom import Vector3d from geom import Point3d Although this method can be brittle due to the fact that one buggy module can break all the imported code in the __init__ module. I usually opt for specifying the module in the import path. From tyler at tysdomain.com Wed Sep 7 14:11:23 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Wed, 07 Sep 2011 12:11:23 -0600 Subject: How to structure packages In-Reply-To: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4E67B3CB.8020600@tysdomain.com> On 9/7/2011 9:56 AM, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > > so I create: > > mypackage > __init__.py > myfunc.py > MyClass.py > > > my __init__.py is blank. > > my MyClass.py looks like: > > import blah > > class MyClass(blahblah): > blah > blah > blah > > > then I have a run.py that looks like > > from mypackage import MyClass > > > x = MyClass() > > > This doesn't work because MyClass is mypackage.MyClass.MyClass. > There's this MyClass module 'in the way'. > You can use the __init__.py to promote that class up. so: from myclass import myclass So that means that myclass will just be in mypackage.myclass, and thus your from mypackage import myclass would work perfectly. I'm not sure if this is how you're supposed to do it, but it works. > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, or is there another way to do this? > > > Thanks. > -- Take care, Ty Web: http://tds-solutions.net Sent from my toaster. From emile at fenx.com Wed Sep 7 14:21:22 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 07 Sep 2011 11:21:22 -0700 Subject: PEP 20 - Silly Question? In-Reply-To: References: <877h5lnq8a.fsf@benfinney.id.au> <4E66C824.6010008@mrabarnett.plus.com> Message-ID: On 9/6/2011 6:31 PM Joshua Miller said... > You sure it wasn't the invisible one? you know the one in the white > text that blends into the background? Aah! So _that's_ significant whitespace! :) Emile From xnews2 at fredp.lautre.net Wed Sep 7 14:24:29 2011 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 07 Sep 2011 18:24:29 GMT Subject: Advice on how to get started with 2D-plotting ? References: <4e6719f1$0$38260$3b214f66@aconews.univie.ac.at> Message-ID: Wow, what an impressive turnout ! Thanks a lot, rantingrick, CM and Herbert, for the fast answers, useful tips and especially the sample code ! Beats starting from a blank page, with a big stick, and will certainly set me on my way much faster... networkx does seem a bit over the top for my simple goal, but both the Tk (I always forget Tk !) and Matplotlib approaches seem to fit the KISS principle just fine... on to the tinkering now :-) Again, thanks to all ! fp From ssegvic at zemris.fer.hr Wed Sep 7 14:33:57 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Wed, 7 Sep 2011 20:33:57 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E6784E8.2040206@shopzeus.com> Message-ID: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "ssegvic" , python-list at python.org > Sent: Wednesday, September 7, 2011 4:51:20 PM > Subject: Re: Portable locale usage > > 1. Is there a way for writing portable Python code dealing with > > locales (as sketched in the beginning)? > I usually do this at the top of my main program, before importing > other modules: > > import locale > locale.setlocale(locale.LC_ALL, '') I have set the system-wide locale to Croatian (Croatia) on my development system as instructed by: http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale Nevertheless, your proposal produces: ('English_United States','1252') Note that I would very much like to avoid changing the system locale (this requires Administrator password and system restart). Setting the locale for my program only would be interesting, but AFAIK this can not be done on Windows (?). > Why are you trying to force a specific locale to your program anyway? Because I wish to be able to correctly sort Croatian names. I expect that most of my Windows users will not care to configure their computers with the national locale (and besides, that does not seem to work, anyway). Cheers, Sinisa From jenn.duerr at gmail.com Wed Sep 7 15:33:03 2011 From: jenn.duerr at gmail.com (noydb) Date: Wed, 7 Sep 2011 12:33:03 -0700 (PDT) Subject: Adding a ranking based on two fields References: <9b98790e-f482-48f9-93e9-80b32f6b4583@g31g2000yqh.googlegroups.com> Message-ID: <0fa8fa0d-51e7-4185-aa37-3bbf358f396b@a12g2000yqi.googlegroups.com> On Aug 25, 4:53?pm, Chris Rebert wrote: > On Thu, Aug 25, 2011 at 1:38 PM, noydb wrote: > > Hello All, > > > Looking for some advice/ideas on how to implement arankingto a > > 'scores' field I have. ?So this scores field has values ranging from > > 1.00-4. ?There is also a count field. ?I want to add a rank field such > > that all the records have a uniqueranking, 1 through the number of > > records (thousands). ?The rank isbasedon the score first, the count > > second. ?So, a record with a score of 4 and a count of 385 is ranked > > higher than a record with a score of 4 and a count of 213 AND higher > > than record with a score of 3.25 with a count of 4640. > > > My thought was to add the unique score values to a list and loop thru > > the list... sort records with score=listItem, addranking... not quite > > sure how to do this! > > things = getListOfYourThings() > things.sort(reverse=True, key=lambda item: (item.score, item.count)) > for i, thing in enumerate(things): > ? ? thing.rank = i + 1 > > Cheers, > Chris > --http://rebertia.com Thanks for this! Someone passed this along, too - helpful http://wiki.python.org/moin/HowTo/Sorting From neubyr at gmail.com Wed Sep 7 15:58:05 2011 From: neubyr at gmail.com (neubyr) Date: Wed, 7 Sep 2011 14:58:05 -0500 Subject: MIMEText encode error - Python 2.6.6 In-Reply-To: <4E669920.3010704@mrabarnett.plus.com> References: <4E669920.3010704@mrabarnett.plus.com> Message-ID: On Tue, Sep 6, 2011 at 5:05 PM, MRAB wrote: > On 06/09/2011 22:52, neubyr wrote: >> >> I am trying to write a program which can email file's content using >> smtplib. I am getting following error while using Python 2.6.6 >> version. >> >> {{{ >> File "./killed_jobs.py", line 88, in sendmail >> ? ?msg = MIMEText(ipfile.read, 'plain') >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", >> line 30, in __init__ >> ? ?self.set_payload(_text, _charset) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", >> line 224, in set_payload >> ? ?self.set_charset(charset) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", >> line 266, in set_charset >> ? ?cte(self) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", >> line 73, in encode_7or8bit >> ? ?orig.encode('ascii') >> AttributeError: 'builtin_function_or_method' object has no attribute >> 'encode' >> >> }}} >> >> >> I am referring to email examples on the doc site >> >> http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples >> . Following is the msg object part in my code: >> >> {{{ >> ... >> ... >> def sendmail(inputfile): >> ? ? ? ? ipfile = open(inputfile, 'r') >> ? ? ? ? msg = MIMEText(ipfile.read, 'plain') >> ? ? ? ? ipfile.close() >> >> ... >> ... >> }}} >> >> I have tried setting subtype and chartype separately as mentioned here >> - http://docs.python.org/release/2.6.6/library/email.mime.html, but >> the error remains same. Any help on what might be wrong here? >> > The docs say: > > ? ?MIMEText(_text[, _subtype[, _charset]]) > > ? ?... _text is the string for the payload ... > > You're passing ipfile.read, which is the read method of the file. You > should be passing the string returned by calling ipfile.read, ie > ipfile.read(). > -- > thanks got pointing that.. -- From t at jollybox.de Wed Sep 7 17:14:26 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 23:14:26 +0200 Subject: Portable locale usage In-Reply-To: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> References: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E67DEB2.5060003@jollybox.de> On 07/09/11 20:33, Sini?a ?egvi? wrote: > I expect that most of my Windows users will not care > to configure their computers with the national locale > (and besides, that does not seem to work, anyway). Are, on Windows, the default system region/language setting, and the locale, distinct? (And, if so, why?!) From anikom15 at gmail.com Wed Sep 7 17:35:25 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 7 Sep 2011 14:35:25 -0700 Subject: How to structure packages In-Reply-To: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <20110907213525.GA6955@Smoke> First of all MyClass.py should be renamed to myclass.py. Module names should be lowercase. Secondly, put this in __init__.py: from .myclass import MyClass and there you go. On Wed, Sep 07, 2011 at 08:56:32AM -0700, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > > so I create: > > mypackage > __init__.py > myfunc.py > MyClass.py > > > my __init__.py is blank. > > my MyClass.py looks like: > > import blah > > class MyClass(blahblah): > blah > blah > blah > > > then I have a run.py that looks like > > from mypackage import MyClass > > > x = MyClass() > > > This doesn't work because MyClass is mypackage.MyClass.MyClass. > There's this MyClass module 'in the way'. > > > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, or is there another way to do this? > > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list From laurent.payot at gmail.com Wed Sep 7 17:35:41 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 14:35:41 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? Message-ID: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Hi there, What is the simplest way to check that you are at the beginning or at the end of an iterable? I'm using enumerate with Python 3.2 (see below) but I'm wondering if there would be a better way. l = ['a', 'b', 'a', 'c'] for pos, i in enumerate(l): if pos == 0: print("head =", i) else: print(i) I know that Python is not exactly a functional language but wouldn't something like "ishead()" or "istail()" be useful? From cs at zip.com.au Wed Sep 7 18:48:24 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 8 Sep 2011 08:48:24 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <20110907224824.GA29885@cskk.homeip.net> On 07Sep2011 14:35, Laurent wrote: | What is the simplest way to check that you are at the beginning or at | the end of an iterable? I'm using enumerate with Python 3.2 (see below) | but I'm wondering if there would be a better way. | | l = ['a', 'b', 'a', 'c'] | | for pos, i in enumerate(l): | if pos == 0: | print("head =", i) | else: | print(i) | | I know that Python is not exactly a functional language but wouldn't | something like "ishead()" or "istail()" be useful? There are a few reasons these do not exist out of the box (quite aside from how easy it is to do on the occasions you actually want it). Tackling ishead and istail in turn... The "ishead()" would need to be a top level function (like "len()") because if it were an iterator method, every iterator would need to have it implemented; currently the number of methods needed to roll your own iterator is just two (iter and next). ishead() could be done as a top level function, though it would need the storage cost of an additional state value to every iterator (i.e. a "first" boolean or equivalent). So you'd be proposing more memory cost and possibly a retrospective code change for all the existing planetwide code, for a minor convenient. As you note, enumerate gets you a pos value, and it is easy enough to write a for loop like this: first = True for i in iterable_thing: if first: print "head =", i else: print i first = False Your istail() is much worse. A generator would need to do lookahead to answer istail() in the general case. Consider iterating over the lines in a file, or better still the lines coming from a pipeline. Or iteraing over packets received on a network connection. You can't answer "istail()" there until you have seen the next line/packet (or EOF/connection close). And that may be an arbitrary amount of time in the future. You're going to stall your whole program for such a question? You can do this easily enough for yourself as an itertools-like thing: write a wrapper generator that answers ishead() and istail() for arbitrary iterators. Completely untested example code: class BoundSensitiveIterator(object): def __init__(self, subiter): self.sofar = 0 self.subiter = subiter self.pending = () def iter(self): return self def next(self): self.sofar += 1 if self.pending is None: raise StopIteration if self.pending: nxt = self.pending[0] self.pending = () return nxt return self.subiter.next() def ishead(self): # maybe <= 1, depending on what you want it to mean return self.sofar == 1 def istail(self): if self.pending is None: return True if self.pending: return False try: nxt = self.subiter.next() except StopIteration: self.pending = None return True else: self.pending = (nxt,) return False I = BoundSensitiveIterator(other_iterable) for n in I: print n, "ishead =", I.ishead(), "istail =", I.istail() You can see it adds some performance and storage overhead, and of course may stall if you every ask istail() of an "on demand" iterable. About the only time I do this is my personal "the()" convenience function: def the(list, context=None): ''' Returns the first element of an iterable, but requires there to be exactly one. ''' icontext="expected exactly one value" if context is not None: icontext=icontext+" for "+context first=True for elem in list: if first: it=elem first=False else: raise IndexError, "%s: got more than one element (%s, %s, ...)" \ % (icontext, it, elem) if first: raise IndexError, "%s: got no elements" % icontext return it Which I use as a definite article in places where an iterable _should_ yield exactly one result (eg SQL SELECTs that _ought_ to get exactly one hit). I can see I wrote that a long time ago - it could do with some style fixes. And a code scan shows it sees little use:-) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Electronic cardboard blurs the line between printed objects and the virtual world. - overhead by WIRED at the Intelligent Printing conference Oct2006 From piet at vanoostrum.org Wed Sep 7 18:52:20 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 00:52:20 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> <9cmq1vFk6fU1@mid.individual.net> <9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> <9cpbddFtidU1@mid.individual.net> Message-ID: "Fokke Nauta" writes: > INFO:DAVServer.fshandler:get_data: d:\webdav not found > XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> > Gecko/ > 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - > XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 > Gecko/ > 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - > >From the log it looks like you are trying to access the server with the url: http://localhost:8008/ or something similar. This won't work as you would try to access the root of your webdav directory in this way (i.e. D:/webdav). The webdav server can only serve files, not directories, so you would have to access http://localhost:8008/somefile.txt where somefile.txt is a file in D:/webdav. This only applies to acces using a browser. If you access the server through a webdav-aware client (for example the Finder on Mac OS X, or probably the Windows Explorer) it can serve the contents of the directory. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From martin.rixham at gmail.com Wed Sep 7 18:57:04 2011 From: martin.rixham at gmail.com (Martin Rixham) Date: Wed, 7 Sep 2011 23:57:04 +0100 Subject: I am confused by Message-ID: Hi all I would appreciate some help understanding something. Basically I am confused by the following: >>> a = [[0, 0], [0, 0]] >>> b = list(a) >>> b[0][0] = 1 >>> a [[1, 0], [0, 0]] I expected the last line to be [[0, 0], [0, 0]] I hope that's clear enough. Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at vanoostrum.org Wed Sep 7 19:01:07 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 01:01:07 +0200 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: "Prasad, Ramit" writes: > It seems to me that if I add a function to the list of class attributes it will automatically wrap with "self" but adding it to the object directly will not wrap the function as a method. Can somebody explain why? I would have thought that any function added to an object would be a method (unless decorated as a class method). The special magic to transform a function into a method is only applied for functions found as attributes of the class, not for instance attributes. It is a matter of design. > Hmm, or does the decoration just tell Python not to turn an object's function into a method? I.e. Is the decorator basically just the syntactic sugar for doing the above? The classmethod decorator transforms the method (or actually the function) into a different kind of object (a class method). -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From laurent.payot at gmail.com Wed Sep 7 19:22:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 16:22:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: I totally understand the performance issue that an hypothetical "istail" would bring, even if I think it would just be the programmer's responsibility not to use it when it's not certain that an end can be detected. But I don't see why *adding* something like "ishead" would be so bad (at worse by using a boolean somewhere as you mentioned). Anyway I was just asking if there is something better than enumerate. So the answer is no? The fact that I have to create a tuple with an incrementing integer for something as simple as checking that I'm at the head just sounds awfully unpythonic to me. From laurent.payot at gmail.com Wed Sep 7 19:22:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 16:22:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: I totally understand the performance issue that an hypothetical "istail" would bring, even if I think it would just be the programmer's responsibility not to use it when it's not certain that an end can be detected. But I don't see why *adding* something like "ishead" would be so bad (at worse by using a boolean somewhere as you mentioned). Anyway I was just asking if there is something better than enumerate. So the answer is no? The fact that I have to create a tuple with an incrementing integer for something as simple as checking that I'm at the head just sounds awfully unpythonic to me. From fnautaNO at SPAMsolfon.nl Wed Sep 7 19:28:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 01:28:03 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net><9cor4gFk15U1@mid.individual.net><9cpbddFtidU1@mid.individual.net> Message-ID: <9cqdb0Fpn4U1@mid.individual.net> "Piet van Oostrum" wrote in message news:m2zkigartn.fsf at cochabamba.vanoostrum.org... > "Fokke Nauta" writes: > > >> INFO:DAVServer.fshandler:get_data: d:\webdav not found >> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >> Gecko/ >> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >> Gecko/ >> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >> > From the log it looks like you are trying to access the server with the > url: > > http://localhost:8008/ or something similar. Yes, I do. > This won't work as you would try to access the root of your webdav > directory in this way (i.e. D:/webdav). The webdav server can only serve > files, not directories, so you would have to access > http://localhost:8008/somefile.txt where somefile.txt is a file in > D:/webdav. OK, thanks. I am not familiar to WebDAV. I tried. Got something different (at least something happened): "Setuptools version 0.6c9 or greater has been installed. (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" Wasn't able to find ez_setup.py yet. > This only applies to acces using a browser. If you access the server > through a webdav-aware client (for example the Finder on Mac OS X, or > probably the Windows Explorer) it can serve the contents of the directory. > -- Thanks. I am just trying to use a calendar with a webdav server. I don't have any experience with that. Simply using my browser to try it out. Fokke From gherron at digipen.edu Wed Sep 7 19:31:37 2011 From: gherron at digipen.edu (Gary Herron) Date: Wed, 07 Sep 2011 16:31:37 -0700 Subject: I am confused by In-Reply-To: References: Message-ID: <4E67FED9.7050609@digipen.edu> On 09/07/2011 03:57 PM, Martin Rixham wrote: > Hi all > I would appreciate some help understanding something. Basically I am > confused by the following: > > >>> a = [[0, 0], [0, 0]] > >>> b = list(a) > >>> b[0][0] = 1 > >>> a > [[1, 0], [0, 0]] > > I expected the last line to be > > [[0, 0], [0, 0]] > > I hope that's clear enough. > > Martin You were expecting the assignment to "b" to create a copy of the original list, and it does, but the copy is only one level deep. So a and b are different lists, but a[i] and b[i] are the same objects for each i. There is a "deepcopy" in the library which may do what you expect. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From python at mrabarnett.plus.com Wed Sep 7 19:39:02 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 00:39:02 +0100 Subject: I am confused by In-Reply-To: References: Message-ID: <4E680096.1020001@mrabarnett.plus.com> On 07/09/2011 23:57, Martin Rixham wrote: > Hi all > I would appreciate some help understanding something. Basically I am > confused by the following: > > >>> a = [[0, 0], [0, 0]] > >>> b = list(a) > >>> b[0][0] = 1 > >>> a > [[1, 0], [0, 0]] > > I expected the last line to be > > [[0, 0], [0, 0]] > > I hope that's clear enough. > What you were expecting is called a "deep copy". You should remember that a list doesn't contain objects themselves, but only _references_ to objects. "list" will copy the list itself (a "shallow copy"), including the references which are in it, but it won't copy the _actual_ objects to which they refer. Try using the "deepcopy" function from the "copy" module: >>> from copy import deepcopy >>> a = [[0, 0], [0, 0]] >>> b = deepcopy(a) >>> b[0][0] = 1 >>> a [[0, 0], [0, 0]] From python.list at tim.thechases.com Wed Sep 7 20:01:33 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 07 Sep 2011 19:01:33 -0500 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <4E6805DD.60607@tim.thechases.com> On 09/07/11 18:22, Laurent wrote: > Anyway I was just asking if there is something better than > enumerate. So the answer is no? The fact that I have to create > a tuple with an incrementing integer for something as simple > as checking that I'm at the head just sounds awfully > unpythonic to me. I've made various generators that are roughly (modulo edge-condition & error checking) something like def with_prev(it): prev = None for i in it: yield prev, i i = prev def with_next(it): prev = it.next() for i in it: yield prev, i prev = i yield prev, None which can then be used something like your original for cur, next in with_next(iterable): if next is None: do_something_with_last(cur) else: do_regular_stuff_with_non_last(cur) for prev, cur in with_prev(iterable): if prev is None: do_something_with_first(cur) else: do_something_with_others(cur) If your iterable can return None, you could create a custom object to signal the non-condition: NO_ITEM = object() and then use NO_ITEM in place of "None" in the above code. -tkc From cs at zip.com.au Wed Sep 7 20:23:14 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 8 Sep 2011 10:23:14 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: <20110908002314.GA15766@cskk.homeip.net> On 07Sep2011 16:22, Laurent wrote: | I totally understand the performance issue that an hypothetical | "istail" would bring, even if I think it would just be the programmer's | responsibility not to use it when it's not certain that an end can | be detected. The trouble with these things is that their presence leads to stallable code, often in libraries. Let the programmer write code dependent on istail() without thinking of the stall case (or even the gratuitous execution case, as in a generator with side effects in calling .next()) and have that buried in a utilities function. Facilities like feof() in C and eof in Pascal already lead to lots of code that runs happily with flat files and behaves badly in interactive or piped input. It is _so_ easy to adopt a style like: while not eof(filehandle): line = filehandle.nextline() ... that is it often thought that having offered the eof() function is a design error. (Of course in the example above the usual python idiom would win out from existing habit, but there are plenty of other situations where is would just be _easy_ to rely of istail() in whatever form.) | But I don't see why *adding* something like "ishead" would be so bad | (at worse by using a boolean somewhere as you mentioned). It is not awful, but as remarked: - extra storage cost to _every_ iterable, for a rarely used facility - extra runtime cost to maintain the state - _retroactive_ burden on _every_ iterator implementation presently existing; every iterator sudden needs to implement and offer this extra facility to be generate purpose use - it is easy to provide the facility on the rare occasions when it is needed Personally, I think point 3 above is the killer and 1 and 2 are serious counter arguments. | Anyway I was just asking if there is something better than enumerate. So | the answer is no? The fact that I have to create a tuple with an | incrementing integer for something as simple as checking that I'm at | the head just sounds awfully unpythonic to me. You can just use a boolean if you like. I have plent of loops like: first = true for i in iterable: if first: blah ... ... first = False Cheap and easy. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Bye and bye, God caught his eye, - Epitaph for a waiter by David McCord From miki.tebeka at gmail.com Wed Sep 7 20:24:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Wed, 7 Sep 2011 17:24:53 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> I guess enumerate is the best way to check for first argument. Note that if someone passes you the iterator as argument you have now way of checking if the consumed items from it. istail can be implemented using itertools.chain, see https://gist.github.com/1202260 From steve+comp.lang.python at pearwood.info Wed Sep 7 20:24:58 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 10:24:58 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Laurent wrote: > Hi there, > > What is the simplest way to check that you are at the beginning or at the > end of an iterable? I don't think this question is meaningful. There are basically two fundamental types of iterables, sequences and iterators. Sequences have random access and a length, so if the "start" and "end" of the sequence is important to you, just use indexing: beginning = sequence[0] end = sequence[-1] for i, x in enumerate(sequence): if i == 0: print("at the beginning") elif i == len(sequence)-1: print("at the end") print(x) Iterators don't have random access, and in general they don't have a beginning or an end. There may not be any internal sequence to speak of: the iterator might be getting data from a hardware device that provides values continuously, or some other series of values without a well-defined beginning or end. Example: def time(): from time import asctime while True: yield asctime() it = time() What would it even mean to say that I am at the beginning or end of it? Iterators have no memory, so in one sense you are *always* at the beginning of the iterator: next() always returns the next item, and the previous item is lost forever. So the answer to the question "Am I at the beginning of an iterator?" is always "You are now". For sequences, the question is best handled differently. For iterators, the question doesn't make sense in general. If you need an iterator that can report its internal state, write your own: import random, time class MyIter(object): def __init__(self): self.start = True self.end = False def __next__(self): if self.start: self.start = False if self.end: raise StopIteration if random.random() < 0.01: self.end = True return time.asctime() def __iter__(self): return self -- Steven From steve+comp.lang.python at pearwood.info Wed Sep 7 20:29:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 10:29:26 +1000 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Peter Otten wrote: > Classes and functions are grouped into > submodules by their functionality rather than employing Java's mechanical > one-class-per-file pattern. Surely it's an anti-pattern? I suppose "one class per file" might be useful for those using an editor with no search functionality. Other than that, is there any justification for this rule? Any Java fans want to defend this? If "one class per file", why not "one method per class" too? Why is the second rule any more silly than the first? -- Steven From cdchong at stanford.edu Wed Sep 7 20:37:51 2011 From: cdchong at stanford.edu (Christophe Chong) Date: Wed, 7 Sep 2011 17:37:51 -0700 Subject: Floating point multiplication in python In-Reply-To: References: Message-ID: And then we learned in class what happens when you're calculating "0.1" with different precision in the industry. http://www.ima.umn.edu/~arnold/disasters/patriot.html Beware. On Tue, Sep 6, 2011 at 3:14 AM, Thomas Rachel < nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de> wrote: > Am 06.09.2011 07:57 schrieb xyz: > >> hi all: >> >> As we know , 1.1 * 1.1 is 1.21 . >> But in python ,I got following : >> >> 1.1 * 1.1 >>>>> >>>> 1.2100000000000002 >> >> why python get wrong result? Who can tell me where's the >> 0.0000000000000002 from? >> > > 1.1 does not fit in a binary floating point number. It is approximated - in > binary! - as 1.000110011001100110011 ... (periodically). > > Note that, while in the decimal system we normally use, only numbers which > have other components in the denominator than 2 or 5 are periodically, in > the binary systems only components with 2 are allowed in order not to be > periodically. > > Example: 3.453 is not periodically, because it is 3453/100 and 100 has only > the factors 2 and 5, each twice. > > 1/3 = .3333333... is periodically, because it has the factor 3. The same > applies to 1/6, which has 2 and 3 as factors. The latter destroys the > non-periodical behaviour. > > As said, in the dual system, only the 2 is allowed. > > .5 (10) = 2** -1 = .1 (2). > .25 (10) = 2 ** -2 = .01 (2). > .75 (10) = their sum = .11 (2). > > But .1 (1/10) is more complicated, -2 would be as well. > > As the IEEE floating point representation is limited, there is a slight > error value which makes the stored value differ from the intended one. > > Look here: > > > > x=(1,0,0,0,1,1,0,0,1,1,0,0,1,**1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,** >>>> 1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,**0,1,1,0,0,1,1,0,0,1,1,0,0,1,1) >>>> a=0 >>>> for n,i in enumerate(x): a += i*2**-n; print a, a-1.1, i*2**-n, a-olda >>>> >>> ... > 1 -0.1 1 1 > 1.0 -0.1 0.0 0.0 > 1.0 -0.1 0.0 0.0 > 1.0 -0.1 0.0 0.0 > 1.0625 -0.0375 0.0625 0.0625 > 1.09375 -0.00625 0.03125 0.03125 > 1.09375 -0.00625 0.0 0.0 > 1.09375 -0.00625 0.0 0.0 > 1.09765625 -0.00234375 0.00390625 0.00390625 > 1.099609375 -0.000390625 0.001953125 0.001953125 > 1.099609375 -0.000390625 0.0 0.0 > 1.099609375 -0.000390625 0.0 0.0 > 1.09985351562 -0.000146484375 0.000244140625 0.000244140625 > 1.09997558594 -2.44140625001e-05 0.0001220703125 0.0001220703125 > 1.09997558594 -2.44140625001e-05 0.0 0.0 > 1.09997558594 -2.44140625001e-05 0.0 0.0 > 1.09999084473 -9.15527343759e-06 1.52587890625e-05 1.52587890625e-05 > 1.09999847412 -1.52587890634e-06 7.62939453125e-06 7.62939453125e-06 > 1.09999847412 -1.52587890634e-06 0.0 0.0 > 1.09999847412 -1.52587890634e-06 0.0 0.0 > 1.0999994278 -5.72204589933e-07 9.53674316406e-07 9.53674316406e-07 > 1.09999990463 -9.53674317294e-08 4.76837158203e-07 4.76837158203e-07 > 1.09999990463 -9.53674317294e-08 0.0 0.0 > 1.09999990463 -9.53674317294e-08 0.0 0.0 > 1.09999996424 -3.57627869541e-08 5.96046447754e-08 5.96046447754e-08 > 1.09999999404 -5.96046456636e-09 2.98023223877e-08 2.98023223877e-08 > 1.09999999404 -5.96046456636e-09 0.0 0.0 > 1.09999999404 -5.96046456636e-09 0.0 0.0 > 1.09999999776 -2.23517426789e-09 3.72529029846e-09 3.72529029846e-09 > 1.09999999963 -3.72529118664e-10 1.86264514923e-09 1.86264514923e-09 > 1.09999999963 -3.72529118664e-10 0.0 0.0 > 1.09999999963 -3.72529118664e-10 0.0 0.0 > 1.09999999986 -1.3969847501e-10 2.32830643654e-10 2.32830643654e-10 > 1.09999999998 -2.32831531832e-11 1.16415321827e-10 1.16415321827e-10 > 1.09999999998 -2.32831531832e-11 0.0 0.0 > 1.09999999998 -2.32831531832e-11 0.0 0.0 > 1.09999999999 -8.73123795486e-12 1.45519152284e-11 1.45519152284e-11 > 1.1 -1.45528034068e-12 7.27595761418e-12 7.27595761418e-12 > 1.1 -1.45528034068e-12 0.0 0.0 > 1.1 -1.45528034068e-12 0.0 0.0 > 1.1 -5.45785638906e-13 9.09494701773e-13 9.09494701773e-13 > 1.1 -9.10382880193e-14 4.54747350886e-13 4.54747350886e-13 > 1.1 -9.10382880193e-14 0.0 0.0 > 1.1 -9.10382880193e-14 0.0 0.0 > 1.1 -3.41948691585e-14 5.68434188608e-14 5.68434188608e-14 > 1.1 -5.77315972805e-15 2.84217094304e-14 2.84217094304e-14 > 1.1 -5.77315972805e-15 0.0 0.0 > 1.1 -5.77315972805e-15 0.0 0.0 > 1.1 -2.22044604925e-15 3.5527136788e-15 3.5527136788e-15 > 1.1 -4.4408920985e-16 1.7763568394e-15 1.7763568394e-15 > 1.1 -4.4408920985e-16 0.0 0.0 > 1.1 -4.4408920985e-16 0.0 0.0 > 1.1 -2.22044604925e-16 2.22044604925e-16 2.22044604925e-16 > 1.1 0.0 1.11022302463e-16 2.22044604925e-16 > 1.1 0.0 0.0 0.0 > 1.1 0.0 0.0 0.0 > 1.1 0.0 1.38777878078e-17 0.0 > 1.1 0.0 6.93889390391e-18 0.0 > > So here we have reached the point where the maximum precision is reached - > a doesn't change anymore, although it should. The error is about 1E-16. > > Now if you multiply two values with an error, the error also propagates > into the result - PLUs the result can have its own error source - in the > same order of magnitude. > > (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e or > (2*a + e) * e. > > -- > http://mail.python.org/**mailman/listinfo/python-list > -- Christophe Chong Department of Economics Stanford University -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.payot at gmail.com Wed Sep 7 20:53:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 17:53:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: Yes of course the use of a boolean variable is obvious but I'm mixing python code with html using Mako templates. In Mako for code readability reasons I try to stick to simple "for" and "if" constructions, and I try to avoid variables declarations inside the html, that's all. Thanks anyway. From laurent.payot at gmail.com Wed Sep 7 20:53:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 17:53:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: Yes of course the use of a boolean variable is obvious but I'm mixing python code with html using Mako templates. In Mako for code readability reasons I try to stick to simple "for" and "if" constructions, and I try to avoid variables declarations inside the html, that's all. Thanks anyway. From laurent.payot at gmail.com Wed Sep 7 21:05:17 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:05:17 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: > I don't think this question is meaningful. There are basically two > fundamental types of iterables, sequences and iterators. > > Sequences have random access and a length, so if the "start" and "end" of > the sequence is important to you, just use indexing: > > beginning = sequence[0] > end = sequence[-1] > for i, x in enumerate(sequence): > if i == 0: print("at the beginning") > elif i == len(sequence)-1: print("at the end") > print(x) > > > Iterators don't have random access, and in general they don't have a > beginning or an end. There may not be any internal sequence to speak of: > the iterator might be getting data from a hardware device that provides > values continuously, or some other series of values without a well-defined > beginning or end. Maybe I should have said "best way to check that you didn't start the iteration process yet" but you see what I mean. Well I guess I have to unlearn my bad lisp/scheme habits... From laurent.payot at gmail.com Wed Sep 7 21:06:53 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:06:53 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> Message-ID: Yes, I was just hoping for something already included that I wouldn't know (i'm new to Python). From tjreedy at udel.edu Wed Sep 7 21:06:56 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 21:06:56 -0400 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <20110908002314.GA15766@cskk.homeip.net> References: <20110908002314.GA15766@cskk.homeip.net> Message-ID: On 9/7/2011 8:23 PM, Cameron Simpson wrote: > On 07Sep2011 16:22, Laurent wrote: > | I totally understand the performance issue that an hypothetical > | "istail" would bring, even if I think it would just be the programmer's > | responsibility not to use it when it's not certain that an end can > | be detected. > > The trouble with these things is that their presence leads to stallable > code, often in libraries. Let the programmer write code dependent on > istail() without thinking of the stall case (or even the gratuitous > execution case, as in a generator with side effects in calling .next()) > and have that buried in a utilities function. > > Facilities like feof() in C and eof in Pascal already lead to lots of > code that runs happily with flat files and behaves badly in interactive > or piped input. It is _so_ easy to adopt a style like: > > while not eof(filehandle): > line = filehandle.nextline() > ... > > that is it often thought that having offered the eof() function is a > design error. (Of course in the example above the usual python idiom > would win out from existing habit, but there are plenty of other > situations where is would just be _easy_ to rely of istail() in whatever > form.) > > | But I don't see why *adding* something like "ishead" would be so bad > | (at worse by using a boolean somewhere as you mentioned). > > It is not awful, but as remarked: > - extra storage cost to _every_ iterable, for a rarely used facility > - extra runtime cost to maintain the state > - _retroactive_ burden on _every_ iterator implementation presently > existing; every iterator sudden needs to implement and offer this > extra facility to be generate purpose use > - it is easy to provide the facility on the rare occasions when it is > needed > > Personally, I think point 3 above is the killer and 1 and 2 are serious > counter arguments. The iterator protocol is intentionally as simple as sensibly possible. > | Anyway I was just asking if there is something better than enumerate. So > | the answer is no? The fact that I have to create a tuple with an > | incrementing integer for something as simple as checking that I'm at > | the head just sounds awfully unpythonic to me. > > You can just use a boolean if you like. I have plent of loops like: > > first = true > for i in iterable: > if first: > blah ... > ... > first = False > > Cheap and easy. Cheers, Or grab and process the first item separately from the rest. it = iter(iterable) try: first = next(it) except StopIteration: raise ValueError("Empty iterable not allowed") for i in it: -- Terry Jan Reedy From tjreedy at udel.edu Wed Sep 7 21:08:11 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 21:08:11 -0400 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/7/2011 8:24 PM, Steven D'Aprano wrote: > I don't think this question is meaningful. There are basically two > fundamental types of iterables, sequences and iterators. And non-sequence iterables like set and dict. > Sequences have random access and a length, so if the "start" and "end" of > the sequence is important to you, just use indexing: > > beginning = sequence[0] > end = sequence[-1] > for i, x in enumerate(sequence): > if i == 0: print("at the beginning") > elif i == len(sequence)-1: print("at the end") > print(x) And finite non-sequences can be turned into sequences with list(iterable). -- Terry Jan Reedy From laurent.payot at gmail.com Wed Sep 7 21:08:51 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:08:51 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Interesting. I will check that yield functionality out. Thanks. From laurent.payot at gmail.com Wed Sep 7 21:08:51 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:08:51 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Interesting. I will check that yield functionality out. Thanks. From jenn.duerr at gmail.com Wed Sep 7 21:32:21 2011 From: jenn.duerr at gmail.com (noydb) Date: Wed, 7 Sep 2011 18:32:21 -0700 (PDT) Subject: how to make fxn argument work with setting a field value Message-ID: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> What do I need to do to line 14 code below to get it to recognize the field name and not the argument name? I get this error with below code at line 13, the print row.rankFld line >RuntimeError: Row: Field rankFld does not exist A field called rankFld does not, should not exist. rankFld is "RANKa" (in this first iteration), which does exist (gets added in line 6, verified). Line 14 fails too, if 13 is commented out. ## import arcpy fc = r"C:\test\scratch.gdb\sort_test1" def rank(inFC, outFC, scoreFld, popFld, rankFld): arcpy.AddField_management(inFC, rankFld, "LONG") arcpy.management.Sort(inFC, outFC, [[scoreFld, "DESCENDING"], [popFld, "DESCENDING"]]) i = 0 print rankFld # >RANKa rows = arcpy.UpdateCursor(fc) for row in rows: i = i + 1 print row.rankFld row.rankFld = i ## line 14 rows.updateRow(row) return sortedFC # out1 = r"C:\test\scratch.gdb\rankfxn6" out2 = r"C:\test\scratch.gdb\rankfxn7" rank(fc, out1, "SCOREa", "COUNT1", "RANKa") rank(out1, out2, "SCOREb", "COUNT2", "RANKb") ## From laurent.payot at gmail.com Wed Sep 7 21:40:23 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:40:23 -0700 (PDT) Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: Neat. But I can see some "print(x)" and some "print x". What is the Python version? From python at mrabarnett.plus.com Wed Sep 7 22:11:07 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 03:11:07 +0100 Subject: how to make fxn argument work with setting a field value In-Reply-To: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: <4E68243B.7060104@mrabarnett.plus.com> On 08/09/2011 02:32, noydb wrote: > What do I need to do to line 14 code below to get it to recognize the > field name and not the argument name? > > I get this error with below code at line 13, the print row.rankFld > line >> RuntimeError: Row: Field rankFld does not exist > A field called rankFld does not, should not exist. rankFld is > "RANKa" (in this first iteration), which does exist (gets added in > line 6, verified). > Line 14 fails too, if 13 is commented out. > > > ## > import arcpy > > fc = r"C:\test\scratch.gdb\sort_test1" > > def rank(inFC, outFC, scoreFld, popFld, rankFld): > arcpy.AddField_management(inFC, rankFld, "LONG") > arcpy.management.Sort(inFC, outFC, [[scoreFld, "DESCENDING"], > [popFld, "DESCENDING"]]) > i = 0 > print rankFld #>RANKa > rows = arcpy.UpdateCursor(fc) > for row in rows: > i = i + 1 > print row.rankFld > row.rankFld = i ## line 14 > rows.updateRow(row) > > return sortedFC > # > > out1 = r"C:\test\scratch.gdb\rankfxn6" > out2 = r"C:\test\scratch.gdb\rankfxn7" > > rank(fc, out1, "SCOREa", "COUNT1", "RANKa") > rank(out1, out2, "SCOREb", "COUNT2", "RANKb") > ## The documentation mentions "getValue" and "setValue": http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z0000001q000000 From clp2 at rebertia.com Wed Sep 7 22:27:09 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 7 Sep 2011 19:27:09 -0700 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> Message-ID: On Wed, Sep 7, 2011 at 5:24 PM, Miki Tebeka wrote: > I guess enumerate is the best way to check for first argument. Note that if someone passes you the iterator as argument you have now way of checking if the consumed items from it. > > istail can be implemented using itertools.chain, see https://gist.github.com/1202260 For the archives, if Gist ever goes down: from itertools import chain def istail(it): '''Check if iterator has one more element. Return True/False and iterator.''' try: i = next(it) except StopIteration: return False, it try: j = next(it) return False, chain([i, j], it) except StopIteration: return True, chain([i], it) t, it = istail(iter([])) print t, list(it) t, it = istail(iter([1])) print t, list(it) t, it = istail(iter([1, 2])) print t, list(it) From rosuav at gmail.com Wed Sep 7 22:39:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 8 Sep 2011 12:39:16 +1000 Subject: How to structure packages In-Reply-To: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Sep 8, 2011 at 10:29 AM, Steven D'Aprano wrote: > Peter Otten wrote: > >> Classes and functions are grouped into >> submodules by their functionality rather than employing Java's mechanical >> one-class-per-file pattern. > > Surely it's an anti-pattern? I don't think that's true; Java merely enforces one _public_ class per source file. A file can have non-public classes, although one .class file has only one class in it (so javac will sometimes make multiple object files from one source file). I'm not wholly sure of the significance of public classes, though, and whether or not it's possible to do your logical grouping and just let them be non-public. BTW, I am not a Java fan, and I don't have any defense prepared. I haven't actually written any serious Java code for a number of years. Used to use it back when IBM reckoned that Java would be the big thing that sells OS/2. ChrisA From sahil at FreeBSD.org Thu Sep 8 00:00:20 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 8 Sep 2011 00:00:20 -0400 Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: <20110908040019.GH3046@magic.hamla.org> On Wed, 2011-09-07 at 18:40:23 -0700, Laurent wrote: > Neat. But I can see some "print(x)" and some "print x". What is the > Python version? See: http://docs.python.org/release/3.2.2/whatsnew/3.0.html#print-is-a-function http://www.python.org/dev/peps/pep-3105/ -- Sahil Tandon From 1248283536 at qq.com Thu Sep 8 00:24:15 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 12:24:15 +0800 Subject: my multi-download program can't finish Message-ID: here is the program, # basic structure,omit something import Queue import httplib2 import threading jobs = Queue.Queue() name=something #omit ,it is a web list to download for x in name: jobs.put(x) def download(): while not jobs.empty(): try: url = jobs.get() hx = httplib2.Http() resp, content = hx.request(url, headers=headers) jobs.task_done() except: print "wrong" , url if __name__ == '__main__': for i in range(10): threading.Thread(target=download).start() jobs.join() when it run ,it can download someting , it is strang:there is wrong output ,some web can't get,but the program can't stop,it stay ,run ,can't fininsh, i don't know why? -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Thu Sep 8 00:50:52 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 12:50:52 +0800 Subject: multi-down in threading module Message-ID: i want to download data in multiprocess ,i know the threading structure,but i can't finish it, would you mind to revise it ? any advice appreciated. [code] import urllib import threading URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') url =[ URL % '+'.join(sym) for sym in symbols] num=rang(3) def down(url): print urllib.urlopen(url).read() for i in num: #these code i can't finish t=threading.Thread(target=down,args= ) threads.append(t) for i in nmu: threads[i].start() for i in num: threads[i].join() [/code] -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 8 01:08:38 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 15:08:38 +1000 Subject: my multi-download program can't finish References: Message-ID: <4e684dd8$0$29970$c3e8da3$5496439d@news.astraweb.com> On Thu, 8 Sep 2011 02:24 pm ???? wrote: [...] > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the program > can't stop,it stay ,run ,can't fininsh, i don't know why? If you read the helpful error messages that Python provides, instead of hiding them and printing a useless message "wrong", you might find out why the failures are happening. Get rid of the try...except and see what exceptions you get. Then you will be in a better situation to decide which exceptions should be caught, and which are bugs that need to be fixed, and which should be allowed through. -- Steven From k.sahithi2862 at gmail.com Thu Sep 8 02:46:13 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Wed, 7 Sep 2011 23:46:13 -0700 (PDT) Subject: FOR EXCLUSIVE HOT ASIN PICS Message-ID: <1bceb162-850e-4ab8-bfe1-dc7658b8c7bc@r40g2000prf.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS SAMANTHA HOT EXCLUSIVE PHOTOS http://southactresstou.blogspot.com/2011/09/south-actress-samantha.html FOR EXCLUSIVE HOT ASIN PICS http://southactresstou.blogspot.com/2011/09/asin.html KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From jialiuonlineshoe03 at 163.com Thu Sep 8 03:29:14 2011 From: jialiuonlineshoe03 at 163.com (ms amy) Date: Thu, 8 Sep 2011 00:29:14 -0700 (PDT) Subject: paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) Message-ID: <0f6e0dd9-b138-4279-90db-f640daf66913@e34g2000prn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale lv shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale NBA shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale antick jeans (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale artful dudger (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hour-buy.com/) paypal wholesale clothing (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Prada (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Puma (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Sand (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Shox (paypal payment)( http://www.24hour-buy.com/) paypal wholesale soccer (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Versace (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Y-3 (paypal payment)( http://www.24hour-buy.com/ ) From 1248283536 at qq.com Thu Sep 8 03:46:55 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 15:46:55 +0800 Subject: =?gbk?B?u9i4tKO6IG15ICBtdWx0aS1kb3dubG9hZCBwcm9n?= =?gbk?B?cmFtIGNhbid0IGZpbmlzaA==?= Message-ID: sometimes,the output is: error: [Errno 104] Connection reset by peer ------------------ ???? ------------------ ???: "Steven D'Aprano"; ????: 2011?9?8?(???) ??1:08 ???: "python-list"; ??: Re: my multi-download program can't finish On Thu, 8 Sep 2011 02:24 pm ???? wrote: [...] > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the program > can't stop,it stay ,run ,can't fininsh, i don't know why? If you read the helpful error messages that Python provides, instead of hiding them and printing a useless message "wrong", you might find out why the failures are happening. Get rid of the try...except and see what exceptions you get. Then you will be in a better situation to decide which exceptions should be caught, and which are bugs that need to be fixed, and which should be allowed through. -- Steven -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenn.duerr at gmail.com Thu Sep 8 03:59:41 2011 From: jenn.duerr at gmail.com (noydb) Date: Thu, 8 Sep 2011 00:59:41 -0700 (PDT) Subject: how to make fxn argument work with setting a field value References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: > The documentation mentions "getValue" and "setValue": > > http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z00...- Hide quoted text - > > - Show quoted text - I have tried row.setValue(rankFld) = i for line 14. Get syntax error - cant assign to function call From gandalf at shopzeus.com Thu Sep 8 04:41:22 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 08 Sep 2011 10:41:22 +0200 Subject: Portable locale usage In-Reply-To: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> References: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E687FB2.9020908@shopzeus.com> > I have set the system-wide locale to Croatian (Croatia) > on my development system as instructed by: > http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale > > Nevertheless, your proposal produces: > ('English_United States','1252') This is what I see on my Hungarian Windows: C:\Users\User>python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'Hungarian_Hungary.1250' >>> locale.getlocale() ('Hungarian_Hungary', '1250') >>> So I'm 100% sure that the problem is with your system locale settings, not Python. > Note that I would very much like > to avoid changing the system locale > (this requires Administrator password and system restart). All right. But you understand, that Croatian ISO8859-2 is not supported on windows? So you will not be able to sort names with that under a windows system? (And it is not a limitation of Python.) >> Why are you trying to force a specific locale to your program anyway? > Because I wish to be able to correctly sort Croatian names. Well, all right. If you want to sort Croatian names from a program that runs on an English (or whatever) system, then you will have to check the platform and use a locale that is supported by the platform. (But again, this is not Python's limitation. Python doesn't know what encodings are supported, in advance, and you cannot use a locale that is not supported...) > I expect that most of my Windows users will not care > to configure their computers with the national locale > (and besides, that does not seem to work, anyway). Croatian users will most likely use a Croatian Windows, out of the box. And on those systems, using locale.setlocale(locale.LC_ALL, '') will work perfectly. I'm not sure why it doesn't work on an English Windows with locale changed... I'm not a big fan of Windows, but I remember once I had to install a language pack for Windows before I could use a localized program. This might be what you need? Best, Laszlo From dan at tombstonezero.net Thu Sep 8 05:51:58 2011 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 8 Sep 2011 09:51:58 +0000 (UTC) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 08 Sep 2011 10:29:26 +1000, Steven D'Aprano wrote: > I suppose "one class per file" might be useful for those using an editor > with no search functionality. Other than that, is there any > justification for this rule? Any Java fans want to defend this? Back in the dark ages known as the 1980s, we had a one-C-function-per- file rule on a project with tens of thousands of C functions. The big benefit was that we always knew which source file contained which function. Computers could search a directory tree much more quickly than that much source code. (The exception was the so-called Information Cluster, a collection of functions surrounding a data store, the predecessor to the modern day object-with-state and/or closure). Not a Java fan'ly yours, Dan From egbertum at xs4all.nl Thu Sep 8 05:55:02 2011 From: egbertum at xs4all.nl (egbert) Date: Thu, 8 Sep 2011 11:55:02 +0200 Subject: DRY and class variables Message-ID: <20110908095502.GA3637@xs4all.nl> My classes correspond to sql tables. In these classes I want to have several class variables that refer to data that are common to all instances. The assignment statements for the class variables are the same in all classes, except that of these instructions needs the name of the class itself. That name is used to read a file with meta-data. So what I have now is something like this (simplified): class TableOne(object): m = Metadata('TableOne') m.do_something() def __init__(self): etc class TableTwo(object): m = Metadata('TableTwo') m.do_something() def __init__(self): etc I have tried: - to eliminate the class name argument, but in this phase of the object creation __class__ and __name__ are not available - to move the two statements to a superclass, but the class variables come in the superclass namespace, not in the subclass namespace. Any ideas ? e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From tartley at tartley.com Thu Sep 8 06:22:05 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 8 Sep 2011 03:22:05 -0700 (PDT) Subject: How to structure packages In-Reply-To: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thursday, September 8, 2011 1:29:26 AM UTC+1, Steven D'Aprano wrote: > Steven D'Aprano wrote: > > Other than that, is there any justification > for this rule? Any Java fans want to defend this? > > If "one class per file", why not "one method per class" too? Why is the > second rule any more silly than the first? Hey. I'm not a Java fan but I'll give it a go. One method per class is not a good idea because a class is a bunch of code that forms a coherent conceptual bundle of functionality. Often, to provide such a bundle, it requires more than one method. To split these methods across several classes would be splitting up a single coherent entity, which makes it harder to understand the purpose and identity of the entity, and more fiddly to delineate the boundary between one such entity and the next. On the other hand, IMHO one class per file is often a good idea. Since a class is a single coherent bundle, then the natural way to split a program into files is often to divide it into these same coherent bundles. Sometimes you have two or more classes that are conceptually very tightly coupled, and it makes sense to gather them up into a single file. However, for me, this is the exception rather than the rule, so in the general case, I usually end up with code that has one class per file. It's only a rule-of-thumb though, and should be broken whenever it seems appropriate. From t at jollybox.de Thu Sep 8 06:22:33 2011 From: t at jollybox.de (Thomas Jollans) Date: Thu, 08 Sep 2011 12:22:33 +0200 Subject: DRY and class variables In-Reply-To: <20110908095502.GA3637@xs4all.nl> References: <20110908095502.GA3637@xs4all.nl> Message-ID: <4E689769.3050701@jollybox.de> On 08/09/11 11:55, egbert wrote: > My classes correspond to sql tables. > In these classes I want to have several class variables > that refer to data that are common to all instances. > > The assignment statements for the class variables are the same > in all classes, except that of these instructions needs the name > of the class itself. That name is used to read a file with meta-data. > > So what I have now is something like this (simplified): > > class TableOne(object): > m = Metadata('TableOne') > m.do_something() > def __init__(self): > etc > > class TableTwo(object): > m = Metadata('TableTwo') > m.do_something() > def __init__(self): > etc > > I have tried: > - to eliminate the class name argument, but in this phase of the > object creation __class__ and __name__ are not available > - to move the two statements to a superclass, but the class variables > come in the superclass namespace, not in the subclass namespace. > > Any ideas ? You should be able to do this with a metaclass (almost certainly overkill), or with a class decorator (Python 2.6+): def with_metadata (cls): cls.m = Metadata (cls.__name__) cls.m.do_something () return cls @with_metadata class TableOne: # foo pass From adam.jorgensen.za at gmail.com Thu Sep 8 06:30:21 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Thu, 8 Sep 2011 12:30:21 +0200 Subject: [Python-ideas] relaxing keyword usage restrictions In-Reply-To: References: <20110906164103.772ed18b@resist.wooz.org> <20110906183346.2bcdfbf8@resist.wooz.org> <20110906215717.62adf161@resist.wooz.org> Message-ID: About the only keyword I can think of this being even slightly useful for would be class and even then I think that clazz is a pretty acceptable substitute. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at vanoostrum.org Thu Sep 8 06:53:45 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 12:53:45 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: Terry Reedy writes: > Indexing objects by their internal id is usually useless. obj.id is not the internal id. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From piet at vanoostrum.org Thu Sep 8 07:01:10 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 13:01:10 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> <9cmq1vFk6fU1@mid.individual.net> <9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> <9cpbddFtidU1@mid.individual.net> <9cqdb0Fpn4U1@mid.individual.net> Message-ID: "Fokke Nauta" writes: > "Piet van Oostrum" wrote in message > news:m2zkigartn.fsf at cochabamba.vanoostrum.org... >> "Fokke Nauta" writes: >> >> >>> INFO:DAVServer.fshandler:get_data: d:\webdav not found >>> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >>> Gecko/ >>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >>> Gecko/ >>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>> >> From the log it looks like you are trying to access the server with the >> url: >> >> http://localhost:8008/ or something similar. > > Yes, I do. > >> This won't work as you would try to access the root of your webdav >> directory in this way (i.e. D:/webdav). The webdav server can only serve >> files, not directories, so you would have to access >> http://localhost:8008/somefile.txt where somefile.txt is a file in >> D:/webdav. > > OK, thanks. I am not familiar to WebDAV. > I tried. Got something different (at least something happened): > "Setuptools version 0.6c9 or greater has been installed. > (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" > > Wasn't able to find ez_setup.py yet. > Google for it and install. But I don't understand. You already had WebDav installed, so why do you need ez_setup.py? >> This only applies to acces using a browser. If you access the server >> through a webdav-aware client (for example the Finder on Mac OS X, or >> probably the Windows Explorer) it can serve the contents of the directory. >> -- > > Thanks. I am just trying to use a calendar with a webdav server. I don't > have any experience with that. > Simply using my browser to try it out. Did you try the calendar with the WebDav server running? Dit you put a file in D:\webdav and try to get it with the browser? -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From rosuav at gmail.com Thu Sep 8 08:12:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 8 Sep 2011 22:12:59 +1000 Subject: lfun and such In-Reply-To: <4E68B08D.2090800@dirix.nu> References: <4E68AC0D.6010007@dirix.nu> <4E68B08D.2090800@dirix.nu> Message-ID: On Thu, Sep 8, 2011 at 10:09 PM, Marc Dirix wrote: > scratch that. > > Silly me. > Heh. I'm curious now as to what was wrong, but am glad it's all working! I just switched back from my test run where I made a minimal class implementing `[]() and `[]=() to see if there was something weirdly wrong. ChrisA From simoncropper at fossworkflowguides.com Thu Sep 8 08:26:31 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Thu, 08 Sep 2011 22:26:31 +1000 Subject: Create an index from a webpage Message-ID: <4E68B477.9020703@fossworkflowguides.com> Hi, I am getting dizzy on google. I am after a way of pointing a python routine to my website and have it create a tree, represented as a hierarchical HTML list in a webpage, of all the pages in that website (recursive list of internal links to HTML documents; ignore images, etc.). It is essentially a contents page or sitemap for the site. Interestingly, despite trying quite a few keyword combinations, I was unable to find such a script. Anyone have any ideas? -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From PointedEars at web.de Thu Sep 8 08:38:53 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Thu, 08 Sep 2011 14:38:53 +0200 Subject: Create an index from a webpage References: Message-ID: <1537032.qVoOGUtdWV@PointedEars.de> Simon Cropper wrote: > I am after a way of pointing a python routine to my website and have it > create a tree, represented as a hierarchical HTML list in a webpage, of > all the pages in that website (recursive list of internal links to HTML > documents; ignore images, etc.). > > It is essentially a contents page or sitemap for the site. If all else fails, use markup parsers like - - and write it yourself. It is not hard to do. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From fnautaNO at SPAMiae.nl Thu Sep 8 09:57:48 2011 From: fnautaNO at SPAMiae.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 15:57:48 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net><9cor4gFk15U1@mid.individual.net><9cpbddFtidU1@mid.individual.net><9cqdb0Fpn4U1@mid.individual.net> Message-ID: <9crvuvFpt2U1@mid.individual.net> "Piet van Oostrum" wrote in message news:m2mxefb8nd.fsf at cochabamba.vanoostrum.org... > "Fokke Nauta" writes: > >> "Piet van Oostrum" wrote in message >> news:m2zkigartn.fsf at cochabamba.vanoostrum.org... >>> "Fokke Nauta" writes: >>> >>> >>>> INFO:DAVServer.fshandler:get_data: d:\webdav not found >>>> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >>>> Gecko/ >>>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>>> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >>>> Gecko/ >>>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>>> >>> From the log it looks like you are trying to access the server with the >>> url: >>> >>> http://localhost:8008/ or something similar. >> >> Yes, I do. >> >>> This won't work as you would try to access the root of your webdav >>> directory in this way (i.e. D:/webdav). The webdav server can only serve >>> files, not directories, so you would have to access >>> http://localhost:8008/somefile.txt where somefile.txt is a file in >>> D:/webdav. >> >> OK, thanks. I am not familiar to WebDAV. >> I tried. Got something different (at least something happened): >> "Setuptools version 0.6c9 or greater has been installed. >> (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" >> >> Wasn't able to find ez_setup.py yet. >> > Google for it and install. I did. > But I don't understand. You already had WebDav installed, so why do you > need ez_setup.py? Well, that was my mistake. I entered in the browser http://10.0.0.140:8081/a.txt (one of the textfiles in the directory d:\webdav on the server) and got the message: "Setuptools version 0.6c9 or greater has been installed. (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" At first I thought this came from the webdav server. That's why I searched for the ez_setup.py script. Once it was there, I ran it. It took me some time before I realized it was the actual content of the document a.txt on the webdav server what I saw. So it worked! Different that I expected, but it works. >>> This only applies to acces using a browser. If you access the server >>> through a webdav-aware client (for example the Finder on Mac OS X, or >>> probably the Windows Explorer) it can serve the contents of the >>> directory. >>> -- >> >> Thanks. I am just trying to use a calendar with a webdav server. I don't >> have any experience with that. >> Simply using my browser to try it out. > > Did you try the calendar with the WebDav server running? Not yet. The next step is the calendar. > Dit you put a file in D:\webdav and try to get it with the browser? Yes, and that worked! I am able to see the contents of text files. In my unfamiliarity with WebDAV I expected to open the directory and see the files in there. Many thanks for your help. Fokke From fnautaNO at SPAMiae.nl Thu Sep 8 10:10:37 2011 From: fnautaNO at SPAMiae.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 16:10:37 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> Message-ID: <9cs0mvFoaU1@mid.individual.net> "Fokke Nauta" wrote in message news:9c4trjFcfmU1 at mid.individual.net... > Hi all, > > I am completely new to Python, but I'm confronted with a problem I can't > solve. > This is my question: > > I'm running a PC with XP Pro32, which acts as a file server/print > server/FTP server and web server. The web server is facilitated by the > Aprelium Abyss X2 server, and has Perl and PHP support on http and https. > It all works fine. > To do some research with some calender systems and to share the Outlook > calendar I need a WebDAV server. After googling I found the Python WebDAV > server. > I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. > Now I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 > and PyXML-0.8.4. In the PyWebDAV README it says: > > Installation and setup of server can be as easy as follows: > > $ easy_install PyWebDAV > $ davserver -D /tmp -n -J > > But of course it doesn't work like that. When I start up Python GUI I see > the ">>>" prompt instead of the "$" prompt. But where do I place the two > directories? And there is no easy_install script in the PyXML-0.8.4 > directory, only a setup.py and ez_setup.py script. I guess the latter is > the one to use. But how? > > How do I proceed next? > > Any help will be appreciated. > Thanks in advance. > > With regards, > Fokke Nauta > I have my webdav server up and running. Many thanks for all who contributed to solving this problem. With regards, Fokke Nauta From wolftracks at invalid.com Thu Sep 8 10:10:54 2011 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 08 Sep 2011 07:10:54 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 9/5/2011 9:36 AM, Colin J. Williams wrote: > On 05-Sep-11 12:22 PM, Dan Nagle wrote: >> Hello, >> >> On 2011-09-05 16:15:20 +0000, W. eWatson said: >> >>> On 9/5/2011 8:24 AM, Chris Angelico wrote: >>>> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson >>>> wrote: >>>>> See Subject. >> >> >> >>>>> To what extent "familiar"? I have it installed on several computers, >>>> but only because it comes with Open Wat C/C++. >>>> >>>> With something off-topic like this, >> >> >> >>>> sierra_mtnview @ sbcglobal.net >>> Here's the story. >>> >>> As far as I can tell F77 1.8 is not available. I've Googled quite a >>> bit for it. My source for 1.9 is >>> . It gives me: >>> open-watcom-f77-win32-1.9.exe. >> >> On Usenet, comp.lang.fortran might be the best source of help for this. >> There's a good chance one of the regulars there can answer you >> within one or two posts. (I'll not cross-post, you can choose for >> yourself.) >> >> HTH >> > > You might get in touch with someone at Waterloo University, which is > located in Kitchener/Waterloo. > > This could have come from the 60's or 70's. > > Good luck. > > Colin W. > Left a message on Tuesday. No return call. I'm starting to make progress on this. From 1248283536 at qq.com Thu Sep 8 10:12:19 2011 From: 1248283536 at qq.com (=?utf-8?B?YWxpYXM=?=) Date: Thu, 8 Sep 2011 22:12:19 +0800 Subject: wrap the queue to multiprocess download Message-ID: here is my part of program,you can see main structure,i want to wrap it in class , class webdata(object): def __init__(self,arg): jobs = Queue.Queue() for x in name: jobs.put(self.url) def download(self): while not self.jobs.empty(): url = self.jobs.get() hx = httplib2.Http() resp, content = hx.request(url, headers=headers).read() self.jobs.task_done() def myrun(self): for i in range(30): threading.Thread(target=self.download).start() self.jobs.join() if __name__=="__main__": s=webdata('quote') s.myrun() when it run ,the output is : Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) File "/home/pengtao/workspace/try.py", line 75, in download resp, content = hx.request(url, headers=headers).read() File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1288, in request (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 201, in urlnorm (scheme, authority, path, query, fragment) = parse_uri(uri) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 197, in parse_uri groups = URI.match(uri).groups() TypeError: expected string or buffer when i use the same structrue, don't wrap it ,it can run . -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at torek.net Thu Sep 8 10:21:23 2011 From: nospam at torek.net (Chris Torek) Date: 8 Sep 2011 14:21:23 GMT Subject: Best way to check that you are at the beginning (the end) of an iterable? References: Message-ID: In article Cameron Simpson wrote: >Facilities like feof() in C and eof in Pascal already lead to lots of >code that runs happily with flat files and behaves badly in interactive >or piped input. It is _so_ easy to adopt a style like: > > while not eof(filehandle): > line = filehandle.nextline() > ... Minor but important point here: eof() in Pascal is predictive (uses a "crystal ball" to peer into the future to see whether EOF is is about to occur -- which really means, reads ahead, causing that interactivity problem you mentioned), but feof() in C is "post-dictive". The feof(stream) function returns a false value if the stream has not yet encountered an EOF, but your very next attempt to read from it may (or may not) immediately encounter that EOF. Thus, feof() in C is sort of (but not really) useless. (The actual use cases are to distinguish between "EOF" and "error" after a failed read from a stream -- since C lacks exceptions, getc() just returns EOF to indicate "failed to get a character due to end of file or error" -- or in some more obscure cases, such as the nonstandard getw(), to distinguish between a valid -1 value and having encountered an EOF. The companion ferror() function tells you whether an earlier EOF value was due to an error.) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From rosuav at gmail.com Thu Sep 8 10:26:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 00:26:03 +1000 Subject: wrap the queue to multiprocess download In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 12:12 AM, alias <1248283536 at qq.com> wrote: > ??? def? __init__(self,arg): > ??????? for? x? in? name: > > ??? s=webdata('quote') What you're doing here is iterating over the letters in the string 'quote'. It's adding one job for each letter. Is that your intention? ChrisA From python at mrabarnett.plus.com Thu Sep 8 11:06:11 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 16:06:11 +0100 Subject: how to make fxn argument work with setting a field value In-Reply-To: References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: <4E68D9E3.8060403@mrabarnett.plus.com> On 08/09/2011 08:59, noydb wrote: >> The documentation mentions "getValue" and "setValue": >> >> http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z00...- Hide quoted text - >> >> - Show quoted text - > > I have tried row.setValue(rankFld) = i for line 14. Get syntax error > - cant assign to function call Of course you can't assign to a function call! It's: row.setValue(rankFld, value) and: value = row.getValue(rankFld) From steve+comp.lang.python at pearwood.info Thu Sep 8 11:11:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 01:11:28 +1000 Subject: Create an index from a webpage References: <1537032.qVoOGUtdWV@PointedEars.de> Message-ID: <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Thomas 'PointedEars' Lahn wrote: > [climbs up on the soapbox and begins rant] Please don't use lmgtfy. The joke, such as it is, stopped being funny about three years ago. It's just annoying, and besides, it doesn't even work without Javascript. Kids today have no respect, get off my lawn, grump grump grump... It's no harder to put the search terms into a google URL, which still gets the point across without being a dick about it: www.google.com/search?q=python+sitemap [ends rant, climbs back down off soapbox] Or better still, use a search engine that doesn't track and bubble your searches: https://duckduckgo.com/html/?q=python+sitemap You can even LMDDGTFY if you insist. http://lmddgtfy.com/ Completely-undermining-my-own-message-ly y'rs, -- Steven From python at mrabarnett.plus.com Thu Sep 8 11:25:53 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 16:25:53 +0100 Subject: my multi-download program can't finish In-Reply-To: References: Message-ID: <4E68DE81.5060809@mrabarnett.plus.com> On 08/09/2011 05:24, ???? wrote: > here is the program, > > # basic structure,omit something > import Queue > import httplib2 > import threading > jobs = Queue.Queue() > name=something #omit ,it is a web list to download > for x in name: > jobs.put(x) > > def download(): > while not jobs.empty(): > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > > if __name__ == '__main__': > > for i in range(10): > threading.Thread(target=download).start() > jobs.join() > > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the > program can't stop,it stay ,run ,can't fininsh, > i don't know why? > The line: jobs.join() will wait until every job has been marked as done by: jobs.task_done() In function "download", if there's an exception, it will go to the exception handler and print a message, but there's no: jobs.task_done() there to tell the queue that the job has been done. You need to tell it when a job has been processed. It doesn't care whether a job succeeded or failed, only whether it has been processed. From ssegvic at zemris.fer.hr Thu Sep 8 11:39:42 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Thu, 8 Sep 2011 17:39:42 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E687FB2.9020908@shopzeus.com> Message-ID: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "Sini?a ?egvi?" , python-list at python.org > Sent: Thursday, September 8, 2011 10:41:22 AM > Subject: Re: Portable locale usage > > I have set the system-wide locale to Croatian (Croatia) > > on my development system as instructed by: > > http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale > > > > Nevertheless, your proposal produces: > > ('English_United States','1252') > This is what I see on my Hungarian Windows: > > > C:\Users\User>python > Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit > (AMD64)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import locale > >>> locale.setlocale(locale.LC_ALL, '') > 'Hungarian_Hungary.1250' > >>> locale.getlocale() > ('Hungarian_Hungary', '1250') > >>> > > So I'm 100% sure that the problem is with your system locale settings, > not Python. I've just found out how to set the user locale on Windows. One has to go to Control panel -> Regional and language options, then select the tab named Formats, and finally set the box Current format to the desired language, which is in my case Croatian (Croatia). The whole tab says nothing about locales, I found this by try and test. This recipe is not affected by the system locale (which I was setting before)! Now locale.setlocale(locale.LC_ALL, '') sets the Croatian locale. > > I expect that most of my Windows users will not care > > to configure their computers with the national locale > > (and besides, that does not seem to work, anyway). > Croatian users will most likely use a Croatian Windows, out of the > box. > And on those systems, using locale.setlocale(locale.LC_ALL, '') will > work perfectly. Yes it's true, you were right, I was setting the Croatian language at the wrong place (I am not a Windows fan neither, I normally work on Linux). However, I am not completely happy with this. OK, no need for system restart, but still, it would be nice if Python program could manage around this by itself, of course, provided that the required locale is installed. > > Note that I would very much like > > to avoid changing the system locale > > (this requires Administrator password and system restart). > All right. But you understand, that Croatian ISO8859-2 is not > supported on windows? Yes I do understand that. I have commented that the Python's locale aliasing engine should not propose iso8859-2 on Windows systems, exactly for the reason you mention. > >> Why are you trying to force a specific locale to your program > >> anyway? > > Because I wish to be able to correctly sort Croatian names. > Well, all right. If you want to sort Croatian names from a program that > runs on an English (or whatever) system, then you will have to check the > platform and use a locale that is supported by the platform. (But again, > this is not Python's limitation. Python doesn't know what encodings are > supported, in advance, and you cannot use a locale that is not supported...) I fully agree. I commented that, if a proper locale is installed, the following should work on any system: locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) Currently the above does not work on Windows, and that is because the locale_alias for 'hr' is bound to 'hr_HR.ISO8859-2'. Check the source: .../Python-3.2.2/Lib/locale.py, line 537 I was arguing that, on a Windows system, the locale_alias for 'hr' should be bound to 'Croatian_Croatia.1250'. Cheers, Sinisa From ericsnowcurrently at gmail.com Thu Sep 8 12:44:04 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 8 Sep 2011 10:44:04 -0600 Subject: DRY and class variables In-Reply-To: <20110908095502.GA3637@xs4all.nl> References: <20110908095502.GA3637@xs4all.nl> Message-ID: On Thu, Sep 8, 2011 at 3:55 AM, egbert wrote: > My classes correspond to sql tables. > In these classes I want to have several class variables > that refer to data that are common to all instances. > > The assignment statements for the class variables are the same > in all classes, except that of these instructions needs the name > of the class itself. That name is used to read a file with meta-data. > > So what I have now is something like this (simplified): > > class TableOne(object): > ? ?m = Metadata('TableOne') > ? ?m.do_something() > ? ?def __init__(self): > ? ? ? ?etc > > class TableTwo(object): > ? ?m = Metadata('TableTwo') > ? ?m.do_something() > ? ?def __init__(self): > ? ? ? ?etc > > I have tried: > - to eliminate the class name argument, but in this phase of the > ?object creation __class__ and __name__ are not available > - to move the two statements to a superclass, but the class variables > ?come in the superclass namespace, not in the subclass namespace. > > Any ideas ? Definitely an interesting problem I've run into before. Here are two solutions: 1. in Python 3, use the metaclass __prepare__() (see http://code.activestate.com/recipes/577813/); 2. in Python 2 or 3, use a descriptor to defer creating your Metadata objects until after the class object is available (see http://code.activestate.com/recipes/577745/). HTH -eric > e > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS ?Amsterdam - 020 6257991 > ======================================================================== > -- > http://mail.python.org/mailman/listinfo/python-list > From tavares at fe.up.pt Thu Sep 8 15:29:57 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 8 Sep 2011 12:29:57 -0700 (PDT) Subject: =?windows-1252?Q?Symposium_=93Experimental_and_Computational_Bio=2DImag?= =?windows-1252?Q?ing_and_Visualization=94_within_ICEM15_=96_Announce_=26_Call_f?= =?windows-1252?Q?or_Papers?= Message-ID: <839676a0-6525-4d74-8232-205ca9100001@cd4g2000vbb.googlegroups.com> Dear Colleague, Within the 15th International Conference on Experimental Mechanics (ICEM15), to be held in Faculty of Engineering, University of Porto, Porto, Portugal, in July 22-27, 2012, (www.fe.up.pt/clme/icem15/ index.htm), we are organizing a Symposium on ?Experimental and Computational Bio-Imaging and Visualization?. The main goal of the Symposium ?Experimental and Computational Bio- Imaging and Visualization? is to bring together researchers, developers and clinicians involved in the related fields of Bio- Imaging and Visualization, including Biomechanics, Experimental Biomechanics, Image Processing and Analysis, Medical Imaging, Mechanobiology, Tissues Engineering, Scientific Visualization and Software and Hardware Development, in order to set the major lines of development for the near future and establish a bridge between them. INSTRUCTIONS & SUBMISSION: - For instructions and submission, please access to the conference website at: www.fe.up.pt/clme/icem15/index.htm; - Please, note that, when submitting your work, you should indicate the Symposium ?Experimental and Computational Bio-Imaging and Visualization?. IMPORTANT DATES: - Submission of abstracts: 30 November, 2011; - Notification of acceptance: 13 January, 2012; - Submission of full-papers: 16 March, 2012. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Yongjie Zhang (Carnegie Mellon University, USA, jessicaz at andrew.cmu.edu) (Symposium organizers) From georgeryoung at gmail.com Thu Sep 8 15:51:17 2011 From: georgeryoung at gmail.com (gry) Date: Thu, 8 Sep 2011 12:51:17 -0700 (PDT) Subject: replace random matches of regexp Message-ID: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> [Python 2.7] I have a body of text (~1MB) that I need to modify. I need to look for matches of a regular expression and replace a random selection of those matches with a new string. There may be several matches on any line, and a random selection of them should be replaced. The probability of replacement should be adjustable. Performance is not an issue. E.g: if I have: SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = sqrt((0.02 + PUBLIC_TT_1.F))) OR I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but only with probability 0.7. I looked and looked for some computed thing in re's that I could stick and expression, but could not find such(for good reasons, I know). Any ideas how to do this? I would go for simple, even if it's wildly inefficient, though elegance is always admired... From python at mrabarnett.plus.com Thu Sep 8 16:12:34 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 21:12:34 +0100 Subject: replace random matches of regexp In-Reply-To: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: <4E6921B2.2010300@mrabarnett.plus.com> On 08/09/2011 20:51, gry wrote: > [Python 2.7] > I have a body of text (~1MB) that I need to modify. I need to look > for matches of a regular expression and replace a random selection of > those matches with a new string. There may be several matches on any > line, and a random selection of them should be replaced. The > probability of replacement should be adjustable. Performance is not > an issue. E.g: if I have: > > SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN > PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, > PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM > (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) > =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = > sqrt((0.02 + PUBLIC_TT_1.F))) OR > > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... re.sub can accept a function as the replacement. It'll call the function when it finds a match, and the string returned by that function will be the replacement. You could write a function which returns either the original substring which was found or a different substring. From ndparker at gmail.com Thu Sep 8 16:18:00 2011 From: ndparker at gmail.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 08 Sep 2011 22:18:00 +0200 Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: <10875052.MZNQO6iqsQ@news.perlig.de> * gry wrote: > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... You can run a re.sub() with a function as replacement value. This function then either returns the replacement or the original match based on a weighted random value. nd -- "Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)" -- aus einer Rezension From __peter__ at web.de Thu Sep 8 16:43:15 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 22:43:15 +0200 Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: gry wrote: > [Python 2.7] > I have a body of text (~1MB) that I need to modify. I need to look > for matches of a regular expression and replace a random selection of > those matches with a new string. There may be several matches on any > line, and a random selection of them should be replaced. The > probability of replacement should be adjustable. Performance is not > an issue. E.g: if I have: > > SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN > PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, > PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM > (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) > =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = > sqrt((0.02 + PUBLIC_TT_1.F))) OR > > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... def make_sub(text, probability): def sub(match): if random.random() < probability: return text + match.group(1) return match.group(1) return sub print re.compile("(max|min|cos|sqrt|ceil)").sub(make_sub(r"public.", .7), sample) or even def make_sub(text, probability): def sub(match): if random.random() < probability: def group_sub(m): return match.group(int(m.group(1))) return re.compile(r"[\\](\d+)").sub(group_sub, text) return match.group(0) return sub print re.compile("(max|min|cos|sqrt|ceil)").sub(make_sub(r"public.\1", .7), sample) From egbertum at xs4all.nl Thu Sep 8 16:53:35 2011 From: egbertum at xs4all.nl (egbert) Date: Thu, 8 Sep 2011 22:53:35 +0200 Subject: DRY and class variables In-Reply-To: <4E689769.3050701@jollybox.de> References: <20110908095502.GA3637@xs4all.nl> <4E689769.3050701@jollybox.de> Message-ID: <20110908205335.GA18306@xs4all.nl> On Thu, Sep 08, 2011 at 12:22:33PM +0200, Thomas Jollans wrote: > You should be able to do this with a metaclass (almost certainly > overkill), or with a class decorator (Python 2.6+): > > def with_metadata (cls): > cls.m = Metadata (cls.__name__) > cls.m.do_something () > return cls > > @with_metadata > class TableOne: > # foo > pass Overnight I have become a decorator fan. I can postpone the study of metaclasses. Thanks. e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From georgeryoung at gmail.com Thu Sep 8 17:19:29 2011 From: georgeryoung at gmail.com (gry) Date: Thu, 8 Sep 2011 14:19:29 -0700 (PDT) Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: On Sep 8, 3:51?pm, gry wrote: To elaborate(always give example of desired output...) I would hope to get something like: SELECT public.max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (public.ceil(0.46) =public.sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = public.sqrt((0.02 + PUBLIC_TT_1.F))) OR notice the 'ceil' on the third line did not get changed. From paul.hermeneutic at gmail.com Thu Sep 8 18:29:39 2011 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Thu, 08 Sep 2011 16:29:39 -0600 Subject: Django or web2py Message-ID: <9cstuhFnm0U1@mid.individual.net> I have read some of the talk around these two frameworks. Would you say that web2py is more geared toward the enterprise? Which one do you believe will be on Python 3 more quickly? From cs at zip.com.au Thu Sep 8 18:39:44 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 9 Sep 2011 08:39:44 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: <20110908223944.GA28756@cskk.homeip.net> On 08Sep2011 14:21, Chris Torek wrote: | In article | Cameron Simpson wrote: | >Facilities like feof() in C and eof in Pascal already lead to lots of | >code that runs happily with flat files and behaves badly in interactive | >or piped input. It is _so_ easy to adopt a style like: | > | > while not eof(filehandle): | > line = filehandle.nextline() | > ... | | Minor but important point here: eof() in Pascal is predictive (uses | a "crystal ball" to peer into the future to see whether EOF is is | about to occur -- which really means, reads ahead, causing that | interactivity problem you mentioned), but feof() in C is "post-dictive". | The feof(stream) function returns a false value if the stream has | not yet encountered an EOF, but your very next attempt to read from | it may (or may not) immediately encounter that EOF. Thanks. I had forgotten this nuance. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ "Where am I?" "In the Village." "What do you want?" "Information." "Whose side are you on?" "That would be telling. We want information. Information. Information!" "You won't get it!" "By hook or by crook, we will." "Who are you?" "The new number 2." "Who is number 1?" "You are number 6." "I am not a number, I am a free man!" [Laughter] From abhishek.vit at gmail.com Thu Sep 8 18:49:51 2011 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Thu, 8 Sep 2011 15:49:51 -0700 Subject: Processing a file using multithreads Message-ID: Hi Guys My experience with python is 2 days and I am looking for a slick way to use multi-threading to process a file. Here is what I would like to do which is somewhat similar to MapReduce in concept. # test case 1. My input file is 10 GB. 2. I want to open 10 file handles each handling 1 GB of the file 3. Each file handle is processed in by an individual thread using the same function ( so total 10 cores are assumed to be available on the machine) 4. There will be 10 different output files 5. once the 10 jobs are complete a reduce kind of function will combine the output. Could you give some ideas ? So given a file I would like to read it in #N chunks through #N file handles and process each of them separately. Best, -Abhi From simoncropper at fossworkflowguides.com Thu Sep 8 19:40:42 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 09:40:42 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E69527A.20608@fossworkflowguides.com> On 09/09/11 01:11, Steven D'Aprano wrote: > [SNIP] > It's no harder to put the search terms into a google URL, which still gets > the point across without being a dick about it: > [SNIP] [RANT] OK I was not going to say anything but... 1. Being told to google-it when I explicitly stated in my initial post that I had been doing this and had not been able to find anything is just plain rude. It is unconstructive and irritating. 2. I presume that python-list is a mail list for python users - beginners, intermediate and advanced. If it is not then tell me and I will go somewhere else. 3. Some searches, particularly for common terms throw millions of hits. 'Python' returns 147,000,000 results on google, 'Sitemap' returns 1,410,000,000 results. Even 'Python AND Sitemap' still returns 5,020 results. Working through these links takes you round and round with no clear solutions. Asking for help on the primary python mail list -- after conducting a preliminary investigation for tools, libraries, code snippets seemed legitimate. 4. AND YES, I could write a program but why recreate code when there is a strong likelihood that code already exists. One of the advantages of python is that a lot of code is redistributed under licences that promote reuse. So why reinvent the wheel when their is a library full of code. Sometimes you just need help finding the door. 4. If someone is willing to help me, rather than lecture me (or poke me to see if they get a response), I would appreciate it. [END RANT] For people that are willing to help. My original request was... I am after a way of pointing a python routine to my website and have it create a tree, represented as a hierarchical HTML list in a webpage, of all the pages in that website (recursive list of internal links to HTML documents; ignore images, etc.). In subsequent notes to Thomas 'PointedEars'... I pointed to an example of the desired output here http://lxml.de/sitemap.html -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From cs at zip.com.au Thu Sep 8 20:03:34 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 9 Sep 2011 10:03:34 +1000 Subject: killing a script In-Reply-To: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110909000334.GA9300@cskk.homeip.net> On 30Aug2011 14:13, Steven D'Aprano wrote: | On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote: | >> Yes, but if I am not mistaken, that will require me to put a line or | >> two after each os.system call. That's almost like whack-a-mole at the | >> code level rather than the Control-C level. OK, not a huge deal for | >> one script, but I was hoping for something simpler. I was hoping I | >> could put one line at the top of the script and be done with it. | > | > Write a function! That's what they're for after all :) | | I'm not sure that this is actually as simple as that, especially using | os.system. | | As I understand it, the scenario is this: | | The main script looks something like this: | | for x in whatever: | os.system('something.py x') | | Each time through the loop, a new Python process is started. Each process | runs in the foreground, capturing standard input, and so hitting Ctrl-C | kills *that* process, not the main script. Unless, by chance, the Ctrl-C | happens after the system call returns, but before the next one starts, it | is completely invisible to the parent process (the main script). Wrapping | os.system in a function does nothing to fix that. Presuming you're talking about UNIX, this is not correct. Ctrl-C at the terminal delivers SIGINT to _every_ process in the controlling process group for the terminal. It also has _nothing_ to do with the standard input. When you run a script, yea even a Python script, thus: myscript ... then job control capable shells (all of them, these days) put the python process running "myscript" in its own process group as the leader (being, initially, the only process in the group). If myscript forks other processes, as happens in os.system(), they are _also_ in that process group. _ALL_ of them receive the SIGINT from your Ctrl-C. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ DRM: the functionality of refusing to function. - Richard Stallman From greg.ewing at canterbury.ac.nz Thu Sep 8 20:03:45 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 09 Sep 2011 12:03:45 +1200 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: <9ct3f4FuvnU1@mid.individual.net> Abhishek Pratap wrote: > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) Are you expecting the processing to be CPU bound or I/O bound? If it's I/O bound, multiple cores won't help you, and neither will threading, because it's the disk doing the work, not the CPU. If it's CPU bound, multiple threads in one Python process won't help, because of the GIL. You'll have to fork multiple OS processes in order to get Python code running in parallel on different cores. -- Greg From rhodri at wildebst.demon.co.uk Thu Sep 8 20:32:42 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 09 Sep 2011 01:32:42 +0100 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 00:40:42 +0100, Simon Cropper wrote: > On 09/09/11 01:11, Steven D'Aprano wrote: >> [SNIP] >> It's no harder to put the search terms into a google URL, which still >> gets >> the point across without being a dick about it: > > [SNIP] > > [RANT] > > OK I was not going to say anything but... Ahem. You should expect a certain amount of ribbing after admitting that your Google-fu is weak. So is mine, but hey. > 4. If someone is willing to help me, rather than lecture me (or poke me > to see if they get a response), I would appreciate it. The Google Python Sitemap Generator (http://www.smart-it-consulting.com/article.htm?node=166&page=128, fourth offering when you google "map a website with Python") looks like a promising start. At least it produces something in XML -- filtering that and turning it into HTML should be fairly straightforward. -- Rhodri James *-* Wildebeest Herder to the Masses From nobody at nowhere.com Thu Sep 8 20:45:42 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 09 Sep 2011 01:45:42 +0100 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 08 Sep 2011 10:29:26 +1000, Steven D'Aprano wrote: > I suppose "one class per file" might be useful for those using an editor > with no search functionality. Other than that, is there any justification > for this rule? Any Java fans want to defend this? Not a Java fan, but: The Java compiler also acts as a "make" program. If it doesn't find a .class file for a needed class, it will search for the corresponding .java file and compile that. So to compile a complex program, you only need to compile the top-level file (e.g. HelloWorld.java), and it will compile everything which is required. No Makefile is needed, as the relationship between classes, object files and source files is fixed. From prachar at gmail.com Thu Sep 8 21:09:31 2011 From: prachar at gmail.com (papu) Date: Thu, 8 Sep 2011 18:09:31 -0700 (PDT) Subject: Python: Deleting specific words from a file. Message-ID: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Hello, I have a data file (un-structed messy file) from which I have to scrub specific list of words (delete words). Here is what I am doing but with no result: infile = "messy_data_file.txt" outfile = "cleaned_file.txt" delete_list = ["word_1","word_2"....,"word_n"] new_file = [] fin=open(infile,"") fout = open(outfile,"w+") for line in fin: for word in delete_list: line.replace(word, "") fout.write(line) fin.close() fout.close() I have put the code above in a file. When I execute it, I dont see the result file. I am not sure what the error is. Please let me know what I am doing wrong. From python at mrabarnett.plus.com Thu Sep 8 21:31:23 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 09 Sep 2011 02:31:23 +0100 Subject: Python: Deleting specific words from a file. In-Reply-To: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: <4E696C6B.7080609@mrabarnett.plus.com> On 09/09/2011 02:09, papu wrote: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > > Here is what I am doing but with no result: > > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] > fin=open(infile,"") > fout = open(outfile,"w+") > for line in fin: > for word in delete_list: > line.replace(word, "") > fout.write(line) > fin.close() > fout.close() > > I have put the code above in a file. When I execute it, I dont see the > result file. I am not sure what the error is. Please let me know what > I am doing wrong. The .replace method _returns_ its result. Strings are immutable, they can't be changed in-place. From davea at ieee.org Thu Sep 8 21:34:16 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 08 Sep 2011 21:34:16 -0400 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: <4E696D18.807@ieee.org> On 01/-10/-28163 02:59 PM, Abhishek Pratap wrote: > Hi Guys > > My experience with python is 2 days and I am looking for a slick way > to use multi-threading to process a file. Here is what I would like to > do which is somewhat similar to MapReduce in concept. > > # test case > > 1. My input file is 10 GB. > 2. I want to open 10 file handles each handling 1 GB of the file > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) > 4. There will be 10 different output files > 5. once the 10 jobs are complete a reduce kind of function will > combine the output. > > Could you give some ideas ? > > So given a file I would like to read it in #N chunks through #N file > handles and process each of them separately. > > Best, > -Abhi > You should probably forget threads, and simply do them as 10 separate processes, all launched by a single parent. Since they don't share any state, there's no need to get the inefficiency of threads. DaveA From rosuav at gmail.com Thu Sep 8 21:37:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 11:37:44 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: > The Java compiler also acts as a "make" program. If it doesn't find > a .class file for a needed class, it will search for the corresponding > .java file and compile that. So to compile a complex program, you only > need to compile the top-level file (e.g. HelloWorld.java), and it will > compile everything which is required. No Makefile is needed, as the > relationship between classes, object files and source files is fixed. > If that's the entire benefit, then I think this is a rather hefty price to pay for the elimination of a makefile. Oh wow, I can type "javac MyClass.java" and it picks up all the others! If you're dividing a project into multiple files already, is it that hard to have one more that defines the relationships between the others? Chris Angelico From simoncropper at fossworkflowguides.com Thu Sep 8 22:09:58 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 12:09:58 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E697576.5030301@fossworkflowguides.com> On 09/09/11 10:32, Rhodri James wrote: > On Fri, 09 Sep 2011 00:40:42 +0100, Simon Cropper > > Ahem. You should expect a certain amount of ribbing after admitting that > your Google-fu is weak. So is mine, but hey. I did not admit anything. I consider my ability to find this quite good actually. Others assumed that my "Google-fu is weak". > >> 4. If someone is willing to help me, rather than lecture me (or poke >> me to see if they get a response), I would appreciate it. > > The Google Python Sitemap Generator > (http://www.smart-it-consulting.com/article.htm?node=166&page=128, > fourth offering when you google "map a website with Python") looks like > a promising start. At least it produces something in XML -- filtering > that and turning it into HTML should be fairly straightforward. > I saw this in my original search. My conclusions were.. 1. The last update was in 2005. That is 6 years ago. In that time we have had numerous upgrades to HTML, Logs, etc. 2. The script expects to run on the webserver. I don't have the ability to run python on my webserver. 3. There are also a number of dead-links and redirects to Google Webmaster Central / Tools, which then request you submit a sitemap (as I alluded we get into a circular confusing cross-referencing situation) 4. The ultimate product - if you can get the package to work - would be a XML file you would need to massage to extract what you needed. To me this seems like overkill. I assume you could import the parent html file, scrap all the links on the same domain, dump these to a hierarchical list and represent this in HTML using BeautifulSoup or something similar. Certainly doable but considering the shear commonality of this task I don't understand why a simple script does not already exist - hence my original request for assistance. It would appear from the feedback so far this 'forum' is not the most appropriate to ask this question. Consequently, I will take your advice and keep looking... and if I don't find something within a reasonable time frame, just write something myself. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From steve+comp.lang.python at pearwood.info Thu Sep 8 22:14:55 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 12:14:55 +1000 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> Simon Cropper wrote: > 1. Being told to google-it when I explicitly stated in my initial post > that I had been doing this and had not been able to find anything is > just plain rude. It is unconstructive and irritating. Why so you did. Even though I wasn't the one who told you to google it, I'll apologise too because I was thinking the same thing. Sorry about that. > 3. Some searches, particularly for common terms throw millions of hits. > 'Python' returns 147,000,000 results on google, 'Sitemap' returns > 1,410,000,000 results. Even 'Python AND Sitemap' still returns 5,020 > results. How about "python generate a site map"? The very first link on DuckDuckGo is this: http://www.conversationmarketing.com/2010/08/python-sitemap-crawler-1.htm Despite the domain, there is actual Python code on the page. Unfortunately it looks like crappy code with broken formatting and a mix of <\br> tags, but it's a start. Searching for "site map" on PyPI returns a page full of hits: http://pypi.python.org/pypi?%3Aaction=search&term=site+map&submit=search Most of them seem to rely on a framework like Django etc, but you might find something useful. > 4. AND YES, I could write a program but why recreate code when there is > a strong likelihood that code already exists. "Strong" likelihood? Given how hard it is to find an appropriate sitemap generator written in Python, I'd say there is a strong likelihood that one that meets your needs and is publicly available under an appropriate licence is vanishingly small. If you do decide to write your own, please consider uploading it to PyPI under a FOSS licence. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 8 22:16:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 12:16:12 +1000 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6976ec$0$29987$c3e8da3$5496439d@news.astraweb.com> Simon Cropper wrote: > Certainly doable but > considering the shear commonality of this task I don't understand why a > simple script does not already exist Perhaps it isn't as common or as simple as you believe. -- Steven From simoncropper at fossworkflowguides.com Thu Sep 8 22:43:58 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 12:43:58 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E697D6E.4010101@fossworkflowguides.com> On 09/09/11 12:14, Steven D'Aprano wrote: > If you do decide to write your own, please consider uploading it to PyPI > under a FOSS licence. At present I am definitely getting the impression that my assumption that something like this' must out there', is wrong. I am following people's links and suggestions (as well as my own; I have spent 1-2 hours looking) but have not found anything that is able to be used with only minor adjustments. I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, this page allows you to create the XML files that can be uploaded to google. But as stated I don't actually want what people now call 'sitemaps' I want a automatically updated 'index / contents page' to my website. For example, if I add a tutorial or update any of my links I want the 'global contents page' to be updated when the python script is run. I am now considering how I might address this requirement. If I create a python script I will post it on PyPI. As with all my work it will be released under the GPLv3 licence. Thanks for your help. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From chinakr at gmail.com Thu Sep 8 22:47:04 2011 From: chinakr at gmail.com (chinakr) Date: Thu, 8 Sep 2011 19:47:04 -0700 (PDT) Subject: Using web2py and deck.js to make HTML5 presentation Message-ID: web2py is one of the most popular Web Frameworks. web2py has MVC architecture, offering us excellent development efficiency and extensibility. web2py is very suitable for Web application development. deck.js is a JavaScript library for making HTML5 presentation. It supports keyboard navigation, themes switching and extensions. With deck.js, making HTML5 presentation becomes easy, beautiful and convinient. SEO Brief Guide is a HTML5 presentation developing with web2py and deck.js, wich is free and open source. Demo? http://openclass.vstudy.cn/seo/training Source code? http://vstudy.htexam.net/soft/download/web2py.app.openclass.w2p From rosuav at gmail.com Thu Sep 8 22:59:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 12:59:09 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4E697D6E.4010101@fossworkflowguides.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> Message-ID: On Fri, Sep 9, 2011 at 12:43 PM, Simon Cropper wrote: > At present I am definitely getting the impression that my assumption that > something like this' must out there', is wrong. > > I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, > this page allows you to create the XML files that can be uploaded to google. > But as stated I don't actually want what people now call 'sitemaps' I want a > automatically updated 'index / contents page' to my website. For example, if > I add a tutorial or update any of my links I want the 'global contents page' > to be updated when the python script is run. What you're looking at may be closer to autogenerated documentation than to a classic site map. There are a variety of tools that generate HTML pages on the basis of *certain information found in* all the files in a directory (as opposed to the entire content of those files). What you're trying to do may be sufficiently specific that it doesn't already exist, but it might be worth having a quick look at autodoc/doxygen - at least for some ideas. Chris Angelico From gordon at panix.com Thu Sep 8 23:16:13 2011 From: gordon at panix.com (John Gordon) Date: Fri, 9 Sep 2011 03:16:13 +0000 (UTC) Subject: Python: Deleting specific words from a file. References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: In <30f9b718-bb3c-4c92-8a03-0f760c993939 at a12g2000yqi.googlegroups.com> papu writes: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > Here is what I am doing but with no result: > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] What does new_file do? I don't see it used anywhere. > fin=open(infile,"") There should be an "r" inside those quotes. In fact this is an error and it will stop your program from running. > fout = open(outfile,"w+") What is the "+" supposed to do? > for line in fin: > for word in delete_list: > line.replace(word, "") replace() returns the modified string; it does not alter the existing string. Do this instead: line = line.replace(word, "") > fout.write(line) > fin.close() > fout.close() > I have put the code above in a file. When I execute it, I dont see the > result file. I am not sure what the error is. Please let me know what > I am doing wrong. When you say you don't see the result file, do you mean it doesn't get created at all? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From jack.bates at gmail.com Thu Sep 8 23:18:54 2011 From: jack.bates at gmail.com (Jack Bates) Date: Thu, 8 Sep 2011 20:18:54 -0700 Subject: buffer() as argument to ctypes function which expects c_void_p? Message-ID: How do you pass a Python buffer() value as an argument to a ctypes function, which expects a c_void_p argument? I keep getting TypeError: ctypes.ArgumentError: argument 2: : wrong type From simoncropper at fossworkflowguides.com Thu Sep 8 23:20:01 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 13:20:01 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> Message-ID: <4E6985E1.9050009@fossworkflowguides.com> On 09/09/11 12:59, Chris Angelico wrote: > On Fri, Sep 9, 2011 at 12:43 PM, Simon Cropper > wrote: >> At present I am definitely getting the impression that my assumption that >> something like this' must out there', is wrong. >> >> I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, >> this page allows you to create the XML files that can be uploaded to google. >> But as stated I don't actually want what people now call 'sitemaps' I want a >> automatically updated 'index / contents page' to my website. For example, if >> I add a tutorial or update any of my links I want the 'global contents page' >> to be updated when the python script is run. > > What you're looking at may be closer to autogenerated documentation > than to a classic site map. There are a variety of tools that generate > HTML pages on the basis of *certain information found in* all the > files in a directory (as opposed to the entire content of those > files). What you're trying to do may be sufficiently specific that it > doesn't already exist, but it might be worth having a quick look at > autodoc/doxygen - at least for some ideas. > > Chris Angelico Chris, You assessment is correct. Working through the PyPI I am having better luck with using different terms than the old-term 'sitemap'. I have found a link to funnelweb which uses the transmogrify library (yeah, as if I would have typed this term into google!) that is described as "Crawl and parse static sites and import to Plone". http://pypi.python.org/pypi/funnelweb/1.0 As funnelweb is modular, using a variety of the transmogrify tools, maybe I could modify this to create a 'non-plone' version. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From rosuav at gmail.com Thu Sep 8 23:46:25 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 13:46:25 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4E6985E1.9050009@fossworkflowguides.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> <4E6985E1.9050009@fossworkflowguides.com> Message-ID: On Fri, Sep 9, 2011 at 1:20 PM, Simon Cropper wrote: > Chris, > > You assessment is correct. Working through the PyPI I am having better luck > with using different terms than the old-term 'sitemap'. > > I have found a link to funnelweb which uses the transmogrify library (yeah, > as if I would have typed this term into google!) that is described as "Crawl > and parse static sites and import to Plone". > And once again, python-list has turned a rant into a useful, informative, and productive thread :) ChrisA From aspineux at gmail.com Fri Sep 9 00:44:34 2011 From: aspineux at gmail.com (aspineux) Date: Thu, 8 Sep 2011 21:44:34 -0700 (PDT) Subject: Processing a file using multithreads References: Message-ID: On Sep 9, 12:49?am, Abhishek Pratap wrote: > Hi Guys > > My experience with python is 2 days and I am looking for a slick way > to use multi-threading to process a file. Here is what I would like to > do which is somewhat similar to MapReduce in concept. > > # test case > > 1. My input file is 10 GB. > 2. I want to open 10 file handles each handling 1 GB of the file > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) > 4. There will be 10 different output files > 5. once the 10 jobs are complete a reduce kind of function will > combine the output. > > Could you give some ideas ? You can use "multiprocessing" module instead of thread to bypass the GIL limitation. First cut your file in 10 "equal" parts. If it is line based search for the first line close to the cut. Be sure to have "start" and "end" for each parts, start is the address of the first character of the first line and end is one line too much (== start of the next block) Then use this function to handle each part . def handle(filename, start, end) f=open(filename) f.seek(start) for l in f: start+=len(l) if start>=end: break # handle line l here print l Do it first in a single process/thread to be sure this is ok (easier to debug) then split in multi processes > > So given a file I would like to read it in #N chunks through #N file > handles and process each of them separately. > > Best, > -Abhi From vineet.deodhar at gmail.com Fri Sep 9 00:52:26 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Thu, 8 Sep 2011 21:52:26 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> Message-ID: <72da7d9b-ca04-4597-8670-22a954481e40@b9g2000prd.googlegroups.com> On Sep 9, 3:29?am, Paul Watson wrote: > I have read some of the talk around these two frameworks. > > Would you say that web2py is more geared toward the enterprise? > > Which one do you believe will be on Python 3 more quickly? Both Django & web2py are good frameworks. I have tried both of them + others & then chosen a hybrid of web2py + DABO bizobj for my work. (DABO is a desktop app framework; so I have chosen only the BizObj layer from it, which can do its job in any other python web or desktop framework). Typically, my apps are data-centric business apps. web2py wins in simplycity yet powerfullness, no install, no dependencies, good docs & community, low learning curve, etc. DABO BizObj excels in managing the business logic aspect (including managing multiple tables insert/update/delete, rollback, before insert, after save, ... the list is quite long) http://web2py.com www.web2pyclices.com http://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.Bizobj.html http://dabodev.com/ Also, there are threads in stackoverflow.com which discuss in-depth the +1 & -1 for these frameworks. Contributors to these threads include the lead developers including Massimo himself. Hope this helps. ---Vineet From jialiuonlineshoe04 at 163.com Fri Sep 9 01:29:03 2011 From: jialiuonlineshoe04 at 163.com (amy) Date: Thu, 8 Sep 2011 22:29:03 -0700 (PDT) Subject: wholesale all brand(UGGBOOTS, SHOES, CLOTHES, HANDBAG, WATCH, JEANS, JERSEY, T-SHIRT, SHIRTS, HOODY, EYEGLASS, CAP, SHAWL, WALLT) and so on. Message-ID: <111713be-0e9f-404f-ac46-1b7747c90f94@f31g2000prj.googlegroups.com> wholesale all brand shoes(NIKE,ADIDAS,LV,GUCCI,CHANEL,PRADA,POLO,UGG BOOTS,D&G,DIOR )and so on. paypal payment wholesale all brand clothing(T- SHIRT,JEANS,JERSEY,HOODIES,JACKETS,HARDY,SWEATER,SHIRTS )and so on . http://www.24hour-buy.com/ paypal payment all brand watch(ROLEX,OMEGA,CHANEL,LV,CARTIER,IWC,GUCCI,RADO )and so on. paypal payment all brand handbag(LV,GUCCI,CHANEL,PRADA,POLO,COACH,FENDI,CHLOE,BUBERRY,JUICY) and so on. paypal payment brand CAP,SHAWL,BELT,WALLET,UNDER WEAR)and so on. More detail land,address: http://www.24hour-buy.com/ From wildeskraut at googlemail.com Fri Sep 9 01:47:34 2011 From: wildeskraut at googlemail.com (Oliver) Date: Thu, 8 Sep 2011 22:47:34 -0700 (PDT) Subject: TypeError: object.__init__() takes no parameters Message-ID: Hello together, let me be honest with you, I am a poor programmer who can only do Perl. I tried to code a program in Perl, but found that another guy already finished this job in Python. Unlucky for me, this guy is now CEO of a company, not really interested in supporting his old code. If I want to run shapes.py I receive this error message: === error message === C:\Documents and Settings\mhg\Desktop\palcalc>shapes.py EE... ====================================================================== ERROR: test_fits (__main__.containerTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 265, in test_fits cont = Container() File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 90, in __init__ super(Container, self).__init__(xsize, ysize) TypeError: object.__init__() takes no parameters ====================================================================== ERROR: test_place_bin (__main__.containerTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 257, in test_place_bin cont = Container() File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 90, in __init__ super(Container, self).__init__(xsize, ysize) TypeError: object.__init__() takes no parameters ---------------------------------------------------------------------- Ran 5 tests in 0.032s FAILED (errors=2) === end of error message === Snippets of source code: Line 264 - 268 def test_fits(self): cont = Container() cont.place_bin(0, 0, 210, 280) self.assertEqual(False, cont.fits(Rectangle(0, 210, 280, 420))) self.assertEqual(True, cont.fits(Rectangle(0, 280, 280, 490))) Line 87 - 93 class Container(object): """Container to store a number of non-overlapping rectangles.""" def __init__(self, xsize=1200, ysize=800): super(Container, self).__init__(xsize, ysize) self.rect = Rectangle(0, 0, xsize, ysize) self.boxes = [] self.last_placement_strategy = 0 Line 254 - 262 class containerTests(unittest.TestCase): """Tests for container objects.""" def test_place_bin(self): cont = Container() cont.place_bin(0, 0, 40, 40) self.failUnlessRaises(RuntimeError, cont.place_bin, 0, 0, 40, 40) cont = Container() cont.place_bin(0, 0, 210, 280) self.failUnlessRaises(RuntimeError, cont.place_bin, 0, 210, 280, 420) I think this is the main function: if __name__ == '__main__': unittest.main() I do not know if I posted what you need to help me, it just would ease my life a lot. If you need more information please let me know - if you want you can even be unfriendly to me :) From tjreedy at udel.edu Fri Sep 9 02:04:15 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 02:04:15 -0400 Subject: Python: Deleting specific words from a file. In-Reply-To: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: On 9/8/2011 9:09 PM, papu wrote: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > > Here is what I am doing but with no result: > > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] > fin=open(infile,"") > fout = open(outfile,"w+") > for line in fin: > for word in delete_list: > line.replace(word, "") > fout.write(line) > fin.close() > fout.close() If you have very many words (and you will need all possible forms of each word if you do exact matches), The following (untested and incomplete) should run faster. delete_set = {"word_1","word_2"....,"word_n"} ... for line in fin: for word in line.split() if word not in delete_set: fout.write(word) # also write space and nl. Depending on what your file is like, you might be better with re.split('(\W+)', line). An example from the manual: >>> re.split('(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', ''] so all non-word separator sequences are preserved and written back out (as they will not match delete set). -- Terry Jan Reedy From mimohammedimran41 at gmail.com Fri Sep 9 02:20:06 2011 From: mimohammedimran41 at gmail.com (mohammed imran) Date: Thu, 8 Sep 2011 23:20:06 -0700 (PDT) Subject: reshma Message-ID: http://123maza.com/65/fun564/ From ben+python at benfinney.id.au Fri Sep 9 02:44:37 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 09 Sep 2011 16:44:37 +1000 Subject: TypeError: object.__init__() takes no parameters References: Message-ID: <87sjo6mcyy.fsf@benfinney.id.au> Oliver writes: > let me be honest with you, I am a poor programmer who can only do > Perl. I strongly suspect you could do more than that. Welcome to the Python discussion forum. > I tried to code a program in Perl, but found that another guy already > finished this job in Python. Unlucky for me, this guy is now CEO of a > company, not really interested in supporting his old code. Then he can hardly complain if someone else re-writes it in their language of choice, can he? :-) > C:\Documents and Settings\mhg\Desktop\palcalc>shapes.py > EE... This, and the rest of your output, is from the call to ?unittest.main?, Python's standard-library module for unit testing. > File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line > 90, in __init__ > super(Container, self).__init__(xsize, ysize) > TypeError: object.__init__() takes no parameters The ?super(Container, self)? call asks for a ?super? object representing the (next) superclass of the type of ?self?. In this case, as the error message indicates, the next superclass type is ?object? ? the base type of all objects. Also as the error message indicates, the initialiser for ?object? doesn't accept the parameters being passed. > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) > self.rect = Rectangle(0, 0, xsize, ysize) > self.boxes = [] > self.last_placement_strategy = 0 So, there's no sense in calling the superclass's ?__init__? method with parameters which won't be accepted because of the function signature. The next thing to do is to ask about the design of these classes (what is the intention of this initialiser?). But you say you're entirely new to it, and that the designer has no interest in it. What are your options for getting their interest and participating in this thread? -- \ ?I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ?? ?F. H. Wales, 1936 | _o__) | Ben Finney From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 9 02:57:31 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 09 Sep 2011 08:57:31 +0200 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: References: Message-ID: Am 09.09.2011 07:47 schrieb Oliver: > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) And this is the nonsense: Container derives from object and tries to call its superclass's constructor with 2 parameters - which won't work. Write this as super(Container, self).__init__(). HTH, Thomas From nmarais at ska.ac.za Fri Sep 9 03:00:21 2011 From: nmarais at ska.ac.za (Neilen Marais) Date: Fri, 9 Sep 2011 00:00:21 -0700 (PDT) Subject: Unittesting SocketServer.StreamRequestHandler subclasses Message-ID: Hi, Is there a recommended way for writing unittests of SocketServer.StreamRequestHandler subclasses? I've tried making a server stub class and a connection stub class with a recv() method that immediately raises socket.error(errno.ECONNRESET, ). This works OK, but it means that whatever unittests I run always happens after the handler's handle() method has already been called. Is there a way to avoid this? Thanks Neilen From vineet.deodhar at gmail.com Fri Sep 9 03:47:37 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Fri, 9 Sep 2011 00:47:37 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> Message-ID: <203ea707-5a86-436e-816b-9f91d5971d82@y8g2000prd.googlegroups.com> On Sep 9, 3:29?am, Paul Watson wrote: > I have read some of the talk around these two frameworks. > > Would you say that web2py is more geared toward the enterprise? > > Which one do you believe will be on Python 3 more quickly? Both Django & web2py are good frameworks. I have tried both of them + others & then chosen a hybrid of web2py + DABO bizobj for my work. (DABO is a desktop app framework; so I have chosen only the BizObj layer from it, which can do its job in any other python web or desktop framework). Typically, my apps are data-centric business apps. web2py wins in simplicity, flexibility, no install, no dependencies, good docs & community, low learning curve, etc. DABO BizObj excels in managing the business logic aspect. With DABO bizobj layer, apart from the business logic, managing multiple tables insert/update/delete, rollback, before-insert, after- save, etc. is very handy... the list is quite long) (I know you will say that every framework has got its own DAL. It's true. But most of them are designed for basic database functions.) Some useful links--- http://web2py.com www.web2pyclices.com http://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.B... http://dabodev.com/ Also, there are threads in stackoverflow.com which discuss in-depth the +1 & -1 for these frameworks. Contributors to these threads include the lead developers including Massimo himself. Hope this helps. ---Vineet From steve+comp.lang.python at pearwood.info Fri Sep 9 04:33:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 18:33:48 +1000 Subject: TypeError: object.__init__() takes no parameters References: Message-ID: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Thomas Rachel wrote: > Am 09.09.2011 07:47 schrieb Oliver: >> class Container(object): >> """Container to store ?a number of non-overlapping rectangles.""" >> def __init__(self, xsize=1200, ysize=800): >> super(Container, self).__init__(xsize, ysize) > > And this is the nonsense: Container derives from object and tries to > call its superclass's constructor with 2 parameters - which won't work. Not nonsense. Merely a backward-incompatible change: [steve at sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> object("two", "parameters") In Python 2.2, the default object constructor accepts, and ignores, any parameters. In Python 2.3 on up, that becomes an error. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 9 05:07:24 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 19:07:24 +1000 Subject: killing a script References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 30Aug2011 14:13, Steven D'Aprano > wrote: > | On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote: > | >> Yes, but if I am not mistaken, that will require me to put a line or > | >> two after each os.system call. That's almost like whack-a-mole at the > | >> code level rather than the Control-C level. OK, not a huge deal for > | >> one script, but I was hoping for something simpler. I was hoping I > | >> could put one line at the top of the script and be done with it. > | > > | > Write a function! That's what they're for after all :) > | > | I'm not sure that this is actually as simple as that, especially using > | os.system. > | > | As I understand it, the scenario is this: > | > | The main script looks something like this: > | > | for x in whatever: > | os.system('something.py x') > | > | Each time through the loop, a new Python process is started. Each > | process runs in the foreground, capturing standard input, and so hitting > | Ctrl-C kills *that* process, not the main script. Unless, by chance, the > | Ctrl-C happens after the system call returns, but before the next one > | starts, it is completely invisible to the parent process (the main > | script). Wrapping os.system in a function does nothing to fix that. > > Presuming you're talking about UNIX, this is not correct. > > Ctrl-C at the terminal delivers SIGINT to _every_ process in the > controlling process group for the terminal. It also has _nothing_ to do > with the standard input. There may be something to what you say, but the behaviour experienced by the Original Poster still needs explaining. See below. > When you run a script, yea even a Python script, thus: > > myscript ... > > then job control capable shells (all of them, these days) put the python > process running "myscript" in its own process group as the leader > (being, initially, the only process in the group). If myscript forks > other processes, as happens in os.system(), they are _also_ in that > process group. _ALL_ of them receive the SIGINT from your Ctrl-C. I can replicate to OP's problem with these two simple Python scripts: [steve at sylar ~]$ cat script.py #!/usr/bin/python print "inside script.py" print "type Ctrl-C to exit" while True: pass [steve at sylar ~]$ cat test.py import os print "calling script.py with os.system" for i in range(3): os.system('./script.py') And now run them: [steve at sylar ~]$ python test.py calling script.py with os.system inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 4, in while True: KeyboardInterrupt inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 5, in pass KeyboardInterrupt inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 4, in while True: KeyboardInterrupt Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of script.py. While script.py is running, it receives the Ctrl-C, the calling process does not. -- Steven From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 9 05:11:06 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 09 Sep 2011 11:11:06 +0200 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 09.09.2011 10:33 schrieb Steven D'Aprano: > Not nonsense. Merely a backward-incompatible change: [1] > In Python 2.2, the default object constructor accepts, and ignores, any > parameters. In Python 2.3 on up, that becomes an error. Thanks, I wasn't aware of that. My first contact with Python was with 2.3... Thomas [1] Another example why backward-incompatible change are bad. Why was it necessary in this case? :-( From vineet.deodhar at gmail.com Fri Sep 9 05:39:31 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Fri, 9 Sep 2011 02:39:31 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> <203ea707-5a86-436e-816b-9f91d5971d82@y8g2000prd.googlegroups.com> Message-ID: On Sep 9, 12:47?pm, Vineet wrote: > On Sep 9, 3:29?am, Paul Watson wrote: > > > I have read some of the talk around these two frameworks. > > > Would you say that web2py is more geared toward the enterprise? > > > Which one do you believe will be on Python 3 more quickly? > > Both Django & web2py are good frameworks. > I have tried both of them + others & then chosen a hybrid of web2py + > DABO bizobj for my work. > (DABO is a desktop app framework; so I have chosen only the BizObj > layer from it, which can do its job in any other python web or desktop > framework). > > Typically, my apps are data-centric business apps. > web2py wins in simplicity, flexibility, no install, no dependencies, > good docs & community, low learning curve, etc. > > DABO BizObj excels in managing the business logic aspect. > With DABO bizobj layer, apart from the business logic, managing > multiple tables insert/update/delete, rollback, before-insert, after- > save, etc. is very handy... the list is quite long) > (I know you will say that every framework has got its own DAL. It's > true. But most of them are designed for basic database functions.) > > Some useful links---http://web2py.comwww.web2pyclices.comhttp://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.B...http://dabodev.com/ > > Also, there are threads in stackoverflow.com which discuss in-depth > the +1 & -1 for these frameworks. > Contributors to these threads include the lead developers including > Massimo himself. > > Hope this helps. > > ---Vineet Re. your point about porting from py2 to py3, the following thread makes it clear. http://groups.google.com/group/web2py/browse_thread/thread/5fcd0e97452e9ab8/d38f99b959778cfb?lnk=gst&q=python+3#d38f99b959778cfb ---Vineet From gandalf at shopzeus.com Fri Sep 9 05:39:52 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 09 Sep 2011 11:39:52 +0200 Subject: Portable locale usage In-Reply-To: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> References: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E69DEE8.9050803@shopzeus.com> >>>> Why are you trying to force a specific locale to your program >>>> anyway? >>> Because I wish to be able to correctly sort Croatian names. >> Well, all right. If you want to sort Croatian names from a program that >> runs on an English (or whatever) system, then you will have to check the >> platform and use a locale that is supported by the platform. (But again, >> this is not Python's limitation. Python doesn't know what encodings are >> supported, in advance, and you cannot use a locale that is not supported...) > I fully agree. > > I commented that, if a proper locale is installed, > the following should work on any system: > > locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) > > Currently the above does not work on Windows, > and that is because the locale_alias for 'hr' > is bound to 'hr_HR.ISO8859-2'. > Check the source: .../Python-3.2.2/Lib/locale.py, line 537 > > I was arguing that, on a Windows system, > the locale_alias for 'hr' should be bound > to 'Croatian_Croatia.1250'. Looks like you have found a bug! :-) Why don't you post a bug report? L From duncan.booth at invalid.invalid Fri Sep 9 05:49:33 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 09:49:33 GMT Subject: TypeError: object.__init__() takes no parameters References: Message-ID: Thomas Rachel wrote: > Am 09.09.2011 07:47 schrieb Oliver: >> class Container(object): >> """Container to store a number of non-overlapping rectangles.""" >> def __init__(self, xsize=1200, ysize=800): >> super(Container, self).__init__(xsize, ysize) > > And this is the nonsense: Container derives from object and tries to > call its superclass's constructor with 2 parameters - which won't work. > > Write this as super(Container, self).__init__(). > It isn't nonsense, just poor and outdated practice. You might subclass Container with something that puts another base class into the mro between Container and object and in that case calling super(Container, self). __init__() would be wrong. object.__init__() used to accept and silently ignore any parameters. This meant you could safely pass any constructor parameters along in case there was an intervening base class that wanted them. However that was changed (presumably after this code was written) and now you have to be a bit more careful with your initialisation parameters. This would be better in general, though if there is actually any code depending on xsize,ysize being passed up to a base class it will still need changing at the call site: def __init__(self, xsize=1200, ysize=800, *args, **kw): super(Container, self).__init__(*args, **kw) That way any xsize and ysize arguments are removed but any additional arguments for other base classes are passed through. -- Duncan Booth http://kupuguy.blogspot.com From hansmu at xs4all.nl Fri Sep 9 06:13:45 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 09 Sep 2011 12:13:45 +0200 Subject: killing a script In-Reply-To: <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69e6da$0$2551$e4fe514c@news2.news.xs4all.nl> On 9/09/11 11:07:24, Steven D'Aprano wrote: > Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of > script.py. While script.py is running, it receives the Ctrl-C, the calling > process does not. You misinterpret what you are seeing: the calling process *does* receive the ctrl-C, it just chooses to ignore it. This is documented behaviour of os.system. It you don't want this, then use the subprocess module, which does not behave this way. -- HansM From duncan.booth at invalid.invalid Fri Sep 9 06:29:47 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 10:29:47 GMT Subject: Create an index from a webpage [RANT, DNFTT] References: Message-ID: Simon Cropper wrote: > Certainly doable but > considering the shear commonality of this task I don't understand why a > simple script does not already exist - hence my original request for > assistance. I think you may have underestimated the complexity of the task in general. To do it for a remote website you need to specify what you consider to be a unique page. Here are some questions: Is case significant for URLs (technically it always is, but IIS sites tend to ignore it and to contain links with random permutations of case)? Are there any query parameters that make two pages distinct? Or any parameters that you should ignore? Is the order of parameters significant? I recently came across a site that not only had multiple links to identical pages with the query parameters in different order but also used a non- standard % to separate parameters instead of &: it's not so easy getting crawlers to handle that mess. Even after ignoring query parameters are there a finite number of pages to the site? For example, Apache has a spelling correction module that can effectively allow any number of spurious subfolders: I've seen a site where "/folder1/index.html" had a link to "folder2/index.html" and "/folder2/index.html" linked to "folder1/index.html". Apache helpfully accepted /folder2/folder1/ as equivalent to /folder1/ and therefore by extension also accepted /folder2/folder1/folder2/folder1/... Zope is also good at creating infinite folder structures. If you want to spider a remote site then there are plenty of off the shelf spidering packages, e.g. httrack. They have a lot of configuration options to try to handle the above gotchas. Your case is probably a lot simpler, but that's just a few reasons why it isn't actually a trivial task. Building a list by scanning a bunch of folders with html files is comparatively easy which is why that is almost always the preferred solution if possible. -- Duncan Booth http://kupuguy.blogspot.com From __peter__ at web.de Fri Sep 9 07:04:57 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 13:04:57 +0200 Subject: Best way to check that you are at the beginning (the end) of an iterable? References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Cameron Simpson wrote: > About the only time I do this is my personal "the()" convenience > function: > > def the(list, context=None): > ''' Returns the first element of an iterable, but requires there to be > exactly one. > ''' > icontext="expected exactly one value" > if context is not None: > icontext=icontext+" for "+context > > first=True > for elem in list: > if first: > it=elem > first=False > else: > raise IndexError, "%s: got more than one element (%s, %s, ...)" \ > % (icontext, it, elem) > > if first: > raise IndexError, "%s: got no elements" % icontext > > return it > > Which I use as a definite article in places where an iterable should > yield exactly one result (eg SQL SELECTs that ought to get exactly > one hit). I can see I wrote that a long time ago - it could do with some > style fixes. And a code scan shows it sees little use:-) A lightweight alternative to that is unpacking: >>> [x] = "" Traceback (most recent call last): File "", line 1, in ValueError: need more than 0 values to unpack >>> [x] = "a" >>> [x] = "ab" Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack From rosuav at gmail.com Fri Sep 9 07:30:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 21:30:03 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: On Fri, Sep 9, 2011 at 9:04 PM, Peter Otten <__peter__ at web.de> wrote: >>>> [x] = "" > Traceback (most recent call last): > ?File "", line 1, in > ValueError: need more than 0 values to unpack >>>> [x] = "a" >>>> [x] = "ab" > Traceback (most recent call last): > ?File "", line 1, in > ValueError: too many values to unpack > Hey look, it's a new operator - the "assign-sole-result-of-iterable" operator! x ,= "a" :) ChrisA From esthar777 at gmail.com Fri Sep 9 07:51:04 2011 From: esthar777 at gmail.com (ESTHU ESHU) Date: Fri, 9 Sep 2011 04:51:04 -0700 (PDT) Subject: plz see this Message-ID: <3285b468-2ddf-4c65-9a1e-357da713b0d6@y8g2000prd.googlegroups.com> http://123maza.com/65/clock747/ From kandrjoshi at gmail.com Fri Sep 9 08:07:03 2011 From: kandrjoshi at gmail.com (kaustubh joshi) Date: Fri, 9 Sep 2011 14:07:03 +0200 Subject: what's the command for (cd ..) in python Message-ID: Hello friends, How do we carry out the command "*cd ..*" in python? My problem is : I have a set of folders say m=1,2,3,4. In each of these folders, I have subfolders with common name say m_5,m_6,m_7,m_8. In each of these subfolder, there is a file which I have edit. 1 2 3 4 | | | | ------------------------------------------------------------------------------------------------------------------------------------------ 1_5, 1_6, 1_7, 1_8 2_5 ,2_6, 2_7, 2_8 3_5, 3_6, 3_7, 3_8 4_5, 4_6, 4_7, 4_8 That is how I designed it When I run my script, it follows the route 1 ---> 1_5-----> do the edit job in the file. Now it need to change the subfolder from 1_5 to 1_6, which is not happening. I created the folders using variable like m for folder taking values 1,2,3,4 and m_n for subfolders with n=5,6,7,8. I am trying with os.chdir(path), but stuck with how to use m_n in it. What I am missing at the moment is something that do the job "cd .." does. Any help Karan -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 9 08:16:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:16:00 +1000 Subject: killing a script References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> <4e69e6da$0$2551$e4fe514c@news2.news.xs4all.nl> Message-ID: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Hans Mulder wrote: > On 9/09/11 11:07:24, Steven D'Aprano wrote: >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of >> script.py. While script.py is running, it receives the Ctrl-C, the >> calling process does not. > > You misinterpret what you are seeing: the calling process *does* receive > the ctrl-C, it just chooses to ignore it. > > This is documented behaviour of os.system. Documented where? Neither the on-line documentation nor the function docstring mentions anything about it that I can see: http://docs.python.org/py3k/library/os.html#os.system >>> help(os.system) Help on built-in function system in module posix: system(...) system(command) -> exit_status Execute the command (a string) in a subshell. -- Steven From vlastimil.brom at gmail.com Fri Sep 9 08:34:59 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 9 Sep 2011 14:34:59 +0200 Subject: what's the command for (cd ..) in python In-Reply-To: References: Message-ID: 2011/9/9 kaustubh joshi : > Hello friends, > ???????????????????????? How do we carry out the command "cd .." in python? > > My problem is : > I have a set of folders say m=1,2,3,4. In each of these folders, I have > subfolders with common name say m_5,m_6,m_7,m_8. In each of these subfolder, > there is a file which I have edit. > ????????????????????????????????????????? 1 > ? ? ? ?? 2?????????? ? ? ? ? ? ? ? ? ? ? ? ?? 3 > ? ? ?? 4 > ???????????????????????????????????????? | > ? ? ? ? ? |????????????? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? ? ??? | > > ------------------------------------------------------------------------------------------------------------------------------------------ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1_5, 1_6, 1_7, 1_8?????????????? 2_5 ,2_6, > 2_7, 2_8?????????? 3_5, 3_6, 3_7, 3_8????????? 4_5, 4_6, 4_7, 4_8 > > That is how I designed it > > When I run my script, it follows the route 1 ---> 1_5-----> do the edit job > in the file. Now it need to change the? subfolder from 1_5 to 1_6, which is > not happening. > > I created the folders using variable like m for folder taking values 1,2,3,4 > and m_n for subfolders with n=5,6,7,8. > > I am trying with os.chdir(path), but stuck with how to use m_n in it. > > What I am missing at the moment is something that do the job "cd .." does. > > Any help > > > Karan > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, Would maybe adjusting the path like this work? >>> my_path = "c://d/e/f/g/" >>> os.path.abspath(my_path + os.pardir) 'c:\\d\\e\\f' >>> hth, vbr From steve+comp.lang.python at pearwood.info Fri Sep 9 09:03:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:03:10 +1000 Subject: what's the command for (cd ..) in python References: Message-ID: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> kaustubh joshi wrote: > Hello friends, > How do we carry out the command "*cd ..*" in > python? import os os.chdir('..') But think carefully before doing this. Some functions may be confused if you change directories while they are running. You may be better off staying in the same directory, and adjusting the path names to the files as you work with them. -- Steven From roy at panix.com Fri Sep 9 09:19:07 2011 From: roy at panix.com (Roy Smith) Date: Fri, 09 Sep 2011 09:19:07 -0400 Subject: Processing a file using multithreads References: Message-ID: In article , aspineux wrote: > On Sep 9, 12:49?am, Abhishek Pratap wrote: > > 1. My input file is 10 GB. > > 2. I want to open 10 file handles each handling 1 GB of the file > > 3. Each file handle is processed in by an individual thread using the > > same function ( so total 10 cores are assumed to be available on the > > machine) > > 4. There will be 10 different output files > > 5. once the 10 jobs are complete a reduce kind of function will > > combine the output. > > > > Could you give some ideas ? > > You can use "multiprocessing" module instead of thread to bypass the > GIL limitation. I agree with this. > First cut your file in 10 "equal" parts. If it is line based search > for the first line close to the cut. Be sure to have "start" and > "end" for each parts, start is the address of the first character of > the first line and end is one line too much (== start of the next > block) How much of the total time will be I/O and how much actual processing? Unless your processing is trivial, the I/O time will be relatively small. In that case, you might do well to just use the unix command-line "split" utility to split the file into pieces first, then process the pieces in parallel. Why waste effort getting the file-splitting-at-line-boundaries logic correct when somebody has done it for you? From duncan.booth at invalid.invalid Fri Sep 9 09:20:54 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 13:20:54 GMT Subject: TypeError: object.__init__() takes no parameters References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Thomas Rachel wrote: > >> Am 09.09.2011 07:47 schrieb Oliver: >>> class Container(object): >>> """Container to store ??a number of non-overlapping rectangles.""" >>> def __init__(self, xsize=1200, ysize=800): >>> super(Container, self).__init__(xsize, ysize) >> >> And this is the nonsense: Container derives from object and tries to >> call its superclass's constructor with 2 parameters - which won't work. > > Not nonsense. Merely a backward-incompatible change: > > > [steve at sylar ~]$ python2.2 > Python 2.2.3 (#1, Aug 12 2010, 01:08:27) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> object("two", "parameters") > > > > In Python 2.2, the default object constructor accepts, and ignores, any > parameters. In Python 2.3 on up, that becomes an error. > More recently than that. It only became an error in 2.6: [dbooth at localhost ~]$ python2.5 -c "object().__init__(42)" [dbooth at localhost ~]$ python2.6 -c "object().__init__(42)" Traceback (most recent call last): File "", line 1, in TypeError: object.__init__() takes no parameters -- Duncan Booth http://kupuguy.blogspot.com From steve+comp.lang.python at pearwood.info Fri Sep 9 09:41:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:41:37 +1000 Subject: TypeError: object.__init__() takes no parameters References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6a1791$0$29984$c3e8da3$5496439d@news.astraweb.com> Duncan Booth wrote: > Steven D'Aprano wrote: >> In Python 2.2, the default object constructor accepts, and ignores, any >> parameters. In Python 2.3 on up, that becomes an error. >> > More recently than that. It only became an error in 2.6: For __init__, sure, but it was an error for __new__ back in 2.3. Sorry for not being more clear. -- Steven From dribnairb at gmail.com Fri Sep 9 10:29:06 2011 From: dribnairb at gmail.com (Brian) Date: Fri, 9 Sep 2011 07:29:06 -0700 (PDT) Subject: Python and Outlook-style rules Message-ID: I'm about to create a system which will need to allow hundreds of users to create and maintain their own rules in a similar fashion to MS Outlook rules. ie. Each rule consists of one or more user configurable conditions and if/ when the conditions are met then one or more user configurable actions will be applied. The conditions will be things like "a specified key in a dictionary is in a specified list of values" (where the user can choose the key and the values), or "a specific record is in the specified database" (where the user chooses the primary key of the record and the database table to look in). The actions will be things like "send an email to address" (where the user chooses the address and the email template to use). The user will do their configuration in a browser. Also, I need to be able to continue to add new conditions and actions to the system over time. Is there a python module (preferably free/open source) which already does (some of) this? I can write the back-end logic easily enough (although I'd rather not re-invent the wheel) but I'd particularly like to find a widget or similar which will make the front-end look nice and be cross-browser compatible. From dreyemi at gmail.com Fri Sep 9 11:57:38 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 9 Sep 2011 16:57:38 +0100 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: You might want to have a look at this: http://www.ccs.neu.edu/home/matthias/htdc.html On Fri, Sep 9, 2011 at 2:37 AM, Chris Angelico wrote: > On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: > > The Java compiler also acts as a "make" program. If it doesn't find > > a .class file for a needed class, it will search for the corresponding > > .java file and compile that. So to compile a complex program, you only > > need to compile the top-level file (e.g. HelloWorld.java), and it will > > compile everything which is required. No Makefile is needed, as the > > relationship between classes, object files and source files is fixed. > > > > If that's the entire benefit, then I think this is a rather hefty > price to pay for the elimination of a makefile. Oh wow, I can type > "javac MyClass.java" and it picks up all the others! If you're > dividing a project into multiple files already, is it that hard to > have one more that defines the relationships between the others? > > Chris Angelico > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Fri Sep 9 12:19:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 10 Sep 2011 02:19:48 +1000 Subject: Python and Outlook-style rules In-Reply-To: References: Message-ID: Something like this? http://stackoverflow.com/questions/387606/using-user-input-to-find-information-in-a-mysql-database On Sat, Sep 10, 2011 at 12:29 AM, Brian wrote: > I'm about to create a system which will need to allow hundreds of > users to create and maintain their own rules in a similar fashion to > MS Outlook rules. ie. > Each rule consists of one or more user configurable conditions and if/ > when the conditions are met then one or more user configurable actions > will be applied. > > The conditions will be things like "a specified key in a dictionary is > in a specified list of values" (where the user can choose the key and > the values), or "a specific record is in the specified > database" (where the user chooses the primary key of the record and > the database table to look in). > > The actions will be things like "send an email to address" (where the > user chooses the address and the email template to use). > > The user will do their configuration in a browser. Also, I need to be > able to continue to add new conditions and actions to the system over > time. > > Is there a python module (preferably free/open source) which already > does (some of) this? I can write the back-end logic easily enough > (although I'd rather not re-invent the wheel) but I'd particularly > like to find a widget or similar which will make the front-end look > nice and be cross-browser compatible. > > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Fri Sep 9 12:38:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 10 Sep 2011 02:38:25 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: Kayode: Are the number of pages in that tutorial planned? :P > On Sat, Sep 10, 2011 at 1:57 AM, Kayode Odeyemi wrote: >> You might want to have a look at this: >> http://www.ccs.neu.edu/home/matthias/htdc.html >> >> On Fri, Sep 9, 2011 at 2:37 AM, Chris Angelico wrote: >>> >>> On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: >>> > The Java compiler also acts as a "make" program. If it doesn't find >>> > a .class file for a needed class, it will search for the corresponding >>> > .java file and compile that. So to compile a complex program, you only >>> > need to compile the top-level file (e.g. HelloWorld.java), and it will >>> > compile everything which is required. No Makefile is needed, as the >>> > relationship between classes, object files and source files is fixed. >>> > >>> >>> If that's the entire benefit, then I think this is a rather hefty >>> price to pay for the elimination of a makefile. Oh wow, I can type >>> "javac MyClass.java" and it picks up all the others! If you're >>> dividing a project into multiple files already, is it that hard to >>> have one more that defines the relationships between the others? >>> >>> Chris Angelico >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> Odeyemi 'Kayode O. >> http://www.sinati.com. t: @charyorde >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > From abhishek.vit at gmail.com Fri Sep 9 13:07:41 2011 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Fri, 9 Sep 2011 10:07:41 -0700 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: Hi All @Roy : split in unix sounds good but will it be as efficient as opening 10 different file handles on a file. I haven't tried it so just wondering if you have any experience with it. Thanks for your input. Also I was not aware of the python's GIL limitation. My application is not I/O bound as far as I can understand it. Each line is read and then processed independently of each other. May be this might sound I/O intensive as #N files will be read but I think if I have 10 processes running under a parent then it might not be a bottle neck. Best, -Abhi On Fri, Sep 9, 2011 at 6:19 AM, Roy Smith wrote: > In article > , > ?aspineux wrote: > >> On Sep 9, 12:49?am, Abhishek Pratap wrote: >> > 1. My input file is 10 GB. >> > 2. I want to open 10 file handles each handling 1 GB of the file >> > 3. Each file handle is processed in by an individual thread using the >> > same function ( so total 10 cores are assumed to be available on the >> > machine) >> > 4. There will be 10 different output files >> > 5. once the 10 jobs are complete a reduce kind of function will >> > combine the output. >> > >> > Could you give some ideas ? >> >> You can use "multiprocessing" module instead of thread to bypass the >> GIL limitation. > > I agree with this. > >> First cut your file in 10 "equal" parts. If it is line based search >> for the first line close to the cut. Be sure to have "start" and >> "end" for each parts, start is the address of the first character of >> the first line and end is one line too much (== start of the next >> block) > > How much of the total time will be I/O and how much actual processing? > Unless your processing is trivial, the I/O time will be relatively > small. ?In that case, you might do well to just use the unix > command-line "split" utility to split the file into pieces first, then > process the pieces in parallel. ?Why waste effort getting the > file-splitting-at-line-boundaries logic correct when somebody has done > it for you? > > -- > http://mail.python.org/mailman/listinfo/python-list > > From tjreedy at udel.edu Fri Sep 9 13:31:21 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 13:31:21 -0400 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: References: Message-ID: On 9/9/2011 1:47 AM, Oliver wrote: > If I want to run shapes.py I receive this error message: Others have explained why code that ran once now does not. > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) Remove this line and the error will go away. It *never* did anything. > self.rect = Rectangle(0, 0, xsize, ysize) > self.boxes = [] > self.last_placement_strategy = 0 -- Terry Jan Reedy From dreadpiratejeff at gmail.com Fri Sep 9 13:32:19 2011 From: dreadpiratejeff at gmail.com (J) Date: Fri, 9 Sep 2011 13:32:19 -0400 Subject: A bit of a boggle about subprocess.poll() and the codes it receives from a process Message-ID: Hi, I need a bit of help sorting this out... I have a memory test script that is a bit of compiled C. The test itself can only ever return a 0 or 1 exit code, this is explicitly coded and there are no other options. I also have a wrapper test script that calls the C program that should also only return 0 or 1 on completion. The problem i'm encountering, however, involves the return code when subprocess.poll() is called against the running memory test process. The current code in my wrapper program looks like this: def run_processes(self, number, command): passed = True pipe = [] for i in range(number): pipe.append(self._command(command)) print "Started: process %u pid %u: %s" % (i, pipe[i].pid, command) sys.stdout.flush() waiting = True while waiting: waiting = False for i in range(number): if pipe[i]: line = pipe[i].communicate()[0] if line and len(line) > 1: print "process %u pid %u: %s" % (i, pipe[i].pid, line) sys.stdout.flush() if pipe[i].poll() == -1: waiting = True else: return_value = pipe[i].poll() if return_value != 0: print "Error: process %u pid %u retuned %u" % (i, pipe[i].pid, return_value) passed = False print "process %u pid %u returned success" % (i, pipe[i].pid) pipe[i] = None sys.stdout.flush() return passed So what happens here is that in the waiting loop, if pipe[i].poll returns a -1, we keep waiting, and then if it returns anything OTHER than -1, we exit and return the return code. BUT, I'm getting, in some cases, a return code of 127, which is impossible to get from the memory test program. The output from this bit of code looks like this in a failing situation: Error: process 0 pid 2187 retuned 127 process 0 pid 2187 returned success Error: process 1 pid 2188 retuned 127 process 1 pid 2188 returned success I'm thinking that I'm hitting some sort of race here where the kernel is reporting -1 while the process is running, then returns 127 or some other status when the process is being killed and then finally 0 or 1 after the process has completely closed out. I "think" that the poll picks up this intermediate exit status and immediately exits the loop, instead of waiting for a 0 or 1. I've got a modified version that I'm getting someone to test for me now that changes if pipe[i].poll() == -1: waiting = True to this if pipe[i].poll() not in [0,1]: waiting = True So my real question is: am I on the right track here, and am I correct in my guess that the kernel is reporting different status codes to subprocess.poll() during the shutdown of the polled process? -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 9 13:35:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 13:35:37 -0400 Subject: what's the command for (cd ..) in python In-Reply-To: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/9/2011 9:03 AM, Steven D'Aprano wrote: > kaustubh joshi wrote: > >> Hello friends, >> How do we carry out the command "*cd ..*" in >> python? > > import os > os.chdir('..') > > But think carefully before doing this. Some functions may be confused if you > change directories while they are running. You may be better off staying in > the same directory, and adjusting the path names to the files as you work > with them. Or, use it once at the top of the main module, with an absolute path, to make sure you start at a known place where you want to start. -- Terry Jan Reedy From ray at aarden.us Fri Sep 9 16:04:30 2011 From: ray at aarden.us (ray) Date: Fri, 9 Sep 2011 13:04:30 -0700 (PDT) Subject: Installing 2.6 on Win 7 Message-ID: I have not found binaries for this install. The page http://www.python.org/download/windows/ takes me to http://www.python.org/download/releases/ which goes to http://www.python.org/download/releases/2.6.7/ Here are Gzip and Bzip tar balls. The readme files describe linux builds and the content seems to match. Are there win binaries or source files? ray From brian.curtin at gmail.com Fri Sep 9 16:14:43 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Fri, 9 Sep 2011 15:14:43 -0500 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 15:04, ray wrote: > > I have not found binaries for this install. ?The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. ?The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? As stated at the top of that page... """Python 2.6.7?is a security-fix only source release for Python 2.6.6, fixing several reported security issues. Python 2.6.7 was released on June 3, 2011.""" If you work backwards, http://www.python.org/download/releases/2.6.6/ is the last version binaries were created for. From benjamin.kaplan at case.edu Fri Sep 9 16:17:00 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 9 Sep 2011 16:17:00 -0400 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: On Sep 9, 2011 4:07 PM, "ray" wrote: > > I have not found binaries for this install. The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? > > ray > -- There is no such thing as the windows source vs. the Linux source. Just different build files, both of which are in those folders. Since 2.6 is in security-fix only mode, python.org doesn't provide binaries. You may be able to find binaries from ActiveState if you don't want to build it yourself. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tyler at tysdomain.com Fri Sep 9 17:00:32 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 15:00:32 -0600 Subject: what's the command for (cd ..) in python In-Reply-To: References: Message-ID: <4E6A7E70.1070807@tysdomain.com> On 9/9/2011 6:07 AM, kaustubh joshi wrote: > Hello friends, > How do we carry out the command "*cd ..*" in > python? > os.chdir, like so: >>> os.getcwd() '/home/tyler' >>> os.chdir("../") >>> os.getcwd() '/home' So you could do something like: os.chdir("../foo") > My problem is : > I have a set of folders say m=1,2,3,4. In each of these folders, I > have subfolders with common name say m_5,m_6,m_7,m_8. In each of these > subfolder, there is a file which I have edit. > 1 > 2 3 > 4 > | > | | > | > > ------------------------------------------------------------------------------------------------------------------------------------------ > 1_5, 1_6, 1_7, 1_8 2_5 > ,2_6, 2_7, 2_8 3_5, 3_6, 3_7, 3_8 4_5, 4_6, 4_7, 4_8 > > That is how I designed it > > When I run my script, it follows the route 1 ---> 1_5-----> do the > edit job in the file. Now it need to change the subfolder from 1_5 to > 1_6, which is not happening. > > I created the folders using variable like m for folder taking values > 1,2,3,4 and m_n for subfolders with n=5,6,7,8. > > I am trying with os.chdir(path), but stuck with how to use m_n in it. > > What I am missing at the moment is something that do the job "cd .." does. > > Any help > > > Karan > > > -- Take care, Ty Web: http://tds-solutions.net Sent from my toaster. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tyler at tysdomain.com Fri Sep 9 17:07:07 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 15:07:07 -0600 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: <4E6A7FFB.90309@tysdomain.com> On 9/9/2011 2:04 PM, ray wrote: > I have not found binaries for this install. The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? > http://www.python.org/getit/releases/2.6.6/ has a release for windows x86 and x64 > ray -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From stefan-usenet at bytereef.org Fri Sep 9 17:41:18 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Fri, 9 Sep 2011 23:41:18 +0200 Subject: try... except with unknown error types In-Reply-To: References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: <20110909214118.GA32405@sleipnir.bytereef.org> Chris Torek wrote: > (I have also never been sure whether something is going to raise > an IOError or an OSError for various OS-related read or write > operation failures -- such as exceeding a resource limit, for > instance -- so most places that do I/O operations on OS files, I > catch both. Still, it sure would be nice to have a static analysis > tool that could answer questions about potential exceptions. :-) ) There is an effort to fix this: http://www.python.org/dev/peps/pep-3151/ And an implementation ... http://hg.python.org/features/pep-3151/ ... together with a feature request: http://bugs.python.org/issue12555 I think the whole concept makes a lot of sense and is really worth taking a look at. Stefan Krah From cs at zip.com.au Fri Sep 9 18:29:02 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 10 Sep 2011 08:29:02 +1000 Subject: killing a script In-Reply-To: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110909222902.GA25985@cskk.homeip.net> On 09Sep2011 22:16, Steven D'Aprano wrote: | Hans Mulder wrote: | > On 9/09/11 11:07:24, Steven D'Aprano wrote: | >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of | >> script.py. While script.py is running, it receives the Ctrl-C, the | >> calling process does not. | > | > You misinterpret what you are seeing: the calling process *does* receive | > the ctrl-C, it just chooses to ignore it. | > | > This is documented behaviour of os.system. | | Documented where? Neither the on-line documentation nor the function | docstring mentions anything about it that I can see: | | http://docs.python.org/py3k/library/os.html#os.system My copy of the 2.7 docs says: This is implemented by calling the Standard C function system(), and has the same limitations. and sure enough, "man 3 system" says: The system() function hands the argument command to the command interpreter sh(1). The calling process waits for the shell to finish executing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD. os.system() is very convenient for simple stuff, but one size does not fit all. Continuing with the Python docs for os.system: On Unix, the return value is the exit status of the process encoded in the format specified for wait(). and it is easy to inspect that value for "the subprocess died from a signal". Not inspecting the exit status correctly will always be an opportunity for incorrect app behaviour. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Mac OS X. Because making Unix user-friendly is easier than debugging Windows. - Mike Dawson, Macintosh Systems Administrator and Consultation. mdawson at mac.com http://herowars.onestop.net From Phillip.M.Feldman at gmail.com Fri Sep 9 19:45:44 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 9 Sep 2011 16:45:44 -0700 (PDT) Subject: can't generate iterator from list Message-ID: <32435519.post@talk.nabble.com> It is supposed to be possible to generate a list representation of any iterator that produces a sequence of finite length, but this doesn't always work. Here's a case where it does work: Input: from itertools import combinations list(combinations(range(4),2)) Output: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] When I define my own classes that produce iterators, conversion to a list works for some of these classes but not for others. Here's a case where it doesn't work: In: list(balls_in_numbered_boxes(2, [3,3,3])) Out: [array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1])] Note that if I apply the `next` method to the object, the output is correct: In [5]: x=balls_in_numbered_boxes(3,[3,3,3]) In [6]: x.next() Out[6]: array([3, 0, 0]) In [7]: x.next() Out[7]: array([2, 1, 0]) In [8]: x.next() Out[8]: array([1, 2, 0]) In [9]: x.next() Out[9]: array([0, 3, 0]) In [10]: x.next() Out[10]: array([0, 2, 1]) In [11]: x.next() Out[11]: array([0, 1, 2]) In [12]: x.next() Out[12]: array([0, 0, 3]) In [13]: x.next() --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) Code is attached (see below). Any suggestions as to what's going wrong will be appreciated. class balls_in_numbered_boxes(object): """ OVERVIEW This class generates an iterator that produces all distinct distributions of indistinguishable balls among numbered boxes with specified capacity limits. (This is a generalization of the most common formulation of the problem, where each box is sufficiently large to accommodate all of the balls, and is an important example of a class of combinatorics problems called 'weak composition' problems). CONSTRUCTOR INPUTS n: the number of balls limits: This argument is a list of length 1 or greater. The length of the list corresponds to the number of boxes. `limits[i]` is a positive integer that specifies the maximum capacity of the ith box. If `limits[i]` equals `n` (or greater), then the ith box can accommodate all `n` balls and thus effectively has unlimited capacity. """ def __init__(self, n=None, limits=None): if n < 0 or not isinstance(n,int): raise BadInput("The number of balls n must be a non-negative integer.") if not isinstance(limits,list) or len(limits)<1: raise BadInput("`limits` must be a non-empty list.") for limit in limits: if not isinstance(limit,int) or limit<1: raise BadInput("Items in `limits` must be positive integers.") # Copy constructor inputs to object attributes. We make a `deepcopy` of # `limits` to protect against the possibility of the calling program # modifying it before all calls to the `next` method have been completed. self.n= n self.limits= deepcopy(limits) self.distribution= None def __iter__(self): return self def next(self): # If `self.distribution` is `None`, this is the initial call to `next`, # in which case we generate the initial distribution by assigning as many # balls as possible to the first box, as many balls that remain to the # next box, and so on. if self.distribution is None: self.distribution= zeros(len(self.limits), dtype='i4') balls= self.n for box in xrange(len(self.limits)): # Store as many balls as possible in the current box: self.distribution[box]= min(balls,self.limits[box]) balls-= self.distribution[box] if balls == 0: break else: # We fell through the above loop, which means that it was impossible # to distribute all of the balls: raise BadInput("The total capacity of the boxes is less than the " "number of balls to be distributed.") # Make first box the "current" box, i.e., the box from which a ball # will be moved when the `next` method is invoked: self.box= 0 return self.distribution # `self.distribution` is not `None`, which means that this is not the # initial invocation of `next`. We create the next distribution by moving # one ball to the right, unless this is impossible. self.distribution[self.box]-= 1 for box in xrange(self.box+1,len(self.limits)): # If this box is full, advance to the next one: if self.distribution[box] == self.limits[box]: continue self.distribution[box]+= 1 break else: # We fell through the above loop, which means that it was impossible # to find a new home for the ball that we were trying to move. raise StopIteration # If the current box--the box from which we have been removing balls-- is # empty, advance to the next box: if self.distribution[self.box] == 0: self.box+= 1 return self.distribution -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32435519.html Sent from the Python - python-list mailing list archive at Nabble.com. From Phillip.M.Feldman at gmail.com Fri Sep 9 20:00:39 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 9 Sep 2011 17:00:39 -0700 (PDT) Subject: can't generate list from iterator In-Reply-To: <32435519.post@talk.nabble.com> References: <32435519.post@talk.nabble.com> Message-ID: <32435569.post@talk.nabble.com> The title should have been "can't generate list from iterator". -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32435569.html Sent from the Python - python-list mailing list archive at Nabble.com. From miki.tebeka at gmail.com Fri Sep 9 20:07:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 9 Sep 2011 17:07:54 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: Message-ID: <1fcf2318-7b76-425b-a100-57d3cd5f8e0f@glegroupsg2000goo.googlegroups.com> 1. Can you post the code somewhere where it's indented properly? (http://paste.pocoo.org/) 2. In the list example you call balls_in_numbered_boxes(2, [3,3,3]) but in the interactive example you call balls_in_numbered_boxes(3,[3,3,3]) From miki.tebeka at gmail.com Fri Sep 9 20:07:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 9 Sep 2011 17:07:54 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: Message-ID: <1fcf2318-7b76-425b-a100-57d3cd5f8e0f@glegroupsg2000goo.googlegroups.com> 1. Can you post the code somewhere where it's indented properly? (http://paste.pocoo.org/) 2. In the list example you call balls_in_numbered_boxes(2, [3,3,3]) but in the interactive example you call balls_in_numbered_boxes(3,[3,3,3]) From matthew.a.hess at gmail.com Fri Sep 9 20:19:38 2011 From: matthew.a.hess at gmail.com (matt) Date: Fri, 9 Sep 2011 17:19:38 -0700 (PDT) Subject: IOError 35 when trying to read the result of call to urllib2.urlopen Message-ID: I'm using urllib2's urlopen function to post to a service which should return a rather lengthy JSON object as the body of its response. Here's the code: {{{ ctype, body = encode_multipart(fields, files) url = 'http://someservice:8080/path/to/resource' headers = {'Content-Type': ctype, 'Content-Length': str(len(body))} req = urllib2.Request(url, body, headers) resp = urllib2.urlopen(req) resp_body = resp.read() }}} When I try to look at "resp_body" I get this error: IOError: [Errno 35] Resource temporarily unavailable I posted to the same URI using curl and it worked fine, so I don't think it has to do with the server. Any thoughts? From steve+comp.lang.python at pearwood.info Fri Sep 9 20:55:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 10:55:53 +1000 Subject: can't generate list from iterator [was: can't generate iterator from list] References: Message-ID: <4e6ab59a$0$30002$c3e8da3$5496439d@news.astraweb.com> Dr. Phillip M. Feldman wrote: > > It is supposed to be possible to generate a list representation of any > iterator that produces a sequence of finite length, but this doesn't > always work. Here's a case where it does work: > > Input: > > from itertools import combinations > list(combinations(range(4),2)) > > Output: > > [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] > > When I define my own classes that produce iterators, conversion to a list > works for some of these classes but not for others. Here's a case where it > doesn't work: > > In: list(balls_in_numbered_boxes(2, [3,3,3])) > > Out: > > [array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1])] But it does work -- it generates a list, exactly as expected. The problem is not that you can't generate a list. The problem is that the list you generate is not what you expect. What you have here is a list containing the same array, repeated three times. When you print the permutations one at a time, you don't notice, but by collecting them all at once, you see clearly that they are the same array object. Try this: combos = list(balls_in_numbered_boxes(2, [3,3,3])) [id(a) for a in combos] I expect you will see something like [123456, 123456, 123456]. The simplest fix is to fix the next() method so that it returns a copy of self.distribution instead of the array itself. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 9 21:02:08 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 11:02:08 +1000 Subject: IOError 35 when trying to read the result of call to urllib2.urlopen References: Message-ID: <4e6ab711$0$29975$c3e8da3$5496439d@news.astraweb.com> matt wrote: > When I try to look at "resp_body" I get this error: > > IOError: [Errno 35] Resource temporarily unavailable > > I posted to the same URI using curl and it worked fine, so I don't > think it has to do with the server. Are your Python code and curl both using the same proxy? It may be that one is going direct and the other is using a proxy. Or perhaps the destination is just flaky, and the resource genuinely is temporarily unavailable. Or it doesn't like your useragent string and is lying. -- Steven From ray at aarden.us Fri Sep 9 21:21:58 2011 From: ray at aarden.us (ray at aarden.us) Date: Fri, 09 Sep 2011 18:21:58 -0700 Subject: Installing 2.6 on Win 7 Message-ID: <20110909182158.1753ead7c2b35a7d15c5b99498690bcc.e87438b7a8.wbe@email11.secureserver.net> An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 9 21:25:40 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 11:25:40 +1000 Subject: killing a script References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 09Sep2011 22:16, Steven D'Aprano > wrote: > | Hans Mulder wrote: > | > On 9/09/11 11:07:24, Steven D'Aprano wrote: > | >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation > | >> of script.py. While script.py is running, it receives the Ctrl-C, the > | >> calling process does not. > | > > | > You misinterpret what you are seeing: the calling process *does* > | > receive the ctrl-C, it just chooses to ignore it. > | > > | > This is documented behaviour of os.system. > | > | Documented where? Neither the on-line documentation nor the function > | docstring mentions anything about it that I can see: > | > | http://docs.python.org/py3k/library/os.html#os.system > > My copy of the 2.7 docs says: > > This is implemented by calling the Standard C function system(), and > has the same limitations. > > and sure enough, "man 3 system" says: I don't consider having to look up documentation for a function in a completely different language (in this case, C) as "documented behaviour of os.system". Does the C standard define the behaviour of system(), or is that implementation dependent? It sounds to me that the Python developers are implicitly refusing responsibility for the detailed behaviour of os.system by noting that it depends on the C function. What do Jython, PyPy and IronPython do? Perhaps the docs for os.system should explicitly note that the behaviour is implementation dependent, rather than just hint at it. Either that or explicitly state what os.system does. > os.system() is very convenient for simple stuff, but one size does not > fit all. I never said it does. Back in my first comment on this thread, I said "Possibly using the subprocess module may help." > Continuing with the Python docs for os.system: > > On Unix, the return value is the exit status of the process encoded in > the format specified for wait(). > > and it is easy to inspect that value for "the subprocess died from a > signal". Not inspecting the exit status correctly will always be an > opportunity for incorrect app behaviour. Except that the subprocess can catch the KeyboardInterrupt before exiting, and there's no guarantee that it will return an appropriate error code. You're right though, os.system is good for simple stuff and not much more. -- Steven From rosuav at gmail.com Fri Sep 9 21:37:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 10 Sep 2011 11:37:53 +1000 Subject: killing a script In-Reply-To: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 10, 2011 at 11:25 AM, Steven D'Aprano wrote: >> ? This is implemented by calling the Standard C function system(), and >> ? has the same limitations. >> >> and sure enough, "man 3 system" says: > > I don't consider having to look up documentation for a function in a > completely different language (in this case, C) as "documented behaviour of > os.system". > The Python docs chain to the C docs. It'd be nice to have a link somewhere, but that's platform-dependent - the online docs could link to an online man page, but local docs can't, etc. It's fairly normal for high level languages to expose a lot of C API functions, with all the concerns and features given. Not a lot of point bloating the Python docs with every little detail, imho. ChrisA From tyler at tysdomain.com Fri Sep 9 23:54:40 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 21:54:40 -0600 Subject: using python in web applications Message-ID: <4E6ADF80.7010607@tysdomain.com> Hello all: I'm curious if there are some good solutions for using Python in web applications. I'm not feeling particularly masochistic, so I do not want to develop this project in PHP; essentially I'm looking to build a web-based MMO. I know that you can use nginx with Python with servers like Flask, but I'm not really sure how well all of those work. Since this will be a game, I can expect quite a few users; I've already got quite a lot of interest. I don't much care for PHP, but the thing that can be said for it is it's pretty quick. How does Python compare? Are there some solutions (I was told about PyPy today) that would be quicker that I could still use for the web app? I'm also curious what databases are suggested? I've always done most of my work in MYSql, but from what I understand postgresql is becoming more popular to. Thanks all for the input, -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From ben+python at benfinney.id.au Sat Sep 10 00:19:22 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 10 Sep 2011 14:19:22 +1000 Subject: using python in web applications References: Message-ID: <87mxedm3lh.fsf@benfinney.id.au> "Littlefield, Tyler" writes: > I'm curious if there are some good solutions for using Python in web > applications. Start with: and try your criteria against what you find there. -- \ ?As scarce as truth is, the supply has always been in excess of | `\ the demand.? ?Josh Billings | _o__) | Ben Finney From timr at probo.com Sat Sep 10 01:43:19 2011 From: timr at probo.com (Tim Roberts) Date: Fri, 09 Sep 2011 22:43:19 -0700 Subject: Processing a file using multithreads References: Message-ID: Abhishek Pratap wrote: > >My application is not I/O bound as far as I can understand it. Each >line is read and then processed independently of each other. May be >this might sound I/O intensive as #N files will be read but I think if >I have 10 processes running under a parent then it might not be a >bottle neck. Your conclusion doesn't follow from your premise. If you are only doing a little bit of processing on each line, then you almost certainly WILL be I/O bound. You will spend most of your time waiting for the disk to deliver more data. In that case, multithreading is not a win. The threads will all compete with each other for the disk. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zak.mc.kraken at libero.it Sat Sep 10 02:23:51 2011 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sat, 10 Sep 2011 08:23:51 +0200 Subject: FYI Message-ID: http://scummos.blogspot.com/2011/09/kdev-python-argument-type-guessing.html I'm not used to big ide/rad for python... but I think this work is excellent! Are there alternatives (pydev? others?) capable of this sort of thinks (I mean "guessing the type" and method autocomplete) -- By ZeD From __peter__ at web.de Sat Sep 10 03:05:43 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 09:05:43 +0200 Subject: can't generate iterator from list References: <32435519.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > > It is supposed to be possible to generate a list representation of any > iterator that produces a sequence of finite length, but this doesn't > always work. Here's a case where it does work: > > Input: > > from itertools import combinations > list(combinations(range(4),2)) > > Output: > > [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] > > When I define my own classes that produce iterators, conversion to a list > works for some of these classes but not for others. Here's a case where it > doesn't work: > > In: list(balls_in_numbered_boxes(2, [3,3,3])) > > Out: > > [array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1])] [snip code where excessive commenting does more bad than good] The problem is that you return the same mutable object on every next() call. Here's a simplified example: >>> def g(items): ... x = [None] ... for item in items: ... x[0] = item ... yield x ... >>> list(g("abc")) [['c'], ['c'], ['c']] When you invoke it using next() you are fooled into thinking that it works as desired: >>> it = g("abc") >>> a = next(it) >>> a ['a'] >>> b = next(it) >>> b ['b'] but only until you look back at the previous item: >>> a ['b'] Once you understand what is going on the fix is easy -- don't reuse the mutable object: >>> def g(items): ... for item in items: ... yield [item] ... >>> list(g("abc")) [['a'], ['b'], ['c']] From hetchkay at gmail.com Sat Sep 10 03:19:42 2011 From: hetchkay at gmail.com (hetchkay) Date: Sat, 10 Sep 2011 00:19:42 -0700 (PDT) Subject: Applying a function recursively Message-ID: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Hi, I want to apply a "convert" function on an object as follows: If the object is of MyType type, invoke the passed in function. If the object is a dictionary, apply on the keys and values of the dictionary recursively. If the object is a set, list or tuple, apply on each element recursively. Else, leave the object as is. I wrote the following code: def convert(obj, func): if isinstance(obj, MyType): return func(obj) elif isinstance(obj, dict): return dict((convert(key, func), convert(value, func)) for key, value in obj.iteritems()) elif isinstance(obj, (list, tuple, set)): return obj.__class__(convert(x, func) for x in obj) else: return obj Is there a better way to do this? Is there any way I can make this code faster? Regards, Krishnan From clp2 at rebertia.com Sat Sep 10 03:40:51 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 00:40:51 -0700 Subject: Applying a function recursively In-Reply-To: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Message-ID: On Sat, Sep 10, 2011 at 12:19 AM, hetchkay wrote: > Hi, > I want to apply a "convert" function on an object as follows: > If the object is of MyType type, invoke the passed in function. > If the object is a dictionary, apply on the keys and values of the > dictionary recursively. > If the object is a set, list or tuple, apply on each element > recursively. > Else, leave the object as is. > > I wrote the following code: > def convert(obj, func): > ? if isinstance(obj, MyType): > ? ? ?return func(obj) > ? elif isinstance(obj, dict): > ? ? ?return dict((convert(key, func), convert(value, func)) for key, > value in obj.iteritems()) > ? elif isinstance(obj, (list, tuple, set)): > ? ? ?return obj.__class__(convert(x, func) for x in obj) > ? else: > ? ? ?return obj > > Is there a better way to do this? None comes to mind. > Is there any way I can make this code faster? Possibly, but it involves ignoring subclasses, and may not actually be faster in your particular case (it comes down to additional function calls vs. cost of if-elif-else chain). It would be along the lines of: def convert_mytype(obj, func): return func(obj) def convert_dict(obj, func): return dict((convert(key, func), convert(value, func)) for key, value in obj.iteritems()) def dont_convert(obj, func): return obj TYPE2FUNC = {MyType : convert_mytype, dict : convert_dict, ... } def convert(obj, func): return TYPE2FUNC.get(type(obj), dont_convert)(obj, func) As they say though, premature optimization is the root of all evil. Cheers, Chris -- http://rebertia.com From ben+python at benfinney.id.au Sat Sep 10 04:13:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 10 Sep 2011 18:13:18 +1000 Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Message-ID: <87ipp0n7c1.fsf@benfinney.id.au> hetchkay writes: > Hi, > I want to apply a "convert" function on an object as follows: > If the object is of MyType type, invoke the passed in function. > If the object is a dictionary, apply on the keys and values of the > dictionary recursively. > If the object is a set, list or tuple, apply on each element > recursively. > Else, leave the object as is. That smells like a bad design. Why are you using the same function for al of those different behaviours? That's not merely rhetorical; the design isn't absolutely wrong. But it's wrong often enough that you need to have a compelling reason to make such a complex behaviour in a single function. I suspect, if you can be explicit about the goal you're aiming for with this code, a better design can be found that doesn't require all those polymorphism-breaking type checks. -- \ ?An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.? ?Niels Bohr | _o__) | Ben Finney From cs at zip.com.au Sat Sep 10 04:49:38 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 10 Sep 2011 18:49:38 +1000 Subject: killing a script In-Reply-To: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110910084938.GA14021@cskk.homeip.net> On 10Sep2011 11:25, Steven D'Aprano wrote: | Cameron Simpson wrote: | > My copy of the 2.7 docs says: | > This is implemented by calling the Standard C function system(), and | > has the same limitations. | > and sure enough, "man 3 system" says: | | I don't consider having to look up documentation for a function in a | completely different language (in this case, C) as "documented behaviour of | os.system". You're kidding, surely? A wrapper function for a system supplied function should recite everything about the wrapped function's behaviour (including the system dependent stuff) in the wrapper doco? | Does the C standard define the behaviour of system(), or is that | implementation dependent? The standard specifies the core behaviour - the behaviour guarrenteed to be present everywhere. Plenty of stuff has platform dependent minor nuances. As long as portable code relies only on the standard behaviour everybody wins. | It sounds to me that the Python developers are | implicitly refusing responsibility for the detailed behaviour of os.system | by noting that it depends on the C function. Of course they are, and they are right to do so. But noting that it calls the standard function does guarrentee various things about what it does. | What do Jython, PyPy and | IronPython do? | | Perhaps the docs for os.system should explicitly note that the behaviour is | implementation dependent, rather than just hint at it. Either that or | explicitly state what os.system does. I find it hard to understand how anyone can read this text: This is implemented by calling the Standard C function system(), and has the same limitations and not imagine it to be dependent on the specification for system(). | > Continuing with the Python docs for os.system: | > | > On Unix, the return value is the exit status of the process encoded in | > the format specified for wait(). | > | > and it is easy to inspect that value for "the subprocess died from a | > signal". Not inspecting the exit status correctly will always be an | > opportunity for incorrect app behaviour. | | Except that the subprocess can catch the KeyboardInterrupt before exiting, This is very true, though such programs usually have a special reason to do so - the default aborting behaviour is often sufficient. | and there's no guarantee that it will return an appropriate error code. Of course. However, the subprocess should still exit with a nonzero exit status (unless it it written badly). If the caller considers success of the called program to be important, it should probably be aborting if the returned value is nonzero anyway. But yeah, people should probably be reaching for subprocess if they want to notice SIGINT specially. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ But pessimism IS realism! - D.L.Bahr From kushal.kumaran+python at gmail.com Sat Sep 10 05:19:08 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sat, 10 Sep 2011 14:49:08 +0530 Subject: A bit of a boggle about subprocess.poll() and the codes it receives from a process In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 11:02 PM, J wrote: > Hi, > I need a bit of help sorting this out... > I have a memory test script that is a bit of compiled C. ?The test itself > can only ever return a 0 or 1 exit code, this is explicitly coded and there > are no other options. > I also have a wrapper test script that calls the C program that should also > only return 0 or 1 on completion. > The problem i'm encountering, however, involves the return code when > subprocess.poll() is called against the running memory test process. ?The > current code in my wrapper program looks like this: > def run_processes(self, number, command): > ? ? ? ? passed = True > ? ? ? ? pipe = [] > ? ? ? ? for i in range(number): > ? ? ? ? ? ? pipe.append(self._command(command)) > ? ? ? ? ? ? print "Started: process %u pid %u: %s" % (i, pipe[i].pid, > command) > ? ? ? ? sys.stdout.flush() > ? ? ? ? waiting = True > ? ? ? ? while waiting: > ? ? ? ? ? ? waiting = False > ? ? ? ? ? ? for i in range(number): > ? ? ? ? ? ? ? ? if pipe[i]: > ? ? ? ? ? ? ? ? ? ? line = pipe[i].communicate()[0] > ? ? ? ? ? ? ? ? ? ? if line and len(line) > 1: > ? ? ? ? ? ? ? ? ? ? ? ? print "process %u pid %u: %s" % (i, pipe[i].pid, > line) > ? ? ? ? ? ? ? ? ? ? ? ? sys.stdout.flush() > ? ? ? ? ? ? ? ? ? ? if pipe[i].poll() == -1: > ? ? ? ? ? ? ? ? ? ? ? ? waiting = True > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? return_value = pipe[i].poll() > ? ? ? ? ? ? ? ? ? ? ? ? if return_value != 0: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? print "Error: process ?%u pid %u retuned %u" % > (i, pipe[i].pid, return_value) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? passed = False > ? ? ? ? ? ? ? ? ? ? ? ? print "process %u pid %u returned success" % (i, > pipe[i].pid) > ? ? ? ? ? ? ? ? ? ? ? ? pipe[i] = None > ? ? ? ? sys.stdout.flush() > ? ? ? ? return passed > So what happens here is that in the waiting loop, if pipe[i].poll returns a > -1, we keep waiting, and then if it returns anything OTHER than -1, we exit > and return the return code. Does self._command return a subprocess.Popen object? The documentation at http://docs.python.org/library/subprocess.html#subprocess.Popen.poll says that the poll method sets and returns the returncode attribute. returncode is expected to be None until the process terminates, and a negative value indicates that the subprocess has been terminated because of a signal. If poll() returns -1, it means that the process has been terminated by signal number 1 (probably SIGHUP). > BUT, I'm getting, in some cases, a return code of 127, which is impossible > to get from the memory test program. > The output from this bit of code looks like this in a failing situation: > Error: process 0 pid 2187 retuned 127 > process 0 pid 2187 returned success > Error: process 1 pid 2188 retuned 127 > process 1 pid 2188 returned success > I'm thinking that I'm hitting some sort of race here where the kernel is > reporting -1 while the process is running, then returns 127 or some other > status when the process is being killed and then finally 0 or 1 after the > process has completely closed out. ?I "think" that the poll picks up this > intermediate exit status and immediately exits the loop, instead of waiting > for a 0 or 1. > I've got a modified version that I'm getting someone to test for me now that > changes > ?if pipe[i].poll() == -1: > ? ? ?waiting = True > to this > if pipe[i].poll() not in [0,1]: > ? ? waiting = True > So my real question is: am I on the right track here, and am I correct in my > guess that the kernel is reporting different status codes to > subprocess.poll() during the shutdown of the polled process? > I'm unaware of any such race condition. It is more likely that the program you are running can return such error codes. Perhaps you should examine its stderr output. It's unclear what you're trying to do here. If you'd just like to wait until all the started processes are finished, you should use the wait() method instead of the poll() method. You should also note that the communicate() method already waits for the process to complete, so further calls to poll() and wait() are superfluous. Normally, after communicate() returns, you would simply check pipe[i].returncode and be on your way. -- regards, kushal From nobody at nowhere.com Sat Sep 10 05:33:03 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 10:33:03 +0100 Subject: try... except with unknown error types References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 31 Aug 2011 21:01:34 +0000, Chris Torek wrote: > Still, it sure would be nice to have a static analysis > tool that could answer questions about potential exceptions. :-) ) That's an impossibility in a dynamic language. If you call f.read() where f was passed in as a parameter, the exceptions which f.read() may throw depend upon exactly what f is; there's no guarantee that it will actually be a built-in file object, only that it will have a .read() method (otherwise you will get an AttributeError). Even if f was returned from open(), there's no guarantee that __builtins__.open() won't have been replaced by the time of the call. From nobody at nowhere.com Sat Sep 10 05:47:29 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 10:47:29 +0100 Subject: killing a script References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, 10 Sep 2011 11:25:40 +1000, Steven D'Aprano wrote: >> and sure enough, "man 3 system" says: > > I don't consider having to look up documentation for a function in a > completely different language (in this case, C) as "documented behaviour of > os.system". Well, tough luck. os.system() is a wrapper around the platform's system(). The authors of the Python documentation cannot possibly know what that function will do on all platforms, even less so once you factor in the user's ability to replace that function via platform-specific means. > Does the C standard define the behaviour of system(), or is that > implementation dependent? The C99 standard says: 7.20.4.5 The system function Synopsis [#1] #include int system(const char *string); Description [#2] If string is a null pointer, the system function determines whether the host environment has a command processor. If string is not a null pointer, the system function passes the string pointed to by string to that command processor to be executed in a manner which the implementation shall document; this might then cause the program calling system to behave in a non-conforming manner or to terminate. Returns [#3] If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value. It doesn't require a platform to even have a command interpreter, let alone specify its behaviour. On Unix, system() is defined to use /bin/sh, which ought to be some kind of Bourne shell; but even then, it might be a minimal shell such as dash or something with many extensions such as bash. On Windows, it uses the interpreter specified by the COMSPEC environment variable, or cmd.exe (NT-based) or command.com (DOS-based) if COMSPEC isn't set (in either case, PATH is used). > It sounds to me that the Python developers are > implicitly refusing responsibility for the detailed behaviour of os.system > by noting that it depends on the C function. Indeed. Which is the correct thing to do. Practically every function in the os module does likewise. > What do Jython, PyPy and IronPython do? I don't know, but I would expect them to use libc's system() function, except for Jython which might use java.lang.Runtime.exec(). From nobody at nowhere.com Sat Sep 10 06:11:37 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 11:11:37 +0100 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 11:37:44 +1000, Chris Angelico wrote: >> The Java compiler also acts as a "make" program. If it doesn't find >> a .class file for a needed class, it will search for the corresponding >> .java file and compile that. So to compile a complex program, you only >> need to compile the top-level file (e.g. HelloWorld.java), and it will >> compile everything which is required. No Makefile is needed, as the >> relationship between classes, object files and source files is fixed. >> > > If that's the entire benefit, then I think this is a rather hefty > price to pay for the elimination of a makefile. It also eliminates the need for TAGS files, browser database (PDB) files, etc. Once you know the class name, all of the filenames follow from that. I suspect that the one-to-one correspondence between classes and .class files is mostly technical (e.g. Java's security model). The one-to-one correspondence between class files and source files could probably be relaxed, but at the expense of complicating the IDE and toolchain. I never saw it as a problem, given that Java is fundamentally class-based: there are no global variables or functions, only classes. From __peter__ at web.de Sat Sep 10 06:17:23 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 12:17:23 +0200 Subject: try... except with unknown error types References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: Chris Torek wrote: > >>> import socket > >>> isinstance(socket.error, IOError) > False Here you test if the socket.error *class* is an instance of IOError; this would print True if IOError were socket.error's metaclass. However: >>> isinstance(socket.error(), IOError) True or more directly: >>> issubclass(socket.error, IOError) True >>> issubclass(socket.error, EnvironmentError) True This is a relatively recent change: $ python2.5 -c'from socket import error; print issubclass(error, IOError), issubclass(error, EnvironmentError)' False False $ python2.6 -c'from socket import error; print issubclass(error, IOError), issubclass(error, EnvironmentError)' True True From rosuav at gmail.com Sat Sep 10 06:29:57 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 10 Sep 2011 20:29:57 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 10, 2011 at 8:11 PM, Nobody wrote: > I suspect that the one-to-one correspondence between classes and .class > files is mostly technical (e.g. Java's security model). The one-to-one > correspondence between class files and source files could probably be > relaxed, but at the expense of complicating the IDE and toolchain. One class per object file isn't a problem - you can always .jar your classes if the proliferation of small files bothers you, and then it's just a different way of indexing the mound of code. One class per source file complicates the human's view in order to simplify the tools'. Not sure that's really worthwhile. > I never saw it as a problem, given that Java is fundamentally class-based: > there are no global variables or functions, only classes. Yeah... of course you can easily simulate globals with static members in a dedicated class, but it's slower. THIS, though, is where Java's security model comes in - you can assign security X to Globals1.class and security Y to Globals2.class, rather than trying to juggle security issues in a monolithic "globals" namespace. IMHO it's not worth the hassle, though. I'd rather just have globals. ChrisA From wm at localhost.localdomain Sat Sep 10 06:32:40 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sat, 10 Sep 2011 12:32:40 +0200 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 23:03:10 +1000, Steven D'Aprano wrote: > But think carefully before doing this. Some functions may be confused if you > change directories while they are running. You may be better off staying in > the same directory, and adjusting the path names to the files as you work > with them. Curious. Do you mean multi-threaded environment or even in single thread? If the latter is the case, I'd say those functions make very nasty assumptions. Who are they, anyways? ;) Br. Waldek From mark.dufour at gmail.com Sat Sep 10 07:08:43 2011 From: mark.dufour at gmail.com (Mark Dufour) Date: Sat, 10 Sep 2011 13:08:43 +0200 Subject: [ANN] Shed Skin 0.9 Message-ID: Hi all, I have just released version 0.9 of Shed Skin, a (restricted-)Python to C++ compiler. Please see my blog for the full announcement: http://shed-skin.blogspot.com The Shed Skin homepage is located here: http://shedskin.googlecode.com Thanks! Mark Dufour. -- http://www.youtube.com/watch?v=E6LsfnBmdnk -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sat Sep 10 07:11:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 21:11:32 +1000 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6b45e6$0$29970$c3e8da3$5496439d@news.astraweb.com> Waldek M. wrote: > On Fri, 09 Sep 2011 23:03:10 +1000, Steven D'Aprano wrote: >> But think carefully before doing this. Some functions may be confused if >> you change directories while they are running. You may be better off >> staying in the same directory, and adjusting the path names to the files >> as you work with them. > > Curious. > Do you mean multi-threaded environment or even in single thread? > If the latter is the case, I'd say those functions make > very nasty assumptions. Who are they, anyways? ;) The main one that comes to mind is os.walk, which has this to say: Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Seems like a reasonable assumption to me. -- Steven From laddosingh at gmail.com Sat Sep 10 07:20:17 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sat, 10 Sep 2011 04:20:17 -0700 (PDT) Subject: Doctest failing Message-ID: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Hi guys. I'm strugglin with some homework stuff and am hoping you can help me out here. This is the code: small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') def book_title(title): """ Takes a string and returns a title-case string. All words EXCEPT for small words are made title case unless the string starts with a preposition, in which case the word is correctly capitalized. >>> book_title('DIVE Into python') 'Dive into Python' >>> book_title('the great gatsby') 'The Great Gatsby' >>> book_title('the WORKS OF AleXANDer dumas') 'The Works of Alexander Dumas' """ new_title = [] title_split = title.strip().lower().split() for word in title_split: if title_split[0] in small_words: new_title.append(word.title()) elif word in small_words: new_title.append(word.lower()) else: new_title.append(word.title()) return(' '.join(new_title)) def _test(): import doctest, refactory return doctest.testmod(refactory) if __name__ == "__main__": _test() All tests are failing even though I am getting the correct output on the first two tests. And the last test still gives me "Of" instead of "of" Any help is appreciated. Rgds T From mwilson at the-wire.com Sat Sep 10 07:43:38 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 10 Sep 2011 07:43:38 -0400 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. > All words EXCEPT for small words are made title case > unless the string starts with a preposition, in which > case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) > return(' '.join(new_title)) > > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > > All tests are failing even though I am getting the correct output on > the first two tests. And the last test still gives me "Of" instead of > "of" > > Any help is appreciated. I don't know about doctest -- I suspect it wants a structured docstring to specify the tests -- but this if title_split[0] in small_words: new_title.append(word.title()) can't be what you want. Mel. From __peter__ at web.de Sat Sep 10 07:47:04 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 13:47:04 +0200 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Tigerstyle wrote: > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) The logic of the for-loop is flawed; the expression title_split[0] in small_words will always evaluate to True if the first word is a "small word", even when the loop is already past the first word. You can work around that with a flag along these lines first = True for word in title_split: if first: # special treatment for the first word first = False else: # put checks for all words but the first here new_title.append(fixed_word) # assuming you have stored the titlecased # or lowercased word in the fixed_word # variable From t at jollybox.de Sat Sep 10 07:50:14 2011 From: t at jollybox.de (Thomas Jollans) Date: Sat, 10 Sep 2011 13:50:14 +0200 Subject: Doctest failing In-Reply-To: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <4E6B4EF6.6050200@jollybox.de> On 10/09/11 13:20, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > All tests are failing even though I am getting the correct output on > the first two tests. And the last test still gives me "Of" instead of > "of" Cannot reproduce. I only get the one, expected, failure. % python -m doctest books.py ********************************************************************** File "books.py", line 12, in books.book_title Failed example: book_title('the WORKS OF AleXANDer dumas') Expected: 'The Works of Alexander Dumas' Got: 'The Works Of Alexander Dumas' ********************************************************************** 1 items had failures: 1 of 3 in books.book_title ***Test Failed*** 1 failures. > > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > What is this "refactory"? Are you testing the right code? What is the output of your test - does it make sense for the module? Thomas From dreyemi at gmail.com Sat Sep 10 07:58:35 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 10 Sep 2011 12:58:35 +0100 Subject: test if a subclass inherits a superclass method Message-ID: Hello, I'm testing Python's class abstractness and inheritance. Since interface doesn't exist, I will like to test how to have access to a superclass method from a subclass without necessary invoking or overriding the superclass method in its subclass. >>> class Equipment(object): ... def fault(): ... return "fault" ... >>> Equipment().__class__ >>> class Vehicle(Equipment): ... # Find out here if Vehicle has access to fault I want to know whether Vehicle has access to Equipment's fault() method. Just want to know if it's there(that a vehicle can also develop a fault). I know I can override it, but I want to know if I can use it directly without overriding it. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sat Sep 10 08:05:08 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 10 Sep 2011 13:05:08 +0100 Subject: test if a subclass inherits a superclass method In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 12:58 PM, Kayode Odeyemi wrote: > Hello, > > I'm testing Python's class abstractness and inheritance. Since interface > doesn't exist, I will > like to test how to have access to a superclass method from a subclass > without necessary > invoking or overriding the superclass method in its subclass. > > >>> class Equipment(object): > ... def fault(): > ... return "fault" > ... > >>> Equipment().__class__ > > >>> class Vehicle(Equipment): > ... # Find out here if Vehicle has access to fault > > I want to know whether Vehicle has access to Equipment's fault() method. > Just want to know if it's there(that a vehicle can also develop a fault). > > I know I can override it, but I want to know if I can use it directly > without overriding it. > OK! I figured it out like this: >>> v = Vehicle() >>> dir(v) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_ _weakref__', 'fault'] Cool stuff. -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.ware at ntlworld.com Sat Sep 10 08:24:25 2011 From: alister.ware at ntlworld.com (Alister Ware) Date: Sat, 10 Sep 2011 12:24:25 GMT Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sat, 10 Sep 2011 04:20:17 -0700, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me out > here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. All words EXCEPT > for small words are made title case unless the string starts with a > preposition, in which case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) > return(' '.join(new_title)) > > def _test(): > import doctest, refactory return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > > All tests are failing even though I am getting the correct output on the > first two tests. And the last test still gives me "Of" instead of "of" > > Any help is appreciated. > > Rgds > > T Ignoring the docttests my process would be to process each word & then manually capitalize he 1st word, .I would als0 use a comprehension as makes for cleaner code:- small_words=('into','the','a','of','at','in','for','on') def capitalize(word): if word in small_words: return word else: return word.title() def set_title(phrase): result=[ capitalize(x.lower()) for x in phrase.split(' ') ] result[0]=result[0].title() return " ".join(result) print set_title('the works of alexander dumas') -- ... I don't like FRANK SINATRA or his CHILDREN. From hetchkay at gmail.com Sat Sep 10 09:28:49 2011 From: hetchkay at gmail.com (hetchkay) Date: Sat, 10 Sep 2011 06:28:49 -0700 (PDT) Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> <87ipp0n7c1.fsf@benfinney.id.au> Message-ID: <4ee53496-ebec-4ee5-be0c-de344ac586c8@y39g2000prd.googlegroups.com> > > I suspect, if you can be explicit about the goal you're aiming for with > this code, a better design can be found that doesn't require all those > polymorphism-breaking type checks. > It is difficult to explain what I am trying to do, but let me try. I am mapping data from one hierarchy into another. The mapping rules are quite complex. I developed a system such that the rules could be defined as "expressions" of the source hierarchy i.e a particular entry in the target hierarchy could be represented as an expression of entries in the source hierarchy. Suppose a point is stored in x, y coordinates in the source hierarchy, and in polar coordinates in the target hierarchy, I could write (forget for the moment what sourcePt is): pointMapping = { sourcePt.key : dict( radius = Sqrt(sourcePt.value['x']**2 + sourcePt.value['y']**2), angle = Atan(sourcePt.value['y']/sourcePt.value['x']), ), } The above dictionary is delay-evaluated. sourcePt is an instance of a class that facilitates the delayed evaluation. Sqrt, Atan etc. are wrappers to the math functions to facilitate delayed evaluation. When I encounter a point object, I could 'evaluate' the above mapping for the point object to get the target dictonary. The actual requirements are much more involved than this. The motivation of the design was to enable application developers (who are not experts in python) to be able to write the mappings. The mappings also need to be readable. You could consider this to be some sort of DSL. However, because of the number of rules involved, I am trying to be as close to Python expressions as possible. If the target setting is to be a tuple, for example, I want to be able to write the tuple directly as "( expr1, expr2 )", rather than, say, "Tuple(expr1, expr2)". There is also a requirement to validate the mapping on load so that run-time errors are minimized. The system we are developing is quite reusable and we have been able to use it for three different mappings so far. At this point, I am trying to profile the code and noticed that a non-trivial amount of time is being spent in the particular function I mentioned in this thread. Regards, Krishnan From wm at localhost.localdomain Sat Sep 10 09:57:16 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sat, 10 Sep 2011 15:57:16 +0200 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e6b45e6$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5yll66t4xv3j.dlg@localhost.localdomain> On Sat, 10 Sep 2011 21:11:32 +1000, Steven D'Aprano wrote: > The main one that comes to mind is os.walk, which has this to say: > > Caution: if you pass a relative pathname for top, don't change the > current working directory between resumptions of walk. walk never > changes the current directory, and assumes that the client doesn't > either. > > Seems like a reasonable assumption to me. Oh, that kind of functions. Yes, that *is* surely reasonable, just as mixing chdir/mkdir/remove and whatever else that affects the directory structure is not a good idea, or at least something to be done carefully. I just wouldn't think to give it some special credit. Thanks Waldek From tyler at tysdomain.com Sat Sep 10 10:04:24 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 08:04:24 -0600 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E6B6E68.9010908@tysdomain.com> On 9/10/2011 4:11 AM, Nobody wrote: > On Fri, 09 Sep 2011 11:37:44 +1000, Chris Angelico wrote: > >>> The Java compiler also acts as a "make" program. If it doesn't find >>> a .class file for a needed class, it will search for the corresponding >>> .java file and compile that. So to compile a complex program, you only >>> need to compile the top-level file (e.g. HelloWorld.java), and it will >>> compile everything which is required. No Makefile is needed, as the >>> relationship between classes, object files and source files is fixed. >>> >> If that's the entire benefit, then I think this is a rather hefty >> price to pay for the elimination of a makefile. > It also eliminates the need for TAGS files, browser database (PDB) files, > etc. Once you know the class name, all of the filenames follow from that. > > I suspect that the one-to-one correspondence between classes and .class > files is mostly technical (e.g. Java's security model). The one-to-one > correspondence between class files and source files could probably be > relaxed, but at the expense of complicating the IDE and toolchain. > > I never saw it as a problem, given that Java is fundamentally class-based: > there are no global variables or functions, only classes. > Sure there are no global variables, but having one class per file is one of the big things I hate about Java. Sure it keeps things organized, but that's a bit to much for me. -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From tyler at tysdomain.com Sat Sep 10 10:08:28 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 08:08:28 -0600 Subject: test if a subclass inherits a superclass method In-Reply-To: References: Message-ID: <4E6B6F5C.8000304@tysdomain.com> On 9/10/2011 5:58 AM, Kayode Odeyemi wrote: > Hello, > > I'm testing Python's class abstractness and inheritance. Since > interface doesn't exist, I will > like to test how to have access to a superclass method from a subclass > without necessary > invoking or overriding the superclass method in its subclass. > > >>> class Equipment(object): > ... def fault(): > ... return "fault" > ... > >>> Equipment().__class__ > > >>> class Vehicle(Equipment): > ... # Find out here if Vehicle has access to fault > > I want to know whether Vehicle has access to Equipment's fault() method. > Just want to know if it's there(that a vehicle can also develop a fault). > > I know I can override it, but I want to know if I can use it directly > without overriding it. Perhaps this helps: http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Sep 10 10:12:32 2011 From: roy at panix.com (Roy Smith) Date: Sat, 10 Sep 2011 10:12:32 -0400 Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> <87ipp0n7c1.fsf@benfinney.id.au> <4ee53496-ebec-4ee5-be0c-de344ac586c8@y39g2000prd.googlegroups.com> Message-ID: In article <4ee53496-ebec-4ee5-be0c-de344ac586c8 at y39g2000prd.googlegroups.com>, hetchkay wrote: [complicated description elided] > You could consider this to be some sort of DSL. However, because of > the number of rules involved, I am trying to be as close to Python > expressions as possible. If the target setting is to be a tuple, for > example, I want to be able to write the tuple directly as "( expr1, > expr2 )", rather than, say, "Tuple(expr1, expr2)". > There is also a requirement to validate the mapping on load so that > run-time errors are minimized. I assume by DSL you mean Domain Specific Language? Having worked with a number of DSLs, my emphatic recommendation is DON'T DO IT! What you will end up with is a language which is almost, but not quite, like some other existing language. That means the people who use it will need to learn something new. If you make it "as close to Python as possible", all that will happen is people will assume it's Python, and constantly be surprised when things don't work the same way. Whatever features of "real Python" you left out, people will invariably be clamoring for. Eventually, you will be forced to duct-tape them into the language. You will end up bogged down forever in language maintenance, adding features, fixing bugs, writing documentation, providing tech support, etc. Think of all the ecosystem stuff which grows up around a real language. Debuggers. Profilers. Language-aware editors (or plugins to emacs, eclipse, etc). Add-in libraries to do a zillion things you never thought you would want to do. Hoards of really smart and enthusiastic people on mailing lists, newsgroups, Stack Overflow, etc willing to help out with problems. Books. Professional training courses. You will end up with replicating all that, or doing without. It sounds like what you really want to do is just use Python as your scripting language. The lazy evaluation features you desire can be handled by writing some library code. From wentlv at gmail.com Sat Sep 10 11:41:20 2011 From: wentlv at gmail.com (crow) Date: Sat, 10 Sep 2011 08:41:20 -0700 (PDT) Subject: Is there anyway to use urllib2 to download a file from http server? Message-ID: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> As the title. Or is there other module that can handle this task? Many thanks in advance From stefan_ml at behnel.de Sat Sep 10 11:53:12 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 10 Sep 2011 17:53:12 +0200 Subject: Is there anyway to use urllib2 to download a file from http server? In-Reply-To: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> References: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> Message-ID: crow, 10.09.2011 17:41: > As the title. > > Or is there other module that can handle this task? Did you notice that is has documentation? http://docs.python.org/library/urllib2.html#examples Stefan From rosuav at gmail.com Sat Sep 10 11:56:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 11 Sep 2011 01:56:32 +1000 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware wrote: > Ignoring the docttests my process would be to process each word & then > manually capitalize he 1st word, .I would als0 use a comprehension as > makes for cleaner code:- > > def capitalize(word): > ? ?if word in small_words: > ? ? ? ?return word > ? ?else: > ? ? ? ?return word.title() And I'd do this with a lambda, but that's just me. Of course, if your logic is more complicated, it makes more sense to keep it in a named function, but a single conditional call can fit nicely into a lambda. ChrisA From tjreedy at udel.edu Sat Sep 10 13:34:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 13:34:19 -0400 Subject: [ANN] Shed Skin 0.9 In-Reply-To: References: Message-ID: On 9/10/2011 7:08 AM, Mark Dufour wrote: > Hi all, > > I have just released version 0.9 of Shed Skin, a (restricted-)Python to > C++ compiler. That should say "Python2.(4-6) to C++ compiler". I do not want to pick on Mark, who I think is doing great work, but I find it annoying when third-party developers use the generic 'Python' to refer to undisclosed older versions of Python. > Please see my blog for the full announcement: > > http://shed-skin.blogspot.com While Mark never reveals this crucial information anywhere on this page, > The Shed Skin homepage is located here: > > http://shedskin.googlecode.com he does specify versions in the first sentence of this page. That is much better than some other projects. -- Terry Jan Reedy From abhijeet.manohar at gmail.com Sat Sep 10 13:37:12 2011 From: abhijeet.manohar at gmail.com (Abhijeet Mahagaonkar) Date: Sat, 10 Sep 2011 23:07:12 +0530 Subject: Is there anyway to use urllib2 to download a file from http server? In-Reply-To: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> References: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> Message-ID: I guess urlretrieve() would do the job -AB On Sat, Sep 10, 2011 at 9:11 PM, crow wrote: > As the title. > > Or is there other module that can handle this task? > > Many thanks in advance > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Sep 10 13:59:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 13:59:02 -0400 Subject: Doctest failing In-Reply-To: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/10/2011 7:20 AM, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. We appreciate you saying so instead of hiding that this is homework. > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. > All words EXCEPT for small words are made title case > unless the string starts with a preposition, in which > case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) The key issue is that you want to treat the first word one way (.title it) and the rest differently (conditionally .title or not) . So immediately separate the first from the rest and then process each. There are at least three ways to do the split. Perhaps I should stop with this hint, and certainly you should think a bit before reading further, but here is what I consider to be the most elegant 3.2 code. . , , , . . . first, *rest = title.strip().lower().split() new_title = [first.title()] for word in rest: if word not in small_words: word = word.title() new_title.append(word) > return(' '.join(new_title)) doctest.testmod() now passes (there is no 'refactory' here) > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 10 15:36:42 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 15:36:42 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' Message-ID: Python's iterator protocol for an iterator 'items' allows combinations of explicit "next(items)" calls with the implicit calls of a "for item in items:" loop. There are at least three situations in which this can be useful. (While the code posted here is not testable, being incomplete or having pseudocode lines, I have tested full examples of each idiom with 3.2.) 1. Process first item of an iterable separately. A traditional solution is a flag variable that is tested for each item. first = True for item in iterable: if first: first = False else: (I have seen code like this posted on this list several times, including today.) Better, to me, is to remove the first item *before* the loop. items = iter(iterable) Sometimes and can be combined in . For instance, "result = []" followed by "result.append(process_first(item))" becomes "result = [process_first(item)]". The statement containing the explicit next(items) call can optionally be wrapped to explicitly handle the case of an empty iterable in whatever manner is desired. try: except StopIteration: raise ValueError("iterable cannot be empty") For an iterable known to have a small number of items, the first item can be removed, with only a small copying penalty, with a simple assignment. first, *rest = iterable The older and harder to write version of this requires the iterable to be a sequence? first, rest = seq[0], seq[1:] 2. Process the last item of an iterable differently. As far as I know, this cannot be done for a generic iterable with a flag. It requires a look ahead. items = iter(iterable) current = next(items) for item in items: current = item To treat both first and last differently, pull off the first before binding 'current'. Wrap next() calls as desired. 3. Process the items of an iterable in pairs. items = iter(iterable) for first in items: second = next(items) This time, StopIteration is raised for an odd number of items. Catch and process as desired. One possibility is to raise ValueError("Iterable must have an even number of items"). A useful example of just sometimes pairing is iterating a (unicode) string by code points ('characters') rather than by code units. This requires combining the surrogate pairs used for supplementary characters when the units are 16 bits. chars = iter(string) for char in chars: if is_first_surrogate(char): char += next(chars) yield char -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 10 15:36:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 15:36:47 -0400 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/10/2011 7:47 AM, Peter Otten wrote: > You can work around that with a > flag along these lines > > first = True > for word in title_split: > if first: > # special treatment for the first word > first = False > else: > # put checks for all words but the first here > new_title.append(fixed_word) # assuming you have stored the titlecased > # or lowercased word in the fixed_word > # variable An alternative to a flag and testing every item is to remove and process the first item *before* the loop. See my response on this thread or my new thread Idioms combining 'next(items)' and 'for item in items:' -- Terry Jan Reedy From Phillip.M.Feldman at gmail.com Sat Sep 10 15:57:21 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 12:57:21 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: <32435519.post@talk.nabble.com> Message-ID: <32439307.post@talk.nabble.com> Very nice explanation! I've circumvented the problem by returning a `deepcopy` of the list. I've also added an acknowledgment. The revised code is attached. I'd like to see both balls in numbered boxes (this code) and balls in unnumbered (indistinguishable) boxes in Python's `itertools` module, but don't know whom to contact about this. Also, I haven't yet worked out a good algorithm for balls in unnumbered boxes. Any suggestions will be appreciated. Phillip http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py balls_in_numbered_boxes.py -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439307.html Sent from the Python - python-list mailing list archive at Nabble.com. From pgiri at yahoo.com Sat Sep 10 16:05:36 2011 From: pgiri at yahoo.com (Giridhar Pemmasani) Date: Sat, 10 Sep 2011 13:05:36 -0700 (PDT) Subject: [ANN] dispy: distribute computations and execute in parallel Message-ID: <1315685136.93773.YahooMailNeo@web160614.mail.bf1.yahoo.com> Hello, I would like to announce dispy (http://dispy.sf.net) that can distribute and parallelize computations among computing nodes over network (yes, yet another implementation of parallelization). This is useful for problems in SIMD paradigm where a computation can be executed with multiple data simultaneously. Salient features of dispy are: ?* Computations (Python functions or standalone programs) and its ? ?dependencies (files, Python functions, classes, modules) are ? ?distributed automatically as and when needed. ?* Computation nodes can be anywhere on the network. For security, ? ?either simple hash based authentication or SSL encryption can be ? ?used. ?* A computation may specify which nodes are allowed to execute it ? ?(for now, using simple patterns of IP addresses). ?* After each execution is finished, the results of execution, output, ? ?errors and exception trace are made available for further ? ?processing. ?* Nodes may become available dynamically: dispy will schedule jobs ? ?whenever a node is available and computations can use that node. If ? ?a node fails while executing scheduled jobs, those jobs may be ? ?resubmitted to other nodes if computations allow it. ?* dispy can be used in a single process to use all the nodes ? ?exclusively (simpler to use) or in multiple processes sharing the ? ?nodes. Currently dispy works with Python 2.7 and has been tested with nodes running Linux and OS X. Thanks, Giri -------------- next part -------------- An HTML attachment was scrubbed... URL: From Phillip.M.Feldman at gmail.com Sat Sep 10 16:32:49 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 13:32:49 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: <32439307.post@talk.nabble.com> References: <32435519.post@talk.nabble.com> <32439307.post@talk.nabble.com> Message-ID: <32439439.post@talk.nabble.com> I just realized that there is a defect in my algorithm, so I will try to code this using a recursive algorithm instead. -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439439.html Sent from the Python - python-list mailing list archive at Nabble.com. From gelonida at gmail.com Sat Sep 10 16:43:39 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 10 Sep 2011 22:43:39 +0200 Subject: optionparse: how to add a line break to the help text Message-ID: I'm having a small question about optionparse. Normaly optionparser will format the help text according to the console's width. I just wondered if there is any way to insert a line breakk into an options help text. Example: from optparse import OptionParser parser = OptionParser() parser.add_option("-f", action="store", help="This option is really really complicated" " and I'd like to write" " a few paragrpahs to explain how it works." "\nHowever the line breaks are stripped off" " and it's thus difficult to structure the help text") args = ['-h'] parser.parse_args(args) Is there any trick to force a new paragraph/ line break before the word 'However'? Thanks in advance for suggestions. From __peter__ at web.de Sat Sep 10 16:49:13 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 22:49:13 +0200 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Terry Reedy wrote: > On 9/10/2011 7:47 AM, Peter Otten wrote: > >> You can work around that with a >> flag along these lines >> >> first = True >> for word in title_split: >> if first: >> # special treatment for the first word >> first = False >> else: >> # put checks for all words but the first here >> new_title.append(fixed_word) # assuming you have stored the >> titlecased >> # or lowercased word in the fixed_word >> # variable > > An alternative to a flag and testing every item is to remove and process > the first item *before* the loop. See my response on this thread or my > new thread > Idioms combining 'next(items)' and 'for item in items:' I reckoned the approach with the flag the most beginner-friendly because you don't have to think too hard about the corner-cases, namely >>> book_title("") '' When I use the "process first item before the loop" approach I usually end up with a helper generator def _words(words, small_words={w.title(): w for w in small_words}): yield next(words) for word in words: yield small_words[word] if word in small_words else word def book_title(s): return " ".join(_words(iter(s.title().split()))) and the nagging thought that I'm making it more complex than need be. From tyler at tysdomain.com Sat Sep 10 16:53:26 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 14:53:26 -0600 Subject: using python in web applications In-Reply-To: <87mxedm3lh.fsf@benfinney.id.au> References: <87mxedm3lh.fsf@benfinney.id.au> Message-ID: <4E6BCE46.3020002@tysdomain.com> On 9/9/2011 10:19 PM, Ben Finney wrote: > "Littlefield, Tyler" writes: > >> I'm curious if there are some good solutions for using Python in web >> applications. > Start with: > > > > Awesome, will do, thanks. > and try your criteria against what you find there. > -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From matthew.a.hess at gmail.com Sat Sep 10 17:44:01 2011 From: matthew.a.hess at gmail.com (matt) Date: Sat, 10 Sep 2011 14:44:01 -0700 (PDT) Subject: IOError 35 when trying to read the result of call to urllib2.urlopen References: <4e6ab711$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0a79dcd3-92e6-4102-b202-dbb33fce634f@e34g2000prn.googlegroups.com> On Sep 9, 6:02?pm, Steven D'Aprano wrote: > matt wrote: > > When I try to look at "resp_body" I get this error: > > > IOError: [Errno 35] Resource temporarily unavailable > > > I posted to the same URI using curl and it worked fine, so I don't > > think it has to do with the server. > > Are your Python code and curl both using the same proxy? It may be that one > is going direct and the other is using a proxy. > > Or perhaps the destination is just flaky, and the resource genuinely is > temporarily unavailable. Or it doesn't like your useragent string and is > lying. > > -- > Steven No proxy. It's all local over the loopback interface (probably should have mentioned that). The service I'm POSTing to is a Python web app with CherryPy as the framework. Also, because of some dependency issues I'm using Python 2.6. From rafadurancastaneda at gmail.com Sat Sep 10 18:16:42 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 11 Sep 2011 00:16:42 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: <4E6BE1CA.9030608@gmail.com> On 10/09/11 22:43, Gelonida N wrote: > I'm having a small question about optionparse. > > Normaly optionparser will format the help text according to the > console's width. > > I just wondered if there is any way to insert a line breakk into an > options help text. > > Example: > > from optparse import OptionParser > > parser = OptionParser() > parser.add_option("-f", action="store", > help="This option is really really complicated" > " and I'd like to write" > " a few paragrpahs to explain how it works." > "\nHowever the line breaks are stripped off" > " and it's thus difficult to structure the help text") > > args = ['-h'] > parser.parse_args(args) > > Is there any trick to force a new paragraph/ line break before the word > 'However'? > > > Thanks in advance for suggestions. > > You can use """ for multiple line texts: >>> text = \ ... """fsdfsfsdfsdf ... sfsdfsfsdf ... sdfsdf s ... ... """ >>> text 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' From dribnairb at gmail.com Sat Sep 10 18:50:09 2011 From: dribnairb at gmail.com (Brian) Date: Sat, 10 Sep 2011 15:50:09 -0700 (PDT) Subject: Python and Outlook-style rules References: Message-ID: <3a160e5e-0dbe-47e3-9dba-901003041bd4@d12g2000vba.googlegroups.com> On Sep 9, 5:19?pm, Alec Taylor wrote: > Something like this? > > http://stackoverflow.com/questions/387606/using-user-input-to-find-in... > Actually, I'm looking for a framework or something similar - something more like this, only for python: http://www.codeproject.com/KB/macros/RulesWizard.aspx From laurent.payot at gmail.com Sat Sep 10 19:35:28 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 16:35:28 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> [troll] For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. [/troll] "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. From laurent.payot at gmail.com Sat Sep 10 19:35:28 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 16:35:28 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> [troll] For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. [/troll] "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. From robert.kern at gmail.com Sat Sep 10 19:44:02 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 10 Sep 2011 18:44:02 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6BE1CA.9030608@gmail.com> References: <4E6BE1CA.9030608@gmail.com> Message-ID: On 9/10/11 5:16 PM, Rafael Dur?n Casta?eda wrote: > On 10/09/11 22:43, Gelonida N wrote: >> I'm having a small question about optionparse. >> >> Normaly optionparser will format the help text according to the >> console's width. >> >> I just wondered if there is any way to insert a line breakk into an >> options help text. >> >> Example: >> >> from optparse import OptionParser >> >> parser = OptionParser() >> parser.add_option("-f", action="store", >> help="This option is really really complicated" >> " and I'd like to write" >> " a few paragrpahs to explain how it works." >> "\nHowever the line breaks are stripped off" >> " and it's thus difficult to structure the help text") >> >> args = ['-h'] >> parser.parse_args(args) >> >> Is there any trick to force a new paragraph/ line break before the word >> 'However'? >> >> >> Thanks in advance for suggestions. >> >> > You can use """ for multiple line texts: > >>> text = \ > ... """fsdfsfsdfsdf > ... sfsdfsfsdf > ... sdfsdf s > ... > ... """ > >>> text > 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' That's not the problem. OptionParser removes all of the original newlines that are in the given text when it formats the text for display. I don't think there is a simple workaround. -- 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 cs at zip.com.au Sat Sep 10 19:50:46 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 11 Sep 2011 09:50:46 +1000 Subject: what's the command for (cd ..) in python In-Reply-To: <5yll66t4xv3j.dlg@localhost.localdomain> References: <5yll66t4xv3j.dlg@localhost.localdomain> Message-ID: <20110910235046.GA12648@cskk.homeip.net> On 10Sep2011 15:57, Waldek M. wrote: | On Sat, 10 Sep 2011 21:11:32 +1000, Steven D'Aprano wrote: | > The main one that comes to mind is os.walk, which has this to say: | > | > Caution: if you pass a relative pathname for top, don't change the | > current working directory between resumptions of walk. walk never | > changes the current directory, and assumes that the client doesn't | > either. | > | > Seems like a reasonable assumption to me. | | Oh, that kind of functions. | Yes, that *is* surely reasonable, just as mixing chdir/mkdir/remove | and whatever else that affects the directory structure is not a good idea, | or at least something to be done carefully. | I just wouldn't think to give it some special credit. It's like umask and friends - they affect a program-wide implicit state. Umask affects default new file permissions, chdir affects starting point for relative pathnames, etc. All implicit. The usual biggie with chdir is that of course your program may have been handed relative file pathnames on the command line. They need resolving _before_ any chdiring happens, if chdiring is going to happen. For this kind of reason chdir, umask et al are generally best used in top level logic only rather than inside library functions. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's hard to believe that something as rational as the metric system was invented by the French. - Henry O. Farad From gelonida at gmail.com Sat Sep 10 20:05:13 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 02:05:13 +0200 Subject: import packet.module without importing packet.__init__ ? Message-ID: Hi, I am little shaky with how exactly python imports packages / modules etc. Is it possible to import a module from a packet without importing its __init__.py ? Full example: ============== # application.py --------------------- print "starting application" import mypacket.module1 # mypacket.__init__.py --------------------- print "importing __init__" # mypacket.module1.py --------------------- print "importing module1" The output, that I get with python 2.6 is $ python application.py > starting application > importing __init__ > importing module1 Under certain circumstances I'd like to avoid the implicit import of __init__.py Due to other constrains of my project I am obliged to have a non empty __init__.py From Phillip.M.Feldman at gmail.com Sat Sep 10 20:43:39 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 17:43:39 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes Message-ID: <32440187.post@talk.nabble.com> I've written a recursive class that creates an iterator to solve a general formulation of the combinatorics problem known as "balls in numbered boxes" (also known as "indistinguishable balls in distinguishable boxes"). The code has been extensively tested and appears to work, but isn't terribly elegant. Any suggestions about how to improve it will be appreciated. Also, I'd like to get this functionality into the Python's `itertools` module (the present set of combinatorics functions in `itertools` does not include "balls in boxes"). Does anyone know whom I should contact about this? Phillip http://old.nabble.com/file/p32440187/balls_in_numbered_boxes.py balls_in_numbered_boxes.py -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32440187.html Sent from the Python - python-list mailing list archive at Nabble.com. From tyler at tysdomain.com Sat Sep 10 20:50:21 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 18:50:21 -0600 Subject: using python in web applications In-Reply-To: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> Message-ID: <4E6C05CD.3010905@tysdomain.com> On 9/10/2011 5:35 PM, Laurent wrote: > [troll] > For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. > [/troll] > I replied to that one off list I guess, but I figured Django was way more overhead than I wanted, doesn't really fit with solving the speed issue. > "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture > > You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. Awesome, thanks. I'm new to this, so some of that flew over my head, but I'll take a look at all of them. I'm not sure of the relevance of stackless in this case; I was looking into PyPy, but I'm not really sure whether that can be connected with nginx. I guess I could just write the web server in Python and use it from that point. -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From steve+comp.lang.python at pearwood.info Sat Sep 10 20:56:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 10:56:42 +1000 Subject: import packet.module without importing packet.__init__ ? References: Message-ID: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Gelonida N wrote: > Is it possible to import a module from a packet without importing its > __init__.py ? Untested, but I think so. But you shouldn't. The solution (if it does work, as I said I haven't tested it) is a hack. Suppose you have a library like this: modules/ +-- spam.py +-- ham.py +-- package/ +-- __init__.py +-- cheese.py The directory "modules" is in your Python path, so you can "import spam" or "import package". The trick is to add "modules/package" to the Python path so that "import cheese" will find cheese.py directly. You can do that by manipulating sys.path, or by setting the environment variable PYTHONPATH. Another hack would be to add a hard link to the top level: modules/ +-- spam.py +-- ham.py +-- cheese.py <------------+ +-- package/ | +-- __init__.py | +-- cheese.py <--------+ This is not a copy, it is a hard link: the same file appears in literally two places. (But note that not all file systems support hard linking.) Soft links or shortcuts might also work. Now you can "import cheese". But generally, you should design your package so that it doesn't matter whether or not __init__.py is imported first. I see three reasnable situations: (1) package.cheese should rely on package, in which case it requires package.__init__ to be imported first. (Sometimes I put code common to the entire package in __init__.py.) (2) Just don't worry about the fact that package.__init__ gets imported first. Do you have any idea how many modules get imported when Python starts up? What's one more? (3) If cheese.py truly is independent of package, then it shouldn't be part of package. Just make it a stand alone module outside the package directory, and be done. (Your installer can still treat cheese.py as a dependency of package, and ensure that they are both installed.) -- Steven From rhodri at wildebst.demon.co.uk Sat Sep 10 21:12:26 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 11 Sep 2011 02:12:26 +0100 Subject: optionparse: how to add a line break to the help text References: Message-ID: On Sat, 10 Sep 2011 23:16:42 +0100, Rafael Dur?n Casta?eda wrote: > On 10/09/11 22:43, Gelonida N wrote: >> I'm having a small question about optionparse. >> >> Normaly optionparser will format the help text according to the >> console's width. >> >> I just wondered if there is any way to insert a line breakk into an >> options help text. >> >> Example: >> >> from optparse import OptionParser >> >> parser = OptionParser() >> parser.add_option("-f", action="store", >> help="This option is really really complicated" >> " and I'd like to write" >> " a few paragrpahs to explain how it works." >> "\nHowever the line breaks are stripped off" >> " and it's thus difficult to structure the help text") >> >> args = ['-h'] >> parser.parse_args(args) >> >> Is there any trick to force a new paragraph/ line break before the word >> 'However'? >> >> >> Thanks in advance for suggestions. >> >> > You can use """ for multiple line texts: > >>> text = \ > ... """fsdfsfsdfsdf > ... sfsdfsfsdf > ... sdfsdf s > ... > ... """ > >>> text > 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' Unfortunately the help text is formatted using textwrap, which presumes that the entire text is a single paragraph. To get paragraphs in the help text, you'll need to write an IndentedHelpFormatter subclass that splits the text on "\n\n", textwraps the split string individually, then re-joins them. _format_text() and format_option() look like the methods that would need replacing. -- Rhodri James *-* Wildebeest Herder to the Masses From gelonida at gmail.com Sat Sep 10 21:54:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 03:54:57 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: Hi James, On 09/11/2011 03:12 AM, Rhodri James wrote: > On Sat, 10 Sep 2011 23:16:42 +0100, Rafael Dur?n Casta?eda > wrote: > >> On 10/09/11 22:43, Gelonida N wrote: >>> >>> from optparse import OptionParser >>> >>> parser = OptionParser() >>> parser.add_option("-f", action="store", >>> help="This option is really really complicated" >>> " and I'd like to write" >>> " a few paragrpahs to explain how it works." >>> "\nHowever the line breaks are stripped off" >>> " and it's thus difficult to structure the help text") >>> >>> args = ['-h'] >>> parser.parse_args(args) >>> >>> Is there any trick to force a new paragraph/ line break before the word >>> 'However'? >> > > Unfortunately the help text is formatted using textwrap, which presumes > that the entire text is a single paragraph. To get paragraphs in the > help text, you'll need to write an IndentedHelpFormatter subclass that > splits the text on "\n\n", textwraps the split string individually, then > re-joins them. _format_text() and format_option() look like the methods > that would need replacing. > Thanks a lot. Good to know, that there are options, though a little more complicated than expected. I'll live withou tthe line break for the time being and will deep dive lateron, when I really want to insist on pragraphs within a help section. I like the idea of '\n\n' as paragraph markes. Long term this could probably even become an enhancement for optparse (with an explicit option to enable it in order to break no existing code) From python.list at tim.thechases.com Sat Sep 10 22:08:45 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 10 Sep 2011 21:08:45 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: <4E6C182D.60905@tim.thechases.com> On 09/10/11 20:54, Gelonida N wrote: >> Unfortunately the help text is formatted using textwrap, which presumes >> that the entire text is a single paragraph. To get paragraphs in the >> help text, you'll need to write an IndentedHelpFormatter subclass that >> splits the text on "\n\n", textwraps the split string individually, then >> re-joins them. _format_text() and format_option() look like the methods >> that would need replacing. > > Thanks a lot. Good to know, that there are options, though a little more > complicated than expected. Just in case you want it: http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse it's come up several times and several years ago I hacked together exactly the solution Rhodri mentions. -tkc From ting at thsu.org Sat Sep 10 22:12:37 2011 From: ting at thsu.org (ting at thsu.org) Date: Sat, 10 Sep 2011 19:12:37 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sep 10, 7:47?am, Peter Otten <__pete... at web.de> wrote: > Tigerstyle wrote: > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > This is the code: > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > ? ? new_title = [] > > ? ? title_split = title.strip().lower().split() > > ? ? for word in title_split: > > ? ? ? ? if title_split[0] in small_words: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? ? ? elif word in small_words: > > ? ? ? ? ? ? new_title.append(word.lower()) > > ? ? ? ? else: > > ? ? ? ? ? ? new_title.append(word.title()) > > The logic of the for-loop is flawed; the expression > > title_split[0] in small_words > > will always evaluate to True if the first word is a "small word", even when > the loop is already past the first word. You can work around that with a > flag along these lines > > first = True > for word in title_split: > ? ? if first: > ? ? ? ? # special treatment for the first word > ? ? ? ? first = False > ? ? else: > ? ? ? ? # put checks for all words but the first here > ? ? new_title.append(fixed_word) # assuming you have stored the titlecased > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# or lowercased word in the fixed_word > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# variable Another way to tackle this is to just capitalize the entire sentence before returning it. new_title = [] title_split = title.strip().lower().split() for word in title_split: if word in small_words: new_title.append(word.lower()) else: new_title.append(word.title()) return(''.join(new_title).capitalize()) However, I'm only helping with your homework, because I want to point out that doctest comments should be *readable*. Don't just throw them in, take the extra 10-15 seconds to make them easier on the eyes. In the workplace, months will pass before you review this code again, so you want to make it easier for an older version of yourself to remember it. And it takes very little effort to make it readable. Here's your doctest string, reformatted with just a tiny bit more whitespace. I even cut out a sentence. def book_title(title): """ All words EXCEPT for small words are made title case unless the string starts with a preposition, in which case the word is correctly capitalized. >>> book_title('DIVE Into python') 'Dive into Python' >>> book_title('the great gatsby') 'The Great Gatsby' >>> book_title('the WORKS OF AleXANDer dumas') 'The Works of Alexander Dumas' """ -- // T.Hsu From clp2 at rebertia.com Sat Sep 10 22:18:47 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 19:18:47 -0700 Subject: recursive algorithm for balls in numbered boxes In-Reply-To: <32440187.post@talk.nabble.com> References: <32440187.post@talk.nabble.com> Message-ID: On Sat, Sep 10, 2011 at 5:43 PM, Dr. Phillip M. Feldman wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered boxes" > (also known as "indistinguishable balls in distinguishable boxes"). ?The > code has been extensively tested and appears to work, but isn't terribly > elegant. ?Any suggestions about how to improve it will be appreciated. Significantly refactored (but untested) version: https://gist.github.com/1209079 Cheers, Chris -- http://rebertia.com From gelonida at gmail.com Sat Sep 10 23:07:28 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 05:07:28 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6C182D.60905@tim.thechases.com> References: <4E6C182D.60905@tim.thechases.com> Message-ID: Hi Tim, Thanks a lot!!! On 09/11/2011 04:08 AM, Tim Chase wrote: > On 09/10/11 20:54, Gelonida N wrote: >>> Unfortunately the help text is formatted using textwrap, which presumes >>> that the entire text is a single paragraph. To get paragraphs in the >>> help text, you'll need to write an IndentedHelpFormatter subclass that >>> splits the text on "\n\n", textwraps the split string individually, then >>> re-joins them. _format_text() and format_option() look like the methods >>> that would need replacing. > > Just in case you want it: > > http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse > It works (of course ;-) ) like a charm. Good to know, that I'm not the only one who want's to structure the help text a little nicer. > > it's come up several times and several years ago I hacked together > exactly the solution Rhodri mentions. Considering, that you posted the snippet in 2007 and this is very probably a reocurring problem for any slighty more complicated help text it is really a pity, that it did not become of part of the standard optparse library :-( Thanks again. From jabba.laci at gmail.com Sat Sep 10 23:20:26 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Sat, 10 Sep 2011 23:20:26 -0400 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: Hi, Thanks, I could put together the pieces and here is my solution: (1) get_cookies_in_cookiejar function to extract cookies and put them in a cookiejar: https://github.com/jabbalaci/jabbapylib/blob/master/jabbapylib/web/export_firefox_cookies.py (2) download page using urllib2 and passing the cookiejar: https://github.com/jabbalaci/jabbapylib/blob/master/jabbapylib/web/web.py See the bottom with get_page_with_cookies_using_cookiejar(url). Laszlo On Mon, Sep 5, 2011 at 22:19, Chris Rebert wrote: > On Mon, Sep 5, 2011 at 6:36 PM, Jabba Laci wrote: >> Hi, >> >> I would like to download a page that requires authentication with >> cookies. I've already figured out how to do it with wget (blog post >> here: http://bit.ly/pp25LP). In short: >> (1) extract cookies from Firefox's cookies.sqlite and store them in a text file >> (2) wget --cookies=on --load-cookies=cookies.txt >> --keep-session-cookies "http://..." >> >> My question is: how to do it from Python? > > http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar > > Cheers, > Chris > From laurent.payot at gmail.com Sat Sep 10 23:21:46 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 20:21:46 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <3c8c4056-aa89-4a7c-a22c-44baf97a02c1@glegroupsg2000goo.googlegroups.com> Well PyPy is just an implementation of Python among many others (but limited to version 2.7). It is not a web server. If you want to make PyPy interact with a web server (such as nginx) you have to use a special protocol such as WSGI or Fast-CGI. For best performances you can for instance use uWSGI that integrates well with nginx but for this you have to recompile nginx. As you see it's a bit complex, you should read the wikis. May the Force be with you. From laurent.payot at gmail.com Sat Sep 10 23:21:46 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 20:21:46 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <3c8c4056-aa89-4a7c-a22c-44baf97a02c1@glegroupsg2000goo.googlegroups.com> Well PyPy is just an implementation of Python among many others (but limited to version 2.7). It is not a web server. If you want to make PyPy interact with a web server (such as nginx) you have to use a special protocol such as WSGI or Fast-CGI. For best performances you can for instance use uWSGI that integrates well with nginx but for this you have to recompile nginx. As you see it's a bit complex, you should read the wikis. May the Force be with you. From gelonida at gmail.com Sat Sep 10 23:39:05 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 05:39:05 +0200 Subject: import packet.module without importing packet.__init__ ? In-Reply-To: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steven, Thanks for your answer. On 09/11/2011 02:56 AM, Steven D'Aprano wrote: > Gelonida N wrote: >> Is it possible to import a module from a packet without importing its >> __init__.py ? > > Untested, but I think so. But you shouldn't. The solution (if it does work, > as I said I haven't tested it) is a hack. > > Suppose you have a library like this: . . . . . . > The directory "modules" is in your Python path, so you can "import spam" > or "import package". The trick is to add "modules/package" to the Python > path so that "import cheese" will find cheese.py directly. > Yes it's a hack, but good to know it exists. Just in case. > Another hack would be to add a hard link to the top level: > As you said: Hard links would be a little annoying on some file systems. > > But generally, you should design your package so that it doesn't matter > whether or not __init__.py is imported first. I see three reasnable > situations: > > (1) package.cheese should rely on package, in which case it requires > package.__init__ to be imported first. (Sometimes I put code common to the > entire package in __init__.py.) > > (2) Just don't worry about the fact that package.__init__ gets imported > first. Do you have any idea how many modules get imported when Python > starts up? What's one more? > > (3) If cheese.py truly is independent of package, then it shouldn't be part > of package. Just make it a stand alone module outside the package > directory, and be done. (Your installer can still treat cheese.py as a > dependency of package, and ensure that they are both installed.) > There's still something, that I am philosophycally missing. Wy do I have to import the entire tree if I'm just interested in a leave. this is not always desired. let's imagine kitchen.__init__ kitchen.knives kitchen.pans kitchen.pots or alternatively os os.path os.wheteverelse Let's assume, that kitchen/__init__.py is importing the sub modules knives, pans and pots then I understand of course, that the next lines would import the entire kitchen > import kitchen # will import all activities > kitchen.pots.boil(egg) But if I know that I just want to boil some eggs I would really appreciate if I could just say > from kitchen.pot import boil > boil(eggs) without having the side effect of getting pans and knives also loaded into memory. Moving pots out into a separate package doesn't really feel right. I agree, that a 10 level deep package tree is not really desirable, but having every package flat on the top level doesn't sound that good either. So it seems, that developers of huge packages shouldn't really do a lot in __init__.py. Otherwise any user would always 'suck in' the entiry package with all its sub modules. To give more details about why I asked this question: The real setup looks a little different and there are some issues, that I am having: One package in question is a huge django application. Within the package is one module defining some constants and tiny functions, which I would like to reuse from some command line tools, which should start quickly without loading any of the django specific modules. (the startup penalty and the memory overhead would be noticable) I am using rpc4django, which expects, that __init__.py of the django application exports some all rpc functions which will basically import 95% of the django application and the entire django frame work (none of which were required by my command tool, support utility for this application) I could of course create a separate package just for this tiny sub module, but somehow it doesn't feel right to me. The second issue is a little more complicated. basically I end up having circular dependencies. as I have two applications that send a few customs django signals forth an back. If I wouldn't import __init__.py or if I moved the declaration of the signals into a third package then circular dependencies would disappear. So it seems, that if I can't avoid loading __init__.py in a nice way I have to create one or two tiny packages outside of my django application, or change the python path as you proposed (increases of course name space clashes) or to find a way for rpc4django of loading / locating the rpc functions without putting them in __init__.py change the rpc functions such, that they will only import the other sub modules when being called the first time (proxies / delayed imports, . . .) From rosuav at gmail.com Sat Sep 10 23:53:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 11 Sep 2011 13:53:44 +1000 Subject: using python in web applications In-Reply-To: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> Message-ID: On Sun, Sep 11, 2011 at 9:35 AM, Laurent wrote: > [troll] > For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. > [/troll] I have been trolled. :) For any sort of web-based real-time game, here's two things to avoid: 1) Snoopability and modifiability of crucial data. Everything should be stored on the server, so that if anyone fiddles, all they do is break their own client so it has to reload from the server. 2) Massive waste of resources due to unnecessary frameworks/facilities. I play a lot of Flash games, and right now I'm playing one that has coped poorly with a miniature slashdotting. A spike in popularity resulted in a spike in server lag. I fired up a little packet sniffer, and discovered that every time you do anything in the game, the client makes a new POST request to its server. Why?! It's not that hard to hold a socket connection open! In another context, a similar issue - not a problem as yet (that I know of), but would be if the system were to be slashdotted. A server whose sole purpose is to handle script-instigated requests (using HTTP POST for its transport) sends back a Set-Cookie header with a session id. This implies that the server is holding session data for all these clients that are never going to send that cookie back. The server appears to be IIS with ASP scripts, so presumably stateful sessions are enabled by default, so it's costing memory and processing to hold, then discard, all those useless (and probably empty) session state tags. And presumably many MANY other servers have the same thing. What's YOUR framework doing that you don't need, and how much is it costing you? Yeah, I was trolled bad. :) ChrisA From bluegene8210 at gmail.com Sat Sep 10 23:54:01 2011 From: bluegene8210 at gmail.com (=?GB2312?B?wLbJq7v50vI=?=) Date: Sat, 10 Sep 2011 20:54:01 -0700 (PDT) Subject: Deadlock problem using multiprocessing Message-ID: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> This is my first touch on the multiprocessing module, and I admit not having a deep understanding of parallel programming, forgive me if there's any obvious error. This is my test code: # deadlock.py import multiprocessing class MPTask: def __init__(self): self._tseq= range(10) # task sequence self._pool= multiprocessing.Pool(2) # process pool def _exe(self, num): return num**2 def run(self): result= self._pool.map_async(self._exe, self._tseq) return result.get() result= MPTask().run() print(result) And seemingly it creates a deadlock, I have to manually kill the processes in the system monitor, yet it would be OK if the _exe() function was defined outside the MPTask class: # no_deadlock.py import multiprocessing def _exe(num): return num**2 class MPTask: def __init__(self): self._tseq= range(10) # task sequence self._pool= multiprocessing.Pool(2) # process pool def run(self): result= self._pool.map_async(_exe, self._tseq) return result.get() result= MPTask().run() print(result) This would give the correct answer without any deadlock. My questions: 1. Why is this, where did the deadlock come from? 2. Besides, is there any material I can refer to about how to avoid deadlocks when using multiple processes in the program? Thanks! From ian.g.kelly at gmail.com Sun Sep 11 00:01:02 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 10 Sep 2011 22:01:02 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: > The statement containing the explicit next(items) call can optionally be > wrapped to explicitly handle the case of an empty iterable in whatever > manner is desired. > > try: > ? ? > except StopIteration: > ? ?raise ValueError("iterable cannot be empty") The only time that's optional is when you're writing an iterator and the try-except would end up looking like this: try: # do stuff with next(items) except StopIteration: raise StopIteration And even then, it's probably a good idea to clearly document that you're allowing a StopIteration from one iterator to propagate up as a StopIteration for another. Apart from that case, whenever you call next() you should always be prepared to catch a StopIteration. Letting a StopIteration propagate up the stack to parts unknown is bad juju because it's a flow control exception, not an error-signaling exception. If it happens to propagate up to another for loop, then it will break out of the for loop, and the exception will simply be swallowed. Cheers, Ian From 1248283536 at qq.com Sun Sep 11 00:46:43 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Sun, 11 Sep 2011 12:46:43 +0800 Subject: convert time Message-ID: how can i convert "Dec 11" into 2011-12? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Sep 11 00:51:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 14:51:18 +1000 Subject: import packet.module without importing packet.__init__ ? References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> Gelonida N wrote: > There's still something, that I am philosophycally missing. > > Wy do I have to import the entire tree if I'm just interested in a leave. You don't. Python just imports the branches leading to the leaf, not the entire tree. [...] > But if I know that I just want to boil some eggs I would really > appreciate if I could just say > >> from kitchen.pot import boil >> boil(eggs) > without having the side effect of getting pans and knives also loaded > into memory. In your example, you stated that kitchen explicitly imports kitchen.pans and kitchen.knives. So in that case, take it up with the designer of the kitchen package -- it was his decision to import them, just like he imported re and math and httplib. (For example.) If kitchen is your package, then it is your choice: if you want to have control over when sub-packages get imported, then don't automatically import them in __init__.py. If you want them to be automatically imported, like os and os.path, then automatically import them. If you don't, don't. But note that you cannot expect to import kitchen.pot without importing kitchen first. > One package in question is a huge django application. > > Within the package is one module defining some constants and tiny > functions, which I would like to reuse from some command line tools, > which should start quickly without loading any of the django specific > modules. (the startup penalty and the memory overhead would be noticable) > > I am using rpc4django, which expects, that __init__.py of the django > application exports some all rpc functions > which will basically import 95% of the django application and the entire > django frame work (none of which were required by my command tool, > support utility for this application) > > > I could of course create a separate package just for this tiny sub > module, but somehow it doesn't feel right to me. Why should it be a package? Just make it a stand-alone module. Or use path manipulation from your command line tool to import it on its own. It might be somewhat of a hack, but if need to do it, do so. Or do something like this: my_app/ +-- __init__.py # lightweight, nearly empty +-- cmd_tools.py +-- module1.py +-- module2.py +-- rpc/ +-- __init__.py # huge, imports my_app.module1, my_app.module2, etc. then point rpc4django at my_app.rpc instead of my_app. -- Steven From steve+comp.lang.python at pearwood.info Sun Sep 11 01:00:55 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 15:00:55 +1000 Subject: convert time References: Message-ID: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> ???? wrote: > how can i convert "Dec 11" into 2011-12? if my_str == "Dec 11": return 1999 # 2011 - 12 Does that help? But seriously... 2011-12 is not a proper date, so the simplest way is probably something like this: def convert(date_str): month, short_year = date_str.split() if len(short_year) == 4: year = short_year else: year = '20' + short_year months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() month = months.index(month) + 1 return year + '-' + str(month) Otherwise see the time and datetime modules: http://docs.python.org/library/time.html http://docs.python.org/library/datetime.html -- Steven From clp2 at rebertia.com Sun Sep 11 01:02:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 22:02:37 -0700 Subject: convert time In-Reply-To: References: Message-ID: 2011/9/10 ???? <1248283536 at qq.com>: > how can i convert "Dec 11" into? 2011-12? Read the fine manuals for the `time` or `datetime` modules. http://docs.python.org/library/datetime.html >>> from datetime import datetime >>> datetime.strptime("Dec 11", "%b %y") datetime.datetime(2011, 12, 1, 0, 0) >>> datetime.strptime("Dec 11", "%b %y").strftime("%Y-%m") '2011-12' Note that this code depends on an appropriate locale setting for parsing the month name abbreviations. Cheers, Chris -- http://rebertia.com From steve+comp.lang.python at pearwood.info Sun Sep 11 01:08:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 15:08:00 +1000 Subject: killing a script References: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6c4231$0$29996$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 10Sep2011 11:25, Steven D'Aprano > wrote: > | Cameron Simpson wrote: > | > My copy of the 2.7 docs says: > | > This is implemented by calling the Standard C function system(), and > | > has the same limitations. > | > and sure enough, "man 3 system" says: > | > | I don't consider having to look up documentation for a function in a > | completely different language (in this case, C) as "documented behaviour > | of os.system". > > You're kidding, surely? No, I meant exactly what I said, but I suspect that you misunderstood what I said. I blame myself for not making myself more clear, sorry. > A wrapper function for a system supplied function > should recite everything about the wrapped function's behaviour (including > the system dependent stuff) in the wrapper doco? Heavens no, I certainly don't mean that. That would be silly. What I mean is that in the context of discussing Python library functions, "documented behaviour" refers to what the Python docs state, namely the function docstring and the docs at http://docs.python.org/ (or the 3.x version). Third-party documentation doesn't count: not blogs, not "some guy sent me an email", and not documentation for other tools either. So if you describe a feature of os.system as "documented", I'm going to understand that as *Python* documentation. Hence my question about where it is documented. If we're discussing external documentation, we should say so up front: not all Python users are using CPython, and not all Python coders know C and have access to the Linux man pages. -- Steven From ben+python at benfinney.id.au Sun Sep 11 01:20:07 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 11 Sep 2011 15:20:07 +1000 Subject: optionparse: how to add a line break to the help text References: <4E6C182D.60905@tim.thechases.com> Message-ID: <87aaabmz94.fsf@benfinney.id.au> Gelonida N writes: > Considering, that you posted the snippet in 2007 and this is very > probably a reocurring problem for any slighty more complicated help > text it is really a pity, that it did not become of part of the > standard optparse library :-( The ?optparse? library is, as the online documentation shows , deprecated for new code: The optparse module is deprecated and will not be developed further; development will continue with the argparse module. The standard library ?argparse? module has a feature you might prefer . -- \ ?An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.? ?Niels Bohr | _o__) | Ben Finney From ben+python at benfinney.id.au Sun Sep 11 01:30:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 11 Sep 2011 15:30:18 +1000 Subject: convert time References: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8762kzmys5.fsf@benfinney.id.au> Steven D'Aprano writes: > But seriously... 2011-12 is not a proper date It's valid by ISO 8601. The standard allows any number of parts to be dropped, from least to most significant, in order to have a value with deliberately reduced precision. > Otherwise see the time and datetime modules: >>> import datetime >>> text = "2011-12" >>> datetime.datetime.strptime(text, "%Y-%m") datetime.datetime(2011, 12, 1, 0, 0) -- \ ?It's not what you pay a man, but what he costs you that | `\ counts.? ?Will Rogers | _o__) | Ben Finney From dreyemi at gmail.com Sun Sep 11 04:18:29 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 11 Sep 2011 09:18:29 +0100 Subject: Invoke a superclass method from a subclass constructor Message-ID: Hello friends, An instance of my subclass doesn't invoke its superclass method, except when it is referenced directly. Here is what I mean: >>> class A(object): ... def log(self, module): ... return str('logged') ... >>> class B(A): ... def __init__(self, module): ... self.module = A().log(module) ... >>> c = B('system') >>> # I expect 'logged' to be printed here >>> print c.log('system') # why do I have to do this? >>> 'logged' Why do I have to make a call to c.log before log() method can be invoked? My reasoning is such that since I have passed the log() method to B's constructor, an instance of B should invoke A's log() method. What could I be missing in class A or B to have this working as expected? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Sun Sep 11 06:41:08 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 11 Sep 2011 12:41:08 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: Message-ID: <4E6C9044.5060302@jollybox.de> On 11/09/11 10:18, Kayode Odeyemi wrote: > Hello friends, > > An instance of my subclass doesn't invoke its superclass method, except > when it is referenced > directly. > > Here is what I mean: > >>>> class A(object): > ... def log(self, module): > ... return str('logged') > ... > >>>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... >>>> c = B('system') >>>> # I expect 'logged' to be printed here >>>> print c.log('system') # why do I have to do this? >>>> 'logged' > > Why do I have to make a call to c.log before log() method can be invoked? > > My reasoning is such that since I have passed the log() method to B's > constructor, an instance > of B should invoke A's log() method. > > What could I be missing in class A or B to have this working as expected? It is working: >>> class A(object): ... def log (self, module): ... return str ('logged') ... >>> class B(A): ... def __init__(self, module): ... self.module = A().log(module) ... >>> c = B('system') >>> c.module 'logged' In B's constructor, you create a new instance of A (a pointless excersise - you already have an instance of A, "self"), call its log() method, and store the return value of that method in the attribute "module". This is how you'd usually call a superclass's method: >>> class B2(A): ... def __init__(self, module): ... # This is the way to call a superclass method: ... self.log (module) ... >>> c2 = B2 ('system') >>> That's what inheritance is. If B is derived from A, any B *is* also an A. Now, something that might be closer to what you're actually heading for, to think about. Please note that I'm using Python 3: explicitly deriving a class from object is no longer necessary, and the "super" function is now simpler. If you want to use Python 2, I'll leave looking up how to use its "super" function as an excersise to the reader. >>> class ModuleLogger: ... def __init__(self, module): ... self.module = module ... print ('module logged: {0}'.format (module)) ... >>> class Foo (ModuleLogger): ... def __init__(self, module): ... # calling a superclass constructor here, in Python 3 syntax: ... super().__init__(module) ... >>> f = Foo ('system') module logged: system >>> Using super() is always necessary when calling a superclass' method that is also implemented in the subclass - self.__init__ would just invoke the Foo constructor, you need super() to get to the ModuleLogger constructor. - Thomas From python.list at tim.thechases.com Sun Sep 11 07:05:56 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 11 Sep 2011 06:05:56 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: <4E6C182D.60905@tim.thechases.com> Message-ID: <4E6C9614.60406@tim.thechases.com> On 09/10/11 22:07, Gelonida N wrote: >> http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse > > It works (of course ;-) ) like a charm. Good to know, that I'm > not the only one who want's to structure the help text a > little nicer. > > Considering, that you posted the snippet in 2007 and this is > very probably a reocurring problem for any slighty more > complicated help text it is really a pity, that it did not > become of part of the standard optparse library :-( Even at the time, the optparse library wasn't readily patchable as the inline documentation gave some dire warning about "don't edit this directly, as this file is generated from some other source"?I never was able to dig up that source to patch against. As Ben Finney replied, optparse is now deprecated, replaced in part by argparse. Unfortunately, argparse wasn't backported to the standard library for earlier 2.x series (I think it became available in 2.7, and may run in earlier versions if manually added like I had to do on my Debian Py2.6 install). But that makes it hard for those of us who want to use a built-in option-parsing library across a wide variety of Python versions. I don't strongly care which I use except that I want it to be broadly available with minimal fuss. -tkc From dreyemi at gmail.com Sun Sep 11 07:17:27 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 11 Sep 2011 12:17:27 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <4E6C9044.5060302@jollybox.de> References: <4E6C9044.5060302@jollybox.de> Message-ID: On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans wrote: > On 11/09/11 10:18, Kayode Odeyemi wrote: > > Hello friends, > > > > An instance of my subclass doesn't invoke its superclass method, except > > when it is referenced > > directly. > > > > Here is what I mean: > > > >>>> class A(object): > > ... def log(self, module): > > ... return str('logged') > > ... > > > >>>> class B(A): > > ... def __init__(self, module): > > ... self.module = A().log(module) > > ... > >>>> c = B('system') > >>>> # I expect 'logged' to be printed here > >>>> print c.log('system') # why do I have to do this? > >>>> 'logged' > > > > Why do I have to make a call to c.log before log() method can be invoked? > > > > My reasoning is such that since I have passed the log() method to B's > > constructor, an instance > > of B should invoke A's log() method. > > > > What could I be missing in class A or B to have this working as expected? > > It is working: > > >>> class A(object): > ... def log (self, module): > ... return str ('logged') > ... > >>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... > >>> c = B('system') > >>> c.module > 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating an instance of B. Could this be a limitation in Py2+? > In B's constructor, you create a new instance of A (a pointless > excersise - you already have an instance of A, "self"), call its log() > method, and store the return value of that method in the attribute > "module". > > This is how you'd usually call a superclass's method: > > >>> class B2(A): > ... def __init__(self, module): > ... # This is the way to call a superclass method: > ... self.log (module) > ... > >>> c2 = B2 ('system') > >>> > > That's what inheritance is. If B is derived from A, any B *is* also an A. > > Now, something that might be closer to what you're actually heading for, > to think about. Please note that I'm using Python 3: explicitly deriving > a class from object is no longer necessary, and the "super" function is > now simpler. If you want to use Python 2, I'll leave looking up how to > use its "super" function as an excersise to the reader. > > >>> class ModuleLogger: > ... def __init__(self, module): > ... self.module = module > ... print ('module logged: {0}'.format (module)) > ... > >>> class Foo (ModuleLogger): > ... def __init__(self, module): > ... # calling a superclass constructor here, in Python 3 syntax: > ... super().__init__(module) > ... > >>> f = Foo ('system') > module logged: system > >>> > > I'm on Py2.7. class ModuleLogger is not the same as class A (the one I'm using as an example). I need the log() method to be an instance of class A. I don't want it declared in class A constructor because I don't want to have access to it when class A is instantiated. Using super() is always necessary when calling a superclass' method that > is also implemented in the subclass - self.__init__ would just invoke > the Foo constructor, you need super() to get to the ModuleLogger > constructor. > Well, I did try using super(), but I got this: >>> class B(A): ... def __init__(self, module): ... super(A, self).log('system') ... >>> c = B('module') Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ AttributeError: 'super' object has no attribute 'log' I hope a reader on Py2+ can help with this. > > - Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Sun Sep 11 07:32:18 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 11 Sep 2011 17:02:18 +0530 Subject: Deadlock problem using multiprocessing In-Reply-To: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> References: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> Message-ID: 2011/9/11 ???? : > This is my first touch on the multiprocessing module, and I admit not > having a deep understanding of parallel programming, forgive me if > there's any obvious error. This is my test code: > > # deadlock.py > > import multiprocessing > > class MPTask: > ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ?self._tseq= range(10) ? # task sequence > ? ? ? ? ? ? ? ?self._pool= multiprocessing.Pool(2) ? ? # process pool > ? ? ? ?def _exe(self, num): > ? ? ? ? ? ? ? ?return num**2 > ? ? ? ?def run(self): > ? ? ? ? ? ? ? ?result= self._pool.map_async(self._exe, self._tseq) > ? ? ? ? ? ? ? ?return result.get() > > result= MPTask().run() > print(result) > > And seemingly it creates a deadlock, I have to manually kill the > processes in the system monitor, yet it would be OK if the _exe() > function was defined outside the MPTask class: > > # no_deadlock.py > import multiprocessing > > def _exe(num): > ? ? ? ?return num**2 > > class MPTask: > ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ?self._tseq= range(10) ? # task sequence > ? ? ? ? ? ? ? ?self._pool= multiprocessing.Pool(2) ? ? # process pool > ? ? ? ?def run(self): > ? ? ? ? ? ? ? ?result= self._pool.map_async(_exe, self._tseq) > ? ? ? ? ? ? ? ?return result.get() > > result= MPTask().run() > print(result) > > This would give the correct answer without any deadlock. My questions: > > 1. Why is this, where did the deadlock come from? > > 2. Besides, is there any material I can refer to about how to avoid > deadlocks when using multiple processes in the program? > I get this exception when I run the first program: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner self.run() File "/usr/lib/python3.1/threading.py", line 469, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in _handle_tasks put(task) File "/usr/lib/python3.1/pickle.py", line 1349, in dumps Pickler(f, protocol, fix_imports=fix_imports).dump(obj) _pickle.PicklingError: Can't pickle : attribute lookup builtins.method failed There is no deadlock. You are hitting this problem: http://stackoverflow.com/questions/1816958/cant-pickle-type-instancemethod-when-using-pythons-multiprocessing-pool-map -- regards, kushal From t at jollybox.de Sun Sep 11 07:32:52 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 11 Sep 2011 13:32:52 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: <4E6C9C64.3030704@jollybox.de> On 11/09/11 13:17, Kayode Odeyemi wrote: > On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans > wrote: > > It is working: > > >>> class A(object): > ... def log (self, module): > ... return str ('logged') > ... > >>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... > >>> c = B('system') > >>> c.module > 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating > an instance of B. > Could this be a limitation in Py2+? > I believe I already answered that question. You quoted my answer directly below your question: > > In B's constructor, you create a new instance of A (a pointless > excersise - you already have an instance of A, "self"), call its log() > method, and store the return value of that method in the attribute > "module". > > This is how you'd usually call a superclass's method: > > >>> class B2(A): > ... def __init__(self, module): > ... # This is the way to call a superclass method: > ... self.log (module) > ... > >>> c2 = B2 ('system') > >>> > > That's what inheritance is. If B is derived from A, any B *is* also > an A. > > Now, something that might be closer to what you're actually heading for, > to think about. Please note that I'm using Python 3: explicitly deriving > a class from object is no longer necessary, and the "super" function is > now simpler. If you want to use Python 2, I'll leave looking up how to > use its "super" function as an excersise to the reader. > > >>> class ModuleLogger: > ... def __init__(self, module): > ... self.module = module > ... print ('module logged: {0}'.format (module)) > ... > >>> class Foo (ModuleLogger): > ... def __init__(self, module): > ... # calling a superclass constructor here, in Python 3 syntax: > ... super().__init__(module) > ... > >>> f = Foo ('system') > module logged: system > >>> > > I'm on Py2.7. > > class ModuleLogger is not the same as class A (the one I'm using as an > example). I need the log() > method to be an instance of class A. I don't want it declared in class A > constructor because I don't > want to have access to it when class A is instantiated. Then do it differently. I was merely offering an example that I hoped might help you acheive your goals. > > Using super() is always necessary when calling a superclass' method that > is also implemented in the subclass - self.__init__ would just invoke > the Foo constructor, you need super() to get to the ModuleLogger > constructor. > > > Well, I did try using super(), but I got this: >>>> class B(A): > ... def __init__(self, module): > ... super(A, self).log('system') > ... >>>> c = B('module') > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in __init__ > AttributeError: 'super' object has no attribute 'log' > > I hope a reader on Py2+ can help with this. If you'd read my previous response carefully, you'd know that in this case, you don't need super(), and you'd also know how to use the superclass' method. From laddosingh at gmail.com Sun Sep 11 07:46:38 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 04:46:38 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 19:59, Terry Reedy wrote: > On 9/10/2011 7:20 AM, Tigerstyle wrote: > > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > We appreciate you saying so instead of hiding that this is homework. > > > > > > > > > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > def book_title(title): > > ? ? ?""" Takes a string and returns a title-case string. > > ? ? ?All words EXCEPT for small words are made title case > > ? ? ?unless the string starts with a preposition, in which > > ? ? ?case the word is correctly capitalized. > > ? ? ?>>> ?book_title('DIVE Into python') > > ? ? ?'Dive into Python' > > ? ? ?>>> ?book_title('the great gatsby') > > ? ? ?'The Great Gatsby' > > ? ? ?>>> ?book_title('the WORKS OF AleXANDer dumas') > > ? ? ?'The Works of Alexander Dumas' > > ? ? ?""" > > ? ? ?new_title = [] > > ? ? ?title_split = title.strip().lower().split() > > ? ? ?for word in title_split: > > ? ? ? ? ?if title_split[0] in small_words: > > ? ? ? ? ? ? ?new_title.append(word.title()) > > ? ? ? ? ?elif word in small_words: > > ? ? ? ? ? ? ?new_title.append(word.lower()) > > ? ? ? ? ?else: > > ? ? ? ? ? ? ?new_title.append(word.title()) > > The key issue is that you want to treat the first word one way (.title > it) and the rest differently (conditionally .title or not) . So > immediately separate the first from the rest and then process each. > There are at least three ways to do the split. Perhaps I should stop > with this hint, and certainly you should think a bit before reading > further, but here is what I consider to be the most elegant 3.2 code. > . > , > , > , > . > . > . > ? ? ?first, *rest = title.strip().lower().split() > ? ? ?new_title = [first.title()] > ? ? ?for word in rest: > ? ? ? ? ?if word not in small_words: > ? ? ? ? ? ? ?word = word.title() > ? ? ? ? ?new_title.append(word) > > > ? ? ?return(' '.join(new_title)) > > doctest.testmod() now passes (there is no 'refactory' here) > > > def _test(): > > ? ? ?import doctest, refactory > > ? ? ?return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? ?_test() > > -- > Terry Jan Reedy Thank you Terry, I went for this solution as it was the easiest for me to understand and comment myself keeping in mind what level I am at right now. Thanks a ton to everyone for sharing so much information and making it easy to read and understand your thoughts. This was surely very very educating read the replies from so many talented people. Thanks and looking forward to hanging around here more :) T From davea at ieee.org Sun Sep 11 07:55:31 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 11 Sep 2011 07:55:31 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: Message-ID: <4E6CA1B3.2060503@ieee.org> On 01/-10/-28163 02:59 PM, Kayode Odeyemi wrote: > Hello friends, > > An instance of my subclass doesn't invoke its superclass method, except when > it is referenced > directly. > > Here is what I mean: > >>>> class A(object): > ... def log(self, module): > ... return str('logged') > ... > >>>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... >>>> c = B('system') >>>> # I expect 'logged' to be printed here >>>> print c.log('system') # why do I have to do this? >>>> 'logged' > Why do I have to make a call to c.log before log() method can be invoked? > > My reasoning is such that since I have passed the log() method to B's > constructor, an instance > of B should invoke A's log() method. > > What could I be missing in class A or B to have this working as expected? What makes you think that A.log() was not invoked??? You have no print statement, so you can't tell that way. All the method does is to modify a temporary object of type A, so you can't tell that way. Perhaps you mean to write self.module = A.log(self, module) So that the return value could do some good. DaveA From python.list at tim.thechases.com Sun Sep 11 08:41:58 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 11 Sep 2011 07:41:58 -0500 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: <4E6CAC96.9000304@tim.thechases.com> On 09/10/11 14:36, Terry Reedy wrote: > 1. Process first item of an iterable separately. > > A traditional solution is a flag variable that is tested for each item. > > first = True > > for item in iterable: > if first: > > first = False > else: > > > (I have seen code like this posted on this list several times, including > today.) > > Better, to me, is to remove the first item *before* the loop. > > items = iter(iterable) > for item in items: > I like to use this one for processing CSV files where I need to clean up the headers: r = csv.reader(f) headers = r.next() header_map = dict( (header.strip().upper(), i) for i, header in enumerate(headers) ) for row in r: item = lambda s: row[header_map[s]].strip() thing = item("THING") whatever = item("WHATEVER") It's mostly like a DictReader, but it isn't as sensitive to the spaces/capitalization that clients love to mess with. -tkc From __peter__ at web.de Sun Sep 11 08:48:41 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 14:48:41 +0200 Subject: recursive algorithm for balls in numbered boxes References: <32440187.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered > boxes" > (also known as "indistinguishable balls in distinguishable boxes"). The > code has been extensively tested and appears to work, but isn't terribly > elegant. Any suggestions about how to improve it will be appreciated. Does the following do what you want? >>> from itertools import product >>> def binb(balls, boxsizes): ... return (fill for fill in product(*[range(bs+1) for bs in boxsizes]) if sum(fill) == balls) ... >>> for item in binb(10, [4, 3, 2, 1, 2]): ... print item ... (2, 3, 2, 1, 2) (3, 2, 2, 1, 2) (3, 3, 1, 1, 2) (3, 3, 2, 0, 2) (3, 3, 2, 1, 1) (4, 1, 2, 1, 2) (4, 2, 1, 1, 2) (4, 2, 2, 0, 2) (4, 2, 2, 1, 1) (4, 3, 0, 1, 2) (4, 3, 1, 0, 2) (4, 3, 1, 1, 1) (4, 3, 2, 0, 1) (4, 3, 2, 1, 0) If so, your implementation misses a few configurations: >>> from balls_in_numbered_boxes import balls_in_numbered_boxes as bb >>> for item in bb(10, [4, 3, 2, 1, 2]): ... print item ... [4 3 2 1 0] [3 3 2 1 1] [2 3 2 1 2] > Also, I'd like to get this functionality into the Python's `itertools` > module (the present set of combinatorics functions in `itertools` does not > include "balls in boxes"). Does anyone know whom I should contact about > this? Basically you have to convince Raymond Hettinger. I recommend that you post your suggestion on python-ideas for a general discussion rather than approaching him directly. From __peter__ at web.de Sun Sep 11 09:41:23 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 15:41:23 +0200 Subject: Idioms combining 'next(items)' and 'for item in items:' References: Message-ID: Terry Reedy wrote: > 3. Process the items of an iterable in pairs. > > items = iter(iterable) > for first in items: > second = next(items) > > > This time, StopIteration is raised for an odd number of items. Catch and > process as desired. One possibility is to raise ValueError("Iterable > must have an even number of items"). Another way is zip-based iteration: (a) silently drop the odd item items = iter(iterable) for first, second in zip(items, items): # itertools.izip in 2.x ... (b) add a fill value for first, second in itertools.zip_longest(items, items): ... (c) raise an exception Unfortunately there is no zip_exc() that guarantees that all iterables are of the same "length", but I've written a recipe some time ago http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures- that-all-iterables/ that achieves near-C speed. From gelonida at gmail.com Sun Sep 11 10:17:56 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 16:17:56 +0200 Subject: import packet.module without importing packet.__init__ ? In-Reply-To: <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steven, Thanks again for your answer. On 09/11/2011 06:51 AM, Steven D'Aprano wrote: > Gelonida N wrote: > > In your example, you stated that kitchen explicitly imports kitchen.pans and > kitchen.knives. So in that case, take it up with the designer of the > kitchen package -- it was his decision to import them, just like he > imported re and math and httplib. (For example.) Exactly. Thus my conclusion, that too many imports (just for commodity) in __init__.py might not be such a good idea if one wants to allow leaf-only imports. > > If kitchen is your package, then it is your choice: if you want to have > control over when sub-packages get imported, then don't automatically > import them in __init__.py. Agreed. This is however my problem: Up to my understanding rpc4django insists on putting code into __init__.py > > >> One package in question is a huge django application. >> >> Within the package is one module defining some constants and tiny >> functions, which I would like to reuse from some command line tools, >> which should start quickly without loading any of the django specific >> modules. (the startup penalty and the memory overhead would be noticable) >> >> I am using rpc4django, which expects, that __init__.py of the django >> application exports some all rpc functions >> which will basically import 95% of the django application and the entire >> django frame work (none of which were required by my command tool, >> support utility for this application) >> >> >> I could of course create a separate package just for this tiny sub >> module, but somehow it doesn't feel right to me. > > Why should it be a package? Just make it a stand-alone module. True > Or do something like this: > > my_app/ > +-- __init__.py # lightweight, nearly empty > +-- cmd_tools.py > +-- module1.py > +-- module2.py > +-- rpc/ > +-- __init__.py # huge, imports my_app.module1, my_app.module2, etc. > > then point rpc4django at my_app.rpc instead of my_app. > Up to my knowledge rpc4django just imports all __inits__ of all django applications to find look for functions with a certain decorator. I'm not sure, whether django allows nested appllications, but this might be a solution. From gelonida at gmail.com Sun Sep 11 10:30:07 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 16:30:07 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: <87aaabmz94.fsf@benfinney.id.au> References: <4E6C182D.60905@tim.thechases.com> <87aaabmz94.fsf@benfinney.id.au> Message-ID: Thanks Ben, On 09/11/2011 07:20 AM, Ben Finney wrote: > Gelonida N writes: > >> Considering, that you posted the snippet in 2007 and this is very >> probably a reocurring problem for any slighty more complicated help >> text it is really a pity, that it did not become of part of the >> standard optparse library :-( > > The ?optparse? library is, as the online documentation shows > , deprecated for new > code: > > The optparse module is deprecated and will not be developed further; > development will continue with the argparse module. This explains the reluctance to fix optparse. In 2007 however python 2.7 wasn't really that common though > > The standard library ?argparse? module has a feature you might prefer > . Most of my code has to run on python 2.5 / 2.6. I just checked, that argparse can be installed (pip install argparse) (didn't check functionality though) for python 2.5 / 2.6 So depending on the situation I had to decide whether I oblige users of my scripts to install argparse or whether I stick with optparse and just add Tim's custom formatter. Probably I'll go for optparse and Tim's custom formatter for tiny scripts with no dependencies except standard libraries and for argparse for new bigger projects with external module dependencies. From mdickinson at enthought.com Sun Sep 11 11:08:17 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Sun, 11 Sep 2011 08:08:17 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes References: Message-ID: On Sep 11, 1:43?am, "Dr. Phillip M. Feldman" wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered boxes" > (also known as "indistinguishable balls in distinguishable boxes"). ?The > code has been extensively tested and appears to work, but isn't terribly > elegant. ?Any suggestions about how to improve it will be appreciated. > > Also, I'd like to get this functionality into the Python's `itertools` > module (the present set of combinatorics functions in `itertools` does not > include "balls in boxes"). ?Does anyone know whom I should contact about > this? Note that for the version without size limits on individual boxes, the itertools.combination function already provides most of what's needed. For example: import itertools def balls_in_boxes(nballs, nboxes): n, k = nballs + nboxes - 1, nboxes - 1 for comb in itertools.combinations(range(n), k): yield [y - x - 1 for y, x in zip(comb + (n,), (-1,) + comb)] print "5 balls in 3 boxes" for combination in balls_in_boxes(5, 3): print combination assert len(combination) == 3 assert sum(combination) == 5 This is a well-known trick: to divide 5 (unlabeled) balls amongst 3 (labeled) boxes, you write down sequences of 5 o's and 2 x's, where the o's represent the 5 balls and the 'x's represent dividers: ooxooxo -> [2, 2, 1] xoooxoo -> [0, 3, 2] And 'combinations(7, 2)' yields successively all the possible different placements for the 2 dividers in the 7 symbols. This question seems to come up often enough (without the box size limit twist) that maybe it would be useful to include something like this recipe in the itertool documentation. For getting this into itertools, I'd suggest opening a feature request on bugs.python.org and assigning it to Raymond Hettinger. -- Mark From bluegene8210 at gmail.com Sun Sep 11 11:46:40 2011 From: bluegene8210 at gmail.com (Jacky Liu) Date: Sun, 11 Sep 2011 08:46:40 -0700 (PDT) Subject: Deadlock problem using multiprocessing References: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> Message-ID: > > I get this exception when I run the first program: > > Exception in thread Thread-1: > Traceback (most recent call last): > ? File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner > ? ? self.run() > ? File "/usr/lib/python3.1/threading.py", line 469, in run > ? ? self._target(*self._args, **self._kwargs) > ? File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in _handle_tasks > ? ? put(task) > ? File "/usr/lib/python3.1/pickle.py", line 1349, in dumps > ? ? Pickler(f, protocol, fix_imports=fix_imports).dump(obj) > _pickle.PicklingError: Can't pickle : attribute lookup > builtins.method failed > > There is no deadlock. ?You are hitting this problem:http://stackoverflow.com/questions/1816958/cant-pickle-type-instancem... > > -- > regards, > kushal You're right. I just realized that I was running the program through my Vim plug-in which would use the subprocess module to open the process, wait for its termination and get the output. It seems that multi-process program would act quite differently such that my Vim plug-in had been halted without getting any error information, so I was to falsely take it as a deadlock. The thread in stackoverflow you referenced is great, now I'm trying to fit the solution in my own program, thanks a lot! From laddosingh at gmail.com Sun Sep 11 12:36:25 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:36:25 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 13:43, Mel wrote: > Tigerstyle wrote: > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > This is the code: > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > def book_title(title): > > ? ? """ Takes a string and returns a title-case string. > > ? ? All words EXCEPT for small words are made title case > > ? ? unless the string starts with a preposition, in which > > ? ? case the word is correctly capitalized. > > ? ? >>> book_title('DIVE Into python') > > ? ? 'Dive into Python' > > ? ? >>> book_title('the great gatsby') > > ? ? 'The Great Gatsby' > > ? ? >>> book_title('the WORKS OF AleXANDer dumas') > > ? ? 'The Works of Alexander Dumas' > > ? ? """ > > ? ? new_title = [] > > ? ? title_split = title.strip().lower().split() > > ? ? for word in title_split: > > ? ? ? ? if title_split[0] in small_words: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? ? ? elif word in small_words: > > ? ? ? ? ? ? new_title.append(word.lower()) > > ? ? ? ? else: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? return(' '.join(new_title)) > > > def _test(): > > ? ? import doctest, refactory > > ? ? return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? _test() > > > All tests are failing even though I am getting the correct output on > > the first two tests. And the last test still gives me "Of" instead of > > "of" > > > Any help is appreciated. > > I don't know about doctest -- I suspect it wants a structured docstring to > specify the tests -- but this > > ? ? ? ? if title_split[0] in small_words: > ? ? ? ? ? ? new_title.append(word.title()) > > can't be what you want. > > ? ? ? ? Mel. Agreed. Not what I need. From laddosingh at gmail.com Sun Sep 11 12:39:12 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:39:12 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 13:50, Thomas Jollans wrote: > On 10/09/11 13:20, Tigerstyle wrote: > > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > All tests are failing even though I am getting the correct output on > > the first two tests. And the last test still gives me "Of" instead of > > "of" > > Cannot reproduce. I only get the one, expected, failure. > > % python -m doctest books.py > ********************************************************************** > File "books.py", line 12, in books.book_title > Failed example: > ? ? book_title('the WORKS OF AleXANDer dumas') > Expected: > ? ? 'The Works of Alexander Dumas' > Got: > ? ? 'The Works Of Alexander Dumas' > ********************************************************************** > 1 items had failures: > ? ?1 of ? 3 in books.book_title > ***Test Failed*** 1 failures. > > > > > def _test(): > > ? ? import doctest, refactory > > ? ? return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? _test() > > What is this "refactory"? Are you testing the right code? What is the > output of your test - does it make sense for the module? > > Thomas Still struggling with my test failing. All 3 tests fail. I'm using Ecplipse and I think Eclipse is what causing this. From laddosingh at gmail.com Sun Sep 11 12:40:26 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:40:26 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 17:56, Chris Angelico wrote: > On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware > > wrote: > > Ignoring the docttests my process would be to process each word & then > > manually capitalize he 1st word, .I would als0 use a comprehension as > > makes for cleaner code:- > > > def capitalize(word): > > ? ?if word in small_words: > > ? ? ? ?return word > > ? ?else: > > ? ? ? ?return word.title() > > And I'd do this with a lambda, but that's just me. Of course, if your > logic is more complicated, it makes more sense to keep it in a named > function, but a single conditional call can fit nicely into a lambda. > > ChrisA Lambda is too complicated for me to understand yet. Will get there after a little while. Where would you put this piece of code? From laddosingh at gmail.com Sun Sep 11 12:42:28 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:42:28 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <8fc2dea1-a5ef-4d7f-a0f2-e0be56e21e22@h7g2000yqm.googlegroups.com> On 11 Sep, 04:12, t... at thsu.org wrote: > On Sep 10, 7:47?am, Peter Otten <__pete... at web.de> wrote: > > > > > > > > > > > Tigerstyle wrote: > > > I'm strugglin with some homework stuff and am hoping you can help me > > > out here. > > > > This is the code: > > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > ? ? new_title = [] > > > ? ? title_split = title.strip().lower().split() > > > ? ? for word in title_split: > > > ? ? ? ? if title_split[0] in small_words: > > > ? ? ? ? ? ? new_title.append(word.title()) > > > ? ? ? ? elif word in small_words: > > > ? ? ? ? ? ? new_title.append(word.lower()) > > > ? ? ? ? else: > > > ? ? ? ? ? ? new_title.append(word.title()) > > > The logic of the for-loop is flawed; the expression > > > title_split[0] in small_words > > > will always evaluate to True if the first word is a "small word", even when > > the loop is already past the first word. You can work around that with a > > flag along these lines > > > first = True > > for word in title_split: > > ? ? if first: > > ? ? ? ? # special treatment for the first word > > ? ? ? ? first = False > > ? ? else: > > ? ? ? ? # put checks for all words but the first here > > ? ? new_title.append(fixed_word) # assuming you have stored the titlecased > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# or lowercased word in the fixed_word > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# variable > > Another way to tackle this is to just capitalize the entire sentence > before returning it. > > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > ? if word in small_words: > ? ? new_title.append(word.lower()) > ? else: > ? ? new_title.append(word.title()) > return(''.join(new_title).capitalize()) > > However, I'm only helping with your homework, because I want to point > out that doctest comments should be *readable*. Don't just throw them > in, take the extra 10-15 seconds to make them easier on the eyes. In > the workplace, months will pass before you review this code again, so > you want to make it easier for an older version of yourself to > remember it. > > And it takes very little effort to make it readable. Here's your > doctest string, reformatted with just a tiny bit more whitespace. I > even cut out a sentence. > > def book_title(title): > ? """ > ? All words EXCEPT for small words are made title case > ? unless the string starts with a preposition, in which > ? case the word is correctly capitalized. > > ? >>> book_title('DIVE Into python') > ? 'Dive into Python' > ? >>> book_title('the great gatsby') > ? 'The Great Gatsby' > ? >>> book_title('the WORKS OF AleXANDer dumas') > ? 'The Works of Alexander Dumas' > ? """ > -- > // T.Hsu It capitalises the phrase, but still the rest of the phrase is in lower case. From laddosingh at gmail.com Sun Sep 11 12:43:31 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:43:31 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <208f1e6b-66ca-4988-a41a-d83924cb8593@m18g2000vbe.googlegroups.com> On 11 Sep, 08:18, Dennis Lee Bieber wrote: > On Sat, 10 Sep 2011 16:25:42 -0700, Dennis Lee Bieber > declaimed the following in > gmane.comp.python.general: > > > > > in the language documentation... It will give you a simple way to know > > if you are looking at the first word. Basically, you want to title-case > > the word IF it is the first word OR the word is NOT in the list of > > lowercase words; anything else goes through as lower case... > > ? ? ? ? Of course, most of this can be done in a single line (including > taking into account that some words may have a punctuation mark which > would confuse the original). > > >>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on' ] > >>> punct = ".,;:?!;'\"(){}[]" > >>> def recase(str = "physicist odd-affection, or how i was taught to stop fretting and adore the weapon of mass destruction"): > > ... ? ? return " ".join( w.title() if i == 0 or w.strip(punct) not in > smalls else w > ... ? ? ? ? ? ? ? ? ? ? for i,w in enumerate(str.lower().strip().split()) ) > ...>>> recase() > > 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting And Adore > the Weapon of Mass Destruction'>>> recase("what? me worry?") > 'What? Me Worry?' > >>> recase("the end of the matter is, to be blunt, a confusion") > > 'The End of the Matter Is, To Be Blunt, a Confusion'>>> recase("the end of the matter is in, to be blunt, a confusion") > > 'The End of the Matter Is in, To Be Blunt, a Confusion'>>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on', "and", "is", "to" ] > >>> recase() > > 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting and Adore > the Weapon of Mass Destruction'>>> recase("the end of the matter is in, to be blunt, a confusion") > > 'The End of the Matter is in, to Be Blunt, a Confusion' > > > > ? ? ? ? Of course, explaining what this construct is doing is the trick to > justifying it for a homework assignment. > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Too much destruction in this post man, and yeah I would not be able to explain the code for my homework. From tjreedy at udel.edu Sun Sep 11 12:47:08 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 12:47:08 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 12:01 AM, Ian Kelly wrote: > On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: >> The statement containing the explicit next(items) call can optionally be >> wrapped to explicitly handle the case of an empty iterable in whatever >> manner is desired. >> >> try: >> >> except StopIteration: >> raise ValueError("iterable cannot be empty") > > The only time that's optional This is an opinion, or rather, a programming philosophy based on technical facts, rather than a fact itself. You do raise an important issue. > is when you're writing an iterator and > the try-except would end up looking like this: > > try: > # do stuff with next(items) > except StopIteration: > raise StopIteration > > And even then, it's probably a good idea to clearly document that > you're allowing a StopIteration from one iterator to propagate up as a > StopIteration for another. In the yield-pairs example, def pairs(iterable): it = iter(iterable) for i in it: yield i, next(it) ignoring StopIteration from the get-even explicit next means ignoring an odd item. If pairs() were in a general purpose library, it should have a doc string that specifies that, and a test case with an odd number of items. I would consider a comment in the code itself to be optional, depending on the intended or expected human audience and the context of presentation. In this context, the explanation is in the text that surrounds the code. > Apart from that case, whenever you call next() you should always be > prepared to catch a StopIteration. To me, it depends on the contract or specification of the function. If the behavior for an empty input iterator is not specified, then there is no basis for writing the body of an except clause. While in the past few months I have written examples of all of the three explicit-next use cases I gave, I was prompted to write them up now by Tigerstyle's 'Doctest failing' thread. The specification by example (perhaps given by an instructor) did not include an empty title that would lead to an empty list of title words. Certainly, the doc for def fix_title(title): small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') twords = iter(title.strip().lower().split()) new_title = [next(twords)] for word in twords: if word not in small_words: word = word.title() new_title.append(word) return(' '.join(new_title)) should start "Given a title with at least one word, ...". The Agile Programming Test-Driven-Development maxim, 'Write the minimum code needed to pass the test' says that the extra lines needed to catch and process StopIteration should *not* be written until there is a test case leading to such. > Letting a StopIteration propagate > up the stack to parts unknown is bad juju because it's a flow control > exception, not an error-signaling exception. If it happens to > propagate up to another for loop, then it will break out of the for > loop, and the exception will simply be swallowed. What you are saying is a) that the following code for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: print(fix_title(title)) will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the worst choice of how to handle the empty title; and c) that in real world world programming, *someone* should decide whether fix_title('') returns '' or raises ValueError. A counter-argument could be 1. that when a function's contract is violated, invoking unspecified behavior, anything is allowed; or 2. that titles are checked for actual content before the case fixup is called, and the time and mental energy required to define and test behavior for impossible input is wasted and better spent on something more useful. -- Terry Jan Reedy From andreas.perstinger at gmx.net Sun Sep 11 12:47:42 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 11 Sep 2011 18:47:42 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: On 2011-09-11 13:17, Kayode Odeyemi wrote: > On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans wrote: >> It is working: >> >> >>> class A(object): >> ... def log (self, module): >> ... return str ('logged') >> ... >> >>> class B(A): >> ... def __init__(self, module): >> ... self.module = A().log(module) >> ... >> >>> c = B('system') >> >>> c.module >> 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating an > instance of B. Why do you expect an output? In B.__init__ you are just assigning the return value from A.log() to the attribute "module" and in A.log() there is no output either. Bye, Andreas From tjreedy at udel.edu Sun Sep 11 13:03:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 13:03:32 -0400 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/11/2011 7:46 AM, Tigerstyle wrote: > Thank you Terry, > I went for this solution as it was the easiest for me to understand > and comment myself keeping in mind what level I am at right now. > Thanks a ton to everyone for sharing so much information and making it > easy to read and understand your thoughts. This was surely very very > educating read the replies from so many talented people. You are welcome. For more, see my thread "Idioms combining 'next(items)' and 'for item in items:'" and the responses. -- Terry Jan Reedy From tjreedy at udel.edu Sun Sep 11 14:09:18 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 14:09:18 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 9:41 AM, Peter Otten wrote: > Terry Reedy wrote: > >> 3. Process the items of an iterable in pairs. >> >> items = iter(iterable) >> for first in items: >> second = next(items) >> >> >> This time, StopIteration is raised for an odd number of items. Catch and >> process as desired. One possibility is to raise ValueError("Iterable >> must have an even number of items"). > > Another way is zip-based iteration: > > (a) silently drop the odd item > > items = iter(iterable) > for first, second in zip(items, items): # itertools.izip in 2.x > ... In practice, I would use this rather than the loop above. However, I wanted to introduce the idea then used in the intermittent pairing of surrogates. > (b) add a fill value > > for first, second in itertools.zip_longest(items, items): > ... > > (c) raise an exception > > Unfortunately there is no zip_exc() that guarantees that all iterables are > of the same "length", but I've written a recipe some time ago > > http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures- > that-all-iterables/ > > that achieves near-C speed. Interesting. It took a moment to see the general idea. For some reason, you timeit examples in the comment now all have "data = [range(1000)]3", missing '*'. -- Terry Jan Reedy From ethan at stoneleaf.us Sun Sep 11 14:43:38 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 11 Sep 2011 11:43:38 -0700 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <4E6D015A.3070500@stoneleaf.us> Chris Angelico wrote: > On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware > wrote: >> Ignoring the docttests my process would be to process each word & then >> manually capitalize he 1st word, .I would als0 use a comprehension as >> makes for cleaner code:- >> >> def capitalize(word): >> if word in small_words: >> return word >> else: >> return word.title() > > And I'd do this with a lambda, but that's just me. Of course, if your > logic is more complicated, it makes more sense to keep it in a named > function, but a single conditional call can fit nicely into a lambda. Lambdas are great when needed, but if don't *need* it, and you have more than a few, debugging can be a nightmare... "Okay, so this is function ... and that is function ... and over here we also have function ... ARGH!" ~Ethan~ From timr at probo.com Sun Sep 11 14:48:01 2011 From: timr at probo.com (Tim Roberts) Date: Sun, 11 Sep 2011 11:48:01 -0700 Subject: using python in web applications References: Message-ID: "Littlefield, Tyler" wrote: > >I don't much care for PHP, but the thing that can be said for it is it's >pretty quick. How does Python compare? PHP is quick for development, in that you can slap together some schlock and have it mostly work. The result, however, is usually schlock. The performance of the language itself is almost entirely irrelevant; the execution time is swamped by the network overhead. >I'm also curious what databases are suggested? I've always >done most of my work in MYSql, but from what I understand postgresql is >becoming more popular to. Well, that's a religious argument. Personally, I've always been confused by the draw of MySql. From the very beginning, Postgres has always been more powerful, more reliable, more standard-compliant, and more professional. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ethan at stoneleaf.us Sun Sep 11 15:01:53 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 11 Sep 2011 12:01:53 -0700 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: <4E6D05A1.5010506@stoneleaf.us> Terry Reedy wrote: > On 9/11/2011 12:01 AM, Ian Kelly wrote: >> On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: >>> The statement containing the explicit next(items) call can optionally be >>> wrapped to explicitly handle the case of an empty iterable in whatever >>> manner is desired. >>> >>> try: >>> >>> except StopIteration: >>> raise ValueError("iterable cannot be empty") >> >> The only time that's optional > > This is an opinion, or rather, a programming philosophy based on > technical facts, rather than a fact itself. You do raise an important > issue. > >> is when you're writing an iterator and >> the try-except would end up looking like this: >> >> try: >> # do stuff with next(items) >> except StopIteration: >> raise StopIteration >> >> And even then, it's probably a good idea to clearly document that >> you're allowing a StopIteration from one iterator to propagate up as a >> StopIteration for another. > > In the yield-pairs example, > > def pairs(iterable): > it = iter(iterable) > for i in it: > yield i, next(it) > > ignoring StopIteration from the get-even explicit next means ignoring an > odd item. If pairs() were in a general purpose library, it should have a > doc string that specifies that, and a test case with an odd number of > items. I would consider a comment in the code itself to be optional, > depending on the intended or expected human audience and the context of > presentation. In this context, the explanation is in the text that > surrounds the code. > >> Apart from that case, whenever you call next() you should always be >> prepared to catch a StopIteration. > > To me, it depends on the contract or specification of the function. If > the behavior for an empty input iterator is not specified, then there is > no basis for writing the body of an except clause. > > While in the past few months I have written examples of all of the three > explicit-next use cases I gave, I was prompted to write them up now by > Tigerstyle's 'Doctest failing' thread. The specification by example > (perhaps given by an instructor) did not include an empty title that > would lead to an empty list of title words. Certainly, the doc for > > def fix_title(title): > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > twords = iter(title.strip().lower().split()) > new_title = [next(twords)] > for word in twords: > if word not in small_words: > word = word.title() > new_title.append(word) > return(' '.join(new_title)) > > should start "Given a title with at least one word, ...". > > The Agile Programming Test-Driven-Development maxim, 'Write the minimum > code needed to pass the test' says that the extra lines needed to catch > and process StopIteration should *not* be written until there is a test > case leading to such. > >> Letting a StopIteration propagate >> up the stack to parts unknown is bad juju because it's a flow control >> exception, not an error-signaling exception. If it happens to >> propagate up to another for loop, then it will break out of the for >> loop, and the exception will simply be swallowed. > > What you are saying is a) that the following code > > for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: > print(fix_title(title)) > > will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the > worst choice of how to handle the empty title; and c) that in real world > world programming, *someone* should decide whether fix_title('') returns > '' or raises ValueError. > > A counter-argument could be 1. that when a function's contract is > violated, invoking unspecified behavior, anything is allowed; or 2. that > titles are checked for actual content before the case fixup is called, > and the time and mental energy required to define and test behavior for > impossible input is wasted and better spent on something more useful. Having spent hours tracking down errors because somebody did not address a corner case, I find counter-argument 1 unhelpful. Counter-argument 2 I can at least partially agree with; however, in this case where the uncaught exception can mess up flow control elsewhere I do not -- the StopIteration should be caught and changed to something appropriate, such as EmptyTitle (assuming blank titles are errors -- which they probably should be... "Hello, do you have the book '' for sale here?") ~Ethan~ From laurent.payot at gmail.com Sun Sep 11 15:22:26 2011 From: laurent.payot at gmail.com (Laurent) Date: Sun, 11 Sep 2011 12:22:26 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <26428844-acd2-4c7b-bc6a-cf5a8a6259bc@glegroupsg2000goo.googlegroups.com> +1 for PostgreSQL. It's faster than MySQL for years now, and is much more seriously featured. If you don't need ACID properties (transactions stuff) you should also give Document-based databases like MongoDB a try. It changed my code life. From laurent.payot at gmail.com Sun Sep 11 15:22:26 2011 From: laurent.payot at gmail.com (Laurent) Date: Sun, 11 Sep 2011 12:22:26 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <26428844-acd2-4c7b-bc6a-cf5a8a6259bc@glegroupsg2000goo.googlegroups.com> +1 for PostgreSQL. It's faster than MySQL for years now, and is much more seriously featured. If you don't need ACID properties (transactions stuff) you should also give Document-based databases like MongoDB a try. It changed my code life. From Phillip.M.Feldman at gmail.com Sun Sep 11 15:41:33 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sun, 11 Sep 2011 12:41:33 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32443548.post@talk.nabble.com> Hello Peter, When I run my code, I get the same 14 configurations that your code produces; the only different that I can see in the output is that the configurations are produced in a different order. Note that your code is not creating an iterator, so thus doesn't do what I want. Also, generating the product set and then testing whether the total number of balls is correct will potentially consider a huge number of cases that must be rejected because the sum is wrong; this is too inefficient. Phillip In [2]: list(balls_in_numbered_boxes(10,[4,3,2,1,2])) Out[2]: [(4, 3, 2, 1, 0), (4, 3, 2, 0, 1), (4, 3, 1, 1, 1), (4, 3, 1, 0, 2), (4, 3, 0, 1, 2), (4, 2, 2, 1, 1), (4, 2, 2, 0, 2), (4, 2, 1, 1, 2), (4, 1, 2, 1, 2), (3, 3, 2, 1, 1), (3, 3, 2, 0, 2), (3, 3, 1, 1, 2), (3, 2, 2, 1, 2), (2, 3, 2, 1, 2)] -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443548.html Sent from the Python - python-list mailing list archive at Nabble.com. From Phillip.M.Feldman at gmail.com Sun Sep 11 15:48:07 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sun, 11 Sep 2011 12:48:07 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32443579.post@talk.nabble.com> Chris, Your code is much cleaner than mine. I will have to figure out exactly how it is working. Thanks! Phillip -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443579.html Sent from the Python - python-list mailing list archive at Nabble.com. From hidura at gmail.com Sun Sep 11 15:53:24 2011 From: hidura at gmail.com (hidura at gmail.com) Date: Sun, 11 Sep 2011 19:53:24 +0000 Subject: using python in web applications In-Reply-To: References: Message-ID: <952711646-1315770807-cardhu_decombobulator_blackberry.rim.net-827506045-@b12.c22.bise6.blackberry> I am agree with postgresql i don' t have any problem, also is better for big applications. And Python is always better language than PHP if you' re going to create a web app. Sent from my BlackBerry? wireless device -----Original Message----- From: Tim Roberts Sender: python-list-bounces+hidura=gmail.com at python.org Date: Sun, 11 Sep 2011 11:48:01 To: Subject: Re: using python in web applications "Littlefield, Tyler" wrote: > >I don't much care for PHP, but the thing that can be said for it is it's >pretty quick. How does Python compare? PHP is quick for development, in that you can slap together some schlock and have it mostly work. The result, however, is usually schlock. The performance of the language itself is almost entirely irrelevant; the execution time is swamped by the network overhead. >I'm also curious what databases are suggested? I've always >done most of my work in MYSql, but from what I understand postgresql is >becoming more popular to. Well, that's a religious argument. Personally, I've always been confused by the draw of MySql. From the very beginning, Postgres has always been more powerful, more reliable, more standard-compliant, and more professional. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Sun Sep 11 16:13:02 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 22:13:02 +0200 Subject: recursive algorithm for balls in numbered boxes References: <32440187.post@talk.nabble.com> <32443548.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > When I run my code, I get the same 14 configurations that your code > produces; I'm sorry, I ran the buggy code from http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py without realizing it was not http://old.nabble.com/file/p32440187/balls_in_numbered_boxes.py > the only different that I can see in the output is that the > configurations are produced in a different order. Note that your code is > not creating an iterator, so thus doesn't do what I want. The outer loop is in a generator expression and thus evaluates lazily. > Also, > generating the product set and then testing whether the total number of > balls is correct will potentially consider a huge number of cases that > must be rejected because the sum is wrong; this is too inefficient. Indeed; I should have added a disclaimer to make that clear. From robert.kern at gmail.com Sun Sep 11 16:22:28 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 11 Sep 2011 15:22:28 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6C9614.60406@tim.thechases.com> References: <4E6C182D.60905@tim.thechases.com> <4E6C9614.60406@tim.thechases.com> Message-ID: On 9/11/11 6:05 AM, Tim Chase wrote: > As Ben Finney replied, optparse is now deprecated, replaced in part by argparse. > Unfortunately, argparse wasn't backported to the standard library for earlier > 2.x series (I think it became available in 2.7, and may run in earlier versions > if manually added like I had to do on my Debian Py2.6 install). But that makes > it hard for those of us who want to use a built-in option-parsing library across > a wide variety of Python versions. I don't strongly care which I use except that > I want it to be broadly available with minimal fuss. argparse.py can be simply dropped into your codebase, if you want. That's about as minimal of fuss as you can ask for. http://pypi.python.org/pypi/argparse -- 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 rosuav at gmail.com Sun Sep 11 18:41:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 08:41:05 +1000 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy wrote: > What you are saying is a) that the following code > > for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: > ? ?print(fix_title(title)) > At least in Python 3.2, this isn't the case. StopIteration breaks the loop only if it's raised during the assignment, not during the body. >>> x=iter([1,2,3,4,5]) >>> for i in x: print("%d - %d"%(i,next(x))) 1 - 2 3 - 4 Traceback (most recent call last): File "", line 2, in print("%d - %d"%(i,next(x))) StopIteration Compare with: >>> def pair(it): while True: yield next(it),next(it) >>> x=iter([1,2,3,4,5]) >>> for i,j in pair(x): print("%d - %d"%(i,j)) 1 - 2 3 - 4 In this case, the StopIteration bubbles up and quietly terminates the loop. ChrisA From tjreedy at udel.edu Sun Sep 11 20:45:41 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 20:45:41 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 6:41 PM, Chris Angelico wrote: > On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy wrote: >> What you are saying is a) that the following code >> >> for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: >> print(fix_title(title)) > At least in Python 3.2, this isn't the case. StopIteration breaks the > loop only if it's raised during the assignment, not during the body. It breaks the loop *silently* only if ... >>>> x=iter([1,2,3,4,5]) >>>> for i in x: > print("%d - %d"%(i,next(x))) > > 1 - 2 > 3 - 4 > Traceback (most recent call last): > File "", line 2, in > print("%d - %d"%(i,next(x))) > StopIteration whereas, you are right, it breaks it noisily in the body. So Ian's claim that StopIteration must be caught to avoid silent termination is not true. Thanks for pointing out what I saw but did not cognize the full implication of before. A better exception and an error message with an explaination might still be a good idea, though. -- Terry Jan Reedy From rosuav at gmail.com Sun Sep 11 21:03:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 11:03:24 +1000 Subject: Doctest failing In-Reply-To: <4E6D015A.3070500@stoneleaf.us> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> Message-ID: On Mon, Sep 12, 2011 at 4:43 AM, Ethan Furman wrote: > Chris Angelico wrote: >> >> And I'd do this with a lambda, but that's just me. Of course, if your >> logic is more complicated, it makes more sense to keep it in a named >> function, but a single conditional call can fit nicely into a lambda. > > Lambdas are great when needed, but if don't *need* it, and you have more > than a few, debugging can be a nightmare... "Okay, so this is function > ... and that is function ... and over here we also have > function ... ARGH!" Yeah, they can be like the Bruces sketch at times. A lambda is basically a function defined in an expression. For instance: def add_one(x): return x+1 is (practically) the same as: add_one = lambda x: x+1 In each case, you can call that function and will get back a value. The advantage of lambdas is that, in a list comprehension or map call, the code is right there instead of being elsewhere in a def statement. But as you can see, they quickly become hard to read: [j+2 for i in [[1,2,3],[4,5,6],[7,8,9]] for j in (lambda x: [q+10 for q in x])(i)] Their main advantage isn't in list comps, where you can already use arbitrary expressions, but in calls that require a function as an argument. The map() function is very similar to a generator expression, but it can iterate over multiple iterables at once: >>> list(map(lambda x,y: x+y,[1,2,3],[40,50,60])) [41, 52, 63] Note how the lambda keeps the code right there, whereas a def would separate it out. It's obvious from this one expression that it's adding successive corresponding pairs. Hope that helps! ChrisA From ben+python at benfinney.id.au Sun Sep 11 21:37:10 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 12 Sep 2011 11:37:10 +1000 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> Message-ID: <87sjo2lewp.fsf@benfinney.id.au> Chris Angelico writes: > A lambda is basically a function defined in an expression. For instance: > > def add_one(x): > return x+1 > > is (practically) the same as: > > add_one = lambda x: x+1 Those are only practically the same if you ignore the practical worth of a function knowing the name it was defined with. The latter does not have that, hence I don't see it as practically the same as the former. -- \ ?The Vatican is not a state.? a state must have territory. This | `\ is a palace with gardens, about as big as an average golf | _o__) course.? ?Geoffrey Robertson, 2010-09-18 | Ben Finney From rosuav at gmail.com Sun Sep 11 23:06:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 13:06:54 +1000 Subject: Doctest failing In-Reply-To: <87sjo2lewp.fsf@benfinney.id.au> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> <87sjo2lewp.fsf@benfinney.id.au> Message-ID: On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney wrote: > Those are only practically the same if you ignore the practical worth of > a function knowing the name it was defined with. The latter does not > have that, hence I don't see it as practically the same as the former. > I know, but in the context of explaining what "lambda" means, it's practically the same. Lambdas can't (afaik) have docstrings either, etc, etc, but in terms of defining lambda, the two are more-or-less equivalent. ChrisA From steve+comp.lang.python at pearwood.info Mon Sep 12 00:29:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 14:29:05 +1000 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> <87sjo2lewp.fsf@benfinney.id.au> Message-ID: <4e6d8a92$0$29972$c3e8da3$5496439d@news.astraweb.com> On Mon, 12 Sep 2011 01:06 pm Chris Angelico wrote: > On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney > wrote: >> Those are only practically the same if you ignore the practical worth of >> a function knowing the name it was defined with. The latter does not >> have that, hence I don't see it as practically the same as the former. >> > > I know, but in the context of explaining what "lambda" means, it's > practically the same. Lambdas can't (afaik) have docstrings either, > etc, etc, but in terms of defining lambda, the two are more-or-less > equivalent. >>> f = lambda x: x+1 >>> f.__name__ '' >>> f.__doc__ = "Return x+1" >>> f.__name__ = "add_one" >>> help(f) Help on function add_one in module __main__: add_one(x) Return x+1 Lambdas are functions, no more, no less. The only difference is that the *syntax* of the lambda statement only allows a single expression rather that the full block of a def, and no name. But because it returns an ordinary function object, you can post-process it just like any other function. Unfortunately, tracebacks ignore the function.__name__ and print the code object name: >>> f >>> f("x") Traceback (most recent call last): File "", line 1, in File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects and the code object name is read-only: >>> f.func_code.co_name '' >>> f.func_code.co_name = "add_one" Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute -- Steven From jpablo.romero at gmail.com Mon Sep 12 00:34:26 2011 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Sun, 11 Sep 2011 23:34:26 -0500 Subject: What do you guys think about adding a method "to_json" Message-ID: Hello, What do you guys think about adding a method "to_json" to dictionaries and sequence types? Perhaps through a module import? Regards, Juan Pablo From clp2 at rebertia.com Mon Sep 12 00:44:01 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 11 Sep 2011 21:44:01 -0700 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: 2011/9/11 Juan Pablo Romero M?ndez : > Hello, > > What do you guys think about adding a method "to_json" to dictionaries > and sequence types? Perhaps through a module import? Why? We already have json.dumps(); seems to cover the use case. Cheers, Chris From adam.jorgensen.za at gmail.com Mon Sep 12 01:39:52 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Mon, 12 Sep 2011 07:39:52 +0200 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: Perhaps an actual use-case would clarify the need for this? 2011/9/12 Chris Rebert > 2011/9/11 Juan Pablo Romero M?ndez : > > Hello, > > > > What do you guys think about adding a method "to_json" to dictionaries > > and sequence types? Perhaps through a module import? > > Why? We already have json.dumps(); seems to cover the use case. > > Cheers, > Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Mon Sep 12 03:49:31 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 12 Sep 2011 17:49:31 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? Message-ID: Good evening, I have converted ODT to HTML using LibreOffice Writer, because I want to convert from HTML to Creole using python-creole. Unfortunately I get this error: "File "Convert to Creole.py", line 17 SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py on line 18, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details". Unfortunately I can't post my document yet (it's a research paper I'm working on), but I'm sure you'll get the same result if you write up a document in LibreOffice Writer and add some End Notes. How do I automate the removal of all non-ascii characters from my code? Thanks for all suggestions, Alec Taylor From gherron at islandtraining.com Mon Sep 12 04:17:44 2011 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 12 Sep 2011 01:17:44 -0700 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: <4E6DC028.1020101@islandtraining.com> On 09/12/2011 12:49 AM, Alec Taylor wrote: > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? > > Thanks for all suggestions, > > Alec Taylor This question does not quite make sense. The error message is complaining about a python file. What does that file have to do with ODT to HTML conversion and LibreOffice? The error message means the python file (wherever it came from) has a non-ascii character (as you noted), and so it needs something to tell it what such a character means. (That what the encoding is.) A comment like this in line 1 or 2 will specify an encoding: # -*- coding: -*- but, we'll have to know more about the file "Convert to Creole.py" to guess what encoding name should be specified there. You might try utf-8 or latin-1. From alec.taylor6 at gmail.com Mon Sep 12 04:33:14 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 12 Sep 2011 18:33:14 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> Message-ID: from creole import html2creole from BeautifulSoup import BeautifulSoup VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br', 'b', 'i', 'a', 'h1', 'h2'] def sanitize_html(value): ? ?soup = BeautifulSoup(value) ? ?for tag in soup.findAll(True): ? ? ? ?if tag.name not in VALID_TAGS: ? ? ? ? ? ?tag.hidden = True ? ?return soup.renderContents() html2creole(u(sanitize_html('''

Abstract

? ?

[more stuff here] """)) On Mon, Sep 12, 2011 at 6:17 PM, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: >> >> Good evening, >> >> I have converted ODT to HTML using LibreOffice Writer, because I want >> to convert from HTML to Creole using python-creole. Unfortunately I >> get this error: "File "Convert to Creole.py", line 17 >> SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py >> on line 18, but no encoding declared; see >> http://www.python.org/peps/pep-0263.html for details". >> >> Unfortunately I can't post my document yet (it's a research paper I'm >> working on), but I'm sure you'll get the same result if you write up a >> document in LibreOffice Writer and add some End Notes. >> >> How do I automate the removal of all non-ascii characters from my code? >> >> Thanks for all suggestions, >> >> Alec Taylor > > > > This question does not quite make sense. ?The error message is complaining > about a python file. ?What does that file have to do with ODT to HTML > conversion and LibreOffice? > > The error message means the python file (wherever it came from) has a > non-ascii character (as you noted), and so it needs something to tell it > what such a character means. ?(That what the encoding is.) > > A comment like this in line 1 or 2 will specify an encoding: > ?# -*- coding: -*- > but, we'll have to know more about the file "Convert to Creole.py" to guess > what encoding name should be specified there. > > You might try utf-8 or latin-1. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjohn.tedro at gmail.com Mon Sep 12 04:35:44 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Mon, 12 Sep 2011 08:35:44 +0000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: <4E6DC028.1020101@islandtraining.com> References: <4E6DC028.1020101@islandtraining.com> Message-ID: On Mon, Sep 12, 2011 at 8:17 AM, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: > >> Good evening, >> >> I have converted ODT to HTML using LibreOffice Writer, because I want >> to convert from HTML to Creole using python-creole. Unfortunately I >> get this error: "File "Convert to Creole.py", line 17 >> SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py >> on line 18, but no encoding declared; see >> http://www.python.org/peps/**pep-0263.htmlfor details". >> >> Unfortunately I can't post my document yet (it's a research paper I'm >> working on), but I'm sure you'll get the same result if you write up a >> document in LibreOffice Writer and add some End Notes. >> >> How do I automate the removal of all non-ascii characters from my code? >> >> Thanks for all suggestions, >> >> Alec Taylor >> > > > > This question does not quite make sense. The error message is complaining > about a python file. What does that file have to do with ODT to HTML > conversion and LibreOffice? > > The error message means the python file (wherever it came from) has a > non-ascii character (as you noted), and so it needs something to tell it > what such a character means. (That what the encoding is.) > > A comment like this in line 1 or 2 will specify an encoding: > # -*- coding: -*- > but, we'll have to know more about the file "Convert to Creole.py" to guess > what encoding name should be specified there. > > You might try utf-8 or latin-1. > > > > -- > http://mail.python.org/**mailman/listinfo/python-list > If you are having trouble figuring out which encoding your file has, the "file" util is often a quick and dirty solution. #> echo "???" > test.txt #> file test.txt test.txt: UTF-8 Unicode text #> iconv test.txt -f utf-8 -t latin1 > test.l1.txt #> file test.l1.txt test.l1.txt: ISO-8859 text Note: I use latin1 (iso-8859-1) because it can describe the characters '?', '?', '?'. Your encoding might be different depending on what system you are using. The gist is that if you specify the correct encoding as mentioned above with the "coding"-comment, your program will probably (ish) run as intended. -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Sep 12 04:43:51 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 12 Sep 2011 10:43:51 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> Message-ID: Alec Taylor, 12.09.2011 10:33: > from creole import html2creole > > from BeautifulSoup import BeautifulSoup > > VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br', 'b', 'i', 'a', 'h1', 'h2'] > > def sanitize_html(value): > > soup = BeautifulSoup(value) > > for tag in soup.findAll(True): > if tag.name not in VALID_TAGS: > tag.hidden = True > > return soup.renderContents() > html2creole(u(sanitize_html('''

style="margin-left:76.8px;margin-right:0;text-indent:0;">Abstract

>

style="margin-left:76.8px;margin-right:0;text-indent:0;"> > [more stuff here] > """)) Hi, I'm not sure what you are trying to say with the above code, but if it's the code that fails for you with the exception you posted, I would guess that the problem is in the "[more stuff here]" part, which likely contains a non-ASCII character. Note that you didn't declare the source file encoding above. Do as Gary told you. Stefan From steve+comp.lang.python at pearwood.info Mon Sep 12 04:44:29 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 18:44:29 +1000 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> On Wed, 31 Aug 2011 10:33 pm Steven D'Aprano wrote: > Twice in a couple of weeks, I have locked up my PC by running a Python 2.5 > script that tries to create a list that is insanely too big. > > In the first case, I (stupidly) did something like: > > mylist = [0]*12345678901234 [...] > Apart from "Then don't do that!", is there anything I can do to prevent > this sort of thing in the future? Like instruct Python not to request more > memory than my PC has? For anyone who may care, I can report that ulimit under Linux will help with this situation. [steve at wow-wow ~]$ ulimit -v 200000 [steve at wow-wow ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> L = range(100000000) Traceback (most recent call last): File "", line 1, in MemoryError (Of course, I would have eventually got a MemoryError even without the ulimit. *Eventually.* After much thrashing and processes crashing and pain.) Does anyone else think it would be useful for Python's memory manager to enforce user-settable limits? Even just a simple thing like "never try to allocate more than N bytes at once" would probably go a long way to prevent a certain class of accidental (or deliberate) DOSes. -- Steven From steve+comp.lang.python at pearwood.info Mon Sep 12 04:49:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 18:49:56 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> Message-ID: <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > I'm not sure what you are trying to say with the above code, but if it's > the code that fails for you with the exception you posted, I would guess > that the problem is in the "[more stuff here]" part, which likely contains > a non-ASCII character. Note that you didn't declare the source file > encoding above. Do as Gary told you. Even with a source code encoding, you will probably have problems with source files including \xe2 and other "bad" chars. Unless they happen to fall inside a quoted string literal, I would expect to get a SyntaxError. I have come across this myself. While I haven't really investigated in great detail, it appears to happen when copying and pasting code from a document (usually HTML) which uses non-breaking spaces instead of \x20 space characters. All it takes is just one to screw things up. -- Steven From ulrich.eckhardt at dominolaser.com Mon Sep 12 06:00:08 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 12:00:08 +0200 Subject: Terminating an embedded interpreter Message-ID: Hi! I'm trying to provide some scripting capabilities to a program. For that, I'm embedding a Python interpreter, running a script in a separate thread to decouple it from the UI. Now, how should I handle rogue scripts? For example, when a script hangs in an endless loop, how do I signal the Python interpreter to shut down? In other words, I want to trigger something like what Control-C does in a "normal" environment. In case it matters, the OS here is MS Windows. Thanks! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From rmorgan466 at gmail.com Mon Sep 12 06:34:52 2011 From: rmorgan466 at gmail.com (Rita) Date: Mon, 12 Sep 2011 06:34:52 -0400 Subject: working with a large file Message-ID: I have a large file, 18gb uncompressed, and I would like to know what is the preferred method to read this file for random access. I have several processes reading the file which different calculate arguments. My server has 64gb of memory. Not sure what is the preferred way to do this? -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Sep 12 06:38:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 20:38:47 +1000 Subject: Terminating an embedded interpreter In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 8:00 PM, Ulrich Eckhardt wrote: > Now, how should I handle rogue scripts? For example, when a script hangs in > an endless loop, how do I signal the Python interpreter to shut down? In > other words, I want to trigger something like what Control-C does in a > "normal" environment. > You can use PyErr_SetInterrupt to raise KeyboardInterrupt, but it can be caught by the script. There's no guaranteed way, short of killing the process. ChrisA From wolfgang at rohdewald.de Mon Sep 12 06:45:00 2011 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Mon, 12 Sep 2011 12:45:00 +0200 Subject: working with a large file In-Reply-To: References: Message-ID: <201109121245.00224.wolfgang@rohdewald.de> On Montag 12 September 2011, Rita wrote: > I have a large file, 18gb uncompressed, and I would like to > know what is the preferred method to read this file for > random access. I have several processes reading the file > which different calculate arguments. My server has 64gb of > memory. Not sure what is the preferred way to do this? if the data is structured, you could store it in something like sqlite -- Wolfgang From steve+comp.lang.python at pearwood.info Mon Sep 12 07:08:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 21:08:22 +1000 Subject: Terminating an embedded interpreter References: Message-ID: <4e6de828$0$29993$c3e8da3$5496439d@news.astraweb.com> Ulrich Eckhardt wrote: > Hi! > > I'm trying to provide some scripting capabilities to a program. For that, > I'm embedding a Python interpreter, running a script in a separate thread > to decouple it from the UI. > > Now, how should I handle rogue scripts? For example, when a script hangs > in an endless loop, how do I signal the Python interpreter to shut down? If you are using threads, they all run within the same Python process. You can ask a thread to shut down, but you can't force it to from the outside. If the thread runs a script that goes rogue, the script may never return control to the thread long enough for it to respond to your request. The main UI loop can still kill itself, and take all the threads with it, by calling sys.exit. Or if you really need to, os.abort or os._exit can be used for immediate "terminate yourself NOW!!!" commands. (But read the docs for them first.) A better way may be to run the script in a separate process. You can kill the process the same way you would any other rogue process: by sending it a signal. See the os and subprocess modules. But Python's sandboxing abilities are not great. If you really fear rogue, or malicious, scripts, perhaps Python is not the right language for this task. Otherwise, just trust the script to be sane. -- Steven From roy at panix.com Mon Sep 12 07:40:00 2011 From: roy at panix.com (Roy Smith) Date: Mon, 12 Sep 2011 07:40:00 -0400 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e6dc66e$0$29986$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > > mylist = [0]*12345678901234 > [...] > > Apart from "Then don't do that!", is there anything I can do to prevent > > this sort of thing in the future? Like instruct Python not to request more > > memory than my PC has? > > > For anyone who may care, I can report that ulimit under Linux will help with > this situation. > [...] > Does anyone else think it would be useful for Python's memory manager to > enforce user-settable limits? Not me. You've already discovered that ulimit does exactly what you want. Why would be gained by having Python duplicate this functionality? From ulrich.eckhardt at dominolaser.com Mon Sep 12 08:01:47 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 14:01:47 +0200 Subject: Terminating an embedded interpreter References: <4e6de828$0$29993$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Ulrich Eckhardt wrote: >> I'm trying to provide some scripting capabilities to a program. For that, >> I'm embedding a Python interpreter, running a script in a separate thread >> to decouple it from the UI. >> >> Now, how should I handle rogue scripts? For example, when a script hangs >> in an endless loop, how do I signal the Python interpreter to shut down? > > If you are using threads, they all run within the same Python process. You > can ask a thread to shut down, but you can't force it to from the outside. > If the thread runs a script that goes rogue, the script may never return > control to the thread long enough for it to respond to your request. Sorry, I described badly what I was doing. The program itself is written in C++ and I'm running the Python interpreter in a thread separate to the UI, just in order to not hang the UI if anything in the interpreter blocks for extended amounts of time. I know that a Python thread is not a "system" thread but handled and scheduled internally by Python. > The main UI loop can still kill itself, and take all the threads with it, > by calling sys.exit. Or if you really need to, os.abort or os._exit can be > used for immediate "terminate yourself NOW!!!" commands. (But read the > docs for them first.) > A better way may be to run the script in a separate process. You can kill > the process the same way you would any other rogue process: by sending it > a signal. See the os and subprocess modules. Yes, a separate process would be much cleaner, but it would complicate communication back to the parent process. The Python code is supposed to call a few functions I exported. I'd have to tunnel these calls through stdin/stdout/stderr and that is more than what I'm willing to do at the moment. It does sound intriguing though, since that would allow me to embed any scripting language, not just Python. > But Python's sandboxing abilities are not great. If you really fear rogue, > or malicious, scripts, perhaps Python is not the right language for this > task. Otherwise, just trust the script to be sane. I'm not fearing malicious scripts. I'm also not concerned about rare hangs since this in an internal tool. In this case, I'd take a simple 99% solution over a complex 100% solution. Thank you for your thoughts, Steven! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ulrich.eckhardt at dominolaser.com Mon Sep 12 08:05:04 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 14:05:04 +0200 Subject: Terminating an embedded interpreter References: Message-ID: Chris Angelico wrote: > You can use PyErr_SetInterrupt to raise KeyboardInterrupt This sounds useful. Just to make sure, this would be called from a different thread than the one running the Python script, is that still OK? > , but it can be caught by the script. There's no guaranteed way, > short of killing the process. This will do for my plans, I'm not trying to defend against anything malicious. Thanks you! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From davea at ieee.org Mon Sep 12 08:09:59 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Sep 2011 08:09:59 -0400 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E6DF697.2010208@ieee.org> On 01/-10/-28163 02:59 PM, Steven D'Aprano wrote: > On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > >> I'm not sure what you are trying to say with the above code, but if it's >> the code that fails for you with the exception you posted, I would guess >> that the problem is in the "[more stuff here]" part, which likely contains >> a non-ASCII character. Note that you didn't declare the source file >> encoding above. Do as Gary told you. > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > > I have come across this myself. While I haven't really investigated in great > detail, it appears to happen when copying and pasting code from a document > (usually HTML) which uses non-breaking spaces instead of \x20 space > characters. All it takes is just one to screw things up. > > For me, more common than non-breaking space is the "smart quotes" characters. In that case, one probably doesn't want to delete them, but instead convert them into standard quotes. DaveA From nobody at nowhere.com Mon Sep 12 08:19:25 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 12 Sep 2011 13:19:25 +0100 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e5e2d81$0$29991$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, 31 Aug 2011 22:47:59 +1000, Steven D'Aprano wrote: >> Linux seems to fair badly when programs use more memory than physically >> available. Perhaps there's some per-process thing that can be used to >> limit things on Linux? > > As far as I know, ulimit ("user limit") won't help. It can limit the amount > of RAM available to a process, but that just makes the process start using > virtual memory more quickly. It can also limit the amount of virtual memory > used by the shell, but not of other processes. In other words, Linux will > try really, really, really hard to give you the 84 gigabytes you've asked > for on a 2 GB system, even if it means DOSing your system for a month. > > Of course, I would be very happy to learn I'm wrong. Resource limits set by ulimit are inherited by any processes spawned from the shell. They also affect the shell itself, but a shell process shouldn't require a lot of resources. You can use a subshell if you want to impose limits on a specific process. For Python, setting the limit on virtual memory (RAM + swap) to no more than the amount of physical RAM is probably a wise move. Some processes can use swap effectively, but the typical Python program probably can't. There are exceptions, e.g. if most of the memory is accounted for by large NumPy arrays and you're careful about the operations which are performed upon them. But using large amounts of memory for many small objects is almost bound to result in swap-thrashing. One problem with doing this automatically (e.g. in .pythonrc) is the inheritance issue; any processes spawned from the interpreter will also be resource limited. Similarly, any binary libraries loaded into the interpreter will be subject to the process' resource limits. Consequently, there would be some advantages to the Python interpreter having its own resource-limiting mechanism. From ssegvic at zemris.fer.hr Mon Sep 12 08:45:38 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Mon, 12 Sep 2011 14:45:38 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E69DEE8.9050803@shopzeus.com> Message-ID: <1616916126.29418.1315831538309.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "Sini?a ?egvi?" , python-list at python.org > Sent: Friday, September 9, 2011 11:39:52 AM > Subject: Re: Portable locale usage > > Looks like you have found a bug! :-) Why don't you post a bug report? I just did: http://bugs.python.org/issue12964 Thanks everyone for helping me to sort this out! Sinisa From rosuav at gmail.com Mon Sep 12 08:49:48 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 22:49:48 +1000 Subject: Terminating an embedded interpreter In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:05 PM, Ulrich Eckhardt wrote: > Chris Angelico wrote: >> You can use PyErr_SetInterrupt to raise KeyboardInterrupt > > This sounds useful. Just to make sure, this would be called from a different > thread than the one running the Python script, is that still OK? > >> , but it can be caught by the script. There's no guaranteed way, >> short of killing the process. > > This will do for my plans, I'm not trying to defend against anything > malicious. Yes, that would be what you want then. The main thing to take care of is a blanket 'except' that doesn't specify what it's accepting - it'll snarf the KeyboardInterrupt and carry on its merry way. ChrisA From duncan.booth at invalid.invalid Mon Sep 12 09:06:47 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Sep 2011 13:06:47 GMT Subject: Idioms combining 'next(items)' and 'for item in items:' References: Message-ID: Terry Reedy wrote: > The statement containing the explicit next(items) call can optionally be > wrapped to explicitly handle the case of an empty iterable in whatever > manner is desired. > > try: > > except StopIteration: > raise ValueError("iterable cannot be empty") > > Alternatively, if all you want is for an empty iterable to do nothing, you could write it like this: items = iter(iterable) for first in items: break for item in items: However, the issue I have with any of this pulling the first element out of the loop is that if you want special processing for the first element you are likely to also want it for the last, and if it is a single item you need to process that item with both bits of special code. I don't see how that works unless you have all elements within the single loop and test for first/last. > 2. Process the last item of an iterable differently. As far as I know, > this cannot be done for a generic iterable with a flag. It requires a > look ahead. I think that must be correct, e.g. if reading from an interactive prompt you cannot detect end of input until you fail to read any more. See my answer to http://stackoverflow.com/questions/7365372/is-there-a-pythonic-way-of-knowing-when-the-first-and-last-loop-in-a-for-is-being/7365552#7365552 for a generator that wraps the lookahead. -- Duncan Booth http://kupuguy.blogspot.com From miki.tebeka at gmail.com Mon Sep 12 09:23:09 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 06:23:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: You can add "# coding=UTF8" to the top of your file (see http://www.python.org/dev/peps/pep-0263/). Of you want to remove unicode, there are several options, one of them is passing the file through "iconv --to ascii". From miki.tebeka at gmail.com Mon Sep 12 09:23:09 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 06:23:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: You can add "# coding=UTF8" to the top of your file (see http://www.python.org/dev/peps/pep-0263/). Of you want to remove unicode, there are several options, one of them is passing the file through "iconv --to ascii". From j.reid at mail.cryst.bbk.ac.uk Mon Sep 12 10:03:40 2011 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Mon, 12 Sep 2011 15:03:40 +0100 Subject: Easiest framework to develop simple interactive web site in python? Message-ID: Hi, I need to write a web interface for some computational biology software I've written: http://sysbio.mrc-bsu.cam.ac.uk/johns/STEME/rst/_build/html/index.html I don't have much experience writing web sites or applications. Can anyone recommend a python framework that will allow me to easily write a few pages? I need to accept some user input in the form of some options and download a potentially large file from the user's computer. The job can take some time to run so I'll need to notify them via email when it has finished. I should say our group already uses an Apache web server so I'd like to host the pages from that server. I know there are various python web frameworks but I don't want to learn a complicated one, I really just want the simplest tool for the job. Are any of the following suitable? Zope, Django, Pylons, Grok, Pyramid I see quite a few are listed here: http://wiki.python.org/moin/WebFrameworks Thanks in advance for any help, John. From stefan_ml at behnel.de Mon Sep 12 10:10:44 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 12 Sep 2011 16:10:44 +0200 Subject: working with a large file In-Reply-To: References: Message-ID: Rita, 12.09.2011 12:34: > I have a large file, 18gb uncompressed, and I would like to know what is the > preferred method to read this file for random access. I have several > processes reading the file which different calculate arguments. My server > has 64gb of memory. Not sure what is the preferred way to do this? It depends on the content (and likely also the operating system), but you might want to take a look at the mmap module. Stefan From wxjmfauth at gmail.com Mon Sep 12 10:39:22 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Mon, 12 Sep 2011 07:39:22 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: Message-ID: <55455989-d2bf-44d6-b3cf-ba50f1e87a01@d14g2000yqb.googlegroups.com> On 12 sep, 10:17, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: > > > > > Good evening, > > > I have converted ODT to HTML using LibreOffice Writer, because I want > > to convert from HTML to Creole using python-creole. Unfortunately I > > get this error: "File "Convert to Creole.py", line 17 > > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > > on line 18, but no encoding declared; see > >http://www.python.org/peps/pep-0263.htmlfor details". > > > Unfortunately I can't post my document yet (it's a research paper I'm > > working on), but I'm sure you'll get the same result if you write up a > > document in LibreOffice Writer and add some End Notes. > > > How do I automate the removal of all non-ascii characters from my code? > > > Thanks for all suggestions, > > > Alec Taylor > The coding of the characters is a domain per se. It is independent from any OS's or applications. When working with (plain) text files, you should always be aware about the coding of the text you are working on. If you are using coding directives, you must ensure your coding directive matches the real coding of the text files. A coding directive is only informative, it does not set the coding. I'm pretty sure, you problem comes from this. There is a mismatch somewhere, you are not aware of. Removing ascii chars is certainly not a valuable solution. It must work. If your are working properly, it can not, not work. Frome a linguistic point of view, the web has informed me Creole (*all the Creoles*) can be composed with the iso-8859-1 coding. That means, iso-8859-1, cp1252 and all Unicode coding variants are possible coding directives. jmf From ericsnowcurrently at gmail.com Mon Sep 12 10:44:01 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Mon, 12 Sep 2011 08:44:01 -0600 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 1:49 AM, Alec Taylor wrote: > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? Perhaps try "The Unicode Hammer". http://code.activestate.com/recipes/251871/ -eric > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > From wxjmfauth at gmail.com Mon Sep 12 10:47:00 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Mon, 12 Sep 2011 07:47:00 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> On 12 sep, 10:49, Steven D'Aprano wrote: > > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > This is absurd and a complete non sense. The purpose of a coding directive is to inform the engine, which is processing a text file, about the "language" it has to speak. Can be a html, py or tex file. If you have problem, it's probably a mismatch between your coding directive and the real coding of the file. Typical case: ascii/utf-8 without signature. jmf From bestenborstel at gmail.com Mon Sep 12 10:51:45 2011 From: bestenborstel at gmail.com (G.) Date: Mon, 12 Sep 2011 07:51:45 -0700 (PDT) Subject: Could you please give me some advise on this piece of code? Message-ID: Dear all, I am a python newbie, but I intend to program a python script that communicates with Labview via a UDP socket. I managed to send LabView strings, but the other way around is not working. The code seems to stop working while in the first while loop. I can see the word "test" being print out. When I start LabView UDP_sender.vi it is supposed to send a string back to python, but sometimes it ends with an error saying the port and the ip is already in usage. Do I have to start first LabView or the python scrip when listening to LabView, please? It would be great if you could have a look on my code and could maybe see why it does nothing after "print test", please. Thank you very much. Kind regards, G. # To change this template, choose Tools | Templates # and open the template in the editor. __author__="User" __date__ ="$11.09.2011 19:34:03$" if __name__ == "__main__": print "Das ist ein Test" import socket import time #Define global variables for UDP_IP and UDP_Port, needs to be changed for PETRA-3 #global UDP_IP UDP_IP="127.0.0.1" print "UDP_IP is", UDP_IP #global UDP_PORT UDP_PORT=21312 print "UDP_PORT is", UDP_PORT def openUDPSocket(UDP_IP,UDP_PORT): #UDP_IP="127.0.0.1" #UDP_PORT=5005 print "Creating socket ..." sock=socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM ) # UDP sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #sock.setblocking(0) #sock.bind((UDP_IP,UDP_PORT)) #sock.listen(1) print "Done." return sock def fastPump(sock): # Start pumping and return MESSAGE="pumpfast" # print "UDP target IP:", UDP_IP # print "UDP target port:", UDP_PORT # print "message:", MESSAGE sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) def slowPump(sock): MESSAGE="pumpslow" sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) pumpsocketUDP=openUDPSocket(UDP_IP,UDP_PORT) # Receive messages counter_while_loop=0 print "test" while counter_while_loop < 3: data,addr = pumpsocketUDP.recvfrom(1024) print "test" if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" counter_while_loop=counter_while_loop+1 counter_while_loop=0 while counter_while_loop < 3: fastPump(pumpsocketUDP) time.sleep(5) slowPump(pumpsocketUDP) time.sleep(3) counter_while_loop=counter_while_loop+1 print "Counter_while_loop", counter_while_loop # Close socket pumpsocketUDP.close() From w.brenig at tu-bs.de Mon Sep 12 11:39:35 2011 From: w.brenig at tu-bs.de (Wolfram Brenig) Date: Mon, 12 Sep 2011 17:39:35 +0200 Subject: ipython -wthread vs. ipython -pylab Message-ID: <9d6n9cFs53U1@mid.dfncis.de> Hi, I have a problem with the ipython shell: frequently, within one session I would like to do 2D plotting, using matplotlib, as well as 3D visualization using mayavi The man page for ipython, matplotlib, and mayavi tell me, that I must invoke ipython with ipython -wthread for mayavi and ipython -pylab for matplotlib in order to avoid blocking (which indeed happens if I don't use those options). However, ipython's manpage also states, that only one of -wthread or -pylab can be given? Does that imply I have to get out of the shell each time I want to switch from matplotlib to mayavi usage? Most likely no. But what should I do? Thanks for your help Wolfram From matthias.huening at fu-berlin.de Mon Sep 12 11:42:56 2011 From: matthias.huening at fu-berlin.de (Matthias Huening) Date: Mon, 12 Sep 2011 17:42:56 +0200 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: <9d6nk0FutiU1@mid.uni-berlin.de> Am 12.09.2011 16:03, schrieb John Reid: > > I don't have much experience writing web sites or applications. Can > anyone recommend a python framework that will allow me to easily write a > few pages? You want a simple framework? Try Bottle: http://bottlepy.org/ Matthias From Phillip.M.Feldman at gmail.com Mon Sep 12 11:47:22 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Mon, 12 Sep 2011 08:47:22 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32449079.post@talk.nabble.com> Mark Dickinson-2 wrote: > > > This is a well-known trick: to divide 5 (unlabeled) balls amongst 3 > (labeled) boxes, you write down sequences of 5 o's and 2 x's, where > the o's represent the 5 balls and the 'x's represent dividers: > > ooxooxo -> [2, 2, 1] > xoooxoo -> [0, 3, 2] > > And 'combinations(7, 2)' yields successively all the possible > different placements for the 2 dividers in the 7 symbols. > > > This question seems to come up often enough (without the box size > limit twist) that maybe it would be useful to include something like > this recipe in the itertool documentation. > > > For getting this into itertools, I'd suggest opening a feature request > on bugs.python.org and assigning it to Raymond Hettinger. > > -- > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > > You are correct--the case without capacity limits can be handled using the existing machinery in `itertools`. BTW--That trick with the dividers is discussed on page 38 of William Feller's classic text, "An Introduction to Probability Theory and Its Applications". As per your suggestion, I have opened a feature request and assigned it to Raymond. Thanks! -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32449079.html Sent from the Python - python-list mailing list archive at Nabble.com. From miki.tebeka at gmail.com Mon Sep 12 12:48:42 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 09:48:42 -0700 (PDT) Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: I personally like CherryPy. But it all depends on your needs and style. I suggest you play with some of the packages and select one that you feel best with. From miki.tebeka at gmail.com Mon Sep 12 12:48:42 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 09:48:42 -0700 (PDT) Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: I personally like CherryPy. But it all depends on your needs and style. I suggest you play with some of the packages and select one that you feel best with. From ian.g.kelly at gmail.com Mon Sep 12 12:55:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 10:55:14 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Sun, Sep 11, 2011 at 6:45 PM, Terry Reedy wrote: > whereas, you are right, it breaks it noisily in the body. So Ian's claim > that StopIteration must be caught to avoid silent termination is not true. > Thanks for pointing out what I saw but did not cognize the full implication > of before. A better exception and an error message with an explaination > might still be a good idea, though. But you can't write the function under the assumption that it will only be called from the function body. The following is a slight reorganization of your example that does exhibit the problem: for title in map(fix_title, ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']): print(title) Output: amazing a Hell of a Fight Note that at first glance, my example would appear to be functionally equivalent to yours -- I've merely pulled the fix_title call out of the loop body and into the iterator. But actually they produce different results because fix_title misbehaves by not catching the StopIteration. Cheers, Ian From ian.g.kelly at gmail.com Mon Sep 12 12:58:05 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 10:58:05 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:55 AM, Ian Kelly wrote: > But you can't write the function under the assumption that it will > only be called from the function body. ?The following is a slight > reorganization of your example that does exhibit the problem: s/function body/for-loop body/ From ian.g.kelly at gmail.com Mon Sep 12 13:41:06 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 11:41:06 -0600 Subject: Could you please give me some advise on this piece of code? In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 8:51 AM, G. wrote: > When I start LabView UDP_sender.vi it is supposed to send a string > back to python, but sometimes it ends with an error saying the port > and the ip is already in usage. Do I have to start first LabView or > the python scrip when listening to LabView, please? If LabView is sending, then the Python script should already be receiving, so start Python first. > def openUDPSocket(UDP_IP,UDP_PORT): > ? ?#UDP_IP="127.0.0.1" > ? ?#UDP_PORT=5005 > ? ?print "Creating socket ..." > ? ?sock=socket.socket( socket.AF_INET, # Internet > ? ? ? ? ? ? ? ? ? ? ? ?socket.SOCK_DGRAM ) # UDP I don't think this is sufficient to create a UDP socket. To be safe, you should specify the protocol as well: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) > ? ?#sock.bind((UDP_IP,UDP_PORT)) Your bind call is commented out, which means that your socket will be bound to an arbitrary port selected by the OS. This will make it hard for LabView to send it messages, since it won't know what port to use. Also, you appear to be using the same address and port for both endpoints. The UDP socket in Python and the UDP socket in LabView should be bound to two separate ports. This is probably why you were getting the "port already in use" error, before you commented this out. > ? ?#sock.listen(1) You don't need this at all. listen() is for TCP sockets. > def fastPump(sock): > ? ?# Start pumping and return > ? ?MESSAGE="pumpfast" > > ? # print "UDP target IP:", UDP_IP > ? # print "UDP target port:", UDP_PORT > ? # print "message:", MESSAGE > > ? ?sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) The IP and port here should be that of the destination, i.e. the address of the LabView socket. > counter_while_loop=0 > print "test" > while counter_while_loop < 3: > ? ? ? ?data,addr = pumpsocketUDP.recvfrom(1024) > ? ? ? ?print "test" > ? ? ? ?if not data: > ? ? ? ? ? ? ? ?print "Client has exited!" > ? ? ? ? ? ? ? ?break > ? ? ? ?else: > ? ? ? ? ? ? ? ?print "\nReceived message '", data,"'" > ? ? ? ?counter_while_loop=counter_while_loop+1 You should really use a for loop here: for counter in range(3): data, addr = pumpsocketUPD.recvfrom(1024) print "Received message %r" % data Note that if data is empty, it means that it received an empty message, not that the client has exited. It may be that you're having the LabView client send an empty message when it exits, but this does not happen automatically. HTH, Ian From pruebauno at latinmail.com Mon Sep 12 13:42:35 2011 From: pruebauno at latinmail.com (nn) Date: Mon, 12 Sep 2011 10:42:35 -0700 (PDT) Subject: convert time References: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 11, 1:00?am, Steven D'Aprano wrote: > ???? wrote: > > how can i convert "Dec 11" into ?2011-12? > > if my_str == "Dec 11": > ? ? return 1999 ?# 2011 - 12 > > Does that help? > > But seriously... 2011-12 is not a proper date, so the simplest way is > probably something like this: > > def convert(date_str): > ? ? month, short_year = date_str.split() > ? ? if len(short_year) == 4: > ? ? ? ? year = short_year > ? ? else: > ? ? ? ? year = '20' + short_year > ? ? months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() > ? ? month = months.index(month) + 1 > ? ? return year + '-' + str(month) > > Otherwise see the time and datetime modules: > > http://docs.python.org/library/time.htmlhttp://docs.python.org/library/datetime.html > > -- > Steven Just a small comment that you can get "months" by doing: from calendar import month_abbr months = list(month_abbr) From stefaan.himpe at gmail.com Mon Sep 12 14:37:49 2011 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Mon, 12 Sep 2011 20:37:49 +0200 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: <1ksbq.2549$ex3.1130@newsfe30.ams2> The simplest one to learn is web2py http://www.web2py.com No configuration needed, just unpack and get started. It also has very good documentation and tons of little examples to get things done. The other options you mentioned are good too :) From tjreedy at udel.edu Mon Sep 12 15:24:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 15:24:14 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/12/2011 9:06 AM, Duncan Booth wrote: > Terry Reedy wrote: > >> The statement containing the explicit next(items) call can optionally be >> wrapped to explicitly handle the case of an empty iterable in whatever >> manner is desired. >> >> try: >> >> except StopIteration: >> raise ValueError("iterable cannot be empty") >> >> > Alternatively, if all you want is for an empty iterable to do nothing, To do nothing, just pass above. If the function does nothing, it returns None. In the fix_title function, it should return '', not None. > you could write it like this: > > items = iter(iterable) > for first in items: > > break I could, but I doubt I would ;-). Try...except StopIteration: pass is more explicit and less roundabout. > for item in items: > > > However, the issue I have with any of this pulling the first element out of > the loop is that if you want special processing for the first element you > are likely to also want it for the last, Likely? I would say occasionally. Sentences have first words; file have headers. Special processing for last items is only an issue if it *replaces* the normal processing, rather than following the normal processing. > and if it is a single item you need > to process that item with both bits of special code. I don't see how that works > unless you have all elements within the single loop and test for first/last. Like so, with tests: def first_last_special(iterable): print("\nIterable is",repr(iterable)) items = iter(iterable) try: first = next(items) except StopIteration: print('Nothing'); return print(first, 'is the first item') try: current = next(items) except StopIteration: current = first else: for item in items: print(current, 'is a middle item') current = item print(current, 'is the last item') first_last_special('') first_last_special('1') first_last_special('12') first_last_special('123') first_last_special('12345') -- Terry Jan Reedy From georgeryoung at gmail.com Mon Sep 12 15:49:51 2011 From: georgeryoung at gmail.com (gry) Date: Mon, 12 Sep 2011 12:49:51 -0700 (PDT) Subject: Python: Deleting specific words from a file. References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> On Sep 9, 2:04?am, Terry Reedy wrote: > On 9/8/2011 9:09 PM, papu wrote: > > > > > Hello, I have a data file (un-structed messy file) from which I have > > to scrub specific list of words (delete words). > > > Here is what I am doing but with no result: > > > infile = "messy_data_file.txt" > > outfile = "cleaned_file.txt" > > > delete_list = ["word_1","word_2"....,"word_n"] > > new_file = [] > > fin=open(infile,"") > > fout = open(outfile,"w+") > > for line in fin: > > ? ? ?for word in delete_list: > > ? ? ? ? ?line.replace(word, "") > > ? ? ?fout.write(line) > > fin.close() > > fout.close() > > If you have very many words (and you will need all possible forms of > each word if you do exact matches), The following (untested and > incomplete) should run faster. > > delete_set = {"word_1","word_2"....,"word_n"} > ... > for line in fin: > ? ? ?for word in line.split() > ? ? ? ? ?if word not in delete_set: > ? ? ? ? ? ? ?fout.write(word) # also write space and nl. > > Depending on what your file is like, you might be better with > re.split('(\W+)', line). An example from the manual: > ?>>> re.split('(\W+)', '...words, words...') > ['', '...', 'words', ', ', 'words', '...', ''] > > so all non-word separator sequences are preserved and written back out > (as they will not match delete set). > > -- > Terry Jan Reedy re.sub is handy too: import re delete_list=('the','rain','in','spain') regex = re.compile('\W' + '|'.join(delete_list) + '\W') infile='messy' with open(infile, 'r') as f: for l in f: print regex.sub('', l) From python at mrabarnett.plus.com Mon Sep 12 16:42:21 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 12 Sep 2011 21:42:21 +0100 Subject: Python: Deleting specific words from a file. In-Reply-To: <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> Message-ID: <4E6E6EAD.5040306@mrabarnett.plus.com> On 12/09/2011 20:49, gry wrote: > On Sep 9, 2:04 am, Terry Reedy wrote: >> On 9/8/2011 9:09 PM, papu wrote: >> >> >> >>> Hello, I have a data file (un-structed messy file) from which I have >>> to scrub specific list of words (delete words). >> >>> Here is what I am doing but with no result: >> >>> infile = "messy_data_file.txt" >>> outfile = "cleaned_file.txt" >> >>> delete_list = ["word_1","word_2"....,"word_n"] >>> new_file = [] >>> fin=open(infile,"") >>> fout = open(outfile,"w+") >>> for line in fin: >>> for word in delete_list: >>> line.replace(word, "") >>> fout.write(line) >>> fin.close() >>> fout.close() >> >> If you have very many words (and you will need all possible forms of >> each word if you do exact matches), The following (untested and >> incomplete) should run faster. >> >> delete_set = {"word_1","word_2"....,"word_n"} >> ... >> for line in fin: >> for word in line.split() >> if word not in delete_set: >> fout.write(word) # also write space and nl. >> >> Depending on what your file is like, you might be better with >> re.split('(\W+)', line). An example from the manual: >> >>> re.split('(\W+)', '...words, words...') >> ['', '...', 'words', ', ', 'words', '...', ''] >> >> so all non-word separator sequences are preserved and written back out >> (as they will not match delete set). >> >> -- >> Terry Jan Reedy > > re.sub is handy too: > import re > delete_list=('the','rain','in','spain') > regex = re.compile('\W' + '|'.join(delete_list) + '\W') You need parentheses around the words (I'm using non-capturing parentheses): regex = re.compile(r'\W(?:' + '|'.join(delete_list) + r')\W') otherwise you'd get: '\Wthe|rain|in|spain\W'. Even better is the word-boundary, in case there's no previous or next character: regex = re.compile(r'\b(?:' + '|'.join(delete_list) + r')\b') Raw string literals are recommended for regexes. > infile='messy' > with open(infile, 'r') as f: > for l in f: > print regex.sub('', l) From tjreedy at udel.edu Mon Sep 12 16:51:01 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 16:51:01 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/12/2011 12:55 PM, Ian Kelly wrote: > On Sun, Sep 11, 2011 at 6:45 PM, Terry Reedy wrote: >> whereas, you are right, it breaks it noisily in the body. So Ian's claim >> that StopIteration must be caught to avoid silent termination is not true. >> Thanks for pointing out what I saw but did not cognize the full implication >> of before. A better exception and an error message with an explaination >> might still be a good idea, though. > > But you can't write the function under the assumption that it will > only be called from the function body. Sigh. You are right. > The following is a slight > reorganization of your example that does exhibit the problem: > > for title in map(fix_title, ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']): > print(title) > > Output: > amazing > a Hell of a Fight > > Note that at first glance, my example would appear to be functionally > equivalent to yours -- I've merely pulled the fix_title call out of > the loop body and into the iterator. But actually they produce > different results because fix_title misbehaves by not catching the > StopIteration. You are right, non-iterators should not raise or pass on StopIteration. There are actually several reasons. 1. The manual defined StopIteration as meaning '[I have] no more values [to give you]'. This is only meaningful coming from an iterator. 2. Your particular point is that StopIteration is (almost) unique in being sometimes, but only sometimes, caught by the interpreter, rather than just by user except clauses. AttributeError is another, which has occasionally caused its own problems. But we cannot stop raising AttributeError while we can always catch StopIteration for explicit next() (and should outside of iterators). 3. In the case of grabbing the first item from an iterator, no first item is a boundary case for the expected, legal type of input. I believe boundary cases should be included in function specifications. While there may be a couple of choices as to response, that is much less than infinity. For fix_title, the choices are ValueError or ''. Any other return would be an error unless explicitly given in the specs. So the boundary case should be included in the test suite to exclude any other random response. 4. StopIteration is an artifact of the choice of implementation. Pulling the first item out before the loop is an alternative to a flag and testing within the loop. Such an implementation detail should not leak into the user's view of the function as an abstraction. If fix_title were a generator function whose instances yielded fixed title words one at a time, then the bare next() would be correct (as you noted). But it is not, and the difference is important, more important than having 'minimal clean code'. Thank you for persisting until I saw that in this context. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 12 16:53:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 16:53:24 -0400 Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/12/2011 7:40 AM, Roy Smith wrote: > In article<4e6dc66e$0$29986$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >>> mylist = [0]*12345678901234 >> [...] >>> Apart from "Then don't do that!", is there anything I can do to prevent >>> this sort of thing in the future? Like instruct Python not to request more >>> memory than my PC has? >> >> >> For anyone who may care, I can report that ulimit under Linux will help with >> this situation. >> [...] >> Does anyone else think it would be useful for Python's memory manager to >> enforce user-settable limits? > > Not me. You've already discovered that ulimit does exactly what you > want. Why would be gained by having Python duplicate this functionality? Having it on Windows. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 12 17:04:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 17:04:50 -0400 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: On 9/12/2011 12:34 AM, Juan Pablo Romero M?ndez wrote: > Hello, > > What do you guys think about adding a method "to_json" to dictionaries > and sequence types? Perhaps through a module import? Negative. If this were added, why not to_yaml, to_marshal, to_pickle, to_zip, and so on. Better to have each storage or transfer class handle its own instance creation. The one to_x method that every class should have is to_string, which is spelled __str__ and inherited from object. -- Terry Jan Reedy From rhodri at wildebst.demon.co.uk Mon Sep 12 17:39:41 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 12 Sep 2011 22:39:41 +0100 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> Message-ID: On Mon, 12 Sep 2011 15:47:00 +0100, jmfauth wrote: > On 12 sep, 10:49, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> >> Even with a source code encoding, you will probably have problems with >> source files including \xe2 and other "bad" chars. Unless they happen to >> fall inside a quoted string literal, I would expect to get a >> SyntaxError. >> > > This is absurd and a complete non sense. The purpose > of a coding directive is to inform the engine, which > is processing a text file, about the "language" it > has to speak. Can be a html, py or tex file. > If you have problem, it's probably a mismatch between > your coding directive and the real coding of the > file. Typical case: ascii/utf-8 without signature. Now read what Steven wrote again. The issue is that the program contains characters that are syntactically illegal. The "engine" can be perfectly correctly translating a character as a smart quote or a non breaking space or an e-umlaut or whatever, but that doesn't make the character legal! -- Rhodri James *-* Wildebeest Herder to the Masses From rantingrick at gmail.com Mon Sep 12 18:04:15 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 12 Sep 2011 15:04:15 -0700 (PDT) Subject: PyWart: Itertools module needs attention Message-ID: ############################################################ # Quote # ############################################################ # The itertools module is great HOWEVER i believe most # # people are recreating the functionalities due to the # # insanely cryptic and/or missing examples from each # # method # ############################################################ py> print itertools.chain.__doc__ chain(*iterables) --> chain object Return a chain object whose .next() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted. ############################################################ # Quote # ############################################################ # Okay not TOO bad however this simple example would # # suffice: # ############################################################ py> list(itertools.chain([1,2], [3,[4,5],6])) [1, 2, 3, [4, 5], 6] ############################################################ # Quote # ############################################################ # Same for these... # ############################################################ py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " hello word "))) 'hello word ' py> ''.join(list(itertools.takewhile(lambda x:x==" ", " hello word "))) ' ' py> print itertools.compress.__doc__ compress(data, selectors) --> iterator over selected data Return data elements corresponding to true selector elements. Forms a shorter iterator from selected data elements using the selectors to choose the data elements. ############################################################ # Quote # ############################################################ # WTF! Would you like to define a Python "selector". Could # # it be that we should be using "selector function" or # # "predicate function" instead? # ############################################################ From nstinemates at gmail.com Mon Sep 12 18:25:49 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Mon, 12 Sep 2011 22:25:49 +0000 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:04 PM, rantingrick wrote: > > ############################################################ > # Quote # > ############################################################ > # The itertools module is great HOWEVER i believe most # > # people are recreating the functionalities due to the # > # insanely cryptic and/or missing examples from each # > # method # > ############################################################ > > py> print itertools.chain.__doc__ > chain(*iterables) --> chain object > Return a chain object whose .next() method returns elements from the > first iterable until it is exhausted, then elements from the next > iterable, until all of the iterables are exhausted. > > ############################################################ > # Quote # > ############################################################ > # Okay not TOO bad however this simple example would # > # suffice: # > ############################################################ > > py> list(itertools.chain([1,2], [3,[4,5],6])) > [1, 2, 3, [4, 5], 6] > > ############################################################ > # Quote # > ############################################################ > # Same for these... # > ############################################################ > > py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " hello > word "))) > 'hello word ' > py> ''.join(list(itertools.takewhile(lambda x:x==" ", " hello > word "))) > ' ' > py> print itertools.compress.__doc__ > compress(data, selectors) --> iterator over selected data > Return data elements corresponding to true selector elements. > Forms a shorter iterator from selected data elements using the > selectors to choose the data elements. > > ############################################################ > # Quote # > ############################################################ > # WTF! Would you like to define a Python "selector". Could # > # it be that we should be using "selector function" or # > # "predicate function" instead? # > ############################################################ > -- > http://mail.python.org/mailman/listinfo/python-list I'm honestly missing the point of this mail. Can you elaborate? -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Mon Sep 12 18:49:49 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 00:49:49 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: 2011/9/12 Alec Taylor : > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > It would obviously help to see the content of the line mentioned in the traceback (and probably its context); however, that value seems to correspond with ? in some European encodings, in which case it would probably be part of some quoted unicode/string literal. (at least in python 2, in python3 it could also be a name of an object in python code, the traceback seems to be the same for both cases.) cf. >>> print '\xe2'.decode("iso-8859-1") ? # and likewise for iso-8859-... 1,2,3,4; 9, 10, 14, 15, 16, some windows- encodings etc. Possibly (as previouslz suggested) adding the encoding information like iso-8859-1 or windows-1252 or others depending on other data etc. at the top of the source file might fix the error. Which would be certainly preferable to throwing all non ascii data away. Zou would add e.g. # -*- coding: iso-8859-1 -*- as the first or second line of the file. hth, vbr From ethan at stoneleaf.us Mon Sep 12 19:29:07 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 12 Sep 2011 16:29:07 -0700 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: <4E6E95C3.7010708@stoneleaf.us> Nick Stinemates wrote: > I'm honestly missing the point of this mail. rantingrick is a well-known troll, and doesn't need to have a point. Please do not feed the troll. ~Ethan~ From 1248283536 at qq.com Mon Sep 12 23:08:57 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 11:08:57 +0800 Subject: =?gbk?B?u9i4tKO6IHN0cmFuZyB0aGluZzo=?= Message-ID: i change open into open1,it's ok now import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open1,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] but i want "open" to be my data field,not open1 to be my field , how can i do? ------------------ ???? ------------------ ???: "Chris Angelico"; ????: 2011?9?6?(???) ??4:22 ???: "python-list"; ??: Re: strang thing: 2011/9/6 ???? <1248283536 at qq.com>: > file = open(filename,'r') > when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Mon Sep 12 23:12:03 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 11:12:03 +0800 Subject: =?gbk?B?u9i4tKO6IHN0cmFuZyB0aGluZzo=?= Message-ID: i change open into open1,it's ok now import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open1,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] but i want "open" to be my data field,not open1 to be my field , how can i do? ------------------ ???? ------------------ ???: "Chris Angelico"; ????: 2011?9?6?(???) ??4:22 ???: "python-list"; ??: Re: strang thing: 2011/9/6 ???? <1248283536 at qq.com>: > file = open(filename,'r') > when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From chunuan723 at gmail.com Mon Sep 12 23:15:10 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 12 Sep 2011 20:15:10 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <14aa0131-2040-456d-9218-0200c968d166@u17g2000prc.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on. From steve+comp.lang.python at pearwood.info Mon Sep 12 23:28:33 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 13 Sep 2011 13:28:33 +1000 Subject: strang thing: References: Message-ID: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> (I sent this reply a week ago, but it seems to have disappeared. So trying again.) On Tue, 6 Sep 2011 06:18 pm ???? wrote: > when i ?add ? ?(date,open,high,low,close,vol,adjclose) = (row[0], row[1], > row[2], row[3],row[4], row[5], row[6]) change the code into Here you define a new variable called "open", which has the value of row[1]. This shadows (hides) the built-in function also called "open", so later when you do this: > ? ? file = open(filename,'r') > TypeError: 'str' object is not callable Python uses your string variable "open" instead of the built-in function. The best solution is to avoid using the name "open", instead call it "open_" (underscore at the end is the usual convention to avoid shadowing built-ins). Or "open_value" or any other appropriate name. Another solution is to save a reference to the open built-in first: my_open = open open = "something" file = my_open("filename", "r") -- Steven From rosuav at gmail.com Mon Sep 12 23:42:56 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 13 Sep 2011 13:42:56 +1000 Subject: strang thing: In-Reply-To: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Sep 13, 2011 at 1:28 PM, Steven D'Aprano wrote: > The best solution is to avoid using the name "open", instead call it "open_" > (underscore at the end is the usual convention to avoid shadowing > built-ins). Or "open_value" or any other appropriate name. > This is why every good programmer keeps a thesaurus handy. I just now had a "concept collision" on the word 'cancel', and did a quick search to come up with 'annul' as an alternative. Although in this case I didn't search my thesaurus, I actually looked for Magic: The Gathering cards... yeah, I'm a nerd, aren't you? :) There's lots of synonyms for open, and it's entirely possible that one will work. Otherwise, Steven's other solution works just fine too, and you can go humorous with that too: sesame = open open = "something" file = sesame("filename", "r") ChrisA From anbumani923 at gmail.com Tue Sep 13 00:12:39 2011 From: anbumani923 at gmail.com (anbu) Date: Mon, 12 Sep 2011 21:12:39 -0700 (PDT) Subject: WANTED FRESHER IT,CSC,CIVIL,MECH Message-ID: http://123maza.com/65/cute540/ From sillyousu at gmail.com Tue Sep 13 00:20:54 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 12 Sep 2011 21:20:54 -0700 (PDT) Subject: =?UTF-8?Q?Should_a_beginner_do_some_coding_excises=3F_How_can_I_?= =?UTF-8?Q?find_the_sources=EF=BC=9F?= Message-ID: I'm reading "Learning Python"? Chinese version?. Before I go through the whole book, I want to do some excises matching each charter. Any tips? Any better advice? From amitatgroups at gmail.com Tue Sep 13 00:26:48 2011 From: amitatgroups at gmail.com (Amit Jain) Date: Mon, 12 Sep 2011 21:26:48 -0700 (PDT) Subject: Default Admin user on weblogic domain deleted after executing create command using WLST Message-ID: Hello All, we observed that user exactly deleted when 'create' cmd is executed: filestore = create("wlstProperties.getProperty(fileStoreName)", "FileStore") jmsServer = create("AUAJMSServer", "JMSServer") ... .. etc. http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/1927322accdb6e6e/223e1c7cd208a86c Please suggestion... regards, Amit J. From jabba.laci at gmail.com Tue Sep 13 00:33:22 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Tue, 13 Sep 2011 00:33:22 -0400 Subject: update all python packages on Debian/Ubuntu Message-ID: Hi, I use Ubuntu and the Python packages on my system were either installed with (1) apt-get, or with (2) pip. Since the number of python packages in the Ubuntu repositories is limited, I had to install several packages with pip. Now I want to upgrade the packages that were installed with pip (and only those packages). I can collect the list of python packages: (pip freeze | cut -d = -f 1 | grep -v FIXME | xargs echo | tr ' ' '\n' >list.txt) 2>/dev/null However, if I update every package in list.txt with "pip install -U", it will also update the ones that were installed with apt-get. Since apt-get builds a database with the installed files, I'm sure it won't like that pip replaces those files. I didn't try it yet but I'm afraid it would mess up the system. So, how to upgrade the python packages correctly? Thanks, Laszlo From memilanuk at gmail.com Tue Sep 13 01:14:02 2011 From: memilanuk at gmail.com (memilanuk) Date: Mon, 12 Sep 2011 22:14:02 -0700 Subject: =?UTF-8?B?UmU6IFNob3VsZCBhIGJlZ2lubmVyIGRvIHNvbWUgY29kaW5nIGV4Y2k=?= =?UTF-8?B?c2VzPyBIb3cgY2FuIEkgZmluZCB0aGUgc291cmNlc++8nw==?= In-Reply-To: References: Message-ID: On 09/12/2011 09:20 PM, sillyou su wrote: > I'm reading "Learning Python"? Chinese version?. Before I go through > the whole book, I want to do some excises matching each charter. > Any tips? Any better advice? > For the code examples, have you tried looking up the home page for the book? Google for 'oreilly learning python' and find the correct edition that you have. If its the 4th ed (current), you should end up on a page like this: http://shop.oreilly.com/product/9780596158071.do Down in the right hand side-bar, there should be a menu 'Essential Links' and one of the options is 'Download code' or something along those lines. The link should take you to a zip file with all the code examples in the book. As far as practice exercises... maybe something like codingbat.com/python would be helpful. Its not related to the book at all, and doesn't go nearly as in depth... but its kind of neat to play with and see how your code works when someone else is grading it! (at least for me). HTH, Monte From data.2 at rediff.com Tue Sep 13 01:24:49 2011 From: data.2 at rediff.com (gaurav) Date: Mon, 12 Sep 2011 22:24:49 -0700 (PDT) Subject: Get careers in Management work. Message-ID: <5fd4f6a9-8404-4bda-a484-12bba1aefdc2@z26g2000pre.googlegroups.com> Wide ranges of careers opportunity. Management careers. http://rojgars1.webs.com/hrm.htm http://topcareer.webs.com/qualitymanagement.htm HRM, PM, marketing manager jobs and accounts jobs move to your next career start earning with manager level. http://todayvacancy.blogspot.com/2011/07/account-assistant.html http://freshersemployment.blogspot.com/2011/07/finance-management.html High-quality careers. All types of Management careers. http://sites.google.com/site/jobinmanagement/operation-management-jobs From wuwei23 at gmail.com Tue Sep 13 02:56:30 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 12 Sep 2011 23:56:30 -0700 (PDT) Subject: using python in web applications References: Message-ID: <775ad552-1452-4b32-bf93-024c6d3761ea@u6g2000prc.googlegroups.com> On Sep 10, 1:54 pm, "Littlefield, Tyler" wrote: > I'm not feeling particularly masochistic, so I do not want to develop > this project in PHP; essentially I'm looking to build a web-based MMO. Google have been promoting the use of appengine along with HTML5 & JS to produce games. One advantage of using GAE to host the server is it takes care of the scaling for you. I found these presentations fascinating: http://cc-2011-html5-games.appspot.com/#1 http://io-2011-html5-games-hr.appspot.com/#1 This article covers the process in a little more depth: http://clouddbs.blogspot.com/2011/02/how-to-write-html5-game-in-30-days-with.html Google are also aggregating platform-specific info here: http://code.google.com/games Hope this helps (and let us know when you have something to show off!) From j.reid at mail.cryst.bbk.ac.uk Tue Sep 13 03:30:42 2011 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Tue, 13 Sep 2011 08:30:42 +0100 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: <1ksbq.2549$ex3.1130@newsfe30.ams2> References: <1ksbq.2549$ex3.1130@newsfe30.ams2> Message-ID: On 12/09/11 19:37, Stefaan Himpe wrote: > The simplest one to learn is web2py http://www.web2py.com > No configuration needed, just unpack and get started. > It also has very good documentation and tons of little examples to get > things done. > > The other options you mentioned are good too :) > OK I've had a look at bottle, cherrypy and web2py and they look fairly straightforward. I'll check out some more and see where I get to. Thanks for the tips, John. From limodou at gmail.com Tue Sep 13 03:45:35 2011 From: limodou at gmail.com (limodou) Date: Tue, 13 Sep 2011 15:45:35 +0800 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: <1ksbq.2549$ex3.1130@newsfe30.ams2> Message-ID: On Tue, Sep 13, 2011 at 3:30 PM, John Reid wrote: > On 12/09/11 19:37, Stefaan Himpe wrote: >> >> The simplest one to learn is web2py http://www.web2py.com >> No configuration needed, just unpack and get started. >> It also has very good documentation and tons of little examples to get >> things done. >> >> The other options you mentioned are good too :) >> > > OK I've had a look at bottle, cherrypy and web2py and they look fairly > straightforward. I'll check out some more and see where I get to. Thanks for > the tips, > John. > maybe you can also try out uliweb. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ UliWeb <>: http://code.google.com/p/uliweb/ My Blog: http://hi.baidu.com/limodou From wxjmfauth at gmail.com Tue Sep 13 03:49:17 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 13 Sep 2011 00:49:17 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> Message-ID: <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> On 12 sep, 23:39, "Rhodri James" wrote: > Now read what Steven wrote again. ?The issue is that the program contains ? > characters that are syntactically illegal. ?The "engine" can be perfectly ? > correctly translating a character as a smart quote or a non breaking space ? > or an e-umlaut or whatever, but that doesn't make the character legal! > Yes, you are right. I did not understand in that way. However, a small correction/precision. Illegal character do not exit. One can "only" have an ill-formed encoded code points or an illegal encoded code point representing a character/glyph. Basically, in the present case. The issue is most probably a mismatch between the coding directive and the real coding, with "no coding directive" == 'ascii'. jmf From yongyingwen at yahoo.com.cn Tue Sep 13 04:13:01 2011 From: yongyingwen at yahoo.com.cn (fashion t shirts seller) Date: Tue, 13 Sep 2011 01:13:01 -0700 (PDT) Subject: Michael Jordan 23. Message-ID: <829dc097-43c4-4192-a631-0e949715499b@x32g2000prf.googlegroups.com> In addition to the expression of this athletes foot propulsion technology that they run very fast from the other major areas, including Air Jordan 2009, satin sheets and the rear panel of nba basketball shoes, said middle layer blown-glass is a unique movement in each shoes. The silk is inspired by the belief that People Michael Jordan in basketball is very similar to the art of personal http://www.cheap-nbabasketballshoes.com/defense to defend themselves in a sport of fencing. Sheets are used to remind the importance of the defensive players wore light clothing fencers irony. Hologram of a diamond shape to be included in the ankle support and insurance, leather, also used in the nba players http://www.cheap-nbabasketballshoes.com/shoes, so that it is not only a function of the courts, but Ye Hao looked at the court. Jordan brand sports shoes, which add an additional buffer to keep athletes safe and comfortable ankle. In order to fully understand this work into the design of http://www.cheap-nbabasketballshoes.com/sports shoes, a person must do a careful observation and analysis of every part of the shoes. For example, the end including the full range of models, which helps to increase the grip, the needle in the upper two rows and deliberately sewn three rows below it in order to reflect the famous Michael Jordan 23. http://www.cheap-nbabasketballshoes.com/ From steve+comp.lang.python at pearwood.info Tue Sep 13 04:15:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 13 Sep 2011 18:15:39 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> Message-ID: <4e6f112c$0$29997$c3e8da3$5496439d@news.astraweb.com> On Tue, 13 Sep 2011 05:49 pm jmfauth wrote: > On 12 sep, 23:39, "Rhodri James" wrote: > > >> Now read what Steven wrote again. ?The issue is that the program contains >> characters that are syntactically illegal. ?The "engine" can be perfectly >> correctly translating a character as a smart quote or a non breaking >> space or an e-umlaut or whatever, but that doesn't make the character >> legal! >> > > Yes, you are right. I did not understand in that way. > > However, a small correction/precision. Illegal character > do not exit. One can "only" have an ill-formed encoded code > points or an illegal encoded code point representing a > character/glyph. You are wrong there. There are many ASCII characters which are illegal in Python source code, at least outside of comments and string literals, and possibly even there. >>> code = "x = 1 + \b 2" # all ASCII characters >>> print(code) x = 1 + 2 >>> exec(code) Traceback (most recent call last): File "", line 1, in File "", line 1 x = 1 + 2 ^ SyntaxError: invalid syntax Now, imagine that somehow a \b ASCII backspace character somehow gets introduced into your source file. When you go to run the file, or import it, you will get a SyntaxError. Changing the encoding will not help. -- Steven From wxjmfauth at gmail.com Tue Sep 13 05:04:09 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 13 Sep 2011 02:04:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> <4e6f112c$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4a674dba-078b-4353-a6ae-01c205460e91@w12g2000yqa.googlegroups.com> On 13 sep, 10:15, Steven D'Aprano wrote: The intrinsic coding of the characters is one thing, The usage of bytes stream supposed to represent a text is one another thing, jmf From sillyousu at gmail.com Tue Sep 13 06:31:06 2011 From: sillyousu at gmail.com (sillyou su) Date: Tue, 13 Sep 2011 03:31:06 -0700 (PDT) Subject: =?UTF-8?Q?Re=3A_Should_a_beginner_do_some_coding_excises=3F_How_ca?= =?UTF-8?Q?n_I_find_the_sources=EF=BC=9F?= References: Message-ID: <1ef0994b-e274-420d-8889-e26556cc7b84@h32g2000prl.googlegroups.com> On Sep 13, 1:14?pm, memilanuk wrote: > On 09/12/2011 09:20 PM, sillyou su wrote: > > > I'm reading "Learning Python"? Chinese version?. Before I go through > > the whole book, I want to do some excises matching each charter. > > Any tips? Any better advice? > > For the code examples, have you tried looking up the home page for the > book? ?Google for 'oreilly learning python' and find the correct edition > that you have. > > If its the 4th ed (current), you should end up on a page like this: > > http://shop.oreilly.com/product/9780596158071.do > > Down in the right hand side-bar, there should be a menu 'Essential > Links' and one of the options is 'Download code' or something along > those lines. ?The link should take you to a zip file with all the code > examples in the book. > > As far as practice exercises... maybe something like > codingbat.com/python would be helpful. ?Its not related to the book at > all, and doesn't go nearly as in depth... but its kind of neat to play > with and see how your code works when someone else is grading it! (at > least for me). > > HTH, > > Monte codingbat.com/python! The website is really interesting. Thank you! From 1248283536 at qq.com Tue Sep 13 07:14:15 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 19:14:15 +0800 Subject: problem:import csv data Message-ID: import sqlite3 con = sqlite3.connect('/home/stock.db') cur = con.cursor() cur.execute('''CREATE TABLE quote (ticker TEXT,date TEXT, popen TEXT, high TEXT, low TEXT,vol TEXT,adjclose TEXT);''') i=/tmp/data.csv cur.execute('.separator "," ') cur.execute('.import %s quote' % i) con.commit() cur.close() con.close() the output is : cur.execute('.separator"," ') sqlite3.OperationalError: near ".": syntax error how to fix it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexander_naumov at opensuse.org Tue Sep 13 08:21:03 2011 From: alexander_naumov at opensuse.org (Alex Naumov) Date: Tue, 13 Sep 2011 14:21:03 +0200 Subject: send string to input of another process Message-ID: Hello everybody, I'm looking for some solution, maybe someone of you can help me. I call another process via os.system("process") and it waits for some input. I have to write a comment (for example, like using svn or git), and after that to close input (for example, like ":wq" using vim). How can I give/write this comment and put it in the input for next process (which start after)? Thanks a lot for your time and help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mimohammedimran41 at gmail.com Tue Sep 13 08:29:37 2011 From: mimohammedimran41 at gmail.com (mohammed imran) Date: Tue, 13 Sep 2011 05:29:37 -0700 (PDT) Subject: mohammedimran Message-ID: http://123maza.com/65/fun564/ From vacorama at gmail.com Tue Sep 13 08:31:59 2011 From: vacorama at gmail.com (ron) Date: Tue, 13 Sep 2011 05:31:59 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 12, 4:49?am, Steven D'Aprano wrote: > On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > > > I'm not sure what you are trying to say with the above code, but if it's > > the code that fails for you with the exception you posted, I would guess > > that the problem is in the "[more stuff here]" part, which likely contains > > a non-ASCII character. Note that you didn't declare the source file > > encoding above. Do as Gary told you. > > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > > I have come across this myself. While I haven't really investigated in great > detail, it appears to happen when copying and pasting code from a document > (usually HTML) which uses non-breaking spaces instead of \x20 space > characters. All it takes is just one to screw things up. > > -- > Steven Depending on the load, you can do something like: "".join([x for x in string if ord(x) < 128]) It's worked great for me in cleaning input on webapps where there's a lot of copy/paste from varied sources. From miki.tebeka at gmail.com Tue Sep 13 09:09:59 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 13 Sep 2011 06:09:59 -0700 (PDT) Subject: problem:import csv data In-Reply-To: References: Message-ID: <40eaa387-16b1-4100-8998-38e90a9f615e@glegroupsg2000goo.googlegroups.com> .separator (and .import) are not SQL commands but "sqlite3" commands. You can get the same effect with the following code: with open('/tmp/data.csv') as fo: reader = csv.reader(fo) cur.executemany('INSERT INTO quote VALUES (?, ?, ?, ?, ?, ?, ?)'), reader) HTH -- Miki Tebeka http://pythonwise.blogspot.com From miki.tebeka at gmail.com Tue Sep 13 09:09:59 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 13 Sep 2011 06:09:59 -0700 (PDT) Subject: problem:import csv data In-Reply-To: References: Message-ID: <40eaa387-16b1-4100-8998-38e90a9f615e@glegroupsg2000goo.googlegroups.com> .separator (and .import) are not SQL commands but "sqlite3" commands. You can get the same effect with the following code: with open('/tmp/data.csv') as fo: reader = csv.reader(fo) cur.executemany('INSERT INTO quote VALUES (?, ?, ?, ?, ?, ?, ?)'), reader) HTH -- Miki Tebeka http://pythonwise.blogspot.com From manodec25 at gmail.com Tue Sep 13 09:22:16 2011 From: manodec25 at gmail.com (mano mano) Date: Tue, 13 Sep 2011 06:22:16 -0700 (PDT) Subject: The Usenet newsgroup news:comp.lang.python ... Message-ID: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Mikael Lyngvig accurately summarizes comp.lang.python discussion of the technical merits of Tkinter, wxPython, and Python-bound JPI. Malcolm Tredinnick ............... http://123maza.com/48/doll789/ From pavlovevidence at gmail.com Tue Sep 13 09:31:52 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 Sep 2011 06:31:52 -0700 (PDT) Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4E5E2BCB.5090903@simplistix.co.uk> Message-ID: <7ae217be-3069-404a-8fcc-e45f4187f30c@glegroupsg2000goo.googlegroups.com> On Wednesday, August 31, 2011 5:49:24 AM UTC-7, Benjamin Kaplan wrote: > 32-bit or 64-bit Python? A 32-bit program will crash once memory hits > 2GB. A 64-bit program will just keep consuming RAM until your computer > starts thrashing. The problem isn't your program using more RAM than > you have, just more RAM than you have free. Last time I faced a > situation like this, I just decided it was better to stick to the > 32-bit program and let it crash if it got too big. On my 64-bit Linux system, I got a memory error in under a second, no thrashing. I have no swap. It's overrated. Carl Banks From vlastimil.brom at gmail.com Tue Sep 13 09:33:00 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 15:33:00 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/13 ron : > > Depending on the load, you can do something like: > > "".join([x for x in string if ord(x) < 128]) > > It's worked great for me in cleaning input on webapps where there's a > lot of copy/paste from varied sources. > -- > http://mail.python.org/mailman/listinfo/python-list > Well, for this kind of dirty "data cleaning" you may as well use e.g. >>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") u'text with non ASCII in between ...' >>> vbr From jon at jaggersoft.com Tue Sep 13 09:34:56 2011 From: jon at jaggersoft.com (Jon Jagger) Date: Tue, 13 Sep 2011 06:34:56 -0700 (PDT) Subject: ACCU conference call for proposals Message-ID: ACCU is a non-profit organisation run by software enthusiasts for software enthusiasts. ACCU warmly invites you to propose a session for this leading software development conference. Call for Proposals - ACCU 2012 April 24-28, 2012. Barcelo Oxford Hotel, Oxford, UK Submission website: https://www.conftool.pro/accu2012/ Submission deadline: 16th of October 2011 twitter: @accu2012 #accu2012 More details can be found here http://accu.org/index.php/conferences/accu_conference_2012/accu2012_Call_for_Papers The conference has always benefited from the strength of its programme. Please help us make 2012 another successful event. Jon Jagger Conference Chair From kushal.kumaran+python at gmail.com Tue Sep 13 10:01:41 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 13 Sep 2011 19:31:41 +0530 Subject: send string to input of another process In-Reply-To: References: Message-ID: On 13 Sep 2011 17:53, "Alex Naumov" wrote: > > Hello everybody, > > I'm looking for some solution, maybe someone of you can help me. > > I call another process via os.system("process") and it waits for some input. I have to write a comment (for example, like using svn or git), and after that to close input (for example, like ":wq" using vim). > How can I give/write this comment and put it in the input for next process (which start after)? > > Take a look at the subprocess module, especially the communicate method. Note that you will not be able to script screen-oriented programs like vim using this, unless it has some mode where you can drive it by piping commands on stdin. If you want to provide commit messages, I'm sure your vc system accepts those on the command line instead. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From saranyamathaiyan at gmail.com Tue Sep 13 10:52:13 2011 From: saranyamathaiyan at gmail.com (saranya saran) Date: Tue, 13 Sep 2011 07:52:13 -0700 (PDT) Subject: HI YOU WILL GET EARN MORE MONEY Message-ID: open this webpage you will get more ideas Webpages: http://123maza.com/65/tiger205/ From alec.taylor6 at gmail.com Tue Sep 13 11:02:05 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 14 Sep 2011 01:02:05 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hmm, nothing mentioned so far works for me... Here's a very small test case: >>> python -u "Convert to Creole.py" File "Convert to Creole.py", line 1 SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details >>> Exit Code: 1 Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") On Tue, Sep 13, 2011 at 11:33 PM, Vlastimil Brom wrote: > 2011/9/13 ron : >> >> Depending on the load, you can do something like: >> >> "".join([x for x in string if ord(x) < 128]) >> >> It's worked great for me in cleaning input on webapps where there's a >> lot of copy/paste from varied sources. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Well, for this kind of dirty "data cleaning" you may as well use e.g. > >>>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") > u'text ?with non ASCII in between ...' >>>> > > vbr > -- > http://mail.python.org/mailman/listinfo/python-list > From jpiitula at ling.helsinki.fi Tue Sep 13 11:29:03 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 13 Sep 2011 18:29:03 +0300 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: Alec Taylor writes: > Hmm, nothing mentioned so far works for me... > > Here's a very small test case: > > >>> python -u "Convert to Creole.py" > File "Convert to Creole.py", line 1 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 1, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > >>> Exit Code: 1 > > Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") The people who told you to declare the source code encoding in the source file would like to see Line 0. See . [1001] ruuvi$ cat ctc.py # coding=utf-8 print u'''x ? 1'''.encode("ascii", "ignore").decode("ascii") [1002] ruuvi$ python ctc.py x 1 [1003] ruuvi$ From ian.g.kelly at gmail.com Tue Sep 13 11:45:03 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 13 Sep 2011 09:45:03 -0600 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 4:04 PM, rantingrick wrote: > > ############################################################ > # ? ? ? ? ? ? ? ? ? ? ? ? ?Quote ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ > # The itertools module is great HOWEVER i believe most ? ? # > # people are recreating the functionalities due to the ? ? # > # insanely cryptic and/or missing examples from each ? ? ? # > # method ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ Have you looked at the online itertools documentation at all? http://docs.python.org/library/itertools.html > py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " ? ?hello > word ? ?"))) > 'hello word ? ?' > py> ''.join(list(itertools.takewhile(lambda x:x==" ", " ? ?hello > word ? ?"))) > ' ? ?' These are too complex to be good examples. Drop the lambda and replace it with a built-in. Also, str.join is perfectly capable of taking an iterator as its argument. There is no reason at all to construct a list first. > py> print itertools.compress.__doc__ > compress(data, selectors) --> iterator over selected data > Return data elements corresponding to true selector elements. > Forms a shorter iterator from selected data elements using the > selectors to choose the data elements. > > ############################################################ > # ? ? ? ? ? ? ? ? ? ? ? ? ?Quote ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ > # WTF! Would you like to define a Python "selector". Could # > # it be that we should be using "selector function" or ? ? # > # "predicate function" instead? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# > ############################################################ Notice that it says "selector elements", not "selector functions". You have misconstrued what this function does. Hint: it does not use predicates at all. I can agree though that this could probably use a simple example in the doc string. From ramit.prasad at jpmorgan.com Tue Sep 13 12:24:10 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 12:24:10 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> Written by Kayode Odeyemi Well, I did try using super(), but I got this: >>> class B(A): ... def __init__(self, module): ... super(A, self).log('system') ... >>> c = B('module') ================================================= You should be passed super the current class you want the super class of, not the type of the super class. So it should be: super(B, self).log('system') # Notice that it passed class B Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Sep 13 12:37:11 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Sep 2011 12:37:11 -0400 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Message-ID: <4E6F86B7.8080601@ieee.org> On 01/-10/-28163 02:59 PM, mano mano wrote: > Mikael Lyngvig accurately summarizes comp.lang.python discussion of > the technical merits of Tkinter, wxPython, and Python-bound JPI. > Malcolm Tredinnick ............... > > http://12......89/ > SPAM ALERT From ramit.prasad at jpmorgan.com Tue Sep 13 12:46:08 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 12:46:08 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> >You should be passed super the current class you want the super class of, not the type of the super class. So it should be: >super(B, self).log('system') # Notice that it passed class B Ugh, apologies for the poor English; my tea has not kicked in. That first line would be more understandable as: 'You should pass the current class (B) you want the super class of, not the type of the super class (A) itself. So it should be:' To clarify, by passing A to super it retrieves the definition for the base class (object) which does not have the function you are trying to access. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Tue Sep 13 12:56:55 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 13 Sep 2011 17:56:55 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Sep 13, 2011 at 5:46 PM, Prasad, Ramit wrote: > >You should be passed super the current class you want the super class of, > not the type of the super class. So it should be:**** > > >super(*B*, self).log('system') # Notice that it passed class B**** > > ** ** > > Ugh, apologies for the poor English; my tea has not kicked in.**** > > ** ** > > That first line would be more understandable as: ?You should pass the > current class (B) you want the super class of, not the type of the super > class (A) itself. So it should be:?**** > > ** ** > > To clarify, by passing A to super it retrieves the definition for the base > class (object) which does not have the function you are trying to access.* > *** > > ** ** > > Ramit > Thanks for helping me clarify on how to use super() in Py2+. That really worked! >>> class B(A): ... def __init__(self, module): ... self.module = A.log(self, module) ... print self.module # printing here is completely unnecessary in a good OOP language ... >>> c = B('system') logged >>> class B(A): ... def __init__(self, module): ... print super(B, self).log('system') # printing here is completely unnecessary in a good OOP language ... >>> c = B('system') logged >>> When an instance of a class is created, all codes within that instance block should be executed. That's my understanding of OOP. Thanks everyone! > **** > > ** ** > > ** ** > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology**** > > 712 Main Street | Houston, TX 77002**** > > work phone: 713 - 216 - 5423**** > > **** > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of securities, > accuracy and completeness of information, viruses, confidentiality, legal > privilege, and legal entity disclaimers, available at > http://www.jpmorgan.com/pages/disclosures/email. > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Sep 13 13:24:34 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 13 Sep 2011 11:24:34 -0600 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Sep 13, 2011 at 10:56 AM, Kayode Odeyemi wrote: >>>> class B(A): > ... ? ? def __init__(self, module): > ... ? ? ? ? ? ? self.module = A.log(self, module) > ... ? ? ? ? ? ? print self.module # printing here is completely unnecessary > in a good OOP language > ... >>>> c = B('system') > logged >>>> class B(A): > ... ? ? def __init__(self, module): > ... ? ? ? ? ? ? print super(B, self).log('system')?# printing here is > completely unnecessary in a good OOP language > ... >>>> c = B('system') > logged >>>> > When an instance of a class is created, all codes within that instance block > should be executed. That's my understanding of OOP. The initializer should be executed, which is what Python does. Your initializer then calls A.log, which does nothing interesting at all. My question is, what exactly is it that you intend A.log to do? As written, it does not do any logging. It merely constructs a string and then returns it. Neither constructing a string, nor returning a string, imply logging it or printing it. From vlastimil.brom at gmail.com Tue Sep 13 14:13:44 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 20:13:44 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/13 Alec Taylor : > Hmm, nothing mentioned so far works for me... > > Here's a very small test case: > >>>> python -u "Convert to Creole.py" > ?File "Convert to Creole.py", line 1 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 1, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details >>>> Exit Code: 1 > > Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") > > On Tue, Sep 13, 2011 at 11:33 PM, Vlastimil Brom > wrote: >> 2011/9/13 ron : >>> >>> Depending on the load, you can do something like: >>> >>> "".join([x for x in string if ord(x) < 128]) >>> >>> It's worked great for me in cleaning input on webapps where there's a >>> lot of copy/paste from varied sources. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> Well, for this kind of dirty "data cleaning" you may as well use e.g. >> >>>>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") >> u'text ?with non ASCII in between ...' >>>>> >> >> vbr >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Ok, in that case the encoding probably would be utf-8; \xe2 is just the first part of the encoded data >>> u'?'.encode("utf-8") '\xe2\x89\xa4' >>> Setting this encoding at the beginning of the file, as mentioned before, might solve the problem while retaining the symbol in question (or you could move from syntax error to some unicode related error depending on other circumstances...). vbr From davea at ieee.org Tue Sep 13 15:31:08 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Sep 2011 15:31:08 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E6FAF7C.40406@ieee.org> On 01/-10/-28163 02:59 PM, Kayode Odeyemi wrote: > > When an instance of a class is created, all codes within that instance block > should be executed. That's my understanding of OOP. > I don't understand this phrasing at all. Could you show a specific example of something that does not execute code you think should be executed? I suspect you're just confused by things the interactive session is printing out, which are not part of the language, and work a bit differently. DaveA From dreyemi at gmail.com Tue Sep 13 15:53:18 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 13 Sep 2011 20:53:18 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <4E6FAF7C.40406@ieee.org> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> <4E6FAF7C.40406@ieee.org> Message-ID: On Tue, Sep 13, 2011 at 8:31 PM, Dave Angel wrote: > I suspect you're just confused by things the interactive session is > printing out, which are not part of the language, and work a bit > differently. You are right. This is where I missed it. The command interface requires a print command, as against using a return statement. My apologies. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Sep 13 16:20:16 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 13 Sep 2011 21:20:16 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 Message-ID: Hi all, Unpyc3 can recreate Python3 source code from code objects, function source code from function objects, and module source code from .pyc files. The current version is able to decompile itself successfully :). It has been tested with Python3.2 only. It currently reconstructs most of Python 3 (see TODO below) constructs but probably needs to be tested more thoroughly. All feedback welcome. Unpyc3 is a single file and is available at http://code.google.com/p/unpyc3/ Example: >>> from unpyc3 import decompile >>> def foo(x, y, z=3, *args): ... global g ... for i, j in zip(x, y): ... if z == i + j or args[i] == j: ... g = i, j ... return ... >>> print(decompile(foo)) def foo(x, y, z=3, *args): global g for i, j in zip(x, y): if z == i + j or args[i] == j: g = i, j return TODO: * Support for keyword-only arguments * Handle assert statements * Show docstrings for functions and modules * Nice spacing between function/class declarations Have fun! Note: unpyc3 is totally unrelated to another project called "unpyc" which I discovered when I tried to register the same project name on google code. -- Arnaud From tjhanson at yahoo.com Tue Sep 13 16:25:06 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 13:25:06 -0700 Subject: Need some experience Message-ID: <201109131325.06524.tjhanson@yahoo.com> I have been a desktop Linux user for better than eleven years, as a hobby. Back when we still did most of our computing on desktops I even set up a rudimentary server setup in my home. Nothing fancy or anything, but I was proud of it and of the fact that it was built Microsoft free. I have no formal education in IT nor programming. Retired now, my career was finance; I was an IRS field agent. Since retiring two years ago, I have renewed my interest in software. I know some C and lately decided to learn Python. I have worked through a couple of the introductory texts and have a feeling for the OOP model, although I won't be able to call myself an experienced practitioner anytime soon. I am looking for an open source project that will allow me to develop my skills further. Financially, I'm set; I'm not looking for a job. I'm looking for some drudge work, where I can look at other peoples' code and make a contribution. Naturally I do not want to do this forever; I'm hoping to get up to speed with my skill set so I can work to more complexity later. Does anyone have some ideas that would help me? From t at jollybox.de Tue Sep 13 16:37:05 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 13 Sep 2011 22:37:05 +0200 Subject: Need some experience In-Reply-To: <201109131325.06524.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> Message-ID: <4E6FBEF1.5020404@jollybox.de> On 13/09/11 22:25, Tim Hanson wrote: > I have been a desktop Linux user for better than eleven years, as a hobby. > Back when we still did most of our computing on desktops I even set up a > rudimentary server setup in my home. Nothing fancy or anything, but I was > proud of it and of the fact that it was built Microsoft free. I have no > formal education in IT nor programming. Retired now, my career was finance; I > was an IRS field agent. > > Since retiring two years ago, I have renewed my interest in software. I know > some C and lately decided to learn Python. I have worked through a couple of > the introductory texts and have a feeling for the OOP model, although I won't > be able to call myself an experienced practitioner anytime soon. > > I am looking for an open source project that will allow me to develop my > skills further. > > Financially, I'm set; I'm not looking for a job. I'm looking for some drudge > work, where I can look at other peoples' code and make a contribution. > Naturally I do not want to do this forever; I'm hoping to get up to speed with > my skill set so I can work to more complexity later. > > Does anyone have some ideas that would help me? This is becoming something of an FAQ - I don't suppose there's a canned response link somewhere ? ;-) I like to recommend CPython itself ? which is a bit hypocritical, as I haven't touched it in quite a while. It has a constantly overflowing bug tracker where I'm sure you can find a lot of fascinating problems that need solving. The community, I have found, is welcoming and friendly. Much of the standard library is written in Python, but if you know C, you can have a go at the C code as well. Thomas From tjhanson at yahoo.com Tue Sep 13 16:52:24 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 13:52:24 -0700 Subject: Need some experience In-Reply-To: <4E6FBEF1.5020404@jollybox.de> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> Message-ID: <201109131352.25059.tjhanson@yahoo.com> On Tuesday, September 13, 2011 01:37:05 pm Thomas Jollans wrote: > On 13/09/11 22:25, Tim Hanson wrote: > > I have been a desktop Linux user for better than eleven years, as a > > hobby. Back when we still did most of our computing on desktops I even > > set up a rudimentary server setup in my home. Nothing fancy or > > anything, but I was proud of it and of the fact that it was built > > Microsoft free. I have no formal education in IT nor programming. > > Retired now, my career was finance; I was an IRS field agent. > > > > Since retiring two years ago, I have renewed my interest in software. I > > know some C and lately decided to learn Python. I have worked through a > > couple of the introductory texts and have a feeling for the OOP model, > > although I won't be able to call myself an experienced practitioner > > anytime soon. > > > > I am looking for an open source project that will allow me to develop my > > skills further. > > > > Financially, I'm set; I'm not looking for a job. I'm looking for some > > drudge work, where I can look at other peoples' code and make a > > contribution. Naturally I do not want to do this forever; I'm hoping to > > get up to speed with my skill set so I can work to more complexity > > later. > > > > Does anyone have some ideas that would help me? > > This is becoming something of an FAQ - I don't suppose there's a canned > response link somewhere ? ;-) > > I like to recommend CPython itself ? which is a bit hypocritical, as I > haven't touched it in quite a while. It has a constantly overflowing bug > tracker where I'm sure you can find a lot of fascinating problems that > need solving. The community, I have found, is welcoming and friendly. > Much of the standard library is written in Python, but if you know C, > you can have a go at the C code as well. > > Thomas That's not a bad idea. From the past I know that bug fixing is a great way to learn a language. If you know a specific site to key in on, feel free to send me there. Otherwise I'll poke around the Python site and find it. From tjhanson at yahoo.com Tue Sep 13 17:14:45 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 14:14:45 -0700 Subject: Need some experience In-Reply-To: <4E6FBEF1.5020404@jollybox.de> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> Message-ID: <201109131414.45610.tjhanson@yahoo.com> On Tuesday, September 13, 2011 01:37:05 pm Thomas Jollans wrote: > On 13/09/11 22:25, Tim Hanson wrote: > > I have been a desktop Linux user for better than eleven years, as a > > hobby. Back when we still did most of our computing on desktops I even > > set up a rudimentary server setup in my home. Nothing fancy or > > anything, but I was proud of it and of the fact that it was built > > Microsoft free. I have no formal education in IT nor programming. > > Retired now, my career was finance; I was an IRS field agent. > > > > Since retiring two years ago, I have renewed my interest in software. I > > know some C and lately decided to learn Python. I have worked through a > > couple of the introductory texts and have a feeling for the OOP model, > > although I won't be able to call myself an experienced practitioner > > anytime soon. > > > > I am looking for an open source project that will allow me to develop my > > skills further. > > > > Financially, I'm set; I'm not looking for a job. I'm looking for some > > drudge work, where I can look at other peoples' code and make a > > contribution. Naturally I do not want to do this forever; I'm hoping to > > get up to speed with my skill set so I can work to more complexity > > later. > > > > Does anyone have some ideas that would help me? > > This is becoming something of an FAQ - I don't suppose there's a canned > response link somewhere ? ;-) > > I like to recommend CPython itself ? which is a bit hypocritical, as I > haven't touched it in quite a while. It has a constantly overflowing bug > tracker where I'm sure you can find a lot of fascinating problems that > need solving. The community, I have found, is welcoming and friendly. > Much of the standard library is written in Python, but if you know C, > you can have a go at the C code as well. > > Thomas Never mind. I found it. From lists at cheimes.de Tue Sep 13 17:36:52 2011 From: lists at cheimes.de (Christian Heimes) Date: Tue, 13 Sep 2011 23:36:52 +0200 Subject: Need some experience In-Reply-To: <201109131352.25059.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> <201109131352.25059.tjhanson@yahoo.com> Message-ID: Am 13.09.2011 22:52, schrieb Tim Hanson: > That's not a bad idea. From the past I know that bug fixing is a great way to > learn a language. If you know a specific site to key in on, feel free to send > me there. Otherwise I'll poke around the Python site and find it. It's a great idea. We are always looking for volunteers that help the community to reduce the amount of open bugs. The bug tracker at http://bugs.python.org/ even has a category for beginners. You just have to search for keyword -> easy and you'll get a bunch of low hanging fruits to pick from. From tjhanson at yahoo.com Tue Sep 13 18:09:42 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 15:09:42 -0700 Subject: Need some experience In-Reply-To: References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> Message-ID: <201109131509.42974.tjhanson@yahoo.com> On Tuesday, September 13, 2011 02:36:52 pm Christian Heimes wrote: > Am 13.09.2011 22:52, schrieb Tim Hanson: > > That's not a bad idea. From the past I know that bug fixing is a great > > way to learn a language. If you know a specific site to key in on, feel > > free to send me there. Otherwise I'll poke around the Python site and > > find it. > > It's a great idea. We are always looking for volunteers that help the > community to reduce the amount of open bugs. The bug tracker at > http://bugs.python.org/ even has a category for beginners. You just have > to search for keyword -> easy and you'll get a bunch of low hanging > fruits to pick from. This is exactly what I'm looking for. I don't know who is the "volunteer" here, me for obvious reasons, or the Python community for doing some free hand-holding. Now I know how I'll spend the next year. Thank you! From jack.bates at gmail.com Tue Sep 13 18:27:32 2011 From: jack.bates at gmail.com (Jack Bates) Date: Tue, 13 Sep 2011 15:27:32 -0700 Subject: ImportError: cannot import name dns Message-ID: Why is the following ImportError raised? $ ./test Traceback (most recent call last): File "./test", line 3, in from foo import dns File "/home/jablko/foo/dns.py", line 1, in from foo import udp File "/home/jablko/foo/udp.py", line 1, in from foo import dns ImportError: cannot import name dns $ I reproduce this error with the following four files and five lines: == foo/dns.py == from foo import udp == foo/udp.py == from foo import dns == foo/__init__.py == (empty) == test == #!/usr/bin/env python from foo import dns From ben+python at benfinney.id.au Tue Sep 13 18:37:02 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 14 Sep 2011 08:37:02 +1000 Subject: Need some experience References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> Message-ID: <87y5xsjchd.fsf@benfinney.id.au> Tim Hanson writes: > On Tuesday, September 13, 2011 02:36:52 pm Christian Heimes wrote: > > We are always looking for volunteers that help the community to > > reduce the amount of open bugs. The bug tracker at > > http://bugs.python.org/ even has a category for beginners. You just > > have to search for keyword -> easy and you'll get a bunch of low > > hanging fruits to pick from. > > This is exactly what I'm looking for. I don't know who is the "volunteer" > here, me for obvious reasons, or the Python community for doing some free > hand-holding. Now I know how I'll spend the next year. Thank you! Excellent attitude. Thank you in advance for contributing to the Python community. -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From ben+python at benfinney.id.au Tue Sep 13 18:40:35 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 14 Sep 2011 08:40:35 +1000 Subject: The Usenet newsgroup news:comp.lang.python ... References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Message-ID: <87ty8gjcbg.fsf@benfinney.id.au> mano mano writes: > Mikael Lyngvig accurately summarizes comp.lang.python discussion No, you're posting spam links. Go away and spend the rest of your miserable life in a deep hole. -- \ ?If society were bound to invent technologies which could only | `\ be used entirely within the law, then we would still be sitting | _o__) in caves sucking our feet.? ?Gene Kan, creator of Gnutella | Ben Finney From ramit.prasad at jpmorgan.com Tue Sep 13 18:53:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 18:53:49 -0400 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <87ty8gjcbg.fsf@benfinney.id.au> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> <87ty8gjcbg.fsf@benfinney.id.au> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> >> Mikael Lyngvig accurately summarizes comp.lang.python discussion >No, you're posting spam links. Go away and spend the rest of your >miserable life in a deep hole. I was wondering since the text seemed like plausible non-spam (to me). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Tue Sep 13 18:58:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 14 Sep 2011 08:58:13 +1000 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> <87ty8gjcbg.fsf@benfinney.id.au> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, Sep 14, 2011 at 8:53 AM, Prasad, Ramit wrote: > I was wondering since the text seemed like plausible non-spam (to me). > I suspect it was autogenerated from subject lines of recent emails. It'd not be hard to design a template that covers comp.lang.* or even comp.*. ChrisA From ramit.prasad at jpmorgan.com Tue Sep 13 19:09:50 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 19:09:50 -0400 Subject: ImportError: cannot import name dns In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Jack Bates Sent: Tuesday, September 13, 2011 5:28 PM To: python-list at python.org Subject: ImportError: cannot import name dns Why is the following ImportError raised? $ ./test Traceback (most recent call last): File "./test", line 3, in from foo import dns File "/home/jablko/foo/dns.py", line 1, in from foo import udp File "/home/jablko/foo/udp.py", line 1, in from foo import dns ImportError: cannot import name dns $ I reproduce this error with the following four files and five lines: == foo/dns.py == from foo import udp == foo/udp.py == from foo import dns == foo/__init__.py == (empty) == test == #!/usr/bin/env python from foo import dns =========================================================================== It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. Circular dependency is a Bad Thing. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tjreedy at udel.edu Tue Sep 13 21:12:27 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 Sep 2011 21:12:27 -0400 Subject: Need some experience In-Reply-To: <201109131509.42974.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> <201109131509.42974.tjhanson@yahoo.com> Message-ID: >> It's a great idea. We are always looking for volunteers that help the >> community to reduce the amount of open bugs. The bug tracker at >> http://bugs.python.org/ even has a category for beginners. You just have >> to search for keyword -> easy and you'll get a bunch of low hanging >> fruits to pick from. > > This is exactly what I'm looking for. I don't know who is the "volunteer" > here, me for obvious reasons, or the Python community for doing some free > hand-holding. Now I know how I'll spend the next year. Thank you! Also consider the core-mentorship mailing list and the dev guide at http://docs.python.org/devguide -- Terry Jan Reedy From elven199208 at gmail.com Tue Sep 13 21:19:37 2011 From: elven199208 at gmail.com (zhenzhen zhang) Date: Tue, 13 Sep 2011 18:19:37 -0700 (PDT) Subject: Offer various hats including Red Bull Hats on http://www.mlbhatshop.com/ Message-ID: Defending MX2 champion Ken is currently leading the MX2 championship while Max Nagl heads to his favourite track of the season looking for points to close the gap on fellow Red Bull Teka KTM Factory Racing team http://www.mlbhatshop.com/ rider Tony Cairoli. by red bull hats. From tjhanson at yahoo.com Tue Sep 13 21:44:41 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 18:44:41 -0700 Subject: Need some experience In-Reply-To: References: <201109131325.06524.tjhanson@yahoo.com> <201109131509.42974.tjhanson@yahoo.com> Message-ID: <201109131844.41562.tjhanson@yahoo.com> On Tuesday, September 13, 2011 06:12:27 pm Terry Reedy wrote: > >> It's a great idea. We are always looking for volunteers that help the > >> community to reduce the amount of open bugs. The bug tracker at > >> http://bugs.python.org/ even has a category for beginners. You just have > >> to search for keyword -> easy and you'll get a bunch of low hanging > >> fruits to pick from. > > > > This is exactly what I'm looking for. I don't know who is the "volunteer" > > here, me for obvious reasons, or the Python community for doing some free > > hand-holding. Now I know how I'll spend the next year. Thank you! > > Also consider the core-mentorship mailing list and the dev guide at > http://docs.python.org/devguide This is equally helpful. Thanks! From rantingrick at gmail.com Tue Sep 13 22:08:34 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 13 Sep 2011 19:08:34 -0700 (PDT) Subject: PyWart: Itertools module needs attention References: Message-ID: <9e8eaa71-6044-422b-ac8f-d3e28ae5751f@b10g2000vbz.googlegroups.com> On Sep 13, 10:45?am, Ian Kelly wrote: > Have you looked at the online itertools documentation at all? > > http://docs.python.org/library/itertools.html Yes the online docs are much better. I really like the source code showing the inner workings of the methods. However i always get upset when i see poorly thought out doc-strings. My philosophy is that we should use the built in help function first and only visit the documentation if more instruction is needed. I may need to create another PyWart on the topic of doc-strings and how the author of these strings needs to forget everything he knows and imagine he is a complete python neophyte. I remember my initial frustrations learning about functions (in another life it seems) and my inability to grasp the concept was due to poor examples. I believe the author use the Fibonacci sequence as an example (Python docs use this example also). What an idiot! What does conditionals, linear assignment, loops, the print function, in-place addition, logic, blah, blah, have to do with understanding a function... NOTHING! The most basic and by far the best first example for functions (in any language) is this... def add(x, y): return x + y Followed by this... def sub(x,y): return x - y Simple and to the point. It simply reeks of "ah ha"! I dare anyone to create a better introductory function example. Dear Tutorial Writer: When writing tutorials please check your ego at the door. Thank you. From anacrolix at gmail.com Tue Sep 13 22:23:52 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Wed, 14 Sep 2011 12:23:52 +1000 Subject: GIL switch interval Message-ID: i'm curious as to what can be done with (and handled better) by adjusting sys.setswitchinterval i've opened a question on SO for this, that people might find of interest: http://stackoverflow.com/questions/7376776/sys-setswitchinterval-in-python-3-2-and-beyond From 1248283536 at qq.com Tue Sep 13 22:39:36 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 14 Sep 2011 10:39:36 +0800 Subject: Connection reset by peer Message-ID: there is a multi-threads program dowloading data from yahoo,the main structure is as the following(omit something unimportant ) class webdata(object): def __init__(self,name): self.jobs = Queue.Queue() if x in name: self.jobs.put(x) def download(self): try: weburl=self.jobs.get() url = weburl hx = httplib2.Http() resp, content = hx.request(url, headers=headers) print self.jobs.task_done() except: print url,"wrong" self.jobs.task_done() def run(self): for i in range(30): threading.Thread(target=self.download).start() self.jobs.join() if __name__=="__main__": webdata('quote').run() quote is a list which i want to download,i was confused ,this program can download something, can't download something, when i cancel try,except , i get the output: File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1436, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1188, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1171, in _conn_request content = response.read() File "/usr/lib/python2.7/httplib.py", line 541, in read return self._read_chunked(amt) File "/usr/lib/python2.7/httplib.py", line 590, in _read_chunked value.append(self._safe_read(chunk_left)) File "/usr/lib/python2.7/httplib.py", line 647, in _safe_read chunk = self.fp.read(min(amt, MAXAMOUNT)) File "/usr/lib/python2.7/socket.py", line 380, in read data = self._sock.recv(left) error: [Errno 104] Connection reset by peer i want to know, my computer(client) reset it ,or the yahoo (server) reset it ,what is the peer?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed Sep 14 00:12:53 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 14 Sep 2011 06:12:53 +0200 Subject: stackoverflow and c.l.py (was: GIL switch interval) In-Reply-To: References: Message-ID: Matt Joiner, 14.09.2011 04:23: > i'm curious as to what can be done with (and handled better) by > adjusting sys.setswitchinterval > i've opened a question on SO for this, that people might find of > interest: http://stackoverflow.com[...] I wonder why people ask this kind of question on stackoverflow, and then come here asking people to go over there, read the question, and (potentially) provide an answer. IMHO, c.l.py is a much better place to ask Python(-related) questions than stackoverflow. It's also a much better place to search for an answer that is already available in the archives. Stefan From steve+comp.lang.python at pearwood.info Wed Sep 14 01:35:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 15:35:37 +1000 Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> On Wed, 14 Sep 2011 02:12 pm Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. You should post that question on stackoverflow, and ask them to reply here. -- Steven From vincent.vandevyvre at swing.be Wed Sep 14 01:53:50 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 07:53:50 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: Message-ID: <4E70416E.5090208@swing.be> An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Wed Sep 14 02:08:00 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 14 Sep 2011 16:08:00 +1000 Subject: memory error Message-ID: Hello All, I keep coming across a memory error when processing many netcdf files. I assume it has something to do with how I loop things and maybe need to close things off properly. In the code below I am looping through a bunch of netcdf files (each file is hourly data for one month) and within each netcdf file I am outputting a *png file every three hours. This works for one netcdf file but when it begins to process the next netcdf file I receive this memory error: *Traceback (most recent call last): File "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", line 44, in TSFC=ncfile.variables['T_SFC'][:] File "netCDF4.pyx", line 2473, in netCDF4.Variable.__getitem__ (netCDF4.c:23094) MemoryError* To reduce processing requirements I have tried making the LAT and LON to only use [0] but I also receive an error: *Traceback (most recent call last): File "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", line 75, in x,y=map(*N.meshgrid(LON,LAT)) File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 3256, in meshgrid numRows, numCols = len(y), len(x) # yes, reversed TypeError: len() of unsized object* finally I have added gc.collect() in a couple of places but that doesn't seem to do anything to help. I am using :*Python 2.7.2 |EPD 7.1-2 (32-bit)| (default, Jul 3 2011, 15:13:59) [MSC v.1500 32 bit (Intel)] on win32* Any feedback will be greatly appreciated! from netCDF4 import Dataset import numpy import numpy as N import matplotlib.pyplot as plt from numpy import ma as MA from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os import gc print "start processing...." inputpath=r'E:/GriddedData/Input/' outputpath=r'E:/GriddedData/Validation/' shapefile1="E:/test_GIS/DSE_REGIONS" for (path, dirs, files) in os.walk(inputpath): for dir in dirs: print dir sourcepath=os.path.join(path,dir) relativepath=os.path.relpath(sourcepath,inputpath) newdir=os.path.join(outputpath,relativepath) if not os.path.exists(newdir): os.makedirs(newdir) for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", ncfile ncfile=os.path.join(sourcepath,ncfile) #print ncfile ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][:,:,:] TIME=ncfile.variables['time'][:] LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] fillvalue=ncfile.variables['T_SFC']._FillValue TSFC=MA.masked_values(TSFC, fillvalue) ncfile.close() gc.collect() print "garbage collected" for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): print TSFC, TIME #convert time from numbers to date and prepare it to have no symbols for saving to filename cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') # compute map projection coordinates for lat/lon grid. x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title('Surface temperature at %s UTC'%ncfiletime) ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) plt.close() gc.collect() print "garbage collected again" print "end of processing" -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Wed Sep 14 02:20:04 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 07:20:04 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E70416E.5090208@swing.be> References: <4E70416E.5090208@swing.be> Message-ID: On 14 September 2011 06:53, Vincent Vande Vyvre wrote: > > Hi, trying your code, I have had numbers of errors: Hi Vincent, thanks for trying it. > ? File "unpyc3.py", line 55, in > ??? SETUP_WITH, > NameError: name 'SETUP_WITH' is not defined > > commented it > > ? File "unpyc3.py", line 58, in > ??? STORE_DEREF, DELETE_DEREF, > NameError: name 'DELETE_DEREF' is not defined > > commented it What version of Python are you running this on? This is module is written for Python 3. It looks like you're using an old version of Python (before the with statement was introduced - 2.5?) > ? File "unpyc3.py", line 96, in dec_module > ??? stream = open(pyc_path, "rb") > UnboundLocalError: local variable 'pyc_path' referenced before assignment > > change pyc_path to path Thanks, I've fixed that. -- Arnaud From ethan at stoneleaf.us Wed Sep 14 02:47:10 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 13 Sep 2011 23:47:10 -0700 Subject: stackoverflow and c.l.py In-Reply-To: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E704DEE.6070603@stoneleaf.us> Steven D'Aprano wrote: > On Wed, 14 Sep 2011 02:12 pm Stefan Behnel wrote: > >> Matt Joiner, 14.09.2011 04:23: >>> i'm curious as to what can be done with (and handled better) by >>> adjusting sys.setswitchinterval >>> i've opened a question on SO for this, that people might find of >>> interest: http://stackoverflow.com[...] >> I wonder why people ask this kind of question on stackoverflow, and then >> come here asking people to go over there, read the question, and >> (potentially) provide an answer. > > You should post that question on stackoverflow, and ask them to reply here. +10! From vincent.vandevyvre at swing.be Wed Sep 14 04:13:15 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 10:13:15 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: <4E70416E.5090208@swing.be> Message-ID: <4E70621B.2000408@swing.be> An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Wed Sep 14 04:24:31 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2011 08:24:31 GMT Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and > then come here asking people to go over there, read the question, and > (potentially) provide an answer. > > IMHO, c.l.py is a much better place to ask Python(-related) questions > than stackoverflow. It's also a much better place to search for an > answer that is already available in the archives. > If you want an answer to how to get a specific bit of code to work then Stackoverflow is better if only because people can see who has already answered so don't need to waste time re-answering every trivial little question about syntax. Also there's a theory that people can search for existing answers so only one person in the class has to ask how to do their homework. I've never actually asked a question on Stackoverflow but I have found the answers to a lot of problems I've had. If you want an open-ended discussion then c.l.py is the place to go. On Stackoverflow you would likely just have the question closed pdq. -- Duncan Booth http://kupuguy.blogspot.com From t at jollybox.de Wed Sep 14 04:37:13 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 14 Sep 2011 10:37:13 +0200 Subject: Connection reset by peer In-Reply-To: References: Message-ID: <4E7067B9.2070102@jollybox.de> On 14/09/11 04:39, ???? wrote: > i want to know, my computer(client) reset it ,or the yahoo > (server) reset it ,what is the peer?? This refers to your program's peer, as in the entity it's communicating with. When you're the client, the other party (which, once the connection is established, is considered to be of equal rank - a peer) is the server. tl;dr: yahoo. From ars.rithika at gmail.com Wed Sep 14 04:42:31 2011 From: ars.rithika at gmail.com (Selvi Arul) Date: Wed, 14 Sep 2011 01:42:31 -0700 (PDT) Subject: www.brunningonline.net/simon/blog/archives/001919.html Message-ID: <4198c5fe-0444-4006-a9df-6239d56214fd@r8g2000prd.googlegroups.com> http://123maza.com/65/orange458/ From vincent.vandevyvre at swing.be Wed Sep 14 04:44:02 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 10:44:02 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E70621B.2000408@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> Message-ID: <4E706952.8000201@swing.be> An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Wed Sep 14 04:44:40 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 14 Sep 2011 18:44:40 +1000 Subject: Replace pip installed package with latest git version? Message-ID: Good evening, I've installed a version of python-creole from pip. How do I upgrade it to the latest git version? (Windows 7 x64 SP1) Thanks for all suggestions, Alec Taylor From ars.rithika at gmail.com Wed Sep 14 04:48:48 2011 From: ars.rithika at gmail.com (Selvi Arul) Date: Wed, 14 Sep 2011 01:48:48 -0700 (PDT) Subject: Python Shutdown hook comp.lang.python. My comp.lang.python post..... Message-ID: <0b5094ac-764c-4374-b58a-b53775b3e521@f24g2000prb.googlegroups.com> http://123maza.com/65/orange458/ From arnodel at gmail.com Wed Sep 14 05:31:50 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 10:31:50 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E706952.8000201@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> Message-ID: On 14 September 2011 09:44, Vincent Vande Vyvre wrote: > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' Could you show me what you do to get this error? Thank you, Arnaud PS: I've checked; DELETE_DEREF was introduced in Python3.2 From vincent.vandevyvre at swing.be Wed Sep 14 06:03:49 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 12:03:49 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> Message-ID: <4E707C05.70103@swing.be> An HTML attachment was scrubbed... URL: From memilanuk at gmail.com Wed Sep 14 08:33:54 2011 From: memilanuk at gmail.com (memilanuk) Date: Wed, 14 Sep 2011 05:33:54 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On 09/13/2011 09:12 PM, Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. > > IMHO, c.l.py is a much better place to ask Python(-related) questions > than stackoverflow. It's also a much better place to search for an > answer that is already available in the archives. > > Stefan > Just an opinion from the unwashed masses... but I don't see the p0rn spam over on SO that I do on c.l.py, for one. I also seem to generally get better results from the search engine there, for two. Not saying one is necessarily better than the other, but just subscribing to the feed for the [python] tag on SO has a pretty good SNR... From rosuav at gmail.com Wed Sep 14 08:47:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 14 Sep 2011 22:47:15 +1000 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 10:33 PM, memilanuk wrote: > Not saying one is necessarily better than the other, but just subscribing to > the feed for the [python] tag on SO has a pretty good SNR... The SNR here isn't bad either. Most of the spam gets filtered out, and even stuff like Ranting Rick posts can be of some amusement when it's a slow day... ChrisA From memilanuk at gmail.com Wed Sep 14 09:05:23 2011 From: memilanuk at gmail.com (memilanuk) Date: Wed, 14 Sep 2011 06:05:23 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On 09/14/2011 05:47 AM, Chris Angelico wrote: > The SNR here isn't bad either. Most of the spam gets filtered out, and > even stuff like Ranting Rick posts can be of some amusement when it's > a slow day... I subscribe to the list via Gmane, and if 'most of the spam' gets filtered out, I'd hate to see how much gets submitted as I still see 2-5 minimum blatant spam per day on here. Rick & Xang Li are two examples of what you *don't* see (or at least I don't) @ SO From anddimario at gmail.com Wed Sep 14 09:06:39 2011 From: anddimario at gmail.com (Andrea Di Mario) Date: Wed, 14 Sep 2011 15:06:39 +0200 Subject: Twisted Perspective Broker: get client ip Message-ID: Hi, i'm writing a perspective broker server. Now, i should get the client IP, that perspective broker writes well in the log. I've tried to get it from MyRealm with: mind.broker.transport.getPeer(), without success. I've tried self.transport.getPeer() to, with this result: exceptions.AttributeError: Listner instance has no attribute 'transport' It's strange, because PB wrote the client IP, infact in log i've line with: 2011-09-11 16:41:58+0200 [Broker,0,127.0.0.1] ............ Could you suggest me something? Thanks. Here the code: from OpenSSL import SSL from twisted.internet import reactor, ssl from ConfigParser import SafeConfigParser from twisted.python import log from twisted.spread import pb from twisted.cred import checkers, portal from zope.interface import implements import hashlib class Listner(pb.Avatar): def __init__(self, name): self.name = name def perspective_getDictionary(self, dictionary): print dictionary def perspective_simplyAccess(self, access): print access def verifyCallback(connection, x509, errnum, errdepth, ok): if not ok: log.msg("Certificato non valido: %s" % x509.get_subject()) return False else: log.msg("Connessione stabilita, vertificato valido: %s" % x509.get_subject()) return True class MyRealm: implements(portal.IRealm) def requestAvatar(self, avatarId, mind, *interfaces): if pb.IPerspective not in interfaces: raise NotImplementedError return pb.IPerspective, Listner(avatarId), lambda:None if __name__ == "__main__": CONFIGURATION = SafeConfigParser() CONFIGURATION.read('server.conf') PORT = CONFIGURATION.get('general', 'port') LOGFILE = CONFIGURATION.get('general', 'log') log.startLogging(open(LOGFILE,'a')) myContextFactory = ssl.DefaultOpenSSLContextFactory(CONFIGURATION.get('general', 'keypath'), CONFIGURATION.get('general', 'certpath')) ctx = myContextFactory.getContext() ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback) ctx.load_verify_locations(CONFIGURATION.get('general', 'cacert')) p = portal.Portal(MyRealm()) c = checkers.FilePasswordDB('passwords.txt', caseSensitive=True, cache=True) p.registerChecker(c) factory = pb.PBServerFactory(p) reactor.listenSSL(int(PORT), factory, myContextFactory) reactor.run() -- Andrea Di Mario From gandalf at shopzeus.com Wed Sep 14 09:08:50 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 14 Sep 2011 15:08:50 +0200 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <4E70A762.1050701@shopzeus.com> On 2011-09-14 15:05, memilanuk wrote: > > Rick & Xang Li are two examples of what you *don't* see (or at least I > don't) @ SO I knew Xang's name would come up. :-) Epic. From roy at panix.com Wed Sep 14 09:42:55 2011 From: roy at panix.com (Roy Smith) Date: Wed, 14 Sep 2011 09:42:55 -0400 Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: In article , Duncan Booth wrote: > If you want an answer to how to get a specific bit of code to work then > Stackoverflow is better if only because people can see who has already > answered so don't need to waste time re-answering every trivial little > question about syntax. Any halfway decent newsreader application will follow threading and put all the responses to a given question in one place. Of course, this is a relatively new feature. If your newsreader is any older than about the mid 1980's, it may not be able to do this. In article , Stefan Behnel wrote: > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. If you ask here you will probably get the correct answer to your question (along with some deep dives into related topics, which are often more valuable than the original answer). If you ask on SO, you may also get the correct answer, but in addition you will earn SO karma points. Maybe even some neat badge. I guess it all depends on what your goal is. Obligatory GIL comment -- I wrote some code the other day that used 4 threads to perform 4 I/O bound operations (fetching 4 jpegs in parallel over http). I figured the fact that they were I/O bound would avoid any GIL problems. I was shocked and dismayed, however, to find that the 4 operations all got serialized. I guess I really didn't understand how the GIL worked after all. So, I rewrote it to use the multiprocessing module. Egads, still serialized! To make a long story short, it turns out we were using some crappy consumer-grade Linksys box as our DNS server, and *it* was single threaded. My 4 threads were blocking on name resolution! We moved to using a real nameserver, and I converted the code back to using threading. Works like a charm now. From alec.taylor6 at gmail.com Wed Sep 14 10:26:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 15 Sep 2011 00:26:48 +1000 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: --editable=git+https://github.com/jedie/python-creole.git is not the right forma t; it must have #egg=Package On Wed, Sep 14, 2011 at 10:54 PM, One Murithi wrote: > pip install -e > On Wed, Sep 14, 2011 at 11:44 AM, Alec Taylor > wrote: >> >> Good evening, >> >> I've installed a version of python-creole from pip. How do I upgrade >> it to the latest git version? >> >> (Windows 7 x64 SP1) >> >> Thanks for all suggestions, >> >> Alec Taylor >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From jack.bates at gmail.com Wed Sep 14 12:22:29 2011 From: jack.bates at gmail.com (Jack Bates) Date: Wed, 14 Sep 2011 09:22:29 -0700 Subject: ImportError: cannot import name dns In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> Message-ID: > It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. > > Circular dependency is a Bad Thing. According to this documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-import_stmt http://effbot.org/zone/import-confusion.htm - I thought Python would do something like: 1. check for "dns" in sys.modules (initially not found) 2. create new empty module, add it to sys.modules as "dns" 3. execute dns.py in new module namespace (executes "from foo import udp") 4. check for "udp" in sys.modules (not found) 5. create new empty module, add it to sys.modules as "udp" 6. execute udp.py in new module namespace (executes "from foo import dns") 7. check for "dns" in sys.modules (found!) 8. done executing udp.py 9. done executing dns.py So I'd expect attempting to access symbols from "dns" while executing udp.py to fail, because dns.py isn't done executing at this point. However I don't attempt to access any symbols from "dns" - so I don't expect this ImportError What is my mistake? From mickyhulse.lists at gmail.com Wed Sep 14 12:58:55 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Wed, 14 Sep 2011 09:58:55 -0700 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: Hello, On Wed, Sep 14, 2011 at 1:44 AM, Alec Taylor wrote: > I've installed a version of python-creole from pip. How do I upgrade > it to the latest git version? Not sure if you got an answer yet, but this is how I would do it: sudo pip install --upgrade git+git://github.com/jedie/python-creole.git#egg=python-creole The "sudo" may or may not be required. Hths. Cheers, Micky From mickyhulse.lists at gmail.com Wed Sep 14 13:06:35 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Wed, 14 Sep 2011 10:06:35 -0700 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 9:58 AM, Micky Hulse wrote: > Not sure if you got an answer yet, but this is how I would do it: > sudo pip install --upgrade > git+git://github.com/jedie/python-creole.git#egg=python-creole Having read your message more closely, it sounds like you did not install the package originally form github? If that's the case, I don't think using --upgrade will be of any help. Sorry 'bout that. I suppose you would have to uninstall the original PIP version: sudo pip uninstall egg-name.egg (or just the package name) ... and then: sudo pip install -e git+git://github.com/jedie/python-creole.git#egg=python-creole Although, I am not sure if that is the best way to do it. Crawling back into my hole now. :) Micky From alec.taylor6 at gmail.com Wed Sep 14 13:11:40 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 15 Sep 2011 03:11:40 +1000 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: Thanks, uninstalling first worked. :D On Thu, Sep 15, 2011 at 3:06 AM, Micky Hulse wrote: > On Wed, Sep 14, 2011 at 9:58 AM, Micky Hulse wrote: >> Not sure if you got an answer yet, but this is how I would do it: >> sudo pip install --upgrade >> git+git://github.com/jedie/python-creole.git#egg=python-creole > > Having read your message more closely, it sounds like you did not > install the package originally form github? If that's the case, I > don't think using --upgrade will be of any help. Sorry 'bout that. > > I suppose you would have to uninstall the original PIP version: > > sudo pip uninstall egg-name.egg (or just the package name) > > ... and then: > > sudo pip install -e > git+git://github.com/jedie/python-creole.git#egg=python-creole > > Although, I am not sure if that is the best way to do it. > > Crawling back into my hole now. :) > > Micky > -- > http://mail.python.org/mailman/listinfo/python-list > From janssen at parc.com Wed Sep 14 14:47:18 2011 From: janssen at parc.com (Bill Janssen) Date: Wed, 14 Sep 2011 11:47:18 PDT Subject: ANN: PyGUI 2.5 In-Reply-To: <962t3eFgd1U1@mid.individual.net> References: <962t3eFgd1U1@mid.individual.net> Message-ID: <17012.1316026038@parc.com> Gregory Ewing wrote: > Terry Reedy wrote: > > > Greg left out the most important to me: > > "Now works with Python 3 on MacOSX and Windows!" > > I'm not making too much of that at the moment, because it > *doesn't* work on Linux yet, and I've no idea how long > it will be before it does. > > The issue is that there will apparently not be any > Python 3 version of pygtk, on the grounds that gobject > introspection can be used instead. Unfortunately, > Gtk 3 and related libraries don't quite handle gobject > introspection well enough to support PyGUI at the moment. One possibility would be to develop a PyGUI branch on top of Tk, so that it would work with Python anywhere. Bill From duncan.booth at invalid.invalid Wed Sep 14 15:00:50 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2011 19:00:50 GMT Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: Roy Smith wrote: > In article , > Duncan Booth wrote: > >> If you want an answer to how to get a specific bit of code to work then >> Stackoverflow is better if only because people can see who has already >> answered so don't need to waste time re-answering every trivial little >> question about syntax. > > Any halfway decent newsreader application will follow threading and put > all the responses to a given question in one place. Of course, this is > a relatively new feature. If your newsreader is any older than about > the mid 1980's, it may not be able to do this. > Sorry, I evidently didn't make myself clear. On Usenet it could be hours before your local server updates with other posts on the thread, on Stackoverflow the answers will update live as they are posted. -- Duncan Booth http://kupuguy.blogspot.com From t at jollybox.de Wed Sep 14 15:34:38 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 14 Sep 2011 21:34:38 +0200 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <4E7101CE.7060103@jollybox.de> On 14/09/11 21:00, Duncan Booth wrote: > Roy Smith wrote: > >> In article , >> Duncan Booth wrote: >> >>> If you want an answer to how to get a specific bit of code to work then >>> Stackoverflow is better if only because people can see who has already >>> answered so don't need to waste time re-answering every trivial little >>> question about syntax. >> >> Any halfway decent newsreader application will follow threading and put >> all the responses to a given question in one place. Of course, this is >> a relatively new feature. If your newsreader is any older than about >> the mid 1980's, it may not be able to do this. >> > Sorry, I evidently didn't make myself clear. On Usenet it could be hours > before your local server updates with other posts on the thread, on > Stackoverflow the answers will update live as they are posted. The mailing list python-list, however, doesn't have this problem. (unless when people post from slow USENET servers of course...) From tim at akwebsoft.com Wed Sep 14 15:50:44 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 14 Sep 2011 11:50:44 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') Message-ID: <20110914195044.GK4331@johnsons-web.com> I have written a class that uses ftplib.FTP as the parent. I need to reconcile the modified time of a workstation file with that same filename on a remote server. Let's say we have a file called '400.shtml'. I get the mtime on my workstation by >> os.path.getmtime('400.shtml') 1311648420.0 And I use >> ftp.sendcmd('MDTM 400.shtml') ## for the remote server '213 20110726004703' My question is how to compare the two outputs? Pointers to documentation and other resources are invited. thanks -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From arnodel at gmail.com Wed Sep 14 15:51:37 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 20:51:37 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E707C05.70103@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> <4E707C05.70103@swing.be> Message-ID: On 14 September 2011 11:03, Vincent Vande Vyvre wrote: > Le 14/09/11 11:31, Arnaud Delobelle a ?crit?: [...] > Could you show me what you do to get this error? Thank you, > [vincent at myhost unpyc3]$ python > Python 3.2.1 (default, Jul 11 2011, 12:37:47) > [GCC 4.6.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from unpyc3 import decompile >>>> print (decompile("shredder.pyc")) > Traceback (most recent call last): > ? File "", line 1, in > ? File "unpyc3.py", line 110, in decompile > ??? return dec_module(obj) > ? File "unpyc3.py", line 99, in dec_module > ??? code = Code(code_obj) > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' >>>> print (decompile("unpyc3.pyc")) > Traceback (most recent call last): > ? File "", line 1, in > ? File "unpyc3.py", line 110, in decompile > ??? return dec_module(obj) > ? File "unpyc3.py", line 99, in dec_module > ??? code = Code(code_obj) > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' >>>> import os >>>> os.path.isfile("shredder.pyc") > True >>>> os.path.isfile("unpyc3.pyc") > True >>>> > > it seems the return of marshal.load(stream) is None I think the reason may be that your unpyc3.pyc and shredder.pyc files were compiled with a different version of python and the read_code function returns None because the magic number in the .pyc file is incorrect because of these two lines: if magic != imp.get_magic(): return None I have now changed this so that it loads the file anyway but prints a warning. I guess this may break badly though. In Python 3.2, .pyc files are "hidden" in a __pycache__ directory. So the Python 3.2 specific unpyc3.pyc file for example is probably located at .../unpyc3/__pycache__/unpyc3-cpython-32.pyc The easiest way to find the path of the .pyc file if you know the path of the .py file is probably as follows: >>> import imp >>> imp.cache_from_source("unpyc3.py") '__pycache__/unpyc3.cpython-32.pyc' Here's an example decompiling the dis module from the standard library: >>> import dis >>> dis.__file__ '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/dis.py' >>> imp.cache_from_source(dis.__file__) '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/__pycache__/dis.cpython-32.pyc' >>> print(decompile(_)) __doc__ = 'Disassembler of Python byte code into mnemonics.' import sys import types from opcode import * from opcode import __all__ as _opcodes_all __all__ = ['code_info', 'dis', 'disassemble', 'distb', 'disco', 'findlinestarts', 'findlabels', 'show_code'] + _opcodes_all del _opcodes_all _have_code = types.MethodType, types.FunctionType, types.CodeType, type def _try_compile(source, name): try: c = compile(source, name, 'eval') except SyntaxError: c = compile(source, name, 'exec') return c [... many more lines ...] I hope this will work for you, -- Arnaud PS: I've also added support for the IMPORT_STAR opcode which I had overlooked. From badouglas at gmail.com Wed Sep 14 16:16:41 2011 From: badouglas at gmail.com (bruce) Date: Wed, 14 Sep 2011 13:16:41 -0700 Subject: libxml2dom quesiton Message-ID: Hi. Test question. Trying to see how to insert a test node into an existing dom tree. For the test, it has a TR/TD with a td[@class="foo"] that has an associated TR.. Trying to figure out how out how to insert a "

" around the tr/td in question... Curious as to how to accomplish this. Thoughts/pointers. thanks -------------------------- sample code/html chunk follows: import libxml2dom text is below tt = libxml2dom.parseString(text, html=1) t1path_=tt.xpath(t1path) aa=tt.createElement("
") print len(t1path_) for a in t1path_: tt.insertBefore(aa,None) print a.nodeName print a.toString() sys.exit() -------------------------------------------- s3== trying to get::
From ladasky at my-deja.com Wed Sep 14 16:47:50 2011 From: ladasky at my-deja.com (John Ladasky) Date: Wed, 14 Sep 2011 13:47:50 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? Message-ID: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Hi folks, Apologies if this is a bit off-topic, but there must be another Pythoneer out there who can help me navigate my current problem. I'm working with matplotlib, the Python graphing package. I need to ask some questions about it, and the place to ask those questions would appear to be the matplotlib-users discussion group. Matplotlib- users appears to be hosted on sourceforge.net (and is not mirrored anywhere else?), so I tried to sign up for an account (at https://sourceforge.net/user/registration). Yesterday, after filling out the registration page, Sourceforge rejected my registration, without any notice that I observed. Today, I tried that registration again. This time, on the upper right corner of the rejection page, I saw the following message: "your registration violated our anti-spam filter." WTF? I tried searching Sourceforge for information on what their anti-spam filter is, and how my registration could possibly have violated it. I found nothing. If anyone out there can tell me how 1) I can actually register with Sourceforge, or 2) how I might post to matplotlib-users without bothering with Sourceforge, I would be most grateful! From anikom15 at gmail.com Wed Sep 14 18:26:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 15:26:40 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <20110914222640.GA4942@Smoke> On Wed, Sep 14, 2011 at 10:47:15PM +1000, Chris Angelico wrote: > On Wed, Sep 14, 2011 at 10:33 PM, memilanuk wrote: > > Not saying one is necessarily better than the other, but just subscribing to > > the feed for the [python] tag on SO has a pretty good SNR... > > The SNR here isn't bad either. Most of the spam gets filtered out, and > even stuff like Ranting Rick posts can be of some amusement when it's > a slow day... > > ChrisA And IMO the quality of [Python] code here is better than at SO. From anikom15 at gmail.com Wed Sep 14 18:27:58 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 15:27:58 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <20110914222757.GB4942@Smoke> On Wed, Sep 14, 2011 at 06:05:23AM -0700, memilanuk wrote: > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >The SNR here isn't bad either. Most of the spam gets filtered out, and > >even stuff like Ranting Rick posts can be of some amusement when it's > >a slow day... > > I subscribe to the list via Gmane, and if 'most of the spam' gets > filtered out, I'd hate to see how much gets submitted as I still see > 2-5 minimum blatant spam per day on here. > > Rick & Xang Li are two examples of what you *don't* see (or at least > I don't) @ SO > I don't understand the matter of spam and trolls. You can just delete it if you don't want it. It's not like we're getting thousands per day. From rhodri at wildebst.demon.co.uk Wed Sep 14 19:26:06 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 15 Sep 2011 00:26:06 +0100 Subject: stackoverflow and c.l.py References: Message-ID: On Wed, 14 Sep 2011 14:05:23 +0100, memilanuk wrote: > Rick & Xang Li are two examples of what you *don't* see (or at least I > don't) @ SO Then you haven't been looking hard enough ;-) -- Rhodri James *-* Wildebeest Herder to the Masses From steve+comp.lang.python at pearwood.info Wed Sep 14 19:58:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 15 Sep 2011 09:58:32 +1000 Subject: stackoverflow and c.l.py References: Message-ID: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> memilanuk wrote: > On 09/14/2011 05:47 AM, Chris Angelico wrote: >> The SNR here isn't bad either. Most of the spam gets filtered out, and >> even stuff like Ranting Rick posts can be of some amusement when it's >> a slow day... > > I subscribe to the list via Gmane, and if 'most of the spam' gets > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > minimum blatant spam per day on here. 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but still.) Since nearly all of it is obvious, it's easy to filter out of your mail client, news client, or if all else fails, your attention. The hard ones to ignore are the ones that look like they might be legitimate, but fortunately most spammers are too lazy or stupid to bother with even the most feeble disguise. Either way, I don't consider half a dozen spam posts a day to be anything more than a minor distraction. Commercial spam is annoying, but otherwise harmless because it is so easy to filter. What's really the problem is crackpots, trollers and griefers, because there is a terrible temptation to engage them in debate: "someone is wrong on the Internet!". If you want to see a news group gone bad, go to something like sci.math. You can't move for the cranks "disproving" Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 is the One True Actual Infinity (I'm not making that last one up!). -- Steven From clp2 at rebertia.com Wed Sep 14 20:41:51 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 17:41:51 -0700 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: <20110914195044.GK4331@johnsons-web.com> References: <20110914195044.GK4331@johnsons-web.com> Message-ID: On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > I have written a class that uses ftplib.FTP as the parent. > I need to reconcile the modified time of a workstation file with > that same filename on a remote server. > Let's say we have a file called '400.shtml'. I get the mtime on > my workstation by >>> os.path.getmtime('400.shtml') > 1311648420.0 http://docs.python.org/library/os.path.html#os.path.getmtime Your sample seems to be a typical Unix timestamp: http://en.wikipedia.org/wiki/Unix_time > And I use >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > '213 20110726004703' RFC 3659 - Extensions to FTP Sec 3. File Modification Time (MDTM) http://tools.ietf.org/html/rfc3659#section-3 (Note: Code 213 = File status response) > My question is how to compare the two outputs? > Pointers to documentation and other resources are invited. Cheers, Chris From du at baow.com Wed Sep 14 21:23:46 2011 From: du at baow.com (=?UTF-8?B?5paH5bGxIOadnA==?=) Date: Wed, 14 Sep 2011 18:23:46 -0700 (PDT) Subject: A documents editor in Firefox with Python Sphinx tool Message-ID: <5b7cd4f0-f3ff-49a1-af00-e899ecb1e93d@z7g2000vbp.googlegroups.com> Baow is a tool that makes it easy to organize your internet resources and create intelligent and beautiful web pages within Firefox web browser. Highlights : * Tree based outline, help you organize internet resources and documents. * Save or bookmark web images, files or pages. * Multi level project management. * Full text search. * Generate web pages by Python Sphinx tools, http://sphinx.pocoo.org . Lots of quick menus help you write and preview Python Sphinx and reStructuredText markup documents. * Multi platform support, Windows, Linux, Mac, etc. Home page: https://addons.mozilla.org/en-US/firefox/addon/baow/ From nevesagar at gmail.com Wed Sep 14 21:41:43 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 07:11:43 +0530 Subject: help regarding re.search Message-ID: Hi, I have a small program where I want to do just a small regex operation. I want to see if value of a variable 'A' is present in an another variable 'B'. The below code works fine but as soon as the variable 'A' has some string including a dot it fails. for example say: B="xxxxyyyydpkg.ipazzzzz The code works fine when A="dpkg" however the code does not work when A="dpkg.ipa" if re.search(A,B): # do something. Can somebody please help me ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nevesagar at gmail.com Wed Sep 14 21:46:06 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 07:16:06 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hi, I have a small program where I want to do just a small regex operation. I want to see if value of a variable 'A' is present in an another variable 'B'. The below code works fine but as soon as the variable 'A' has some string including a dot it fails. for example say: B="xxxxyyyydpkg.ipazzzzz The code works fine when A="dpkg" however the code does not work when A="dpkg.ipa" if re.search(A,B): # do something. Can somebody please help me ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Sep 14 21:55:12 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 18:55:12 -0700 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 6:41 PM, Sagar Neve wrote: > Hi, > I have a small program where I want to do just a small regex operation. > I want to see if value of a variable 'A' is present in an another variable > 'B'.? The below code works fine but as soon as the variable 'A' has some > string including a dot it fails. There's no need to use regexes at all! Just do: if A in B: # do something > for example say: > B="xxxxyyyydpkg.ipazzzzz > The code works fine? when A="dpkg" > however the code does not work when A="dpkg.ipa" Right, because period is a regex metacharacter. To have it treated as a literal character to match, escape it: http://docs.python.org/library/re.html#re.escape Cheers, Chris -- http://rebertia.com From chris at rebertia.com Wed Sep 14 21:57:54 2011 From: chris at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 18:57:54 -0700 Subject: Problem with Dos command by python script In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 1:13 PM, Jonatas Emidio wrote: > Here i come!! > > I have the following problem... > I need run by python script a string with some "DOS commands - Windows > prompt"!! > For exemple: > print 'cd temp' > print 'mkdir temp_app' > > How can i run this string in the python, but as a DOS interpreter? Use the `subprocess` module, and pass shell=True. http://docs.python.org/library/subprocess.html Cheers, Chris From tim at akwebsoft.com Wed Sep 14 22:02:42 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 14 Sep 2011 18:02:42 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: References: <20110914195044.GK4331@johnsons-web.com> Message-ID: <20110915020242.GL4331@johnsons-web.com> * Chris Rebert [110914 16:46]: > On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > > I have written a class that uses ftplib.FTP as the parent. > > I need to reconcile the modified time of a workstation file with > > that same filename on a remote server. > > Let's say we have a file called '400.shtml'. I get the mtime on > > my workstation by > >>> os.path.getmtime('400.shtml') > > 1311648420.0 > > http://docs.python.org/library/os.path.html#os.path.getmtime > Your sample seems to be a typical Unix timestamp: Yup. Needs to be converted to a timedate stamp, methinks. > http://en.wikipedia.org/wiki/Unix_time I'll look at that tomorrow. Late here. > > And I use > >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > > '213 20110726004703' > RFC 3659 - Extensions to FTP > Sec 3. File Modification Time (MDTM) > http://tools.ietf.org/html/rfc3659#section-3 > > (Note: Code 213 = File status response) and '213 20110726004703'[4:] should give me the string representation of the timedate stamp on the remote file. Thanks. I will look at the unix_time entry soon. -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From elven199208 at gmail.com Wed Sep 14 22:26:35 2011 From: elven199208 at gmail.com (zhenzhen zhang) Date: Wed, 14 Sep 2011 19:26:35 -0700 (PDT) Subject: Offer Red Bull Hats superior in quality and price is favourable on http://www.mlbhatshop.com/ Message-ID: <3cc9671e-37d2-4a40-9800-fac7f7a5fdd6@a7g2000yqb.googlegroups.com> MLBHatShop with Original Red Bull Hats, New Era Hats, Monster Energy Hats, Red Bull Beanies, DC Hats, Red Bull New Era Hats, Monster Beanies Sales Promotion. Door to Door Free Shipping. http://www.mlbhatshop.com/ From anikom15 at gmail.com Wed Sep 14 23:05:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 20:05:40 -0700 Subject: stackoverflow and c.l.py In-Reply-To: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110915030540.GA5695@Smoke> On Thu, Sep 15, 2011 at 09:58:32AM +1000, Steven D'Aprano wrote: > memilanuk wrote: > > > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >> The SNR here isn't bad either. Most of the spam gets filtered out, and > >> even stuff like Ranting Rick posts can be of some amusement when it's > >> a slow day... > > > > I subscribe to the list via Gmane, and if 'most of the spam' gets > > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > > minimum blatant spam per day on here. > > 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but > still.) Since nearly all of it is obvious, it's easy to filter out of your > mail client, news client, or if all else fails, your attention. The hard > ones to ignore are the ones that look like they might be legitimate, but > fortunately most spammers are too lazy or stupid to bother with even the > most feeble disguise. > > Either way, I don't consider half a dozen spam posts a day to be anything > more than a minor distraction. > > Commercial spam is annoying, but otherwise harmless because it is so easy to > filter. What's really the problem is crackpots, trollers and griefers, > because there is a terrible temptation to engage them in debate: "someone > is wrong on the Internet!". If you want to see a news group gone bad, go to > something like sci.math. You can't move for the cranks "disproving" > Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 > is the One True Actual Infinity (I'm not making that last one up!). > > > This is really what I love and hate about the internet. It's full of people who argue for the sake of venting their internal frustrations. How many discussions comparing declarative and imperative programming languages have you seen on the web? They are everywhere. Really, there's no point to these discussions, just use what you like, but it's still fun to read and think. This goes into all kinds of subjects. That said, this post is somewhat of a rant and may spur debate. It is what it is, no matter where you are, the internet is just a natural breeder of this kind of thing. From nevesagar at gmail.com Wed Sep 14 23:33:59 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 09:03:59 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: If A in B: does nt seem to be working. Am I missing something here. -$agar On Sep 15, 2011 7:25 AM, "Chris Rebert" wrote: > On Wed, Sep 14, 2011 at 6:41 PM, Sagar Neve wrote: >> Hi, >> I have a small program where I want to do just a small regex operation. >> I want to see if value of a variable 'A' is present in an another variable >> 'B'. The below code works fine but as soon as the variable 'A' has some >> string including a dot it fails. > > There's no need to use regexes at all! Just do: > if A in B: > # do something > >> for example say: >> B="xxxxyyyydpkg.ipazzzzz >> The code works fine when A="dpkg" >> however the code does not work when A="dpkg.ipa" > > Right, because period is a regex metacharacter. To have it treated as > a literal character to match, escape it: > http://docs.python.org/library/re.html#re.escape > > Cheers, > Chris > -- > http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Sep 14 23:35:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 20:35:23 -0700 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: > If A in B: > does nt seem to be working. > Am I missing something here. Please provide a snippet of the code in question, and be specific about how it's not working. Cheers, Chris -- http://rebertia.com From greg.ewing at canterbury.ac.nz Thu Sep 15 00:28:49 2011 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 15 Sep 2011 16:28:49 +1200 Subject: ANN: PyGUI 2.5 In-Reply-To: <17012.1316026038@parc.com> References: <962t3eFgd1U1@mid.individual.net> <17012.1316026038@parc.com> Message-ID: <4E717F01.5090806@canterbury.ac.nz> On 15/09/11 06:47, Bill Janssen wrote: > One possibility would be to develop a PyGUI branch on top of Tk, so that > it would work with Python anywhere. Unfortunately, I doubt whether Tk would be up to the task of supporting PyGUI efficiently. The philosophies of model-view separation and allowing more than one view of a model are at odds with the way Tk works. Anyone who wants to have a go at it is welcome to try, though. -- Greg From nevesagar at gmail.com Thu Sep 15 00:41:53 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:11:53 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Here is the code url="http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa " Man_Param="/us/r1000" Opt_Param1="Purple" Opt_Param2="dpkg.ipa" if (Opt_Param2 in url): print "hello." else: print "bye." It gives me: ./sample.py: line 9: syntax error near unexpected token `:' ./sample.py: line 9: `if (Opt_Param2 in url): ' Help. On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: > On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: > > If A in B: > > does nt seem to be working. > > Am I missing something here. > > Please provide a snippet of the code in question, and be specific > about how it's not working. > > Cheers, > Chris > -- > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Sep 15 00:49:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 14:49:31 +1000 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 2:41 PM, Sagar Neve wrote: > ./sample.py: line 9: syntax error near unexpected token `:' > ./sample.py: line 9: `if (Opt_Param2 in url):??? ' > It worked for me in Python 3.2. What version of Python are you using? ChrisA From nevesagar at gmail.com Thu Sep 15 00:54:13 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:24:13 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: I figured it out with the sample program I gave you. It was my mistake; However, the same thing with same values is not working in my main program. Here is what I am trying: The program traverses with correct values upto the if condition we just discussed; but fails to quality that if condition; instead it should qualify. for key in dictionary: m=re.search(key, url) if m !=None: values=dictionary[key] for v in values: v_array=v.split(',') Man_Param=v_array[4] Opt_Param1=v_array[5] Opt_Param2=v_array[6] Cat=v_array[1] Man_Param=re.sub(r'"(?P.*?)"','\g', Man_Param) Opt_Param1=re.sub(r'"(?P.*?)"','\g', Opt_Param1) Opt_Param2=re.sub(r'"(?P.*?)"','\g', Opt_Param2) Cat=re.sub(r'"(?P.*?)"','\g', Cat) Cat=re.sub(r':','_', Cat) Cat=re.sub(r' ','_', Cat) print "hello..Man_Param=%s,Opt_Param1=%s, Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) #sys.exit(1) if len(Opt_Param1): if len(Opt_Param2): #if (re.search(Man_Param,url) and re.search(Opt_Param1,url) and re.search(Opt_Param2,url) ): print url * if (Man_Param in url):#and (Opt_Param1 in url) and (Opt_Param2 in url): * print "all are found..\n" sys.exit(1) if((int(cl) < 5000 or int(rc) == 206) and re.match(r"AS_D",Cat) ): Cat= Cat + "_cont" foutname = "output" + "/" + Cat +"." + str(cnt) fout =open(foutname, "a") fout.write(line) fout.close else: print "here\n"; sys.exit(1) On Thu, Sep 15, 2011 at 10:19 AM, Chris Angelico wrote: > On Thu, Sep 15, 2011 at 2:41 PM, Sagar Neve wrote: > > ./sample.py: line 9: syntax error near unexpected token `:' > > ./sample.py: line 9: `if (Opt_Param2 in url): ' > > > > It worked for me in Python 3.2. What version of Python are you using? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Thu Sep 15 00:55:19 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 15 Sep 2011 10:25:19 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 10:11 AM, Sagar Neve wrote: > Here is the code > > > url="http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa" > > Man_Param="/us/r1000" > Opt_Param1="Purple" > Opt_Param2="dpkg.ipa" > > if (Opt_Param2 in url): > ??? print "hello." > else: > ??? print "bye." > > It? gives me: > > ./sample.py: line 9: syntax error near unexpected token `:' > ./sample.py: line 9: `if (Opt_Param2 in url):??? ' > > That looks like a bash error message. Syntax errors in python show up with a stack trace. Run your program using the python interpreter like this: python file.py OR python3 file.py whatever is applicable in your environment. > > > On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: >> >> On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: >> > If A in B: >> > does nt seem to be working. >> > Am I missing something here. >> >> Please provide a snippet of the code in question, and be specific >> about how it's not working. >> -- regards, kushal From nevesagar at gmail.com Thu Sep 15 00:58:21 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:28:21 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Yes. It is been resolved now for the sample program. however, as mentioned in other post. It is not working in the main program On Thu, Sep 15, 2011 at 10:25 AM, Kushal Kumaran < kushal.kumaran+python at gmail.com> wrote: > On Thu, Sep 15, 2011 at 10:11 AM, Sagar Neve wrote: > > Here is the code > > > > > > url=" > http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa" > > > > Man_Param="/us/r1000" > > Opt_Param1="Purple" > > Opt_Param2="dpkg.ipa" > > > > if (Opt_Param2 in url): > > print "hello." > > else: > > print "bye." > > > > It gives me: > > > > ./sample.py: line 9: syntax error near unexpected token `:' > > ./sample.py: line 9: `if (Opt_Param2 in url): ' > > > > > > That looks like a bash error message. Syntax errors in python show up > with a stack trace. Run your program using the python interpreter > like this: > > python file.py > OR > python3 file.py > > whatever is applicable in your environment. > > > > > > > On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: > >> > >> On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve > wrote: > >> > If A in B: > >> > does nt seem to be working. > >> > Am I missing something here. > >> > >> Please provide a snippet of the code in question, and be specific > >> about how it's not working. > >> > > -- > regards, > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Sep 15 01:01:52 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 15:01:52 +1000 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 2:55 PM, Kushal Kumaran wrote: > That looks like a bash error message. ?Syntax errors in python show up > with a stack trace. ?Run your program using the python interpreter > like this: > > python file.py > OR > python3 file.py > > whatever is applicable in your environment. > Or add a shebang to the top of your script. ChrisA From python at bdurham.com Thu Sep 15 01:19:20 2011 From: python at bdurham.com (python at bdurham.com) Date: Thu, 15 Sep 2011 01:19:20 -0400 Subject: Cancel or timeout a long running regular expression Message-ID: <1316063960.26516.140258141338017@webmail.messagingengine.com> Is there a way to cancel or timeout a long running regular expression? I have a program that accepts regular expressions from users and I'm concerned about how to handle worst case regular expressions that seem to run forever. Ideally I'm looking for a way to evaluate a regular expression and timeout after a specified time period if the regular expression hasn't completed yet. Or a way for a user to cancel a long running regular expression. I was thinking there might be a technique I could use to evaluate regular expressions in a thread or another process launched via multiprocessing module and then kill the thread/process after a specified timeout period. My concern about the multiprocessing module technique is that launching a process for every regex evaluation sounds pretty inefficient. And I don't think the threading module supports the ability to kill threads from outside a thread itself. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt.pounsett at gmail.com Thu Sep 15 01:20:19 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Wed, 14 Sep 2011 22:20:19 -0700 (PDT) Subject: cause __init__ to return a different class? Message-ID: I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. I've tried both returning the subclass (as I would when overloading an operator) but I get the complaint that __init__ wants to return None instead of a type. The other thing I tried was overwriting 'self' while inside __init__ but that doesn't seem to work either. class Parent(object): def __init__(self, foo): if foo == True: self = Child(foo) class Child(Parent): def __init__(self, foo): pass Is there a way to do this? From GadgetSteve at live.co.uk Thu Sep 15 01:31:06 2011 From: GadgetSteve at live.co.uk (Gadget/Steve) Date: Thu, 15 Sep 2011 06:31:06 +0100 Subject: Problem with Dos command by python script In-Reply-To: References: Message-ID: On 14/09/2011 9:13 PM, Jonatas Emidio wrote: > Here i come!! > > I have the following problem... > I need run by python script a string with some "DOS commands - Windows > prompt"!! > For exemple: > print 'cd temp' > print 'mkdir temp_app' > > How can i run this string in the python, but as a DOS interpreter? The direct answer to your question is to tell you to take a look at the subprocess module documentation but if the above is what you would like to do then take a look as os.chdir(), os.mkdir(), os.mkdirs() and then do the above in python. I would also suggest that you should raise this sort of question at Gadget/Steve From clp2 at rebertia.com Thu Sep 15 01:35:26 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 22:35:26 -0700 Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett wrote: > I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. ?My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. > Is there a way to do this? Override __new__() instead: http://docs.python.org/reference/datamodel.html#object.__new__ Cheers, Chris From ryan at rfk.id.au Thu Sep 15 01:54:06 2011 From: ryan at rfk.id.au (Ryan Kelly) Date: Thu, 15 Sep 2011 15:54:06 +1000 Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: <4E7192FE.7050904@rfk.id.au> On 15/09/11 15:35, Chris Rebert wrote: > On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett > wrote: >> I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. > >> Is there a way to do this? > > Override __new__() instead: > http://docs.python.org/reference/datamodel.html#object.__new__ The above will do exactly what you want, but it's generally bad style unless you have a very specific use-case. Is there a particular reason you need to "magically" return a subclass, rather than making this explicit in the code? To be friendlier to others reading your code, I would consider using a classmethod to create an alternative constructor: class MyBaseClass(object): @classmethod def get_random_subclass(cls, *args, **kwds) subcls = random.choice(cls.__subclasses__()) return subcls(*args, **kwds) To me, this reads pretty cleanly and makes it obvious that something unusual is going on: obj = MyBaseClass.get_random_subclass() While this hides the intention of the code and would require additional documentation or comments: obj = MyBaseClass() # note: actually returns a subclass! Just a thought :-) Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From steve+comp.lang.python at pearwood.info Thu Sep 15 02:00:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 15 Sep 2011 16:00:26 +1000 Subject: cause __init__ to return a different class? References: Message-ID: <4e71947b$0$29998$c3e8da3$5496439d@news.astraweb.com> On Thu, 15 Sep 2011 03:20 pm Matthew Pounsett wrote: > I'm wondering if there's a way in python to cause __init__ to return a > class other than the one initially specified. My use case is that I'd > like to have a superclass that's capable of generating an instance of a > random subclass. You need to override the constructor, not the initializer. By the time __init__ is called, the instance has already been created. > I've tried both returning the subclass (as I would when overloading an > operator) but I get the complaint that __init__ wants to return None > instead of a type. > > The other thing I tried was overwriting 'self' while inside __init__ but > that doesn't seem to work either. No, because self is just an ordinary local variable. Overwriting self just changes the local variable, not the instance. However, you can sometimes modify the instance's class. One sometimes useful trick is something like this: class Test(object): def __init__(self): if condition(): self.__class__ = AnotherClass which will work, and is supported, so long as Test class and AnotherClass are compatible. (If they're not compatible, you'll get an exception.) -- Steven From see.my.homepage at gmail.com Thu Sep 15 02:46:09 2011 From: see.my.homepage at gmail.com (Maciej Sobczak) Date: Wed, 14 Sep 2011 23:46:09 -0700 (PDT) Subject: YAMI4 1.4.0 released Message-ID: <48755301-61d9-4a0e-8baf-52094a719b06@bl1g2000vbb.googlegroups.com> I am pleased to announce that the 1.4.0 version of YAMI4 is available for download: http://www.inspirel.com/yami4 YAMI4 is a messaging solution for distributed systems that supports Ada, C++, Java, .NET and Python. An important improvement in the Python module (both for 2.x and 3.x variants) is that the wrapping interface layer in a natively compiled module was changed so that previously known bugs in the Python standard library (ctypes) were bypassed and now the YAMI4 module should work also on 64-bit platforms. Apart from this strictly Python-related improvement, this new release bring a GUI management console that allows to browse and manage name servers, message brokers and individual agents in a bigger distributed system. -- Maciej Sobczak * http://www.msobczak.com * http://www.inspirel.com From sajuptpm at gmail.com Thu Sep 15 03:44:55 2011 From: sajuptpm at gmail.com (sajuptpm) Date: Thu, 15 Sep 2011 00:44:55 -0700 (PDT) Subject: Change Location in the google search page Message-ID: <2fb9a504-eeca-4b95-b844-cc695e63161d@l7g2000vbz.googlegroups.com> Hi, I want to open Google search page and Change the Location link in the left hand nav of Google) from the users current location to a different location, then return the results of the updated search. I tried to change google search location through http://www.google.co.in/preferences?hl=en#loc , but getting error mechanize._response.httperror_seek_wrapper: HTTP Error 404: Not Found Here is the code i tried ========================================= 1 import re import cookielib from mechanize import Browser import mechanize br1= Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br1.set_cookiejar(cj) br1.set_handle_robots(False) br1.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en- US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] P_URL = "http://www.google.co.in/preferences?hl=en#loc" s_page = br1.open(P_URL) loc_form = br1.select_form(name="langform") br1.form['luul'] = u'bangaluru' # <------ New location resp = br1.submit() print "---------resp---------",resp.read() Output ======= $ python a11.py Traceback (most recent call last): File "a11.py", line 94, in ? resp = br1.submit() File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 541, in submit File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 255, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 404: Not Found ========================================= 2 Tried this also, but getting blank google search page. import re from mechanize import Browser LOGIN_URL = "http://www.google.co.in/search?q=new+york +locksmith&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en- US:official&client=firefox-a" br = Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] s_page = br.open(LOGIN_URL) loc_form = br.select_form(nr=1) loc_text_fld = br.form.find_control(id='lc-input') loc_text_fld.__dict__['_value'] = 'kerala' #Change the Location resp = br.submit() print "\n\n----------resp----------", resp.read() #Returning blank google search page. From gnujohn at gmail.com Thu Sep 15 04:01:37 2011 From: gnujohn at gmail.com (john) Date: Thu, 15 Sep 2011 01:01:37 -0700 (PDT) Subject: stackoverflow and c.l.py References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87120dfa-6b7d-4e03-8ff1-6926cc247cbc@bl1g2000vbb.googlegroups.com> On Sep 14, 4:58?pm, Steven D'Aprano wrote: > memilanuk wrote: > > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >> The SNR here isn't bad either. Most of the spam gets filtered out, and > >> even stuff like Ranting Rick posts can be of some amusement when it's > >> a slow day... > > > I subscribe to the list via Gmane, and if 'most of the spam' gets > > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > > minimum blatant spam per day on here. > > 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but > still.) Since nearly all of it is obvious, it's easy to filter out of your > mail client, news client, or if all else fails, your attention. The hard > ones to ignore are the ones that look like they might be legitimate, but > fortunately most spammers are too lazy or stupid to bother with even the > most feeble disguise. > > Either way, I don't consider half a dozen spam posts a day to be anything > more than a minor distraction. > > Commercial spam is annoying, but otherwise harmless because it is so easy to > filter. What's really the problem is crackpots, trollers and griefers, > because there is a terrible temptation to engage them in debate: "someone > is wrong on the Internet!". If you want to see a news group gone bad, go to > something like sci.math. You can't move for the cranks "disproving" > Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 > is the One True Actual Infinity (I'm not making that last one up!). > > -- > Steven And, all this time, I'd thought it was ((10**603) - 1) that was the highest. Oh, well. From 1248283536 at qq.com Thu Sep 15 04:28:51 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 15 Sep 2011 16:28:51 +0800 Subject: method:wrong structure Message-ID: there are three programs,all of them left main structure, code0 is ok,i don't know why code2 and code3 can't run,how to fix them? code0 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): #loadstatus={'equity':self.loadequity(),'option':self,loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() s.loadequity() code1 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): loadstatus={'equity':self.loadequity(),'option':self,loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() loadstatus['equity'] wrong output is name 'self' is not defined code2 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): loadstatus={'equity':loadequity(),'option':loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() s.loadequity() wrong output is : TypeError: loadequity() takes exactly 1 argument (0 given) -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Sep 15 04:39:48 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 15 Sep 2011 01:39:48 -0700 Subject: method:wrong structure In-Reply-To: References: Message-ID: 2011/9/15 ???? <1248283536 at qq.com>: > there are? three? programs,all of them? left? main? structure, > code0 is ok,i don't know why code2 and code3 can't run,how to fix them? > code0 > class?? webdata(object): > ??? def? __init__(self,arg): > > ??? def? loadequity(self): > > ??? def? loadoption(self): > > ??? #loadstatus={'equity':self.loadequity(),'option':self,loadoption()} > > ??? def? run(self): > > if? __name__=="__main__": > ???? s=webdata('equity').run() > ???? s.loadequity() > > code1 > class?? webdata(object): > ??? def? __init__(self,arg): > > ??? def? loadequity(self): > > ??? def? loadoption(self): > > ??? loadstatus={'equity':self.loadequity(),'option':self,loadoption()} Class definitions are executable code. So the assignment to loadstatus happens *while the class webdata is still being defined*. There is therefore no class instance object or `self` at this point, hence the error when you try and do self.loadequity(): you're trying to call an instance method before it's even possible for there to be instances of the class. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Thu Sep 15 04:39:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 18:39:53 +1000 Subject: stackoverflow and c.l.py In-Reply-To: <20110915030540.GA5695@Smoke> References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> <20110915030540.GA5695@Smoke> Message-ID: On Thu, Sep 15, 2011 at 1:05 PM, Westley Mart?nez wrote: > This is really what I love and hate about the internet. ?It's full of > people who argue for the sake of venting their internal frustrations. > How many discussions comparing declarative and imperative programming > languages have you seen on the web? Yes, it's both normal and useful on the internet to break off conversation to argue about a minor technicality. But it's completely inappropriate in other contexts, to the point that it can be used for comedy. Two characters, in the middle of a rather heated debate, stop to discuss grammar: "Listen - I've come to pinch her!" "Mercy! Whom?" "You mean who." "Nay! It is the accusative after the verb!" ChrisA From gelonida at gmail.com Thu Sep 15 05:05:53 2011 From: gelonida at gmail.com (Gelonida N) Date: Thu, 15 Sep 2011 11:05:53 +0200 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hi Sagar, In order to be able to help you I propose following: On 09/15/2011 06:54 AM, Sagar Neve wrote: . . . > print "hello..Man_Param=%s,Opt_Param1=%s, > Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) Change above line into > print "hello..Man_Param=%r,Opt_Param1=%r, > Opt_Param2=%r\n" %(Man_Param,Opt_Param1,Opt_Param2) and show us the output of an example which is NOT working. printing with '%r" might help to show some 'hidden special characters' From nizamov.shawkat at gmail.com Thu Sep 15 05:08:50 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Thu, 15 Sep 2011 11:08:50 +0200 Subject: method:wrong structure In-Reply-To: References: Message-ID: > > ??? loadstatus={'equity':self.loadequity(),'option':self,loadoption()} > comma instead of dot after self. From nevesagar at gmail.com Thu Sep 15 05:38:12 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 15:08:12 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hey Thanks. I just resolved it and yes you are right there was a (hidden) new-line to it. I found it in a crude way of putting dots before and after. I was to post about it here and saw your message. I was not knowing about %r. Thanks for that. Thats a good addition to my knowledge. Thanks a bunch of all. My day is saved. Best Regards, Sagar Neve. On Thu, Sep 15, 2011 at 2:35 PM, Gelonida N wrote: > Hi Sagar, > > In order to be able to help you I propose following: > > On 09/15/2011 06:54 AM, Sagar Neve wrote: > . . . > > print "hello..Man_Param=%s,Opt_Param1=%s, > > Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) > > Change above line into > > > print "hello..Man_Param=%r,Opt_Param1=%r, > > Opt_Param2=%r\n" %(Man_Param,Opt_Param1,Opt_Param2) > > > and show us the output of an example which is NOT working. > > printing with '%r" might help to show some 'hidden special characters' > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From k.sahithi2862 at gmail.com Thu Sep 15 06:06:43 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Thu, 15 Sep 2011 03:06:43 -0700 (PDT) Subject: DEEPIKA PADUKONE IN DUM MARO DUM MOVIE Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html AISHWARYA RAI DIFFERENT PICS http://southactresstou.blogspot.com/2011/05/aishwarya-rai.html DEEPIKA PADUKONE NEW STILLS http://southactresstou.blogspot.com/2011/05/deepika-padukone_22.html SAMANTHA HOT EXCLUSIVE PHOTOS http://southactresstou.blogspot.com/2011/09/south-actress-samantha.html FOR EXCLUSIVE HOT ASIN PICS http://southactresstou.blogspot.com/2011/09/asin.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From tartley at tartley.com Thu Sep 15 06:31:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 15 Sep 2011 03:31:16 -0700 (PDT) Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: <73c4a919-555b-453c-8cf7-eec3e645e419@glegroupsg2000goo.googlegroups.com> Perhaps a more idiomatic way of achieving the same thing is to use a factory function, which returns instances of different classes: def PersonFactory(foo): if foo: return Person() else: return Child() Apologies if the code is messed up, I'm posting from Google groups web UI. From arnodel at gmail.com Thu Sep 15 07:10:58 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 12:10:58 +0100 Subject: How does a function know the docstring of its code object? Message-ID: Hi all, You can do: def foo(): "foodoc" pass function = type(lambda:0) foo2 = function(foo.__code__, globals()) assert foo2.__doc__ == "foodoc" I am wondering how the function constructor knows that foo.__code__ has a docstring. I can see that foo.__code__.co_consts == ('foodoc',) But I can't find where in foo.__code__ is stored the information that the first constant in foo.__code__ is actually a docstring. -- Arnaud From keymint1498 at gmail.com Thu Sep 15 08:51:45 2011 From: keymint1498 at gmail.com (superhappyfuntime) Date: 15 Sep 2011 12:51:45 GMT Subject: What is wrong with this code? Message-ID: it's not running. here it is: #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. #this is defines what means what. you can just read howto.pdf instead of this part. here it is: = '\begin{document}' it's an article = '\documentclass article' it's a book = '\documentclass{book}' it's a letter = '\documentclass{letter}' it's a report = '\documentclass{report}' it's called = '\title{' it's over! = '\end{document}' #this is where you come in: type what you want below using the terms explained in howto.pdf print ('it's an article it's called test} here it is: Hello World! it's over!') -- I'm trying a new usenet client for Mac, Nemo OS X, since 0 days. You can download it at http://www.malcom-mac.com/nemo From python at mrabarnett.plus.com Thu Sep 15 09:02:27 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 15 Sep 2011 14:02:27 +0100 Subject: Turkic I and re Message-ID: <4E71F763.2010109@mrabarnett.plus.com> I'm interested to know the opinion of Turkish users of the re or regex module. When the re module performs a case-insensitive match, it matches 'I' with 'i'. In Turkish, however, it should match 'I' with '?' and '?' with 'i'. The regex module at http://pypi.python.org/pypi/regex currently uses a compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' with 'i'. I was wondering if it would be preferable to have a TURKIC flag instead ("(?T)" or "(?T:...)" in the pattern). Without the Turkic flag it would match 'I' with 'i'; with Turkic flag it would match 'I' with '?' and '?' with 'i'. From me at alanplum.com Thu Sep 15 09:16:15 2011 From: me at alanplum.com (Alan Plum) Date: Thu, 15 Sep 2011 15:16:15 +0200 Subject: Turkic I and re In-Reply-To: <4E71F763.2010109@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4E71FA9F.8090702@alanplum.com> On 2011-09-15 15:02, MRAB wrote: > The regex module at http://pypi.python.org/pypi/regex currently uses a > compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' > with 'i'. > > I was wondering if it would be preferable to have a TURKIC flag instead > ("(?T)" or "(?T:...)" in the pattern). I think the problem many people ignore when coming up with solutions like this is that while this behaviour is pretty much unique for Turkish script, there is no guarantee that Turkish substrings won't appear in other language strings (or vice versa). For example, foreign names in Turkish are often given as spelled in their native (non-Turkish) script variants. Likewise, Turkish names in other languages are often given as spelled in Turkish. The Turkish 'I' is a peculiarity that will probably haunt us programmers until hell freezes over. Unless Turkey abandons its traditional orthography or people start speaking only a single language at a time (including names), there's no easy way to deal with this. In other words: the only way to make use of your proposed flag is if you have a fully language-tagged input (e.g. an XML document making extensive use of xml:lang) and only ever apply regular expressions to substrings containing one culture at a time. From me at alanplum.com Thu Sep 15 09:24:45 2011 From: me at alanplum.com (Alan Plum) Date: Thu, 15 Sep 2011 15:24:45 +0200 Subject: using python in web applications In-Reply-To: <4E6C05CD.3010905@tysdomain.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> <4E6C05CD.3010905@tysdomain.com> Message-ID: <4E71FC9D.1080603@alanplum.com> On 2011-09-11 02:50, Littlefield, Tyler wrote: > I replied to that one off list I guess, but I figured Django was way > more overhead than I wanted, doesn't really fit with solving the speed > issue. Depending on your needs, you may find something like bottle or Flask a better choice then. Django can be scaled down a lot, but it's a full-featured framework at its heart. Bottle is pretty minimal (IIRC it doesn't even come with any templating). Flask is somewhere in between as it bundles Werkzeug (a pure WSGI framework) with Jinja (a template library) with some glue code. I have used Flask in the past but often found myself implementing half of Django anyway, which is why I eventually switched. When I only need a bare API with no database and without templates, I usually go for Bottle these days. If you feel like coding closer to the metal and care more about performance than readability, you might also find Twisted useful. From roy at panix.com Thu Sep 15 09:42:33 2011 From: roy at panix.com (Roy Smith) Date: Thu, 15 Sep 2011 09:42:33 -0400 Subject: using python in web applications References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> <4E6C05CD.3010905@tysdomain.com> Message-ID: In article , Alan Plum wrote: > Django can be scaled down a lot, but it's a full-featured framework at > its heart. You can pick and chose which parts of django you want to use. You don't need to use any of the Django model stuff. You don't need to use any of the template system. You can tear out all or most of the default middleware. At that point, about all that's left is the route parser and dispatch code. The nice thing about this is that as you incrementally discover which pieces of it you really do need, it's easy to pull them in. That being said, we've made a lot of use of Tornado for small stand-alone web services with just a couple of routes. In retrospect, it's unclear if there's any justifiable argument for why we use both Tornado and Django, other than hysterical raisins. From johnjohn.tedro at gmail.com Thu Sep 15 09:44:54 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Thu, 15 Sep 2011 13:44:54 +0000 Subject: Turkic I and re In-Reply-To: <4E71FA9F.8090702@alanplum.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> Message-ID: On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum wrote: > On 2011-09-15 15:02, MRAB wrote: > >> The regex module at http://pypi.python.org/pypi/**regexcurrently uses a >> compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' >> with 'i'. >> >> I was wondering if it would be preferable to have a TURKIC flag instead >> ("(?T)" or "(?T:...)" in the pattern). >> > > I think the problem many people ignore when coming up with solutions like > this is that while this behaviour is pretty much unique for Turkish script, > there is no guarantee that Turkish substrings won't appear in other language > strings (or vice versa). > > For example, foreign names in Turkish are often given as spelled in their > native (non-Turkish) script variants. Likewise, Turkish names in other > languages are often given as spelled in Turkish. > > The Turkish 'I' is a peculiarity that will probably haunt us programmers > until hell freezes over. Unless Turkey abandons its traditional orthography > or people start speaking only a single language at a time (including names), > there's no easy way to deal with this. > > In other words: the only way to make use of your proposed flag is if you > have a fully language-tagged input (e.g. an XML document making extensive > use of xml:lang) and only ever apply regular expressions to substrings > containing one culture at a time. > > -- > http://mail.python.org/**mailman/listinfo/python-list > Python does not appear to support special cases mapping, in effect, it is not 100% compliant with the unicode standard. The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case Mappings) of the unicode standard. http://www.unicode.org/versions/Unicode6.0.0/ch05.pdf#G21180 AFAIK, the case methods of python strings seems to be built around the assumption that len("string") == len("string".upper()), but some of these casing rules require that the string grow. Like uppercasing of the german sharp s "?" which should be translated to the expanded string "SS". These special cases should be triggered on specific locales, but I have not been able to verify that the Turkic uppercasing of "i" works on either python 2.6, 2.7 or 3.1: locale.setlocale(locale.LC_ALL, "tr_TR.utf8") # warning, requires turkish locale on your system. ord("i".upper()) == 0x130 # is False for me, but should be True I wouldn't be surprised if these issues are translated into the 're' module. The only support appears to be 'L' switch, but it only makes "\w, \W, \b, \B, \s and \S dependent on the current locale". Which probably does not yield to the special rules mentioned above, but I could be wrong. Make sure that your locale is correct and test again. If you are unsuccessful, I don't see a 'Turkic flag' being introduced into re module any time soon, given the following from PEP 20 "Special cases aren't special enough to break the rules" Cheers, -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Sep 15 10:06:08 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 15 Sep 2011 15:06:08 +0100 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> Message-ID: <4E720650.8010101@mrabarnett.plus.com> On 15/09/2011 14:44, John-John Tedro wrote: > On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum > wrote: > > On 2011-09-15 15:02, MRAB wrote: > > The regex module at http://pypi.python.org/pypi/__regex > currently uses a > compromise, where it matches 'I' with 'i' and also 'I' with '?' > and '?' > with 'i'. > > I was wondering if it would be preferable to have a TURKIC flag > instead > ("(?T)" or "(?T:...)" in the pattern). > > > I think the problem many people ignore when coming up with solutions > like this is that while this behaviour is pretty much unique for > Turkish script, there is no guarantee that Turkish substrings won't > appear in other language strings (or vice versa). > > For example, foreign names in Turkish are often given as spelled in > their native (non-Turkish) script variants. Likewise, Turkish names > in other languages are often given as spelled in Turkish. > > The Turkish 'I' is a peculiarity that will probably haunt us > programmers until hell freezes over. Unless Turkey abandons its > traditional orthography or people start speaking only a single > language at a time (including names), there's no easy way to deal > with this. > > In other words: the only way to make use of your proposed flag is if > you have a fully language-tagged input (e.g. an XML document making > extensive use of xml:lang) and only ever apply regular expressions > to substrings containing one culture at a time. > > -- > http://mail.python.org/__mailman/listinfo/python-list > > > > Python does not appear to support special cases mapping, in effect, it > is not 100% compliant with the unicode standard. > > The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case > Mappings ) > of the unicode standard. > http://www.unicode.org/versions/Unicode6.0.0/ch05.pdf#G21180 > > AFAIK, the case methods of python strings seems to be built around the > assumption that len("string") == len("string".upper()), but some of > these casing rules require that the string grow. Like uppercasing of the > german sharp s "?" which should be translated to the expanded string "SS". > These special cases should be triggered on specific locales, but I have > not been able to verify that the Turkic uppercasing of "i" works on > either python 2.6, 2.7 or 3.1: > > locale.setlocale(locale.LC_ALL, "tr_TR.utf8") # warning, requires > turkish locale on your system. > ord("i".upper()) == 0x130 # is False for me, but should be True > > I wouldn't be surprised if these issues are translated into the 're' module. > There has been some discussion on the Python-dev list about improving Unicode support in Python 3. It's somewhat unlikely that Unicode will become locale-dependent in Python because it would cause problems; you don't want: "i".upper() == "I" to be maybe true, maybe false. An option would be to specify whether it should be locale-dependent. > The only support appears to be 'L' switch, but it only makes "\w, \W, > \b, \B, \s and \S dependent on the current locale". That flag is for locale-dependent 8-bit encodings. The ASCII (Python 3), LOCALE and UNICODE flags are mutually exclusive. > Which probably does not yield to the special rules mentioned above, but > I could be wrong. Make sure that your locale is correct and test again. > > If you are unsuccessful, I don't see a 'Turkic flag' being introduced > into re module any time soon, given the following from PEP 20 > "Special cases aren't special enough to break the rules" > That's why I'm interested in the view of Turkish users. The rest of us will probably never have to worry about it! :-) (There's a report in the Python bug tracker about this issue, which is why the regex module has the compromise.) From ulrich.eckhardt at dominolaser.com Thu Sep 15 10:17:18 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 15 Sep 2011 16:17:18 +0200 Subject: What is wrong with this code? References: Message-ID: <38d9k8-u8t.ln1@satorlaser.homedns.org> superhappyfuntime wrote: > #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. It's LaTeX, not Python. Uli From gordon at panix.com Thu Sep 15 10:21:41 2011 From: gordon at panix.com (John Gordon) Date: Thu, 15 Sep 2011 14:21:41 +0000 (UTC) Subject: What is wrong with this code? References: Message-ID: In superhappyfuntime writes: > it's not running. here it is: > #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > #this is defines what means what. you can just read howto.pdf instead > of this part. > here it is: = '\begin{document}' > it's an article = '\documentclass article' > it's a book = '\documentclass{book}' > it's a letter = '\documentclass{letter}' > it's a report = '\documentclass{report}' > it's called = '\title{' > it's over! = '\end{document}' > #this is where you come in: type what you want below using the terms > explained in howto.pdf > print ('it's an article it's called test} here it is: Hello World! > it's over!') You cannot use words like it's inside a single-quoted string. Either escape the word like this: it\'s or enclose the entire string in double quotes. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From matt.pounsett at gmail.com Thu Sep 15 10:41:29 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Thu, 15 Sep 2011 07:41:29 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> On Sep 15, 1:35?am, Chris Rebert wrote: > Override __new__() instead: > http://docs.python.org/reference/datamodel.html#object.__new__ Aha.. thanks! The reference book I'm working from neglects to mention __new__, so I'd assumed __init__ was the constructor. It hadn't occurred to me that python would separate the functions (I still don't see exactly why it would be useful to do that, but perhaps insight will come with time). From matt.pounsett at gmail.com Thu Sep 15 10:45:12 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Thu, 15 Sep 2011 07:45:12 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <028d3cb7-3724-42e8-b347-31eedf9ef149@i5g2000vbw.googlegroups.com> On Sep 15, 1:54?am, Ryan Kelly wrote: > The above will do exactly what you want, but it's generally bad style > unless you have a very specific use-case. ?Is there a particular reason > you need to "magically" return a subclass, rather than making this > explicit in the code? > > To be friendlier to others reading your code, I would consider using a > classmethod to create an alternative constructor: Yeah, I was considering doing this as well, particularly if I couldn't have made the other work. The reason I'm not too concerned about anyone misinterpreting what's going on is that in this case the base class is actually named for being a constructor, and any rare case where I want a specific subclass the subclass will be created directly. Thanks very much for your help! From python.list at tim.thechases.com Thu Sep 15 11:00:09 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Sep 2011 10:00:09 -0500 Subject: Turkic I and re In-Reply-To: <4E720650.8010101@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> <4E720650.8010101@mrabarnett.plus.com> Message-ID: <4E7212F9.4040804@tim.thechases.com> On 09/15/11 09:06, MRAB wrote: > It's somewhat unlikely that Unicode will become locale-dependent in > Python because it would cause problems; you don't want: > > "i".upper() == "I" > > to be maybe true, maybe false. > > An option would be to specify whether it should be locale-dependent. There have been several times when I've wished that unicode strings would grow something like .locale_aware_insensitive_cmp(other[, locale=locale.getdefaultlocale()] ) to return -1/0/1 like cmp(), or in case sort-order is nonsensical/arbitrary (such as for things like Mandarin glyphs) .insensitive_locale_equal(other,[, locale=locale.getdefaultlocale()] ) so you could do something like if "i".locale_aware_insensitive_cmp("I"): not_equal() else: equal() or if "i".insensitive_locale_equal("I"): equal() else: not_equal() because while I know that .upper() or .lower() doesn't work in a lot of cases, I don't really care about the upper/lower'ness of the result, I want to do an insensitive compare (and most of teh time it's just for equality, not for sorting). It's my understanding[1] that the same goes for the German where "?".upper() is traditionally written as "SS" but "SS".lower() is traditionally just "ss" instead of "?". So if these language-dependent comparisons were relegated to a well-tested core method of a unicode string, it may simplify the work/issue for you. -tkc [1] http://en.wikipedia.org/wiki/Letter_case#Special_cases From yasar11732 at gmail.com Thu Sep 15 11:04:27 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 15 Sep 2011 18:04:27 +0300 Subject: Turkic I and re In-Reply-To: <4E720650.8010101@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> <4E720650.8010101@mrabarnett.plus.com> Message-ID: Hi, I am a Turkish self-taught python user. Personally, I don't think I am in a position to discuss a issue in this scale. But in my opinion, I think pardus* developers should be invited to join to this discussion. As they are using python heavily on most of their projects** I think they would have something valueable to say about this subject. Here is the pardus-developers mailing list : http://liste.pardus.org.tr/mailman/listinfo/pardus-devel And as for me, I always expect Turkish locale might cause problems, and use some workarounds if neccessary. For example, If I needed to match lower-case or upper-case Turkish "i", I would probably go with [i?] with unicode flag. *) a linux distro developed by Scientific & Technological Research Council of Turkey **) http://developer.pardus.org.tr/projects/index.html 2011/9/15 MRAB > On 15/09/2011 14:44, John-John Tedro wrote: > >> On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum > > wrote: >> >> On 2011-09-15 15:02, MRAB wrote: >> >> The regex module at http://pypi.python.org/pypi/__**regex >> > >> currently uses a >> compromise, where it matches 'I' with 'i' and also 'I' with '?' >> and '?' >> with 'i'. >> >> I was wondering if it would be preferable to have a TURKIC flag >> instead >> ("(?T)" or "(?T:...)" in the pattern). >> >> >> I think the problem many people ignore when coming up with solutions >> like this is that while this behaviour is pretty much unique for >> Turkish script, there is no guarantee that Turkish substrings won't >> appear in other language strings (or vice versa). >> >> For example, foreign names in Turkish are often given as spelled in >> their native (non-Turkish) script variants. Likewise, Turkish names >> in other languages are often given as spelled in Turkish. >> >> The Turkish 'I' is a peculiarity that will probably haunt us >> programmers until hell freezes over. Unless Turkey abandons its >> traditional orthography or people start speaking only a single >> language at a time (including names), there's no easy way to deal >> with this. >> >> In other words: the only way to make use of your proposed flag is if >> you have a fully language-tagged input (e.g. an XML document making >> extensive use of xml:lang) and only ever apply regular expressions >> to substrings containing one culture at a time. >> >> -- >> http://mail.python.org/__**mailman/listinfo/python-list >> >> > >> >> >> Python does not appear to support special cases mapping, in effect, it >> is not 100% compliant with the unicode standard. >> >> The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case >> Mappings > pdf#G21180 >> >) >> >> of the unicode standard. >> http://www.unicode.org/**versions/Unicode6.0.0/ch05.**pdf#G21180 >> >> AFAIK, the case methods of python strings seems to be built around the >> assumption that len("string") == len("string".upper()), but some of >> these casing rules require that the string grow. Like uppercasing of the >> german sharp s "?" which should be translated to the expanded string "SS". >> These special cases should be triggered on specific locales, but I have >> not been able to verify that the Turkic uppercasing of "i" works on >> either python 2.6, 2.7 or 3.1: >> >> locale.setlocale(locale.LC_**ALL, "tr_TR.utf8") # warning, requires >> turkish locale on your system. >> ord("i".upper()) == 0x130 # is False for me, but should be True >> >> I wouldn't be surprised if these issues are translated into the 're' >> module. >> >> There has been some discussion on the Python-dev list about improving > Unicode support in Python 3. > > It's somewhat unlikely that Unicode will become locale-dependent in > Python because it would cause problems; you don't want: > > "i".upper() == "I" > > to be maybe true, maybe false. > > An option would be to specify whether it should be locale-dependent. > > > The only support appears to be 'L' switch, but it only makes "\w, \W, >> \b, \B, \s and \S dependent on the current locale". >> > > That flag is for locale-dependent 8-bit encodings. The ASCII (Python > 3), LOCALE and UNICODE flags are mutually exclusive. > > > Which probably does not yield to the special rules mentioned above, but >> I could be wrong. Make sure that your locale is correct and test again. >> >> If you are unsuccessful, I don't see a 'Turkic flag' being introduced >> into re module any time soon, given the following from PEP 20 >> "Special cases aren't special enough to break the rules" >> >> That's why I'm interested in the view of Turkish users. The rest of us > will probably never have to worry about it! :-) > > (There's a report in the Python bug tracker about this issue, which is > why the regex module has the compromise.) > > -- > http://mail.python.org/**mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Sep 15 11:17:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 15 Sep 2011 09:17:53 -0600 Subject: How does a function know the docstring of its code object? In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 5:10 AM, Arnaud Delobelle wrote: > Hi all, > > You can do: > > def foo(): > ? ?"foodoc" > ? ?pass > > function = type(lambda:0) > foo2 = function(foo.__code__, globals()) > assert foo2.__doc__ == "foodoc" > > I am wondering how the function constructor knows that foo.__code__ > has a docstring. ?I can see that > > ? ?foo.__code__.co_consts == ('foodoc',) > > But I can't find where in foo.__code__ is stored the information that > the first constant in foo.__code__ is actually a docstring. >From what I'm seeing, it appears that if there is no docstring, the first constant will always be None. So if the first constant is a string, then it's a docstring. From Genevieve.Diagorn at open-groupe.com Thu Sep 15 11:30:11 2011 From: Genevieve.Diagorn at open-groupe.com (=?iso-8859-1?Q?Genevi=E8ve_Diagorn?=) Date: Thu, 15 Sep 2011 17:30:11 +0200 Subject: From Python on Solaris to Python on LINUX Message-ID: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Hi, I work on projects developed in Python 2.3 on Solaris. The customer asks us to pass on LINUX in a recent version of Python. Is it someone has already realized this modification? What are the traps to be avoided? Is it a long and difficult phase? What is the most recent version on LINUX? Thanks. Genevi?ve -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Thu Sep 15 11:44:46 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 16:44:46 +0100 Subject: How does a function know the docstring of its code object? In-Reply-To: References: Message-ID: On 15 September 2011 16:17, Ian Kelly wrote: > On Thu, Sep 15, 2011 at 5:10 AM, Arnaud Delobelle wrote: >> Hi all, >> >> You can do: >> >> def foo(): >> ? ?"foodoc" >> ? ?pass >> >> function = type(lambda:0) >> foo2 = function(foo.__code__, globals()) >> assert foo2.__doc__ == "foodoc" >> >> I am wondering how the function constructor knows that foo.__code__ >> has a docstring. [...] > > From what I'm seeing, it appears that if there is no docstring, the > first constant will always be None. ?So if the first constant is a > string, then it's a docstring. > Yes it seems to be the case. Even if None is not used in the function, it appears in co_consts. Good thinking! Thanks, -- Arnaud From fulvio.valente at strath.ac.uk Thu Sep 15 11:55:13 2011 From: fulvio.valente at strath.ac.uk (Fulvio Valente) Date: Thu, 15 Sep 2011 16:55:13 +0100 Subject: Request for research feedback Message-ID: <4296A2DFD9C6B4499A22AA3E585D715902D6AF01B7F1@E2K7-MS3.ds.strath.ac.uk> Hi, I am a research intern at the University of Strathclyde who has been doing a summer research internship. I hope that this is not an inappropriate place to ask, but I am looking for participants willing to use and evaluate an application that was written as part of this internship. If you choose to participate, this should only take no more than an hour or two of your time at the very most, unless you wish to not use the analysis files provided. My project is to experiment with ways of inferring and displaying socio-technical information about a software project from a version control repository by creating a prototype application. The application infers authorship information in the form of "closeness scores" between authors and the files they have worked on by traversing the history of a Mercurial repository. This is then displayed as a map of socio-technical dependencies between files and the authors that worked on them and between authors and the files they have worked on, which should allow for easy visual comparisons of closeness. Some potential applications and use cases I can envision in the program's current form include discovering who the key figures are (i.e. who to talk to about a problem) or what the bus factor (how many people need to be "hit by a bus" before a project is in trouble because there's nobody left who understands it) is for a project or a subsystem within it. Perhaps a little more depressingly, this also maybe be used to highlight potential cases of poor productivity to be investigated. The program itself, Jimmy (for lack of a better name), has a binary distribution which can be found at http://geeksoc.org/~fvalente/jimmy/jimmy_r1.zip and only requires Java 7 and Mercurial (other libraries are included), getting you started quickly. The source is available at https://bitbucket.org/fvalente/jimmy and if you wish to build it yourself, it depends on Guava r09 and JUNG 2.0.1 (api, algorithms, graph-impl, visualization) which itself depends on Apache Commons collections-generic 4.0.1. To perform a basic analysis of a project, you can open a directory that's a Mercurial repository and it will just look at the list of commits and the files that changed, adding 1 to a score each time an author touches a file, which should only take a minute or two, even for large projects. If you have more time, you can do the more expensive diff stats analysis which compares the size of each diff with the average diff size of the project, excluding empty diffs and binary changes. Unfortunately, the diff stats analysis is very slow due to retrieving each diff requiring the spawning of a hg subprocess (for reference, my 4 year old quad-core machine can do only ~10,000 commits per hour). I don't have a progress UI yet, but progress status is sent to stdout when doing a diff stats analysis. Once analysis is complete, you can save the results to review later by using the open analysis results option. To navigate the results you can switch to viewing a particular file or author of interest from the file and author lists on the left. For files, this will display that file as a node in the centre with the authors that have been involved with it as orbiting nodes, with the connecting lines' length, thickness and colour shortening, thickening and approaching red respectively as the closeness score between that author and the file increases. For authors, it is the same except the files they have worked on will be the orbiting nodes. You can also directly navigate to having a display based on an orbiting node by clicking it in the display rather than searching through the file or author lists. The display can be zoomed by using the scroll wheel and can be translated with the scroll bars or by dragging on an area not occupied by a node. What I would like is for you to please run Jimmy on one or more Mercurial repositories of your choice and to give some feedback on it. Some questions I'd particularly like answered are: * Do the closeness scores it produces match with your perception of the relationships between people and code in the project? (e.g. if you're looking at a particular file and some authors involved in it are shown as closer than others, is this the result you would have expected from a perfect version of Jimmy?) * Does the visualisation of the scores substantially improve your ability to draw conclusions from the data compared to just reading a saved analysis (which is just plaintext)? * If, hypothetically, you had no prior knowledge about the project, would using it help you to discover the key figures (e.g. maintainer, BDFL) behind the project or any of its subsystems? (Alternatively, do such people correctly show up as having touched a wider variety of files and with closer relations to them than other people?) * If you were a manager would you be able to use it to discover potential productivity issues that you would then investigate further? To help save you time from having to do a full analysis of a project, I have supplied analysis files from 3 open-source projects which you can open with the "Open analysis results" option: * cpython: http://geeksoc.org/~fvalente/jimmy/cpython.txt * libSDL: http://geeksoc.org/~fvalente/jimmy/libsdl.txt * Go: http://geeksoc.org/~fvalente/jimmy/golang.txt Some general suggestions on whether and why the current ways of inferring closeness scores and visualising that data are flawed would also be greatly appreciated, as well as potential avenues to explore for improving them. Suggestions I've already received include: * Being able to collapse files into folders or subsystem groups to make larger projects more navigable, perhaps with autoexpansion when zooming the display. In its current form, Jimmy produces disappointing/funny results when you want to see a diagram for, say, a large project's maintainer. * Being able to mine data from a subset of the repository (time range, revision range, include/exclude files/directories, etc.) * Reducing the closeness score contributions of multiple commits made in quick succession, or another method of mitigating the bias in favour of fine-grained committers * Reducing the closeness score contributions of older commits * Interfacing with Mercurial via the recently introduced command server API, which should hopefully make performance non-abysmal * Support for more version control systems. Git would top this list * Perhaps the ability to see a timeline for the project and how closeness changes over time Responses can be made privately to me, if you wish. For the purposes of my report, I will also anonymise all responses received in line with ethical best practices. Thank you for reading. From dmitrey15 at gmail.com Thu Sep 15 12:24:58 2011 From: dmitrey15 at gmail.com (dmitrey) Date: Thu, 15 Sep 2011 09:24:58 -0700 (PDT) Subject: [ANN} OpenOpt, FuncDesigner, DerApproximator, SpaceFuncs release 0.36 Options Message-ID: Hi all, new release of our free scientific soft (OpenOpt, FuncDesigner, DerApproximator, SpaceFuncs) v. 0.36 is out: OpenOpt: Now solver interalg can handle all types of constraints and integration problems Some minor improvements and code cleanup FuncDesigner: Interval analysis now can involve min, max and 1-d monotone splines R -> R of 1st and 3rd order Some bugfixes and improvements SpaceFuncs: Some minor changes DerApproximator: Some improvements for obtaining derivatives in points from R^n where left or right derivative for a variable is absent, especially for stencil > 1 See http://openopt.org for more details. Regards, D. From phihag at phihag.de Thu Sep 15 12:26:04 2011 From: phihag at phihag.de (Philipp Hagemeister) Date: Thu, 15 Sep 2011 18:26:04 +0200 Subject: From Python on Solaris to Python on LINUX In-Reply-To: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> References: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Message-ID: <4E72271C.1020502@phihag.de> > What are the traps to be avoided? Assuming you're not using any OS features (scan the code for "/dev" and "/proc"), the transition from Solaris to Linux will be seamless. Your main problem will be the transition from the archaic Python 2.3 to a modern one. Luckily, all 2.x Pythons should be backwards-compatible. In summary, your application should work just fine (although being written in 2.3, it's probably not as maintainable as a modern application would). > What is the most recent version on LINUX? There are multiple Linux distributions which can differ quite a lot. debian, Ubuntu, and CentOS are popular ones. As you can see on http://www.debian.org/CD/ , the current debian version is 6.0. As you can't see at the moment on http://kernel.org/ , the current Linux kernel version is 3.0 (although most distribution will want to test the kernel and therefore include a slightly older one). -- Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature URL: From miki.tebeka at gmail.com Thu Sep 15 12:37:44 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 15 Sep 2011 09:37:44 -0700 (PDT) Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: I'd go for a factory function (http://en.wikipedia.org/wiki/Factory_method_pattern): def create(foo): return Child(foo) if foo else Parent() From neuroniru at gmail.com Thu Sep 15 12:40:01 2011 From: neuroniru at gmail.com (neeru K) Date: Thu, 15 Sep 2011 22:10:01 +0530 Subject: help regarding extracting a smaller list from larger one Message-ID: Dear Python Users, I am trying to write a code for visualization (raster plots and peri-event time histogram) of time series electrophysiological data using numpy, scipy and matlplotlib in python. I am importing the data into list using loadtext command. I was curious if anyone is aware of a function in numpy that can *extract a smaller list containing numbers from a larger list* given the upper and lower limit of the values between which the smaller list lies. Thank you in advance. Sincerely, niranjan -- Niranjan Kambi Senior Research Fellow, Neeraj Lab, National Brain Research Centre, Manesar, Gurgaon-122050 Haryana, INDIA Ph:+919818654846 website:- http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html email:- neuro.niru at nbrc.res.in, neuroniru at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Thu Sep 15 12:57:24 2011 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 15 Sep 2011 18:57:24 +0200 Subject: how to make a nested list Message-ID: <4E722E74.7030908@gmail.com> hello, I need a nested list, like this >>> A= [ [None,None], [None,None], [None, None] ] >>> A[2][0] =77 >>> A [[None, None], [None, None], [77, None]] Because the list is much larger, I need a shortcut (ok I can use a for loop) So I tried >>> B = 3 * [ [ None, None ]] >>> B[2][0] = 77 >>> B [[77, None], [77, None], [77, None]] which doesn't work as expected. any suggestions ? thanks, Stef From ramit.prasad at jpmorgan.com Thu Sep 15 13:09:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 13:09:07 -0400 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFACA@EMARC112VS01.exchad.jpmchase.net> >>> B = 3 * [ [ None, None ]] That makes a list of the exact same list object: [ a, a, a ] where a = [ None, None ]. Instead I would do something like (untested python2.x): B = [ [ None, None ] for x in xrange(3) ] Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ppearson at nowhere.invalid Thu Sep 15 13:17:42 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 15 Sep 2011 17:17:42 GMT Subject: how to make a nested list References: Message-ID: <9deq9lFpo7U1@mid.individual.net> On Thu, 15 Sep 2011 18:57:24 +0200, Stef Mientki wrote: [snip] > Because the list is much larger, I need a shortcut (ok I can use a for loop) > So I tried > >>> B = 3 * [ [ None, None ]] > >>> B[2][0] = 77 > >>> B > [[77, None], [77, None], [77, None]] > > which doesn't work as expected. > > any suggestions ? >>> b = [[None, None] for i in range(3)] >>> b[2][0] = 77 >>> b [[None, None], [None, None], [77, None]] If you don't understand why the other approach resulted in [[77, None], [77, None], [77, None]], feel free to ask. It's a mistake that I think everybody makes at least once. -- To email me, substitute nowhere->spamcop, invalid->net. From gherron at digipen.edu Thu Sep 15 13:24:15 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 10:24:15 -0700 Subject: help regarding extracting a smaller list from larger one In-Reply-To: References: Message-ID: <4E7234BF.5030101@digipen.edu> On 09/15/2011 09:40 AM, neeru K wrote: > Dear Python Users, > I am trying to write a code for visualization (raster plots and > peri-event time histogram) of time series electrophysiological data > using numpy, scipy and matlplotlib in python. I am importing the data > into list using loadtext command. > I was curious if anyone is aware of a function in numpy that can > *extract a smaller list containing numbers from a larger list* given > the upper and lower limit of the values between which the smaller list > lies. > Thank you in advance. > Sincerely, > niranjan > > -- > Niranjan Kambi > Senior Research Fellow, > Neeraj Lab, > National Brain Research Centre, > Manesar, Gurgaon-122050 > Haryana, INDIA > Ph:+919818654846 > website:- > http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html > email:- neuro.niru at nbrc.res.in , > neuroniru at gmail.com > Do mean to extract a sub-list from a list based on lower and upper indexes into the list? Python has a standard notation for indicating sub-lists, and numpy implements them: >>> a = numpy.array(range(10)) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a[3:6] array([3, 4, 5]) If you mean something else, please be more specific, and we'll try again. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From howe.steven at gmail.com Thu Sep 15 13:27:53 2011 From: howe.steven at gmail.com (GrayShark) Date: Thu, 15 Sep 2011 12:27:53 -0500 Subject: From Python on Solaris to Python on LINUX References: Message-ID: I think that was more of a version question the Kernel questin 1) you can install any and all versions python on a linux computer. You just need you app to select the correct path, correct python interpret. Likely there many be some some drivers in /dev that are not the same as in Solaris. But that shouldn't daunt you. So start by installing python2.3, then test and fix version by version through python2.7. python3.0 might be a pretty be rewrite. 2) Try to pick a version of linux supported locally; likely SuSE, even though Novell/Attachmate owns it. SuSE seems popular in Europe. On Thu, 15 Sep 2011 18:26:04 +0200, Philipp Hagemeister wrote: >> What are the traps to be avoided? > > Assuming you're not using any OS features (scan the code for "/dev" and > "/proc"), the transition from Solaris to Linux will be seamless. > > Your main problem will be the transition from the archaic Python 2.3 to > a modern one. Luckily, all 2.x Pythons should be backwards-compatible. > > In summary, your application should work just fine (although being > written in 2.3, it's probably not as maintainable as a modern > application would). > >> What is the most recent version on LINUX? > There are multiple Linux distributions which can differ quite a lot. > debian, Ubuntu, and CentOS are popular ones. As you can see on > http://www.debian.org/CD/ , the current debian version is 6.0. As you > can't see at the moment on http://kernel.org/ , the current Linux kernel > version is 3.0 (although most distribution will want to test the kernel > and therefore include a slightly older one). > > -- Philipp From gherron at digipen.edu Thu Sep 15 13:28:23 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 10:28:23 -0700 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: <4E7235B7.4030207@digipen.edu> On 09/15/2011 09:57 AM, Stef Mientki wrote: > hello, > > I need a nested list, like this > > >>> A= [ [None,None], [None,None], [None, None] ] > >>> A[2][0] =77 > >>> A > [[None, None], [None, None], [77, None]] > > > Because the list is much larger, I need a shortcut (ok I can use a for > loop) > So I tried > >>> B = 3 * [ [ None, None ]] > >>> B[2][0] = 77 > >>> B > [[77, None], [77, None], [77, None]] > > which doesn't work as expected. > > any suggestions ? > > thanks, > Stef A for loop to fill in the array would work, but list comprehension (which is really just an internal loop for filling an array) is probably more efficient, certainly less code, and arguably more Pythonic. A = [ [None,None] for i in range(1000) ] Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From tim at akwebsoft.com Thu Sep 15 13:38:16 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 15 Sep 2011 09:38:16 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: <20110915020242.GL4331@johnsons-web.com> References: <20110914195044.GK4331@johnsons-web.com> <20110915020242.GL4331@johnsons-web.com> Message-ID: <20110915173816.GM4331@johnsons-web.com> * Tim Johnson [110914 18:18]: > * Chris Rebert [110914 16:46]: > > On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > > > I have written a class that uses ftplib.FTP as the parent. > > > I need to reconcile the modified time of a workstation file with > > > that same filename on a remote server. > > > Let's say we have a file called '400.shtml'. I get the mtime on > > > my workstation by > > >>> os.path.getmtime('400.shtml') > > > 1311648420.0 > > > > http://docs.python.org/library/os.path.html#os.path.getmtime > > Your sample seems to be a typical Unix timestamp: > Yup. Needs to be converted to a timedate stamp, methinks. > > http://en.wikipedia.org/wiki/Unix_time > I'll look at that tomorrow. Late here. > > > And I use > > >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > > > '213 20110726004703' > > > RFC 3659 - Extensions to FTP > > Sec 3. File Modification Time (MDTM) > > http://tools.ietf.org/html/rfc3659#section-3 > > > > (Note: Code 213 = File status response) > and '213 20110726004703'[4:] should give me > the string representation of the timedate stamp on the > remote file. FYI: datetime.datetime.fromtimestamp(mod_time) Is probably what I was looking for. However, for my purposes - I'm going to take another approach. Every uploaded file is defined in an object stored on my workstationr: I will store the MDTM string after upload and then on the next upload, compare the stored string with the return value from ftp.sendcmd('MDTM ' + filename) Thanks for the input. -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From arnodel at gmail.com Thu Sep 15 13:39:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 18:39:34 +0100 Subject: cause __init__ to return a different class? In-Reply-To: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> References: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> Message-ID: On 15 September 2011 15:41, Matthew Pounsett wrote: > On Sep 15, 1:35?am, Chris Rebert wrote: >> Override __new__() instead: >> http://docs.python.org/reference/datamodel.html#object.__new__ > > Aha.. thanks! ?The reference book I'm working from neglects to mention > __new__, so I'd assumed __init__ was the constructor. ?It hadn't > occurred to me that python would separate the functions (I still don't > see exactly why it would be useful to do that, but perhaps insight > will come with time). If you're interested in the reason, I suggest you read Guido's essay on "new style classes" which were introduced in Python 2.2 (and are now a good 10 years old I think): http://www.python.org/download/releases/2.2.3/descrintro -- Arnaud From ladasky at my-deja.com Thu Sep 15 14:43:33 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 11:43:33 -0700 (PDT) Subject: how to make a nested list References: Message-ID: Stef, Are your bottom-level lists always of length 2? If so, then you could use an array, instead of a list of lists. Python ships with a module called array, but it doesn't allow you to put non-numeric types into arrays, and it looks like you want the NoneType. I use the popular numpy module, which does allow non- numeric types. You might also like the slice notation that numpy uses for referencing items in the array. The indices go inside a single set of square brackets, and are separated by commas. >>> from numpy import empty >>> B = empty((3,2), object) >>> B array([[None, None], [None, None], [None, None]], dtype=object) >>> B[2,0] = 77 >>> B array([[None, None], [None, None], [77, None]], dtype=object) From tjreedy at udel.edu Thu Sep 15 14:54:57 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Sep 2011 14:54:57 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: <1316063960.26516.140258141338017@webmail.messagingengine.com> References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On 9/15/2011 1:19 AM, python at bdurham.com wrote: > Is there a way to cancel or timeout a long running regular expression? > I have a program that accepts regular expressions from users and I'm > concerned about how to handle worst case regular expressions that seem > to run forever. Ideally I'm looking for a way to evaluate a regular > expression and timeout after a specified time period if the regular > expression hasn't completed yet. Or a way for a user to cancel a long > running regular expression. This is a general problem when evaluating *any* expression from the outside. [0]*10000*10000 will eat space as well as time. At least, as far as I know, an re cannot cause a disk reformat ;-). There have been previous discussions on this generally topic. > I was thinking there might be a technique I could use to evaluate > regular expressions in a thread or another process launched via > multiprocessing module and then kill the thread/process after a > specified timeout period. Only solution I remember ever seen posted. I wonder if there are any heuristics for detecting exponential time re's. > My concern about the multiprocessing module > technique is that launching a process for every regex evaluation sounds > pretty inefficient. And I don't think the threading module supports the > ability to kill threads from outside a thread itself. -- Terry Jan Reedy From neuroniru at gmail.com Thu Sep 15 14:55:08 2011 From: neuroniru at gmail.com (neeru K) Date: Fri, 16 Sep 2011 00:25:08 +0530 Subject: help regarding extracting a smaller list from larger one In-Reply-To: <4E7234BF.5030101@digipen.edu> References: <4E7234BF.5030101@digipen.edu> Message-ID: Dear Gary, thank you for the reply. I will be more specific and take the same example that you have given and tell you what is my problem - array([0.0, 1.3, 2.45, 3.87, 4.54, 5.11, 6.90, 7.78, 8.23, 9.01]) from this array I want to a sub-list with lower and upper indexes that are not present in the above array for example - sub-list[3, 8] Is there a function for this? thank you niranjan On Thu, Sep 15, 2011 at 10:54 PM, Gary Herron wrote: > On 09/15/2011 09:40 AM, neeru K wrote: > >> Dear Python Users, >> I am trying to write a code for visualization (raster plots and peri-event >> time histogram) of time series electrophysiological data using numpy, scipy >> and matlplotlib in python. I am importing the data into list using loadtext >> command. >> I was curious if anyone is aware of a function in numpy that can *extract >> a smaller list containing numbers from a larger list* given the upper and >> lower limit of the values between which the smaller list lies. >> Thank you in advance. >> Sincerely, >> niranjan >> >> -- >> Niranjan Kambi >> Senior Research Fellow, >> Neeraj Lab, >> National Brain Research Centre, >> Manesar, Gurgaon-122050 >> Haryana, INDIA >> Ph:+919818654846 >> website:- http://www.nbrc.ac.in/faculty/**neeraj/Lab_webpage/Niranjan_** >> Kambi.html >> email:- neuro.niru at nbrc.res.in , >> neuroniru at gmail.com >> >> Do mean to extract a sub-list from a list based on lower and upper > indexes into the list? Python has a standard notation for indicating > sub-lists, and numpy implements them: > > >>> a = numpy.array(range(10)) > >>> a > array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >>> a[3:6] > array([3, 4, 5]) > > If you mean something else, please be more specific, and we'll try again. > > Gary Herron > > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wm at localhost.localdomain Thu Sep 15 15:14:11 2011 From: wm at localhost.localdomain (Waldek M.) Date: Thu, 15 Sep 2011 21:14:11 +0200 Subject: Request for research feedback References: Message-ID: <1oxwvsczcdfj4$.dlg@localhost.localdomain> On Thu, 15 Sep 2011 16:55:13 +0100, Fulvio Valente wrote: > Hi, I am a research intern at the University of Strathclyde > who has been doing a summer research internship. I don't want to be rude, but please: could you rather first research how to use a newsreader before you use it? These long lines (a few times the limit of 78 characters per line) make your post unreadable. Thanks, Waldek From nagle at animats.com Thu Sep 15 15:27:58 2011 From: nagle at animats.com (John Nagle) Date: Thu, 15 Sep 2011 12:27:58 -0700 Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7251c1$0$1673$742ec2ed@news.sonic.net> On 8/31/2011 5:40 AM, Chris Withers wrote: > On 31/08/2011 13:33, Steven D'Aprano wrote: >> I am using Linux desktops; both incidents were with Python 2.5. Do newer >> versions of Python respond to this sort of situation more gracefully? > > Ironically, Windows does better here and dumps you out with a > MemoryError before slowly recovering. > > Linux seems to fair badly when programs use more memory than physically > available. Linux virtual memory has some known design problems. For example, you can crash many Linux systems with a program which opens large files and accesses them randomly, combined with another program which is spawning processes that need a fair amount of memory. The disk caching system tries to use all unused memory, and when process startup is consuming pages, it's possible to get into a situation where a page is needed, the task requesting it can't block, and a lock preventing freeing a file cache page is set. Arguably, paging to disk is obsolete. RAM is too cheap and disk is too slow. John Nagle From ramit.prasad at jpmorgan.com Thu Sep 15 16:11:13 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 16:11:13 -0400 Subject: Request for research feedback In-Reply-To: <1oxwvsczcdfj4$.dlg@localhost.localdomain> References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFF05@EMARC112VS01.exchad.jpmchase.net> I don't want to be rude but... Rude: >I don't want to be rude, but please: could you rather first research >how to use a newsreader before you use it? >These long lines (a few times the limit of 78 characters per line) >make your post unreadable. Not rude: >These long lines (a few times the limit of 78 characters per line) >make your post unreadable. Sincerely, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From fulvio.valente at strath.ac.uk Thu Sep 15 16:19:46 2011 From: fulvio.valente at strath.ac.uk (Fulvio Valente) Date: Thu, 15 Sep 2011 21:19:46 +0100 Subject: Request for research feedback In-Reply-To: <1oxwvsczcdfj4$.dlg@localhost.localdomain> References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <4E725DE2.7050704@strath.ac.uk> Whoops, I thought the rather iffy Exchange web client at my institution would've wrapped outgoing messages automatically. I'm now using a proper client for that account which should prevent such issues in the future. Thanks for the heads up. For anyone who couldn't stand to read the original message, a fixed version is at http://geeksoc.org/~fvalente/jimmy/request.txt (figured it'd be rude to repost it directly in this message). On 15/09/2011 20:14, Waldek M. wrote: > On Thu, 15 Sep 2011 16:55:13 +0100, Fulvio Valente wrote: > >> Hi, I am a research intern at the University of Strathclyde >> who has been doing a summer research internship. > > I don't want to be rude, but please: could you rather first research > how to use a newsreader before you use it? > These long lines (a few times the limit of 78 characters per line) > make your post unreadable. > > Thanks, > Waldek -- Regards, - Fulvio From ladasky at my-deja.com Thu Sep 15 16:52:45 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 13:52:45 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption Message-ID: Suppose that I have a multi-core computer with N CPU's, and I create a multiprocessing.Pool in Python 2.6 with N-1 Processes. (My rationale for choosing N-1 Processes was discussed here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/65ba3ccd4be8228c) Then I use Pool.map_async() to break up a long-running task T1 into M chunks, where M > 2N. Suppose that I have a second, parallelizable, long-running task T2 that I want to address in REAL TIME when the need arises. Using Pool, is there a way for me to insert the chunks of T2 at the HEAD of the task queue, instead of at its TAIL? I've been snooping around inside Pool, and I would guess that what I want to do is to manipulate Pool._inqueue, which is a multiprocessing.queues.SimpleQueue object. I haven't found any documentation for SimpleQueue. It appears to have only the most rudimentary of public methods -- put, get, and empty. Reading further, I can see that multiprocessing.Queue (not the same as SimpleQueue) has put_nowait(), which looks like what I need. Assuming that I had access to put_nowait(), then I would need an option in map_async() which would invoke put_nowait() rather than just plain put(). Does anyone know of an efficient way to accomplish this? I'm thinking that a subclass of Pool which replaces the SimpleQueue with a full- fledged Queue, and which overrides map_async() allowing for a no-wait task, would be very useful... but maybe I'm re-inventing the wheel. Thanks for your advice! From ladasky at my-deja.com Thu Sep 15 17:49:53 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 14:49:53 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Message-ID: Hate to bump this, but... I found Sourceforge's IRC, and tried to ask for help there, and it doesn't look like I can get any help until business hours tomorrow. Anyone? From vlastimil.brom at gmail.com Thu Sep 15 18:02:10 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 16 Sep 2011 00:02:10 +0200 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: 2011/9/15 Stef Mientki : > hello, > > I need a nested list, like this > >>>> A= [ [None,None], [None,None], [None, None] ] >>>> A[2][0] =77 >>>> A > [[None, None], [None, None], [77, None]] > ... > > thanks, > Stef > -- > http://mail.python.org/mailman/listinfo/python-list > Besides the above sugestions to correct the nested list approach, if you need to set and access the data at the given "coordinates" you could also use a nested defaultdict, which doesn't need to be pre-filled before setting, e.g.: >>> from collections import defaultdict as dd >>> def dd_dd(): ... return dd(dd) ... >>> dd_matrix = dd(dd_dd) >>> >>> dd_matrix[2][0] = 77 >>> dd_matrix[2][0] 77 >>> dd_matrix defaultdict(, {2: defaultdict(, {0: 77})}) >>> However, the nested list are concise enough, I guess. Regards, vbr From rosuav at gmail.com Thu Sep 15 18:14:00 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:14:00 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: References: Message-ID: On Fri, Sep 16, 2011 at 6:52 AM, John Ladasky wrote: > Suppose that I have a second, parallelizable, long-running task T2 > that I want to address in REAL TIME when the need arises. ?Using Pool, > is there a way for me to insert the chunks of T2 at the HEAD of the > task queue, instead of at its TAIL? > That's a self-contradiction there. Even if you insert a task into the head of the queue, it won't be addressed in real time; the only way to do that would be to have a dedicated process, always ready to handle the real-time events, or else some kind of interrupt system. But if you just want them handled when there's a worker available, what you're after is a priority queue system. I don't know if one exists in Python already or not, but if not, it'd be a worthwhile addition. ChrisA From rosuav at gmail.com Thu Sep 15 18:22:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:22:42 +1000 Subject: how to make a nested list In-Reply-To: References: <4E722E74.7030908@gmail.com> Message-ID: On Fri, Sep 16, 2011 at 8:02 AM, Vlastimil Brom wrote: > Besides the above sugestions to correct the nested list approach, > if you need to set and access the data at the given "coordinates" you > could also use a nested defaultdict... The defaultdict is efficient for a sparse matrix, but I suspect that it'd be rather worse if you use all the elements. ChrisA From gherron at digipen.edu Thu Sep 15 18:25:18 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 15:25:18 -0700 Subject: help regarding extracting a smaller list from larger one In-Reply-To: References: <4E7234BF.5030101@digipen.edu> Message-ID: <4E727B4E.4000400@digipen.edu> On 09/15/2011 11:55 AM, neeru K wrote: > Dear Gary, > thank you for the reply. > I will be more specific and take the same example that you have given > and tell you what is my problem - > array([0.0, 1.3, 2.45, 3.87, 4.54, 5.11, 6.90, 7.78, 8.23, 9.01]) > from this array I want to a sub-list with lower and upper indexes that > are not present in the above array for example - sub-list[3, 8] > Is there a function for this? > thank you > niranjan You say "index", but I think that is not what you mean. An index is in integer referring to an element's position in the array. The "value" at an index is what I believe you are referring to. Nevertheless, I think list comprehension is what you want: [ x for x in A if 3.0 <= x <= 8.0 ] will extract all the values between 3 and 8 from the array A and create a new list containing them. If you want the new list to be a numpy array then numpy.array([ x for x in A if 3.0 <= x <= 8.0 ]) > > > On Thu, Sep 15, 2011 at 10:54 PM, Gary Herron > wrote: > > On 09/15/2011 09:40 AM, neeru K wrote: > > Dear Python Users, > I am trying to write a code for visualization (raster plots > and peri-event time histogram) of time series > electrophysiological data using numpy, scipy and matlplotlib > in python. I am importing the data into list using loadtext > command. > I was curious if anyone is aware of a function in numpy that > can *extract a smaller list containing numbers from a larger > list* given the upper and lower limit of the values between > which the smaller list lies. > Thank you in advance. > Sincerely, > niranjan > > -- > Niranjan Kambi > Senior Research Fellow, > Neeraj Lab, > National Brain Research Centre, > Manesar, Gurgaon-122050 > Haryana, INDIA > Ph:+919818654846 > website:- > http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html > email:- neuro.niru at nbrc.res.in > >, neuroniru at gmail.com > > > > Do mean to extract a sub-list from a list based on lower and upper > indexes into the list? Python has a standard notation for > indicating sub-lists, and numpy implements them: > > >>> a = numpy.array(range(10)) > >>> a > array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >>> a[3:6] > array([3, 4, 5]) > > If you mean something else, please be more specific, and we'll try > again. > > Gary Herron > > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From ladasky at my-deja.com Thu Sep 15 18:25:49 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 15:25:49 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> On Sep 15, 3:14?pm, Chris Angelico wrote: > On Fri, Sep 16, 2011 at 6:52 AM, John Ladasky wrote: > > Suppose that I have a second, parallelizable, long-running task T2 > > that I want to address in REAL TIME when the need arises. ?Using Pool, > > is there a way for me to insert the chunks of T2 at the HEAD of the > > task queue, instead of at its TAIL? > > That's a self-contradiction there. Even if you insert a task into the > head of the queue, it won't be addressed in real time; the only way to > do that would be to have a dedicated process, always ready to handle > the real-time events, or else some kind of interrupt system. > > But if you just want them handled when there's a worker available, > what you're after is a priority queue system. I don't know if one > exists in Python already or not, but if not, it'd be a worthwhile > addition. > > ChrisA Hi, Chris, Sorry if I'm not quite familiar with the proper terminology for queues. Let me try to define what I need as precisely as I can. 1) I aim to keep all five child Processes as busy as possible at all times, crunching numbers. 2) I break my data for the low-priority task, T1, into large enough chunks to benefit from multiprocessing, but small enough so that any given Process should become available fairly frequently -- say, every 50 milliseconds. Starting 50 milliseconds late would be close enough to "real time" for my purposes. 3) But let's say that T1 still has twenty chunks in the Process queue when T2 comes along. I could be waiting 300 milliseconds for the queue to empty. If I could just ensure that T2 gets the next available Processes, I would be happy. Since T2 is also parallelizable and I am using five child Processes, I would divide T2 into exactly five chunks. These chunks should get inserted at positions 0-4 in the queue rather than at 20-24. T2 would briefly commandeer all five Processes and then clear out. If that's not putting T2 at the head of the queue, I guess I don't know a better way to describe it. From ladasky at my-deja.com Thu Sep 15 18:32:43 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 15:32:43 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> Ah. Now, see? Having the right vocabulary helps. Searching for "priority queue" brings up this discussion from back in January: http://groups.google.com/group/comp.lang.python/browse_frm/thread/b69aeced28634898 Now, this discussion refers to a PriorityPool class which doesn't appear to be a standard part of Python (2.6, anyway). But I'm not the first one to ask the question, and there's code out there. From rosuav at gmail.com Thu Sep 15 18:32:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:32:53 +1000 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Fri, Sep 16, 2011 at 4:54 AM, Terry Reedy wrote: > On 9/15/2011 1:19 AM, python at bdurham.com wrote: >> I was thinking there might be a technique I could use to evaluate >> regular expressions in a thread or another process launched via >> multiprocessing module and then kill the thread/process after a >> specified timeout period. > > Only solution I remember ever seen posted. Then here's a minor refinement. Since long-running RE is the exceptional case, optimize for the other. Keep the process around and feed it all the jobs you get, and on problem, kill and respawn. That way, you pay most of the overhead cost only when you make use of the separation. (There's still some IPC overhead of course. Can't escape that.) ChrisA From rosuav at gmail.com Thu Sep 15 18:35:20 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:35:20 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> References: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> Message-ID: On Fri, Sep 16, 2011 at 8:25 AM, John Ladasky wrote: > Starting 50 milliseconds late would be close enough > to "real time" for my purposes. > ... > > If that's not putting T2 at the head of the queue, I guess I don't > know a better way to describe it. Yep, your terms are correct, with that caveat ("immediate" or "urgent" without being "real-time"). So you're definitely looking for a priority queue. It may be possible to patch a different queue object straight into Pool, but I've never done anything like that. It's probably best to dig in the code and add an option somewhere to pass in a queue object - that'd be a very useful feature imho. ChrisA From rosuav at gmail.com Thu Sep 15 18:52:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:52:46 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> References: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> Message-ID: On Fri, Sep 16, 2011 at 8:32 AM, John Ladasky wrote: > Ah. Now, see? ?Having the right vocabulary helps. ?Searching for > "priority queue" brings up this discussion from back in January: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/b69aeced28634898 > > Now, this discussion refers to a PriorityPool class which doesn't > appear to be a standard part of Python (2.6, anyway). ?But I'm not the > first one to ask the question, and there's code out there. Awesome! I wasn't aware of that (although considering the volume of traffic on this list, I doubt there's any human who knows everything that's been discussed). Previously-solved problems save everyone a lot of trouble. ChrisA From cs at zip.com.au Thu Sep 15 18:54:40 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 16 Sep 2011 08:54:40 +1000 Subject: From Python on Solaris to Python on LINUX In-Reply-To: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> References: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Message-ID: <20110915225440.GA26026@cskk.homeip.net> On 15Sep2011 17:30, Genevi?ve Diagorn wrote: | I work on projects developed in Python 2.3 on Solaris. The customer asks us | to pass on LINUX in a recent version of Python. | | Is it someone has already realized this modification? What are the traps to | be avoided? | | Is it a long and difficult phase? Aside from the very minor things mentioned by others, only two things occur to me: - if you use the struct module and you're moving from SPARC to Intel the endianness of some things may change - if you call external shell commands, there are (usually minor) differences between the Solaris and GNU toolsets Neither seems likely to be a big problem and of course both are "outside Python" in a sense. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Do not taunt Happy Fun Coder. From ramit.prasad at jpmorgan.com Thu Sep 15 19:16:05 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 19:16:05 -0400 Subject: help regarding extracting a smaller list from larger one In-Reply-To: <4E727B4E.4000400@digipen.edu> References: <4E7234BF.5030101@digipen.edu> <4E727B4E.4000400@digipen.edu> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CF01B7@EMARC112VS01.exchad.jpmchase.net> >Nevertheless, I think list comprehension is what you want: > [ x for x in A if 3.0 <= x <= 8.0 ] >will extract all the values between 3 and 8 from the array A and create >a new list containing them. >If you want the new list to be a numpy array then > numpy.array([ x for x in A if 3.0 <= x <= 8.0 ]) I have been told that the following is much faster than list generation for filtering if you are using numpy arrays. I have not looked to see if this claim is accurate, but since it was one of the SciPy creators....I trust him :) YMMV foo = numpy.array([ [1.2,2.3,1.3], [4.3,2.1,6.2], [3.2,1.2,6.5], [1.4,2.1,4.3]]) #if we want 2nd element > 2 and 3rd element < 6 mask = (foo[:,2]>2)&(foo[:,2]<6) v = foo[mask] #this is a view and if you want a new list, you will have to wrap it # I assume np.array(v) will create new array (untested). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From sohel807 at gmail.com Fri Sep 16 00:48:30 2011 From: sohel807 at gmail.com (Akand Islam) Date: Thu, 15 Sep 2011 21:48:30 -0700 (PDT) Subject: Comparisons of computation timing Message-ID: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> I have run my codes (written in Python) in my Notebook (3 GB Ram, Dual- core CPU T4500 @ 2.3 GHz) and in my lab machine (11.57 GB Ram, i7-920 CPU @ 2.67 GHz). However, I have found execution time in Notebook 250.3 seconds, and in Lab machine 333.2 seconds. How is it possible? Good configuration machine performs slower??? I reran the codes, same finding whatsoever. I run Windows 7 in my laptop, and Ubuntu 11.04 in lab machine. Both are 64 bit. When I ran my simulation in Notebook, I also did some other stuffs; however for the case of lab machine I did nothing other than running simulation only. About the codes: Basically it simply solves some non-linear equations using "fsolve" along with some other calculations. I will appreciate if some one discusses about possible reasons? For fair comparisons, in both machines I ran exactly the same codes. My codes are not parallelized, is this the main reason i7 processes show slower performance? Thanks in advance, Akand From wm at localhost.localdomain Fri Sep 16 01:46:52 2011 From: wm at localhost.localdomain (Waldek M.) Date: Fri, 16 Sep 2011 07:46:52 +0200 Subject: Request for research feedback References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <1drj37uduixks$.dlg@localhost.localdomain> On Thu, 15 Sep 2011 16:11:13 -0400, Prasad, Ramit wrote: > I don't want to be rude but... > Not rude: > Rude: You're right. I must have gotten a few bad habits I didn't even realize. Thanks. Waldek From ladasky at my-deja.com Fri Sep 16 02:31:49 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 23:31:49 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: On Sep 15, 1:52?pm, John Ladasky wrote: > I've been snooping around inside Pool, and I would guess that what I > want to do is to manipulate Pool._inqueue, which is a > multiprocessing.queues.SimpleQueue object. ?I haven't found any > documentation for SimpleQueue. ?It appears to have only the most > rudimentary of public methods -- put, get, and empty. Reading more deeply, I think that my first guess was incorrect. There's also Pool._taskqueue, and it's a full-fledged Queue. It appears that map.async() puts pending jobs there, not in Pool._inqueue. If this is true, then all that should have to be done is to override a few methods. I'm going to try it. From chunuan723 at gmail.com Fri Sep 16 02:39:23 2011 From: chunuan723 at gmail.com (he sharon) Date: Thu, 15 Sep 2011 23:39:23 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <43895317-a79b-44ef-b85e-9adccd37309a@i5g2000vbw.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on. on our site: www.popbaseballhats.com From 1248283536 at qq.com Fri Sep 16 02:39:28 2011 From: 1248283536 at qq.com (=?utf-8?B?YWxpYXM=?=) Date: Fri, 16 Sep 2011 14:39:28 +0800 Subject: parse html:what is the meaning of "//"? Message-ID: code1: import lxml.html import urllib down='http://finance.yahoo.com/q/op?s=C+Options' content=urllib.urlopen(down).read() root=lxml.html.document_fromstring(content) table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] tds=table.xpath("tr[@valign='top']//td") for td in tds: print td.text_content() what i get is : Call Options Expire at close Friday, September 16, 2011 these are waht i want. code2 import lxml.html import urllib down='http://finance.yahoo.com/q/op?s=C+Options' content=urllib.urlopen(down).read() root=lxml.html.document_fromstring(content) table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] tds=table.xpath("//tr[@valign='top']//td") for td in tds: print td.text_content() what i get is : N/A N/A 2 114 48.00 C110917P00048000 16.75 0.00 N/A N/A 0 23 50.00 C110917P00050000 23.16 0.00 N/A N/A 115 2,411 Highlighted options are in-the-money. (omit something) there is only one difference between code1 and code2 : in code1 is : tds=table.xpath("tr[@valign='top']//td") in code2 is: tds=table.xpath("//tr[@valign='top']//td") i want to know why the "//" make output different? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 16 03:01:39 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 16 Sep 2011 09:01:39 +0200 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: Am 15.09.2011 15:16 schrieb Alan Plum: > The Turkish 'I' is a peculiarity that will probably haunt us programmers > until hell freezes over. That's why it would have been nice if the Unicode guys had defined "both Turkish i-s" at separate codepoints. Then one could have the three pairs I, i ("normal") I (other one), ? and ?, i (the other one). But alas, they haven't. Thomas From steve+comp.lang.python at pearwood.info Fri Sep 16 03:19:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 17:19:05 +1000 Subject: Comparisons of computation timing References: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> Message-ID: <4e72f86a$0$29976$c3e8da3$5496439d@news.astraweb.com> Akand Islam wrote: > I have run my codes (written in Python) in my Notebook (3 GB Ram, Dual- > core CPU T4500 @ 2.3 GHz) and in my lab machine (11.57 GB Ram, i7-920 > CPU @ 2.67 GHz). However, I have found execution time in Notebook > 250.3 seconds, and in Lab machine 333.2 seconds. How is it possible? > Good configuration machine performs slower??? I reran the codes, same > finding whatsoever. I run Windows 7 in my laptop, and Ubuntu 11.04 in > lab machine. Both are 64 bit. When I ran my simulation in Notebook, I > also did some other stuffs; however for the case of lab machine I did > nothing other than running simulation only. In a modern, multi-processing operating system like Windows, Mac OS or Linux, you can *never* run only the simulation. There are always other processes running. Even if you have no other applications running, the system itself could have dozens or hundreds of processes running in the background. On one of my Linux systems, a desktop running about four applications, I have over two hundred processes: [steve at orac ~]$ ps aux | wc -l 218 Without knowing more about the two systems, and the code you ran, it is impossible to say why one is faster than the other. Your question is like this: "I drove from home to work with an old Toyota, and it took twenty minutes. Then the next day, I borrowed my cousin's brand new Ferrari, and the same journey took thirty minutes. How is this possible?" On the Ubuntu machine, what does "ulimit -a" report? How does that compare to the Window machine? Where there any cron jobs running at the time? Did your Ubuntu system decide that this was a good time to download a whole lot of system updates? Can you use the "nice" command to run at a higher priority? Is your code limited by CPU, memory or disk I/O? Which desktop environment is your Ubuntu system running, Gnome, Unity, KDE, Ratpoison, or something else? There could be dozens of factors that make a difference to speed. > About the codes: Basically it simply solves some non-linear equations > using "fsolve" along with some other calculations. What is "fsolve"? > I will appreciate if some one discusses about possible reasons? For > fair comparisons, in both machines I ran exactly the same codes. My > codes are not parallelized, is this the main reason i7 processes show > slower performance? Don't believe hardware manufacturer's advertising. These days, chip speed is not so important. Cache misses are MUCH more critical: a slow chip with a big cache will out-perform a fast chip with a small cache nearly always. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 16 03:25:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 17:25:39 +1000 Subject: Turkic I and re References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4e72f9f4$0$30003$c3e8da3$5496439d@news.astraweb.com> Thomas Rachel wrote: > Am 15.09.2011 15:16 schrieb Alan Plum: > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers >> until hell freezes over. Meh, I don't think it's much more peculiar that any other diacritic issue. If I'm German or English, I probably want ? and O to match during case-insensitive comparisons, so that Z?e and ZOE match. If I'm Icelandic, I don't. I don't really see why Turkic gets singled out. > That's why it would have been nice if the Unicode guys had defined "both > Turkish i-s" at separate codepoints. > > Then one could have the three pairs > I, i ("normal") > I (other one), ? > > and > > ?, i (the other one). And then people will say, "How can I match both sorts of dotless uppercase I but not dotted I when I'm doing comparisons?" -- Steven From nizamov.shawkat at gmail.com Fri Sep 16 03:30:01 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Fri, 16 Sep 2011 09:30:01 +0200 Subject: Comparisons of computation timing In-Reply-To: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> References: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> Message-ID: > About the codes: Basically it simply solves some non-linear equations > using "fsolve" along with some other calculations. > Looks like you are using some third party libraries like numpy/scipy. Do these libraries have the same version on both platforms? What about python interpreter versions - are they the same? Best regards, Shavkat Nizamov From johnjohn.tedro at gmail.com Fri Sep 16 04:00:16 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Fri, 16 Sep 2011 08:00:16 +0000 Subject: Fwd: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> <4e72f9f4$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 16, 2011 at 7:25 AM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > Thomas Rachel wrote: > > > Am 15.09.2011 15:16 schrieb Alan Plum: > > > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers > >> until hell freezes over. > > > Meh, I don't think it's much more peculiar that any other diacritic issue. > If I'm German or English, I probably want ? and O to match during > case-insensitive comparisons, so that Z?e and ZOE match. If I'm Icelandic, > I don't. I don't really see why Turkic gets singled out. > > > > That's why it would have been nice if the Unicode guys had defined "both > > Turkish i-s" at separate codepoints. > > > > Then one could have the three pairs > > I, i ("normal") > > I (other one), ? > > > > and > > > > ?, i (the other one). > > And then people will say, "How can I match both sorts of dotless uppercase > I > but not dotted I when I'm doing comparisons?" > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > Yeah, it's more probable that language conventions and functions grow around characters that look right. No one except developers care what specific codepoint they have, so soon you would have a mish-mash of special rules converting between each special case. P.S. Sorry Steven, i missed clicking "reply to all". -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From keobox at gmail.com Fri Sep 16 05:30:08 2011 From: keobox at gmail.com (keobox) Date: Fri, 16 Sep 2011 02:30:08 -0700 (PDT) Subject: why ps/fname of a python interpreter changes across platforms? Message-ID: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Hello, I'm writing a little supervisor of some python scripts. To check if the scrips are running I'm using the ps -o pid,fname command on both RH Linux and solaris 10. All the scripts are launched using "python script.py" command, they are not launched with exec permissions. I don't know why the fname of the python interpreter changes across platforms. I saw a "isapytho" in some solaris 10 platforms. I saw "python2." in some Linux platforms. On most platforms the value is "python". Why? Ok, I know that I can easily work around the problem by not using "fname" and parse the ps output in another way, but I don't understand how is possible that the combination of ps and python behaves so badly. Any idea? Regards, Cesare From kevin.p.dwyer at gmail.com Fri Sep 16 07:01:14 2011 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Fri, 16 Sep 2011 12:01:14 +0100 Subject: parse html:what is the meaning of "//"? References: Message-ID: alias wrote: > > > > Highlighted options are in-the-money. > (omit something) > there is only one difference between code1 and code2 : > in code1 is : tds=table.xpath("tr[@valign='top']//td") > in code2 is: tds=table.xpath("//tr[@valign='top']//td") > > i want to know why the "//" make output different? This is an XPATH question, not really Python-related. See http://www.w3schools.com/xpath/xpath_syntax.asp Cheers, Kev From stefan_ml at behnel.de Fri Sep 16 07:02:06 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 16 Sep 2011 13:02:06 +0200 Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: alias, 16.09.2011 08:39: > code1: > import lxml.html > import urllib > down='http://finance.yahoo.com/q/op?s=C+Options' > content=urllib.urlopen(down).read() > root=lxml.html.document_fromstring(content) I see this quite often, but many people don't know that this can be simplified to import lxml.html url = 'http://finance.yahoo.com/q/op?s=C+Options' root = lxml.html.parse(url).getroot() which is less code, but substantially more efficient. > table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] > tds=table.xpath("tr[@valign='top']//td") > for td in tds: > print td.text_content() > > what i get is : > Call Options > Expire at close Friday, September 16, 2011 > these are waht i want. > > code2 > import lxml.html > import urllib > down='http://finance.yahoo.com/q/op?s=C+Options' > content=urllib.urlopen(down).read() > root=lxml.html.document_fromstring(content) > table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] > tds=table.xpath("//tr[@valign='top']//td") Here, you are looking for all "tr" tags in the table recursively, instead of taking just the ones that are direct children of the "table" tag. That's what "//" is there for, it's a recursive subtree selector. You might want to read up on XPath expressions. > what i get is : > N/A > N/A > 2 > 114 > 48.00 > C110917P00048000 > 16.75 > 0.00 > N/A > N/A > 0 > 23 > 50.00 > C110917P00050000 > 23.16 > 0.00 > N/A > N/A > 115 > 2,411 > > > Highlighted options are in-the-money. I don't see any highlighting in your text above, and I don't know what you mean by "in-the-money". Stefan From andrea.crotti.0 at gmail.com Fri Sep 16 07:13:15 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 16 Sep 2011 12:13:15 +0100 Subject: create a directory structure Message-ID: <4E732F4B.3090409@gmail.com> I would like to write a program which creates a directory structure and fills in a few templated fields some values passed in as arguments. So for example create_struct.py might create base_dir: |_ sub_dir1: |_ sub_file1 ... It's quite simple in theory, but I would also like to make it very easily maintanable, for example with a nice representation of the structure (an INI file maybe). Any ideas/advise on how to make it easy to write and to maintain? From steve+comp.lang.python at pearwood.info Fri Sep 16 07:13:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 21:13:43 +1000 Subject: why ps/fname of a python interpreter changes across platforms? References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Message-ID: <4e732f68$0$29997$c3e8da3$5496439d@news.astraweb.com> keobox wrote: > Hello, > I'm writing a little supervisor of some python scripts. > To check if the scrips are running I'm using the ps -o pid,fname > command on both RH Linux and solaris 10. > All the scripts are launched using "python script.py" command, they > are not launched with exec permissions. > > I don't know why the fname of the python interpreter changes across > platforms. Ask the person who built the system, or the people who made the distribution. They are free to name the Python executable anything they like. -- Steven From yasar11732 at gmail.com Fri Sep 16 07:34:37 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Fri, 16 Sep 2011 14:34:37 +0300 Subject: Fwd: why ps/fname of a python interpreter changes across platforms? In-Reply-To: References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> <4e732f68$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: ---------- Y?nlendirilmi? ileti ---------- Kimden: Ya?ar Arabac? Tarih: 16 Eyl?l 2011 14:33 Konu: Re: why ps/fname of a python interpreter changes across platforms? Kime: Steven D'Aprano For example, in arch linux, I had 3 different interpreters named python, python26 and python27 because some of the applications needed one, and some needed others. That might be the reason. 2011/9/16 Steven D'Aprano > keobox wrote: > > > Hello, > > I'm writing a little supervisor of some python scripts. > > To check if the scrips are running I'm using the ps -o pid,fname > > command on both RH Linux and solaris 10. > > All the scripts are launched using "python script.py" command, they > > are not launched with exec permissions. > > > > I don't know why the fname of the python interpreter changes across > > platforms. > > Ask the person who built the system, or the people who made the > distribution. They are free to name the Python executable anything they > like. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From oktaysafak at superonline.com Fri Sep 16 08:12:50 2011 From: oktaysafak at superonline.com (Oktay Safak) Date: Fri, 16 Sep 2011 15:12:50 +0300 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4E733D42.90400@superonline.com> Well, I'm a self taught Turkish python coder. I was bitten by this first in Python 2.3 and asked the group about it then. You can find the correspondence by googling "unicode bug in turkish characters? " There are a couple of posts with that topic line but they don't come out in one thread. So check them all. Anyway, to summarize, Martin v.L?wis answered my question back then and suggested some locale settings but the problem seems to be with Windows actually. His method worked on Linux, but not on windows. He said that Python delegates uppercasing of strings to the operating system on Windows, and Windows is broken there. What he said was: "Python delegates the toupper call to the operating system. It does not, in itself, include a database of lower/upper case conversions for all locales. So there is nothing we can do about that; ask Microsoft." So I ended up not asking Microsoft of course, but using [i?] in re and writing a couple of utility functions upper_tr(), lower_tr() and title_tr() etc to use in my own projects. But of course when foreign language names etc. are mixed in a text it blows but I can't see a way to avoid it when that's the case. I hope this helps, Oktay Safak Thomas Rachel wrote: > Am 15.09.2011 15:16 schrieb Alan Plum: > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers >> until hell freezes over. > > That's why it would have been nice if the Unicode guys had defined > "both Turkish i-s" at separate codepoints. > > Then one could have the three pairs > I, i ("normal") > I (other one), ? > > and > > ?, i (the other one). > > But alas, they haven't. > > > Thomas -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Fri Sep 16 09:08:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 06:08:54 -0700 (PDT) Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) From miki.tebeka at gmail.com Fri Sep 16 09:08:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 06:08:54 -0700 (PDT) Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) From JKPeck at gmail.com Fri Sep 16 09:09:30 2011 From: JKPeck at gmail.com (JKPeck) Date: Fri, 16 Sep 2011 06:09:30 -0700 (PDT) Subject: Strange Python internal error Message-ID: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> We have a user on Windows with Python 2.6 who gets this error message when executing an import statement. from extension import Template, Syntax, processcmd SystemError: ..\Objects\listobject.c:169: bad argument to internal function The module can be imported directly via import extension with no problem. And large numbers of other users execute this same code with no problem. Does anybody have a clue as to how this might arise? TIA, Jon Peck From 1248283536 at qq.com Fri Sep 16 09:26:28 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 16 Sep 2011 21:26:28 +0800 Subject: parse html:what is the meaning of "//"? Message-ID: through the following code,i get the content of webpage, import lxml.html url = 'http://finance.yahoo.com/q/op?s=C+Options' root = lxml.html.parse(url).getroot() with your method ,how can i get the content of webpage in my python program? ------------------ Original ------------------ From: "Miki Tebeka"; Date: Fri, Sep 16, 2011 09:08 PM To: "python-list"; Cc: "python-list"; Subject: Re: parse html:what is the meaning of "//"? As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Fri Sep 16 09:52:16 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Fri, 16 Sep 2011 15:52:16 +0200 Subject: Different class 'str' between v3. In-Reply-To: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> Message-ID: <4E735490.4060509@swing.be> An HTML attachment was scrubbed... URL: From nobody at nowhere.com Fri Sep 16 09:57:06 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 16 Sep 2011 14:57:06 +0100 Subject: Cancel or timeout a long running regular expression References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Thu, 15 Sep 2011 14:54:57 -0400, Terry Reedy wrote: >> I was thinking there might be a technique I could use to evaluate >> regular expressions in a thread or another process launched via >> multiprocessing module and then kill the thread/process after a >> specified timeout period. > > Only solution I remember ever seen posted. I wonder if there are any > heuristics for detecting exponential time re's. Exponential growth results from non-determinism, i.e. if there are multiple transitions for a given character from a given state. Common patterns include: ...(a...)?a... ...(a...)*a... ...(a...)+a... with a choice between matching the "a" at the start of the bracketed pattern or the "a" following it. (xxxa...|xxxb...|xxxc...) with a choice between branches which cannot be resolved until more data has been read. For re.search (as opposed to re.match): axxxa... When axxx has been read, a following "a" gives a choice between continuing the existing match with the second "a", or aborting and matching against the first "a". For patterns which contain many copies of the initial character, each copy creates another branch. Also, using back-references in a regexp [sic] can be a significant performance killer, as it rules out the use of a DFA (which, IIRC, Python doesn't do anyhow) and can require brute-forcing many combinations. A particularly bad case is: (a*)\1 matching against "aaaaaaaa...". If the performance issue is with re.match/re.search rather than with re.compile, one option is to use ctypes to access libc's regexp functions. Those are likely to provide better searching throughput at the expense of potentially increased compilation time. From andrea.crotti.0 at gmail.com Fri Sep 16 10:00:10 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 16 Sep 2011 15:00:10 +0100 Subject: create a directory structure In-Reply-To: <4E732F4B.3090409@gmail.com> References: <4E732F4B.3090409@gmail.com> Message-ID: <4E73566A.1010808@gmail.com> After some research, I think that paste-script is the best choice in this case. I can define templates and I'll get my directory structure nicely populated for me. From duncan.booth at invalid.invalid Fri Sep 16 10:44:12 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2011 14:44:12 GMT Subject: why ps/fname of a python interpreter changes across platforms? References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Message-ID: keobox wrote: > I don't know why the fname of the python interpreter changes across > platforms. > > I saw a "isapytho" in some solaris 10 platforms. > I saw "python2." in some Linux platforms. > On most platforms the value is "python". > Why? > It shows you part of the name of the program that is running. On a typical Linux system you could run python using the default interpreter 'python', or you could be explicit about the version you want to run and use 'python2.4', 'python2.5', 'python2.6', 'python2.7', 'python3.2' (all of these are available on the system in from of me). Of course 4 of those will be truncated to 'python2.' if you only look at the first 8 characters (which is what your command does) but you also get 'python' and 'python3.' That's why there's a lot of variation. I have no idea why it has a strange name on Solaris, maybe someone compiled their own private version. -- Duncan Booth http://kupuguy.blogspot.com From aspineux at gmail.com Fri Sep 16 11:42:25 2011 From: aspineux at gmail.com (aspineux) Date: Fri, 16 Sep 2011 08:42:25 -0700 (PDT) Subject: pyzmail-0.9.9 mail library to read, compose and send emails easily, support for py3k Message-ID: Now pyzmail include support for python 3.2 and above pyzmail is a high level mail library for Python. It provides functions and classes that help to read, compose and send emails. pyzmail exists because their is no reasons that handling mails with Python would be more difficult than with popular mail clients like Outlook or Thunderbird. pyzmail hide the difficulties of the MIME structure and MIME encoding/decoding. It also hide the problem of the internationalized header encoding/decoding. The library contains lot of sample and is very well documented. http://www.magiksys.net/pyzmail/ Alain Spineux From miki.tebeka at gmail.com Fri Sep 16 12:13:14 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 09:13:14 -0700 (PDT) Subject: Strange Python internal error In-Reply-To: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> Message-ID: <1e1f841b-dc17-42d3-bf88-86a27a92752e@glegroupsg2000goo.googlegroups.com> Try to narrow it down: from extension import Template from extension import Syntax from extension import processcmd Which one fails? What is this "extension" package? From martin.schoon at gmail.com Fri Sep 16 13:29:53 2011 From: martin.schoon at gmail.com (Martin =?UTF-8?Q?Sch=C3=B6=C3=B6n?=) Date: 16 Sep 2011 17:29:53 GMT Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Message-ID: <9dhfchFvt2U1@mid.individual.net> On 2011-09-15, John Ladasky wrote: > Hate to bump this, but... I found Sourceforge's IRC, and tried to ask > for help there, and it doesn't look like I can get any help until > business hours tomorrow. Anyone? No help really but I 'joined' Sourceforge about a year ago and had no problems whatsoever. Could it be some anti-robot filter that's gotten overly picky? /Martin From ramit.prasad at jpmorgan.com Fri Sep 16 13:52:33 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 13:52:33 -0400 Subject: ImportError: cannot import name dns In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB5052@EMARC112VS01.exchad.jpmchase.net> NOTE: This is all speculation on my part. I am hoping someone on the list will give us more concrete details. 1. check for "dns" in sys.modules (initially not found) 2. create new empty module, add it to sys.modules as "dns" 3. execute dns.py in new module namespace (executes "from foo import udp") It has not yet added anything defined in dns because it is still on import statement 4. check for "udp" in sys.modules (not found) 5. create new empty module, add it to sys.modules as "udp" 6. execute udp.py in new module namespace (executes "from foo import dns") Cannot do this because dns is still not defined even though it the name is in sys.modules and since we are still in the middle of the first statement defining dns, it raises an error. 7. check for "dns" in sys.modules (found!) 8. done executing udp.py 9. done executing dns.py Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: Jack Bates [mailto:jack.bates at gmail.com] Sent: Wednesday, September 14, 2011 11:22 AM To: Prasad, Ramit Cc: python-list at python.org Subject: Re: ImportError: cannot import name dns > It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. > > Circular dependency is a Bad Thing. According to this documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-import_stmt http://effbot.org/zone/import-confusion.htm - I thought Python would do something like: So I'd expect attempting to access symbols from "dns" while executing udp.py to fail, because dns.py isn't done executing at this point. However I don't attempt to access any symbols from "dns" - so I don't expect this ImportError What is my mistake? This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From brandonfigura at gmail.com Fri Sep 16 14:12:21 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:12:21 -0700 (PDT) Subject: strange results Message-ID: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> I am having a problem with a graphics program that I created. Actually, I don't know if it is the program or a bug in Python. The code for the program is as follows; from gasp import * begin_graphics(width=640, height=480, title='Houses at Night', background=color.BLACK) def draw_house(x, y): a = (x, y + 100) b = (x +50, y +140) c = (x +100, y + 100) Box((x, y), 100, 100, filled=True, color=color.BLUE) # the house Box((x + 35, y), 30, 50, filled=True, color=color.GREEN) # the door Circle((x + 62, y + 16), 1, filled=True, color=color.GOLD) # the door knob Box((x + 20, y + 60), 20, 20, filled=True, color=color.YELLOW) # the left window Line((x + 20, y + 71), (x + 40, y + 71), color=color.ORANGE) # horizontal line (left window) Line((x + 29, y + 60), (x + 29, y + 80), color=color.ORANGE) # vertical line (left window) Box((x + 60, y + 60), 20, 20, filled=True, color=color.YELLOW) # the right window Line((x + 60, y + 71), (x + 80, y + 71), color=color.ORANGE) # horizontal line (right window) Line((x + 69, y + 60), (x + 69, y + 80), color=color.ORANGE) # vertical line (right window) Polygon([a, b, c], filled=True, color=color.RED) # the roof draw_house(20, 20) draw_house(270, 20) draw_house(520, 20) draw_house(145, 180) draw_house(395, 180) draw_house(270, 340) update_when('key_pressed') end_graphics() ends here, but it When I run the program, I do not get any error messages but there are parts of the 'draw_house' function missing on the canvas. Each call to 'draw_house has different things missing, they are not all the exact same. There are some parts that show in one call to 'draw_house' that do not show in others and visa versa. Does anyone have any idea what may be going on? From brandonfigura at gmail.com Fri Sep 16 14:35:12 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:35:12 -0700 (PDT) Subject: unexpected results Message-ID: <13f31aba-e7e3-4697-96fa-74ab26bfc18a@s20g2000yql.googlegroups.com> I am having a problem when I run a graphics program that I created. I do not get an error when I run the program, there are just some weird things going on. I do not know if it is the program causing the problem or a bug in Python. Here is the code for the program: from gasp import * begin_graphics(width=640, height=480, title='Houses at Night', background=color.BLACK) def draw_house(x, y): # function for drawing a house a = (x, y + 100) # 'a' coordinate for Polygon b = (x +50, y +140) # 'b' coordinate for Polygon c = (x +100, y + 100) # 'c' coordinate for Polygon Box((x, y), 100, 100, filled=True, color=color.BLUE) # the house Box((x + 35, y), 30, 50, filled=True, color=color.GREEN) # the door Circle((x + 62, y + 16), 1, filled=True, color=color.GOLD) # the door knob Box((x + 20, y + 60), 20, 20, filled=True, color=color.YELLOW) # the left window Line((x + 20, y + 71), (x + 40, y + 71), color=color.ORANGE) # horizontal line (left window) Line((x + 29, y + 60), (x + 29, y + 80), color=color.ORANGE) # vertical line (left window) Box((x + 60, y + 60), 20, 20, filled=True, color=color.YELLOW) # the right window Line((x + 60, y + 71), (x + 80, y + 71), color=color.ORANGE) # horizontal line (right window) Line((x + 69, y + 60), (x + 69, y + 80), color=color.ORANGE) # vertical line (right window) Polygon([a, b, c], filled=True, color=color.RED) # the roof draw_house(20, 20) draw_house(270, 20) draw_house(520, 20) draw_house(145, 180) draw_house(395, 180) draw_house(270, 340) update_when('key_pressed') end_graphics() The program launches just fine, bringing up the gasp window like it should. The problem is that almost all of the calls to 'draw_house' are different. Some features will show up in one house but not in another and visa versa. Does anyone have any idea what the problem may be? From brandonfigura at gmail.com Fri Sep 16 14:39:54 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:39:54 -0700 (PDT) Subject: unexpected results References: <13f31aba-e7e3-4697-96fa-74ab26bfc18a@s20g2000yql.googlegroups.com> Message-ID: Sorry, Everyone. I got an error when posting the first post and did'nt come in to see if it had actually posted before I tried another post. From ben.r.shepherd at gmail.com Fri Sep 16 14:47:43 2011 From: ben.r.shepherd at gmail.com (Benshep) Date: Fri, 16 Sep 2011 11:47:43 -0700 (PDT) Subject: Using tuples to eliminate multiple dict values Message-ID: I need a dictionary that returns the same value for multiple keys. i.e. (1) >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } (2) >>>dict[1] (3) 'text' I cant figure out what i need on line 2 to make this scenario work. Is there a simple way to check if the a number is present in the key and then return the value? Thanks From thatiparthysreenivas at gmail.com Fri Sep 16 15:21:06 2011 From: thatiparthysreenivas at gmail.com (zombie) Date: Fri, 16 Sep 2011 12:21:06 -0700 (PDT) Subject: way to calculate 2**1000 without expanding it? Message-ID: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Hi guys, i am writing a program to sum up the digits of a number 2**1000? Is there a way/formula to do it without expanding it? From ramit.prasad at jpmorgan.com Fri Sep 16 15:28:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 15:28:07 -0400 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB52AB@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Benshep Sent: Friday, September 16, 2011 1:48 PM To: python-list at python.org Subject: Using tuples to eliminate multiple dict values I need a dictionary that returns the same value for multiple keys. i.e. (1) >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } (2) >>>dict[1] (3) 'text' I cant figure out what i need on line 2 to make this scenario work. Is there a simple way to check if the a number is present in the key and then return the value? Thanks ---------------------------------------------------------------- I think I must be missing something. Can you not do the following? >>> d = { 1:'text', 2:'text', 3:'text', 5:'other text', 6:'other text', 7:'other text' } >>> d[1] 'text' If you are they need to share the same value you can also do something like this. >>> t1 = [ 'text' ] >>> t2 = [ 'other text' ] >>> d = { 1:t1, 2:t1, 3:t1, 5:t2, 6:t2, 7:t2 } >>> d[1] ['text'] >>> d[1][0]='new text' >>> d[2][0] 'new text' >>> d {1: ['new text'], 2: ['new text'], 3: ['new text'], 5: ['other text'], 6: ['other text'], 7: ['other text']} Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python at mrabarnett.plus.com Fri Sep 16 15:29:41 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 16 Sep 2011 20:29:41 +0100 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <4E73A3A5.3090209@mrabarnett.plus.com> On 16/09/2011 19:47, Benshep wrote: > I need a dictionary that returns the same value for multiple keys. > > i.e. > > (1)>>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } That will create a dict with 2 keys, both of which are tuples. > (2)>>>dict[1] > (3) 'text' > > I cant figure out what i need on line 2 to make this scenario work. Is > there a simple way to check if the a number is present in the key and > then return the value? > If you want multiple keys, then you must provide them separately: my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other text', 7: 'other text'} or use 'for' to iterate through the keys for each value: my_dict = dict([(k, 'text') for k in (1, 2, 3)] + [(k, 'other text') for k in (5, 6, 7)]) or something similar. From ben.r.shepherd at gmail.com Fri Sep 16 15:47:14 2011 From: ben.r.shepherd at gmail.com (Benshep) Date: Fri, 16 Sep 2011 12:47:14 -0700 (PDT) Subject: Using tuples to eliminate multiple dict values References: Message-ID: <3827f27a-8a37-4609-a9b1-62f06635c76d@hg2g2000vbb.googlegroups.com> thanks, I had a feeling that may be the way to go and my data just changed so it will work better that way. Thanks for the quick reply From arnodel at gmail.com Fri Sep 16 16:00:24 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:00:24 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 20:21, zombie wrote: > Hi guys, > ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? > Is there a way/formula to do it without expanding it? > > -- > http://mail.python.org/mailman/listinfo/python-list > In base 2, the answer is 1 :) Hopefully-helpfully-but-not-so-sure'ly yours, -- Arnaud From ian.g.kelly at gmail.com Fri Sep 16 16:06:34 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 14:06:34 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: > Hi guys, > ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? > Is there a way/formula to do it without expanding it? Possibly, but why worry about it? It's only around 300 digits. Since this sounds like homework, I won't post the one-liner I used to do it the brute-force way, but I will note that it takes about 200 microseconds to run on my laptop. Cheers, Ian From ramit.prasad at jpmorgan.com Fri Sep 16 16:16:03 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 16:16:03 -0400 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB53D3@EMARC112VS01.exchad.jpmchase.net> >> Hi guys, >> i am writing a program to sum up the digits of a number 2**1000? >> Is there a way/formula to do it without expanding it? >Since this sounds like homework, I won't post the one-liner I used to >do it the brute-force way, but I will note that it takes about 200 >microseconds to run on my laptop. If you happen to be new to Python, I will say I used these functions to create a one liner (in alphabetical order). Int Lambda Map Reduce Str Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From arnodel at gmail.com Fri Sep 16 16:17:45 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:17:45 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 21:06, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >> Hi guys, >> ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? >> Is there a way/formula to do it without expanding it? > > Possibly, but why worry about it? ?It's only around 300 digits. > > Since this sounds like homework, I won't post the one-liner I used to > do it the brute-force way, but I will note that it takes about 200 > microseconds to run on my laptop. Ah go on, let's make a codegolf contest out of it. My entry: >>> sum(map(int,str(2**1000))) 1366 -- Arnaud From ian.g.kelly at gmail.com Fri Sep 16 16:20:46 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 14:20:46 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 2:17 PM, Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 That is exactly what mine was. From nagle at animats.com Fri Sep 16 16:50:45 2011 From: nagle at animats.com (John Nagle) Date: Fri, 16 Sep 2011 13:50:45 -0700 Subject: Why do closures do this? In-Reply-To: References: <20110828134505.795cd32b8fc5ccc472f85ae3@johnohagan.com> Message-ID: <4e73b6a7$0$1667$742ec2ed@news.sonic.net> On 8/27/2011 9:19 PM, Terry Reedy wrote: > On 8/27/2011 11:45 PM, John O'Hagan wrote: >> Somewhat apropos of the recent "function principle" thread, I was >> recently surprised by this: >> >> funcs=[] >> for n in range(3): >> def f(): >> return n >> funcs.append(f) >> >> >> >> The last expression, IMO surprisingly, is [2,2,2], not [0,1,2]. That's correct behavior, because a closure captures the binding of a nonlocal variable, not its value. There is only one "n" for all iterations. If you create a local variable within the closed function: def f() localn = n return(localn) there's a copy of "localn" for each iteration, and you're returning it. Try this in PyPy, which tries not to box numbers, and see what happens there. This is one of those Python features which complicates optimization. For performance, an implementation should handle numbers as machine numbers, not objects. (Creating an object to hold a machine primitive like an int, float, or bool is called "boxing' the number.) CPython always carries around a full CObject for ordinary numbers, which is why CPython numeric performance is so bad. PyPy tries not to do that, although there are rare cases when it has to, like this one. John Nagle From gherron at digipen.edu Fri Sep 16 16:53:10 2011 From: gherron at digipen.edu (Gary Herron) Date: Fri, 16 Sep 2011 13:53:10 -0700 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4E73B736.7060401@digipen.edu> On 09/16/2011 01:17 PM, Arnaud Delobelle wrote: > On 16 September 2011 21:06, Ian Kelly wrote: >> On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >>> Hi guys, >>> i am writing a program to sum up the digits of a number 2**1000? >>> Is there a way/formula to do it without expanding it? >> Possibly, but why worry about it? It's only around 300 digits. >> >> Since this sounds like homework, I won't post the one-liner I used to >> do it the brute-force way, but I will note that it takes about 200 >> microseconds to run on my laptop. > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 > Here's another one-liner using a generator instead of map: sum(int(c) for c in str(2**1000)) Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From arnodel at gmail.com Fri Sep 16 16:57:12 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:57:12 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 21:20, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 2:17 PM, Arnaud Delobelle wrote: >> Ah go on, let's make a codegolf contest out of it. >> My entry: >> >>>>> sum(map(int,str(2**1000))) >> 1366 > > That is exactly what mine was. > Slightly longer: >>> eval("+".join(str(2**1000))) 1366 This looks like a winner but I cheated (the result depends on the state of the interpreter): >>> eval("+".join(`2**1000`)) 1366 -- Arnaud From stefan-usenet at bytereef.org Fri Sep 16 17:07:31 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Fri, 16 Sep 2011 23:07:31 +0200 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <4E73B736.7060401@digipen.edu> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> <4E73B736.7060401@digipen.edu> Message-ID: <20110916210731.GA20553@sleipnir.bytereef.org> Gary Herron wrote: >>>> i am writing a program to sum up the digits of a number 2**1000? >>>> Is there a way/formula to do it without expanding it? > > Here's another one-liner using a generator instead of map: > > sum(int(c) for c in str(2**1000)) The OP did not specify the base: >>> bin(2**1000).count('1') 1 Or just: >>> print(1) 1 Stefan Krah From ramit.prasad at jpmorgan.com Fri Sep 16 17:13:38 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 17:13:38 -0400 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB54F7@EMARC112VS01.exchad.jpmchase.net> >>> sum(map(int,str(2**1000))) *smacks face* Gah, forgot about sum. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tjreedy at udel.edu Fri Sep 16 18:01:27 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:01:27 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On 9/16/2011 9:57 AM, Nobody wrote: >>I wonder if there are any >> heuristics for detecting exponential time re's. > > Exponential growth results from non-determinism, i.e. if there are > multiple transitions for a given character from a given state. > > Common patterns include: > > ...(a...)?a... > ...(a...)*a... > ...(a...)+a... > > with a choice between matching the "a" at the start of the bracketed > pattern or the "a" following it. > > (xxxa...|xxxb...|xxxc...) > > with a choice between branches which cannot be resolved until more data > has been read. > > For re.search (as opposed to re.match): > > axxxa... > > When axxx has been read, a following "a" gives a choice between > continuing the existing match with the second "a", or aborting and > matching against the first "a". For patterns which contain many copies of > the initial character, each copy creates another branch. > > Also, using back-references in a regexp [sic] can be a significant > performance killer, as it rules out the use of a DFA (which, IIRC, Python > doesn't do anyhow) and can require brute-forcing many combinations. A > particularly bad case is: > > (a*)\1 > > matching against "aaaaaaaa...". > > If the performance issue is with re.match/re.search rather than with > re.compile, one option is to use ctypes to access libc's regexp functions. > Those are likely to provide better searching throughput at the expense of > potentially increased compilation time. Now, can you write that as a heuristic *algorithm* def dangerous_re(some_re):? -- Terry Jan Reedy From tjreedy at udel.edu Fri Sep 16 18:16:43 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:16:43 -0400 Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: On 9/16/2011 7:02 AM, Stefan Behnel wrote: >> 0.00 >> N/A >> N/A >> 115 >> 2,411 >> >> >> Highlighted options are in-the-money. > > I don't see any highlighting in your text above, Gone with the ascii conversion. > and I don't know what you mean by "in-the-money". If a stock sells now for $20, an option to buy it for $19 is in-the-money and has definite value while an option to buy it for $21 is not, but is out-of-the-money and only has value according to one's subjective estimate of the likelihood of a rise above $21 before the option expires. -- Terry Jan Reedy From emekamicro at gmail.com Fri Sep 16 18:19:05 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 00:19:05 +0200 Subject: Code Review Message-ID: Hello All, While learning Python I put together another Text Twist. I would want somebody to go through it and comment. https://github.com/janus/Text-Twist -- Regards, Emeka * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 16 18:30:03 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:30:03 -0400 Subject: Different class 'str' between v3. In-Reply-To: <4E735490.4060509@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: On 9/16/2011 9:52 AM, Vincent Vande Vyvre wrote: > Testing the following code, I've differend return with python 3.1.2 and > 3.2.2 running on two different machines with two different versions of Linux. I get > # -*- coding: utf-8 -*- > > import os > import sys > import platform > > print('\nPython version: ', sys.version.split()[0]) > print(platform.platform()) > > paths = ['/home/vincent/image.jpg', '/home/vincent/?????.jpg'] > > for path in paths: > print('\nPath: {0}, Type: {1}'.format(path, type(path))) > if not os.path.exists(path) or not os.path.isfile(path): > print('File not found: {0}'.format(path)) > else: > print('File exists') I get Python version: 3.2.2rc1 Windows-7-6.1.7601-SP1 Path: /home/vincent/image.jpg, Type: File not found: /home/vincent/image.jpg Path: /home/vincent/?????.jpg, Type: File not found: /home/vincent/?????.jpg so > [vincent at myhost ~]$ python string_2.py > > Python version: 3.2.2 > Linux-3.0-ARCH-x86_64-Pentium-R-_Dual-Core_CPU_T4500_ at _2.30GHz-with-glibc2.2.5 > > Path: /home/vincent/image.jpg, Type: > File exists > Traceback (most recent call last): > File "string_2.py", line 13, in > print('\nPath: {0}, Type: {1}'.format(path, type(path))) > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 21-25: ordinal not in range(128) is not specific to 3.2.2 in general. Try the two Python versions on the same machine. Or try the test suite on each. See the test module doc for how. -- Terry Jan Reedy From brandonfigura at gmail.com Fri Sep 16 19:09:33 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 16:09:33 -0700 (PDT) Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: I took out all of the color commands that were in the shape functions and all of the features to the 'draw_house' function showed showed up. I started putting the color commands back into the shape functions and have no problems with some of them but when I put the color command back into others, some of the features start to disappear. As far as I can see, all of the code is right but I'm just a beginner so I am not for sure. Can anyone tell me why this is doing what it is. From rosuav at gmail.com Fri Sep 16 19:19:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 17 Sep 2011 09:19:53 +1000 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 4:47 AM, Benshep wrote: > (1) ? >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } > As I understand it, you're looking for a simple syntax for what MRAB posted: > my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other text', 7: 'other text'} Since your first line of code is syntactically legal, you could do a simple check afterwards to translate it: my_dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } for k in list(my_dict.keys()): if isinstance(k,tuple): val=my_dict.pop(k) for i in k: my_dict[i]=val Tested in Python 3.2; in Python 2, the list() call is superfluous, everything else should work fine. Chris Angelico From ian.g.kelly at gmail.com Fri Sep 16 19:28:39 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 17:28:39 -0600 Subject: Different class 'str' between v3. In-Reply-To: <4E735490.4060509@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: On Fri, Sep 16, 2011 at 7:52 AM, Vincent Vande Vyvre wrote: > [vincent at myhost ~]$ python string_2.py > > Python version:? 3.2.2 > Linux-3.0-ARCH-x86_64-Pentium-R-_Dual-Core_CPU_T4500_ at _2.30GHz-with-glibc2.2.5 > > Path: /home/vincent/image.jpg, Type: > File exists > Traceback (most recent call last): > ? File "string_2.py", line 13, in > ??? print('\nPath: {0}, Type: {1}'.format(path, type(path))) > UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-25: > ordinal not in range(128) This looks like a terminal encoding issue on the second PC. Your terminal is probably not using a unicode encoding, and so it is unable to print a unicode string. Cheers, Ian From ppaterson at gmail.com Fri Sep 16 19:48:08 2011 From: ppaterson at gmail.com (Paul Paterson) Date: Fri, 16 Sep 2011 16:48:08 -0700 (PDT) Subject: setuptools: getting data files to be installed Message-ID: <9476205.3046.1316216888277.JavaMail.geo-discussion-forums@prdy8> I'm having a problem using setuptools to create a distribution for a project that includes data files. I can get the data files to be included in the zipped package file (*.tar.gz) but when I easy_install the package the data files are not installed. (Ubuntu 11.04, Python2.7). I'm trying to use easy_install because the project is a game with dependencies and so it would be nice for easy_install to handle all that for people. My setup.py file is below at the end of the post. I create the zip with, > python setup.py egg_info ... > python setup.py sdist Then the dist/tacman-0.1.tar.gz includes my data files as identified in the MANIFEST.in file. But when I do, > sudo easy_install dist/tacman-0.1.tar.gz ... the python modules appear in /usr/local/lib/python27/dist-packages/tacman-0.1-py2.7.egg but the data files are nowhere to be seen. I tried locating them using pkg_resources but that didn't help. Some Googling suggested /usr/share as a location but they weren't there either. Am I looking in the right place or did they just not get installed? The whole distribution file is at http://perpetualpyramid.com/tacman-0.1.tar.gz in case that helps. The file is bit large because it is a game and the zip includes the music and graphics. Thanks for any help and pointers. Paul --- setup.py --- from setuptools import setup, find_packages import game.common setup(name='tacman', version=game.common.version, scripts=['tacman.py'], entry_points = { 'console_scripts' : [ 'tacman = tacman.tacman', ] }, description='A tactical, turn-based clone on PACMAN', author='Paul Paterson', author_email='ppaterson at gmail.com', url='http://www.perpetualpyramid/tacman.html', download_url=('http://perpetualpyramid.com/tacman-%s.tar.gz' % game.common.version), include_package_data=True, zip_safe=False, packages=[ 'serge', 'serge.blocks', 'serge.tools', 'serge.tools.template', 'game', ], package_dir={'':'.'}, classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Games/Entertainment", "Topic :: Games/Entertainment :: Puzzle Games", ], install_requires=[ 'pygame', 'networkx', ], long_description='''\ TACMAN ------ A turn-based, tactical version of PACMAN. Play a PACMAN clone where the action is turn based. You move and then the ghosts move. The turn-based action adds additional tactical elements to the game and allows you to plan ahead and outwit the ghosts! Requires: Python 2.6+, pygame 1.9+, networkx ''', ) From python.list at tim.thechases.com Fri Sep 16 19:48:40 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 16 Sep 2011 18:48:40 -0500 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <4E73E058.6010303@tim.thechases.com> On 09/16/11 13:47, Benshep wrote: > I need a dictionary that returns the same value for multiple keys. > > i.e. > > (1)>>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } > (2)>>>dict[1] > (3) 'text' > > I cant figure out what i need on line 2 to make this scenario work. Is > there a simple way to check if the a number is present in the key and > then return the value? You could use something like d = dict( (k,v) for keys in ( ((1,2,3), 'text'), ((5,6,7), 'other text'), ) for k in keys ) which seems to do what you want with minimal redundancy of declarations. - From steve+comp.lang.python at pearwood.info Fri Sep 16 22:17:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 17 Sep 2011 12:17:05 +1000 Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4e740322$0$29983$c3e8da3$5496439d@news.astraweb.com> Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 Time for some obfuscated Python! b = (16,13624) for i in range(23, 42, 3): b = (b[0]*b[0], b[1]+1024) for j in range(12345, 8929, -7): b = (b[0]+b[0], b[1]-3) while b > (0,9876): b = tuple((lambda a,b: map(lambda a,b:a+b, a,b)) ((lambda a,b: map(lambda a,b:a*b, a,b)) (b,(0,1)), (lambda a,b: map(lambda a,b:a-b, a,b)) (divmod(b[0],10),(0,64)))) print b[1] -- Steven From invalid at invalid.invalid Fri Sep 16 22:19:12 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 17 Sep 2011 02:19:12 +0000 (UTC) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 2011-09-16, Gary Herron wrote: > On 09/16/2011 01:17 PM, Arnaud Delobelle wrote: >> On 16 September 2011 21:06, Ian Kelly wrote: >>> On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >>>> Hi guys, >>>> i am writing a program to sum up the digits of a number 2**1000? >>>> Is there a way/formula to do it without expanding it? >>> Possibly, but why worry about it? It's only around 300 digits. >>> >>> Since this sounds like homework, I won't post the one-liner I used to >>> do it the brute-force way, but I will note that it takes about 200 >>> microseconds to run on my laptop. >> Ah go on, let's make a codegolf contest out of it. >> My entry: >> >>>>> sum(map(int,str(2**1000))) >> 1366 >> > > Here's another one-liner using a generator instead of map: > > sum(int(c) for c in str(2**1000)) Just in case you can't spare the 3KB required for the list of integers that map creates. :) In this case it doesn't matter, but it's not hard to find problems where the difference between the memory requirements for a generator and a map/list-comprehension are significant enough to worry about. -- Grant From chunuan723 at gmail.com Fri Sep 16 22:56:41 2011 From: chunuan723 at gmail.com (he sharon) Date: Fri, 16 Sep 2011 19:56:41 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <18e9f5c3-055e-4515-a7dc-517f46e90ec5@s2g2000vby.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From chunuan723 at gmail.com Fri Sep 16 22:58:59 2011 From: chunuan723 at gmail.com (he sharon) Date: Fri, 16 Sep 2011 19:58:59 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From ian.g.kelly at gmail.com Fri Sep 16 23:11:44 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 21:11:44 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 8:19 PM, Grant Edwards wrote: >> Here's another one-liner using a generator instead of map: >> >> ? ? ?sum(int(c) for c in str(2**1000)) > > Just in case you can't spare the 3KB required for the list of integers > that map creates. :) > > In this case it doesn't matter, but it's not hard to find problems > where the difference between the memory requirements for a generator > and a map/list-comprehension are significant enough to worry about. Unless otherwise specified, I generally assume that code on this list is for Python 3, and map in Python 3 returns an iterator. Cheers, Ian From vincent.vandevyvre at swing.be Fri Sep 16 23:28:25 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sat, 17 Sep 2011 05:28:25 +0200 Subject: Different class 'str' between v3. In-Reply-To: References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: <4E7413D9.4000706@swing.be> An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Sat Sep 17 00:55:41 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sat, 17 Sep 2011 06:55:41 +0200 Subject: Different class 'str' between v3. In-Reply-To: <4E7413D9.4000706@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> <4E7413D9.4000706@swing.be> Message-ID: <4E74284D.7090900@swing.be> An HTML attachment was scrubbed... URL: From alex.kapps at web.de Sat Sep 17 02:59:10 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 17 Sep 2011 08:59:10 +0200 Subject: strange results In-Reply-To: References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: <4E74453E.2020908@web.de> On 17.09.2011 01:09, Fig wrote: > I took out all of the color commands that were in the shape functions > and all of the features to the 'draw_house' function showed showed up. > I started putting the color commands back into the shape functions and > have no problems with some of them but when I put the color command > back into others, some of the features start to disappear. As far as I > can see, all of the code is right but I'm just a beginner so I am not > for sure. Can anyone tell me why this is doing what it is. > Just tried your program on Ubuntu 10.04 with Python 2.6.5 and GASP 0.3.3 and it worked fine. What OS, Python version and GASP version are you using? If you don't get an answer here, try asking on the Launchpad project site: https://launchpad.net/gasp From ladasky at my-deja.com Sat Sep 17 03:26:19 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 00:26:19 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> <9dhfchFvt2U1@mid.individual.net> Message-ID: <03b8d48e-4fdf-4aaf-8249-367ac618d4f1@s3g2000vbx.googlegroups.com> On Sep 16, 10:29?am, Martin Sch??n wrote: > On 2011-09-15, John Ladasky wrote: > > > Hate to bump this, but... I found Sourceforge's IRC, and tried to ask > > for help there, and it doesn't look like I can get any help until > > business hours tomorrow. ?Anyone? > > No help really but I 'joined' Sourceforge about a year ago and > had no problems whatsoever. > > Could it be some anti-robot filter that's gotten overly picky? > > /Martin Well, I got through to Sourceforge today, and succeeded in subscribing. A support person said that their site's registration web page has compatibility issues with certain web browsers and/or their extensions. I was using Chrome. They asked me to try another browser, I tried Firefox, and it worked. Personally, I find that to be pretty bizarre -- but it worked. From ladasky at my-deja.com Sat Sep 17 04:34:18 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 01:34:18 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: Hey, this pretty easy hack appears to work! [code] from multiprocessing.pool import Pool, RUN, MapResult, mapstar class PriorityPool(Pool): def map_async_nowait(self, func, iterable, chunksize=None, \ callback=None): """ Same as map_async(), except uses put_nowait() and thus posts tasks to the head of the task queue rather than its tail. """ assert self._state == RUN if not hasattr(iterable, '__len__'): iterable = list(iterable) if chunksize is None: chunksize, extra = divmod(len(iterable), len(self._pool) * 4) if extra: chunksize += 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self._cache, chunksize, len(iterable), \ callback) self._taskqueue.put_nowait((((result._job, i, mapstar, (x,), {}) \ for i, x in enumerate(task_batches)), None)) return result def size(self): """ This is not an essential function, but I use it in the demo to ensure that I initially create enough tasks to occupy every Process. """ return len(self._pool) ##================================================================## if __name__ == "__main__": from time import sleep def demo_task(args): num, time = args sleep(time) print num, time pool = PriorityPool() size = pool.size() print "\nConstructed a pool which contains", size, "Processes." print "Queueing", 2*size, "normal-priority tasks." normal = enumerate([3.0 + t for t in range(2*size)]) pool.map_async(demo_task, normal, chunksize = 1) print "Queueing", size, "high-priority tasks." high = [(2*size + t, 0.2 + 0.1*t) for t in range(size)] pool.map_async_nowait(demo_task, high, chunksize = 1) sleep(30) # Give all tasks on the queue time to complete. print "Complete." [/code] Below is a typical output from my six-core CPU system. The output differs slightly from run to run -- that's multiprocessing for you, it's asynchronous. The tasks are given numbers which correspond to the order that they are added to the queue. The high-priority tasks are added last and are thus numbered 12-17 (I place asterisks next to these in the output, below). Each task prints its number and its time when it completes. I expect the normal-priority tasks 0-5 to finish before any high-priority tasks, and they always do. Tasks 6 and 7 are then interleaved among the high-priority tasks -- not quite what I expect, but that may have something to do with my rather arbitrary choices of sleep times. But tasks 8-11 always get pushed to the back, and complete last. [output] Constructed a pool which contains 6 Processes. Queueing 12 normal-priority tasks. Queueing 6 high-priority tasks. 0 3.0 1 4.0 2 5.0 3 6.0 4 7.0 5 8.0 6 9.0 12 0.2 * 13 0.3 * 14 0.4 * 15 0.5 * 7 10.0 16 0.6 * 17 0.7 * 8 11.0 9 12.0 10 13.0 11 14.0 [/output] Please feel free to use this, though I would appreciate an acknowledgment in your code if you do. :^) From phihag at phihag.de Sat Sep 17 07:19:01 2011 From: phihag at phihag.de (Philipp Hagemeister) Date: Sat, 17 Sep 2011 13:19:01 +0200 Subject: Code Review In-Reply-To: References: Message-ID: <4E748225.8020602@phihag.de> Instead of comments, you can often use docstrings (http://www.python.org/dev/peps/pep-0257/ ): This is hard to read due to the indentation, and cannot be accessed programmatically: #Update the GUI def update_gui(self, new_word): Instead, use this: def update_gui(self, new_word): "Update the GUI." Now, you can use help(Message) to get information about the method. You'll notice "Update the GUI." is not helpfull at all for a method called update_gui. Comments (and docstrings) that reproduce the method name are not useful. A couple of minor things: * If you delete code, delete it, don't comment it out. * Use newlines between two methods. Compare def a(self): pass def b(self): pass def c(self): pass with def a(self): pass def b(self): pass def c(self): pass The latter looks neat and not nearly as crammed as the former. * Don't use newlines where they shouldn't be, for example in if val == 0: label.unbind('') * Even if it's just the comments, typos make a very bad impression of a coder and the code. I'd automatically assume lots of bugs and untested code when I see more than the occasional typo. * GUI programming is fun, but does not lend itself to structured programming and good practices. You should never use global. Instead, have an object encapsulating the state and pass that object to the method itself or its object. * Don't commit .pyc files, they're totally useless. Since python 2.6, you can add the following in your .bashrc to make python not create them: export "PYTHONDONTWRITEBYTECODE=dont" In git, you can add the following in your project's .gitignore or ~/.gitignore_global: *.pyc [More on .gitignore: http://help.github.com/ignore-files/ ] * Otherwise, the code looks pretty good for a beginner. You may, however, want to replace def word_not_found(word): if word in searchedwordset: return 0 else: return 1 with just: def word_not_found(word): return word not in searchedwordset (or just skip this method and write word not in searchedwordset). Cheers, Philipp Emeka wrote: > Hello All, > > While learning Python I put together another Text Twist. I would want > somebody to go through it and comment. > https://github.com/janus/Text-Twist > > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature URL: From rafadurancastaneda at gmail.com Sat Sep 17 07:56:25 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sat, 17 Sep 2011 13:56:25 +0200 Subject: create a directory structure In-Reply-To: <4E73566A.1010808@gmail.com> References: <4E732F4B.3090409@gmail.com> <4E73566A.1010808@gmail.com> Message-ID: 2011/9/16 Andrea Crotti > After some research, I think that paste-script is the best choice in this > case. > > I can define templates and I'll get my directory structure nicely populated > for me. > > -- > http://mail.python.org/**mailman/listinfo/python-list > I think you might want to look at Fabricor vagrant -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Sat Sep 17 09:26:23 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 14:26:23 +0100 Subject: Code Review In-Reply-To: <4E748225.8020602@phihag.de> References: <4E748225.8020602@phihag.de> Message-ID: Philipp, Thanks so much for your time and comment. I will re-work my code accordingly. Regards, Emeka On Sat, Sep 17, 2011 at 12:19 PM, Philipp Hagemeister wrote: > Instead of comments, you can often use docstrings > (http://www.python.org/dev/peps/pep-0257/ ): > > This is hard to read due to the indentation, and cannot be accessed > programmatically: > > #Update the GUI > def update_gui(self, new_word): > > Instead, use this: > > def update_gui(self, new_word): > "Update the GUI." > > Now, you can use help(Message) to get information about the method. > You'll notice "Update the GUI." is not helpfull at all for a method > called update_gui. Comments (and docstrings) that reproduce the method > name are not useful. > > A couple of minor things: > > * If you delete code, delete it, don't comment it out. > * Use newlines between two methods. Compare > def a(self): > pass > def b(self): > pass > def c(self): > pass > > with > > def a(self): > pass > > def b(self): > pass > > def c(self): > pass > > The latter looks neat and not nearly as crammed as the former. > * Don't use newlines where they shouldn't be, for example in > if val == 0: > > label.unbind('') > * Even if it's just the comments, typos make a very bad impression of a > coder and the code. I'd automatically assume lots of bugs and untested > code when I see more than the occasional typo. > * GUI programming is fun, but does not lend itself to structured > programming and good practices. You should never use global. Instead, > have an object encapsulating the state and pass that object to the > method itself or its object. > * Don't commit .pyc files, they're totally useless. Since python 2.6, > you can add the following in your .bashrc to make python not create them: > > export "PYTHONDONTWRITEBYTECODE=dont" > > In git, you can add the following in your project's .gitignore or > ~/.gitignore_global: > > *.pyc > > [More on .gitignore: http://help.github.com/ignore-files/ ] > * Otherwise, the code looks pretty good for a beginner. You may, > however, want to replace > > def word_not_found(word): > if word in searchedwordset: > return 0 > else: > return 1 > > with just: > > def word_not_found(word): > return word not in searchedwordset > > (or just skip this method and write word not in searchedwordset). > > Cheers, > > Philipp > > > > Emeka wrote: > > Hello All, > > > > While learning Python I put together another Text Twist. I would want > > somebody to go through it and comment. > > https://github.com/janus/Text-Twist > > > > > > > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From brandonfigura at gmail.com Sat Sep 17 09:58:27 2011 From: brandonfigura at gmail.com (Fig) Date: Sat, 17 Sep 2011 06:58:27 -0700 (PDT) Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: On Sep 17, 1:59?am, Alexander Kapps wrote: > On 17.09.2011 01:09, Fig wrote: > > > I took out all of the color commands that were in the shape functions > > and all of the features to the 'draw_house' function showed showed up. > > I started putting the color commands back into the shape functions and > > have no problems with some of them but when I put the color command > > back into others, some of the features start to disappear. As far as I > > can see, all of the code is right but I'm just a beginner so I am not > > for sure. Can anyone tell me why this is doing what it is. > > Just tried your program on Ubuntu 10.04 with Python 2.6.5 and GASP > 0.3.3 and it worked fine. What OS, Python version and GASP version > are you using? > > If you don't get an answer here, try asking on the Launchpad project > site: > > https://launchpad.net/gasp My OS is Windows 7, Python 2.7.2, I downloaded and installed the python-gasp-0.2.0beta1.win32.exe file, and I also have these installed: Python 2.7 pygame-1.9.2a0 and Python 2.7 pywin32-216 From yasar11732 at gmail.com Sat Sep 17 11:10:31 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sat, 17 Sep 2011 18:10:31 +0300 Subject: Modifiying __getattribute__ of an instance Message-ID: I am trying to modify __getattribute__() method for an instance, as you may already know,__getattirbute__ is read-only attribute in Python. What I have in mind is, create a new object like this: def create_new_instace(old_instance): class temp(old_instance.__class__): def __init__(self,*args,**kwargs): "Since we will copy an already inited instance" pass def __getattribute__(self,attr): # do stuff new_instance = temp() # magically copy all attrs of old_instance to new_instance return new_instance Is this kind of thing possible? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From as at sci.fi Sat Sep 17 11:25:11 2011 From: as at sci.fi (Anssi Saari) Date: Sat, 17 Sep 2011 18:25:11 +0300 Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: Fig writes: > My OS is Windows 7, Python 2.7.2, I downloaded and installed the > python-gasp-0.2.0beta1.win32.exe file, and I also have these > installed: Python 2.7 pygame-1.9.2a0 and Python 2.7 pywin32-216 Then maybe that old beta version is your problem? For the record, your code works for me too in Linux and python-gasp 0.3.3. Looks like there's no Windows installer for newer python-gasp. Maybe you could install with easy_install as they describe on the site? From missive at hotmail.com Sat Sep 17 11:58:32 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 17 Sep 2011 20:28:32 +0430 Subject: os independent rename Message-ID: I just got a bug report the heart of which is the difference between unix and windows in using os.rename (ie, "On Windows, if dst already exists, OSError will be raised") Hmm, I thought, maybe I'm supposed to use shutil here. That is the "high-level" operations. Unfortunately, shutil.move says it depends on os.rename So, what is the best way to do this that will behave the same across operating systems? From ian.g.kelly at gmail.com Sat Sep 17 12:41:18 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 17 Sep 2011 10:41:18 -0600 Subject: os independent rename In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 9:58 AM, Lee Harr wrote: > > I just got a bug report the heart of which is the > difference between unix and windows in using > os.rename > > (ie, "On Windows, if dst already exists, OSError will be raised") > > Hmm, I thought, maybe I'm supposed to use > shutil here. That is the "high-level" operations. > Unfortunately, shutil.move says it depends on > os.rename > > So, what is the best way to do this that will > behave the same across operating systems? shutil.move works for me, at least in Python 2.7. The docstring doesn't seem to match the code here: try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src) From invalid at invalid.invalid Sat Sep 17 12:42:18 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 17 Sep 2011 16:42:18 +0000 (UTC) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 2011-09-17, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 8:19 PM, Grant Edwards wrote: >>> Here's another one-liner using a generator instead of map: >>> >>> ? ? ?sum(int(c) for c in str(2**1000)) >> >> Just in case you can't spare the 3KB required for the list of integers >> that map creates. :) >> >> In this case it doesn't matter, but it's not hard to find problems >> where the difference between the memory requirements for a generator >> and a map/list-comprehension are significant enough to worry about. > > Unless otherwise specified, I generally assume that code on this list > is for Python 3, and map in Python 3 returns an iterator. Indeed, I forgot about that (I'm still using Python 2 since I use some libraries that haven't been ported). -- Grant From kw at codebykevin.com Sat Sep 17 14:01:47 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 17 Sep 2011 14:01:47 -0400 Subject: Python bug in Windows 8--report now, or later? Message-ID: I have been testing my Python application on the just-released developer preview of Windows 8 and have noted an error: the application does not create an app folder in the user's "application data" directory. This causes the app to crash on startup. Manually creating the directory solves the problem. Since the app uses an os.mkdir() call to create the directory, and since the app runs fine on Windows 7, my guess is that the bug lies somewhere in the interaction between Python (I'm using ActivePython 2.7) and Windows. Here's the relevant code: #make preferences directory if it does not exist def makePrefsDir(self): self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], 'MyApp')) if not os.path.exists(self.appdir): os.mkdir(self.appdir) I realize that this developer preview of Windows is still at somewhere between alpha- and beta-level, and it's possible things will get better. Should I wait to report this as a bug until Windows 8 is released, or do the Python developers test Python on pre-release versions of Windows? From missive at hotmail.com Sat Sep 17 14:40:02 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 17 Sep 2011 23:10:02 +0430 Subject: os independent rename Message-ID: > shutil.move works for me, at least in Python 2.7. The docstring> doesn't seem to match the code Thanks for checking that. Looks like there is a closed report about the misleading docs:http://bugs.python.org/issue12577 Closed a couple of months ago, but the docs have not madeit to the web yet.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From shajiashish at gmail.com Sat Sep 17 14:41:18 2011 From: shajiashish at gmail.com (Indian Entertainment) Date: Sat, 17 Sep 2011 11:41:18 -0700 (PDT) Subject: All Posters Com Message-ID: With more than 1,000,000 images, AllPosters is your one-stop-shop for wall art, providing a huge assortment of posters, art prints and other items to suit all interests, decorating styles and budgets. Browse the latest posters in music, movies, sports, and more. Find your favorite art prints from the classic masters. Discover up-and-coming artists. Explore our special collections. Then choose from a wide array of custom-framing, canvas, wood-mounting and other service options to truly make it your own ? all high quality and at amazing prices. Start searching now and see for yourself how AllPosters is transforming the way the world discovers and personalizes art. Check out the art we're digging right now and what's on our gotta-hang-it list. We've narrowed down the 1,000,000 options (and counting) on AllPosters.com to our select favorites, including vintage posters, retro comics, Warhol masterpieces and a samurai. http://tinyurl.com/44skelw From nobody at nowhere.com Sat Sep 17 15:00:53 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 17 Sep 2011 20:00:53 +0100 Subject: Cancel or timeout a long running regular expression References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Fri, 16 Sep 2011 18:01:27 -0400, Terry Reedy wrote: > Now, can you write that as a heuristic *algorithm* > def dangerous_re(some_re):? return re.search(r'\\\d', some_re) is not None That will handle the most extreme case ;) If the OP is serious about analysing regexps, sre_parse.parse() will decompose a regexp to a more convenient form. However, I wouldn't rely upon being able to catch every possible bad case. The only robust solution is to use a separate process (threads won't suffice, as they don't have a .kill() method). From nobody at nowhere.com Sat Sep 17 15:18:19 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 17 Sep 2011 20:18:19 +0100 Subject: os independent rename References: Message-ID: On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: > So, what is the best way to do this that will > behave the same across operating systems? Delete the destination first, but after checking that it isn't the same as the source. On Windows, that last bit is harder than it seems. A string-based comparison won't work. Even if you ignore case, there's the issue of 8.3 filenames, and some other odd cases. From tjreedy at udel.edu Sat Sep 17 17:19:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Sep 2011 17:19:26 -0400 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On 9/17/2011 2:01 PM, Kevin Walzer wrote: > I have been testing my Python application on the just-released developer > preview of Windows 8 and have noted an error: the application does not > create an app folder in the user's "application data" directory. This > causes the app to crash on startup. Manually creating the directory > solves the problem. Since the app uses an os.mkdir() call to create the > directory, and since the app runs fine on Windows 7, my guess is that > the bug lies somewhere in the interaction between Python (I'm using > ActivePython 2.7) and Windows. We need more that guesses to act. I think is premature to call this a 'Python bug'. > Here's the relevant code: > > #make preferences directory if it does not exist > def makePrefsDir(self): > self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], 'MyApp')) > if not os.path.exists(self.appdir): > os.mkdir(self.appdir) > > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do > the Python developers test Python on pre-release versions of Windows? 3 days ago (Sept 14) someone asked about 'Windows 8 support' on pydev list. The answers were 1) 2.7 and 3.2 appear to run fine on the Dev release (but there was no report of test suite results); 2) Python directly uses so little of the Win interface that problems are not anticipated; 3) applications might have to make Win 8 specific adjustments and should test before the release. Of course, if MS accidentally changes thinly wrapped system calls such as os.environ, .exists, and .makedir, there will be a problem but that is their bug. My impression is that they are not intentionally breaking such things. I anticipate 3.3 and some future 2.7.z will be officially supported (and tested) on Win 8. -- Terry Jan Reedy From rosuav at gmail.com Sat Sep 17 17:20:26 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 07:20:26 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 4:01 AM, Kevin Walzer wrote: > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do the > Python developers test Python on pre-release versions of Windows? I would consider reporting it as a bug in Windows 8, not a bug in Python. Chris Angelico From rosuav at gmail.com Sat Sep 17 17:35:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 07:35:01 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) Message-ID: On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: > The only robust solution is to use a separate process (threads won't > suffice, as they don't have a .kill() method). > Forking a thread to discuss threads.... ahem. Why is it that threads can't be killed? Do Python threads correspond to OS-provided threads (eg POSIX threads on Linux)? Every OS threading library I've seen has some way of killing threads, although I've not looked in detail into POSIX threads there (there seem to be two options, pthread_kill and pthread_cancel, that could be used, but I've not used either). If nothing else, it ought to be possible to implement a high level kill simply by setting a flag that the interpreter will inspect every few commands, the same way that KeyboardInterrupt is checked for. Is it just that nobody's implemented it, or is there a good reason for avoiding offering this sort of thing? Chris Angelico From clp2 at rebertia.com Sat Sep 17 18:27:45 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 17 Sep 2011 15:27:45 -0700 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 2:35 PM, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: >> The only robust solution is to use a separate process (threads won't >> suffice, as they don't have a .kill() method). > > Forking a thread to discuss threads.... ahem. > > Why is it that threads can't be killed? Do Python threads correspond > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading > library I've seen has some way of killing threads, although I've not > looked in detail into POSIX threads there (there seem to be two > options, pthread_kill and pthread_cancel, that could be used, but I've > not used either). If nothing else, it ought to be possible to > implement a high level kill simply by setting a flag that the > interpreter will inspect every few commands, the same way that > KeyboardInterrupt is checked for. > > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? It's possible that the reason is analogous to why Java has deprecated its equivalent, Thread.stop(): http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Cheers, Chris From rosuav at gmail.com Sat Sep 17 19:19:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 09:19:46 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 8:27 AM, Chris Rebert wrote: > It's possible that the reason is analogous to why Java has deprecated > its equivalent, Thread.stop(): > http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Interesting. The main argument against having a way to raise an arbitrary exception in a different thread is that it gets around Java's requirement to declare all exceptions that a routine might throw - a requirement that Python doesn't have. So does that mean it'd be reasonable to have a way to trigger a "TerminateThread" exception (like SystemExit but for one thread) remotely? The above article recommends polling a variable, but that's the exact sort of thing that exceptions are meant to save you from doing. ChrisA From cs at zip.com.au Sat Sep 17 19:23:38 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 18 Sep 2011 09:23:38 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <20110917232338.GA22838@cskk.homeip.net> On 17Sep2011 15:27, Chris Rebert wrote: | On Sat, Sep 17, 2011 at 2:35 PM, Chris Angelico wrote: | > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: | >> The only robust solution is to use a separate process (threads won't | >> suffice, as they don't have a .kill() method). | > | > Forking a thread to discuss threads.... ahem. | > | > Why is it that threads can't be killed? Do Python threads correspond | > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading | > library I've seen has some way of killing threads, although I've not | > looked in detail into POSIX threads there (there seem to be two | > options, pthread_kill and pthread_cancel, that could be used, but I've | > not used either). If nothing else, it ought to be possible to | > implement a high level kill simply by setting a flag that the | > interpreter will inspect every few commands, the same way that | > KeyboardInterrupt is checked for. | > | > Is it just that nobody's implemented it, or is there a good reason for | > avoiding offering this sort of thing? | | It's possible that the reason is analogous to why Java has deprecated | its equivalent, Thread.stop(): | http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Interesting. A lot of that discussion concerns exceptions that the Java app is unprepared for. Java's strong typing includes the throwable exceptions, so that's a quite legitimate concern. The aborting mutex regions thing is also very real. Conversely, Python can have unexpected exceptions anywhere, anytime because it is not strongly typed in this way. That doesn't make it magicly robust against this, but does mean this is _already_ an issue in Python programs, threaded or otherwise. Context managers can help a lot here, in that they offer a reliable exception handler in a less ad hoc fashion than try/except because it is tied to the locking object; but they won't magicly step in save your basic: with my_lock: stuff... Personally I'm of the view that thread stopping should be part of the overt program logic, not a low level facility (such as causing a ThreadDeath exception asynchronously). The latter has all the troubles in the cited URL. Doing it overtly would go like this: ... outside ... that_thread.stop() # sets the "stopping" flag on the thread object that_thread.join() # and now maybe we wait for it... ... thread code ... ... do stuff, eg: with my_lock: muck about ... if thread.stopping: abort now, _outside_ the mutex ... This avoids the issue of aborting in the middle of supposedly mutex-safe code. It still requires scattering checks on thread.stopping through library code such as the OP's rogue regexp evaluator. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ One measure of `programming complexity' is the number of mental objects you have to keep in mind simultaneously in order to understand a program. The mental juggling act is one of the most difficult aspects of programming and is the reason programming requires more concentration than other activities. It is the reason programmers get upset about `quick interruptions' -- such interruptions are tantamount to asking a juggler to keep three balls in the air and hold your groceries at the same time. - Steve McConnell, _Code Complete_ From cs at zip.com.au Sat Sep 17 19:27:54 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 18 Sep 2011 09:27:54 +1000 Subject: os independent rename In-Reply-To: References: Message-ID: <20110917232754.GA24525@cskk.homeip.net> On 17Sep2011 20:18, Nobody wrote: | On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: | > So, what is the best way to do this that will | > behave the same across operating systems? | | Delete the destination first, but after checking that it isn't the same as | the source. This is usually a step that the UNIX os.rename is designed to avoid. By deleting first, there is a window where the destination doesn't exist at all. Also, if the subsequent rename fails, the destination is missing long term. os.rename() on UNIX specifies that after the call either the new items is at destination (success) or the old item is (failure). Either way you still have a valid destination object. So you're breaking the model that os.rename() strives explicitly to provide. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Q: How many user support people does it take to change a light bulb? A: We have an exact copy of the light bulb here and it seems to be working fine. Can you tell me what kind of system you have? From tjreedy at udel.edu Sat Sep 17 19:30:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Sep 2011 19:30:31 -0400 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On 9/17/2011 7:19 PM, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 8:27 AM, Chris Rebert wrote: >> It's possible that the reason is analogous to why Java has deprecated >> its equivalent, Thread.stop(): >> http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html > > Interesting. The main argument against having a way to raise an > arbitrary exception in a different thread is that it gets around > Java's requirement to declare all exceptions that a routine might > throw - a requirement that Python doesn't have. I saw the main argument as being that stopping a thread at an arbitrary point can have an arbitrary, unpredictable effect on all other threads. And more so that shutting down an independent process. -- Terry Jan Reedy From rosuav at gmail.com Sat Sep 17 19:38:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 09:38:05 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 9:26 AM, Dennis Lee Bieber wrote: > def threadWork(lock, a1, a2, rate): > ? ? ? ?while True: > ? ? ? ? ? ? ? ?time.sleep(rate) > ? ? ? ? ? ? ? ?lock.lock() > ? ? ? ? ? ? ? ?t = a2.balance / 2 > ? ? ? ? ? ? ? ?a1.balance += t > ? ? ? ? ? ? ? ?#say a thread.kill kills at this point > ? ? ? ? ? ? ? ?a2.balance -= t > ? ? ? ? ? ? ? ?lock.release() > It's obviously going to be an issue with killing processes too, which is why database engines have so much code specifically to protect against this. But if it's done as an exception, all you need is to catch that exception and reraise it: def threadWork(lock, a1, a2, rate): try: while True: time.sleep(rate) lock.lock() t = a2.balance / 2 a1.balance += t #say a thread.kill kills at this point a2.balance -= t lock.release() except: # roll back the transaction in some way lock.release() raise It'd require some care in coding, but it could be done. And if the lock/transaction object can be coded for it, it could even be done automatically: def threadWork(lock, a1, a2, rate): while True: time.sleep(rate) transaction.begin() t = a2.balance / 2 transaction.apply(a1.balance,t) #say a thread.kill kills at this point transaction.apply(a2.balance,-t) transaction.commit() If the transaction object doesn't get its commit() called, it does no actions at all, thus eliminating all issues of locks. Obviously there won't be any problem with the Python interpreter itself (refcounts etc) if the kill is done by exception - that would be a potential risk if using OS-level kills. ChrisA From python at mrabarnett.plus.com Sat Sep 17 19:52:15 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 18 Sep 2011 00:52:15 +0100 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <4E7532AF.8000707@mrabarnett.plus.com> On 18/09/2011 00:26, Dennis Lee Bieber wrote: > On Sun, 18 Sep 2011 07:35:01 +1000, Chris Angelico > declaimed the following in gmane.comp.python.general: > >> Is it just that nobody's implemented it, or is there a good reason for >> avoiding offering this sort of thing? >> > Any asynchronous "kill" runs the risk of leaving shared data > structures in a corrupt state. {Stupid example, but, in pseudo-Python: > > import time > > class Account(object): > def __init__(self, initial=0.0) > self.balance = initial > > myAccount = Account(100.0) > yourAccount = Account(100.0) > > accountLock = threading.Lock() > > def threadWork(lock, a1, a2, rate): > while True: > time.sleep(rate) > lock.lock() > t = a2.balance / 2 > a1.balance += t > #say a thread.kill kills at this point > a2.balance -= t > lock.release() > > # create/start thread1 passing (accountLock, myAccount, yourAccount, 60) > # create/start thread2 passing (accountLock, yourAccount, myAccount, > 120) > > time.sleep(300) > thread1.kill() > > So... Thread1 may be killed after one account gets incremented but > before the other is decremented... And what happens to the lock? If it > doesn't get released as part of the .kill() processing, they program is > dead-locked (and the magically appearing money will never be seen). If > it does get released, then the sum total of "money" in the system will > have increased. > [snip] The lock won't be released if an exception is raised, for example, if 'a1' isn't an Account instance and has no 'balance' attribute. Using a context manager would help in that case. From davea at ieee.org Sat Sep 17 20:04:42 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 17 Sep 2011 20:04:42 -0400 Subject: os independent rename In-Reply-To: References: Message-ID: <4E75359A.6060907@ieee.org> On 01/-10/-28163 02:59 PM, Nobody wrote: > On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: > >> So, what is the best way to do this that will >> behave the same across operating systems? > Delete the destination first, but after checking that it isn't the same as > the source. > > On Windows, that last bit is harder than it seems. A string-based > comparison won't work. Even if you ignore case, there's the issue of 8.3 > filenames, and some other odd cases. > > Or rename it twice, with the intermediate file being something that does not exist. For example, generate a random name, and if it exists, repeat till you come up with one that does not. Once the first rename has succeeded, you can safely delete the destination. Even this approach can have problems in the face of symlinks or multiple partitions. DaveA From missive at hotmail.com Sat Sep 17 20:41:33 2011 From: missive at hotmail.com (Lee Harr) Date: Sun, 18 Sep 2011 05:11:33 +0430 Subject: tool to point out os dependence problems? Message-ID: One thing that I've always liked about python is that itmakes it?pretty easy to write programs that run acrossoperating?systems. After running in to a problem today with os.renameI am wondering if there is a tool out there that canpoint out any known os dependence issues. A quick trip to google shows nothing obvious. From ladasky at my-deja.com Sat Sep 17 23:06:27 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 20:06:27 -0700 (PDT) Subject: Python bug in Windows 8--report now, or later? References: Message-ID: <49c99fa3-d0e0-4acb-b6fa-68959bbca52f@o9g2000vbo.googlegroups.com> On Sep 17, 2:20?pm, Chris Angelico wrote: > I would consider reporting it as a bug in Windows 8, not a bug in Python. > > Chris Angelico +1, beat me to it. :^) From invalid at invalid.invalid Sun Sep 18 00:15:57 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 18 Sep 2011 04:15:57 +0000 (UTC) Subject: Python bug in Windows 8--report now, or later? References: Message-ID: On 2011-09-17, Chris Angelico wrote: > I would consider reporting it as a bug in Windows 8, not a bug in Good luck with that plan. ;) [I don't know anything about this particular issue, but I do know that when there is a bug in Windows, it's usually everyboyd else that has to change to work around it.] From anikom15 at gmail.com Sun Sep 18 00:40:32 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Sat, 17 Sep 2011 21:40:32 -0700 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: <20110918044032.GA17257@Smoke> On Sun, Sep 18, 2011 at 04:15:57AM +0000, Grant Edwards wrote: > On 2011-09-17, Chris Angelico wrote: > > > I would consider reporting it as a bug in Windows 8, not a bug in > > Good luck with that plan. ;) > > [I don't know anything about this particular issue, but I do know that > when there is a bug in Windows, it's usually everyboyd else that has > to change to work around it.] > > Actually Microsoft usually goes out of its way to ensure backwards- compatibily, even when the app developer is DOING IT WRONG. From alec.taylor6 at gmail.com Sun Sep 18 01:42:00 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sun, 18 Sep 2011 15:42:00 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: <20110918044032.GA17257@Smoke> References: <20110918044032.GA17257@Smoke> Message-ID: On Sun, Sep 18, 2011 at 2:40 PM, Westley Mart?nez wrote: > On Sun, Sep 18, 2011 at 04:15:57AM +0000, Grant Edwards wrote: >> On 2011-09-17, Chris Angelico wrote: >> >> > I would consider reporting it as a bug in Windows 8, not a bug in >> >> Good luck with that plan. ?;) >> >> [I don't know anything about this particular issue, but I do know that >> when there is a bug in Windows, it's usually everyboyd else that has >> to change to work around it.] >> >> > > Actually Microsoft usually goes out of its way to ensure backwards- > compatibily, even when the app developer is DOING IT WRONG. > -- > http://mail.python.org/mailman/listinfo/python-list > For those interested, Windows 8 is available here: http://msdn.microsoft.com/windows/apps/br229516/ From dreyemi at gmail.com Sun Sep 18 05:39:03 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 10:39:03 +0100 Subject: Getting a list value from key/value pair Message-ID: Hi all, If I have a list with key/value pair, how do I get the value of the key? I'm working with this code snippet: >>> items = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status', 'pending'), ('timeout','120')]} >>> print [items[i] for i in items.keys()] [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), ('timeout' , 60)]] >>> -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From r32813 at freescale.com Sun Sep 18 05:41:30 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Sun, 18 Sep 2011 09:41:30 +0000 Subject: Python 2.7.1 64-bit Build on HP-UX11.31 ia64 with aCC - Many modules failed to build In-Reply-To: References: Message-ID: <02EA6D704E30CE499C5071776509A925F52AAB@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I have posted this in Compiler SIG and re-post here in case anyone who knows about this issue is not subscribed to that group. I am working on python build on my server using HP-UX ANSI C Compiler. I want to be consistent using aCC throughout instead of gcc for my python and cx_Oracle build as Oracle is not supporting gcc build much. Here is my aCC version. # swlist -l product | grep Compiler ACXX C.06.26.EVAL HP C/aC++ Compiler C-ANSI-C C.06.26.EVAL HP C/aC++ Compiler COMPLIBS B.11.31 Compiler Support Libraries Anyhow, my issue now is when I am building my python in 64-bit, I am encountering many modules failed to build issue, despite the python executable is successfully built. There are just so many modules that failed, that I would conclude my build failed. :P I followed through the instruction in README file for 64-bit build using HP-UX compiler (--without-gcc option is used in configure). I exported and unexported the environment variables before configure and make is run, respectively. I also removed -O option in the Makefile before running make. I have a few questions. 1.) Why Makefile is re-generated after python executable is created? I noticed the removal of optimization flag in Makefile is gone/restored after python binary is generated. 2.) 64-bit option. It seems that this is a bad flag that linker doesn't recognize? Many important modules failed to build, and I believe its due to this error. When I manually execute ld without passing in +DD64 flag, the module is generated successfull. ld -b +DD64 -lxnet build/temp.hp-ux-B.11.31-ia64-2.7/home/r32813/Build/2.7.1/Python-2.7.1/Modules/mathmodule.o build/temp.hp-ux-B.11.31-ia64-2.7/home/r32813/Build/2.7.1/Python-2.7.1/Modules/_math.o -L/usr/local/lib -lm -o build/lib.hp-ux-B.11.31-ia64-2.7/math.so ld: Unrecognized argument: +DD64 Fatal error. Above is just showing one of the modules that failed to build. 3.) Built in modules, I see the compiler cannot find the bit of information required to build _tkinter module. How do I make the configure able to locate my tcl/tk source code or binary which I have already installed and built separately (and successfully)? So, where do I place the source code if I need to put it so that the compiler can find? To end my question, here is the outcome of my build. For build in modules, I just need my _tkinter running. For shared libraries, I think need most of them, those are the basic functions that my application calls. Thanks in advance for your reply. Python build finished, but the necessary bits to build these modules were not found: _bsddb _curses _curses_panel _sqlite3 _ssl _tkinter bsddb185 bz2 dl gdbm imageop linuxaudiodev ossaudiodev readline spwd sunaudiodev zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _bisect _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _ctypes _ctypes_test _elementtree _functools _heapq _hotshot _io _json _locale _lsprof _md5 _multibytecodec _multiprocessing _random _sha _socket _struct _testcapi array audioop binascii cmath cPickle crypt cStringIO datetime dbm fcntl future_builtins grp itertools math mmap nis operator parser pyexpat resource select strop syslog termios time unicodedata From t at jollybox.de Sun Sep 18 06:16:09 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 18 Sep 2011 12:16:09 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C4E9.60209@jollybox.de> On 18/09/11 11:39, Kayode Odeyemi wrote: > Hi all, > > If I have a list with key/value pair, how do I get the value of the key? > > I'm working with this code snippet: Python 3.2.2 (default, Sep 5 2011, 04:33:58) [GCC 4.6.1 20110819 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> lst = [ ('key1', 'value1'), ('key2', 'value2') ] >>> d = dict (lst) >>> d['key1'] 'value1' >>> > >>>> items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} >>>> print [items[i] for i in items.keys()] > [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), > ('timeout' > , 60)]] >>>> > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > > From vincent.vandevyvre at swing.be Sun Sep 18 06:22:00 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sun, 18 Sep 2011 12:22:00 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C648.7070000@swing.be> An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Sun Sep 18 06:25:41 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sun, 18 Sep 2011 12:25:41 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C725.2050903@swing.be> An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sun Sep 18 06:30:06 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 11:30:06 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C648.7070000@swing.be> References: <4E75C648.7070000@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:22 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > Like that: > > # -*- coding: utf-8 -*- > > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in items.iteritems(): > print "\n {0}".format(key) > for val in value: > print "\t{0}: {1}".format(val[0], val[1]) > > for python 2.x > Thank you very much :) -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.crotti.0 at gmail.com Sun Sep 18 06:44:59 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 18 Sep 2011 11:44:59 +0100 Subject: create a directory structure In-Reply-To: References: <4E732F4B.3090409@gmail.com> <4E73566A.1010808@gmail.com> Message-ID: <4E75CBAB.6060204@gmail.com> On 09/17/2011 12:56 PM, Rafael Dur?n Casta?eda wrote: > I think you might want to look at Fabric > or vagrant > > > Thanks, but I don't understand how these two project would help me... I don't need to deploy on many machines via ssh, I only need that each machine is able to create an initial infrastructure. Paste-script allows me to do that, and in plus is ready to do many other things. Doing it in a hand-made fashion might also work well, but I think using paste-script is better for future extensions/improvements. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sun Sep 18 06:50:53 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 11:50:53 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C725.2050903@swing.be> References: <4E75C725.2050903@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:25 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > Hi all, > > > If I have a list with key/value pair, how do I get the value of the key? > > > I'm working with this code snippet: > > >>> items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > >>> print [items[i] for i in items.keys()] > [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), > ('timeout' > , 60)]] > >>> > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > Sorry, for python3.x > > # -*- coding: utf-8 -*- > > > d = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in d.items(): > > print("\n {0}".format(key)) > for val in value: > print("\t{0}: {1}".format(val[0], val[1])) > > Very helpful! I gave your karma at http://stackoverflow.com/questions/7460675/getting-a-list-value-from-key-value-pair -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sun Sep 18 08:13:03 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 18 Sep 2011 05:13:03 -0700 (PDT) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> On Sep 16, 9:17?pm, Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > > >>> sum(map(int,str(2**1000))) You could save another character by replacing "2**1000" with "2<<999" -- Mark From dreyemi at gmail.com Sun Sep 18 08:44:50 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 13:44:50 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C648.7070000@swing.be> References: <4E75C648.7070000@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:22 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > Like that: > > # -*- coding: utf-8 -*- > > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in items.iteritems(): > print "\n {0}".format(key) > for val in value: > print "\t{0}: {1}".format(val[0], val[1]) > > for python 2.x > Vincent, with: values = ('status', 'pending') ('timeout', '120') ('status', 'pending') ('timeout', 60) How do I comma separate it and put each each item in a dict? >>> for key, value in items.iteritems(): ... for val in value: ... md = {} ... for q in val: ... md.update(q) ... print md ... Traceback (most recent call last): File "", line 5, in ValueError: dictionary update sequence element #0 has length 1; 2 is required Thank you -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sun Sep 18 09:50:40 2011 From: python at bdurham.com (python at bdurham.com) Date: Sun, 18 Sep 2011 09:50:40 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: <1316353840.13565.140258142485365@webmail.messagingengine.com> Thanks for everyone's comments - much appreciated! Malcolm (the OP) From arnodel at gmail.com Sun Sep 18 10:10:10 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 18 Sep 2011 15:10:10 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> Message-ID: On Sep 18, 2011 1:20 PM, "Mark Dickinson" wrote: > > On Sep 16, 9:17 pm, Arnaud Delobelle wrote: > > Ah go on, let's make a codegolf contest out of it. > > My entry: > > > > >>> sum(map(int,str(2**1000))) > > You could save another character by replacing "2**1000" with "2<<999" > Excellent! -- Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From anbumani923 at gmail.com Sun Sep 18 10:30:34 2011 From: anbumani923 at gmail.com (anbu) Date: Sun, 18 Sep 2011 07:30:34 -0700 (PDT) Subject: 2011 NEW MODAL GIRLS SEX VIDEO AND PICTURES FREE DOWNLOAD Message-ID: http://123maza.com/65/cute540/ From zdoor at xs4all.nl Sun Sep 18 11:55:08 2011 From: zdoor at xs4all.nl (Alex van der Spek) Date: Sun, 18 Sep 2011 17:55:08 +0200 Subject: Numpy.array with dtype works on list of tuples not on list of lists? Message-ID: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Why does this not work? >>> dat=[[1,2,3],[4,5,6]] >>> col=[('a','f4'),('b','f4'),('c','f4')] >>> arr=numpy.array(dat,dtype=col) Traceback (most recent call last): File "", line 1, in arr=numpy.array(dat,dtype=col) TypeError: expected a readable buffer object >>> But this does: >>> dat=[(1,2,3),(4,5,6)] >>> arr=numpy.array(dat,dtype=col) >>> arr array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', '>> The only difference that the object is a list of tuples now? Thanks for clarification, Alex van der Spek From rosuav at gmail.com Sun Sep 18 13:55:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 19 Sep 2011 03:55:16 +1000 Subject: GTK2.TextView examples In-Reply-To: <1316367199.2789.YahooMailRC@web83811.mail.sp1.yahoo.com> References: <1316367199.2789.YahooMailRC@web83811.mail.sp1.yahoo.com> Message-ID: On Mon, Sep 19, 2011 at 3:33 AM, Lance Dillon wrote: > Here are some examples that use GTK2.TextTag. Interestingly, neither runs on my Windows system - I don't have GDK2 or Pango. Much appreciate the examples though - can some of them go into the official docs? It may well be that I'm using completely the wrong tools here. What I want to do is write a console in Pike, more or less a telnet/MUD client. Is it better to use TextView, or to use a GdkDisplay or somesuch and draw the text myself? ChrisA From philip at semanchuk.com Sun Sep 18 13:57:10 2011 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 18 Sep 2011 13:57:10 -0400 Subject: Numpy.array with dtype works on list of tuples not on list of lists? In-Reply-To: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> References: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Message-ID: <119665A7-EF5F-49D4-9B59-83C8D21EEA8A@semanchuk.com> On Sep 18, 2011, at 11:55 AM, Alex van der Spek wrote: > Why does this not work? > >>>> dat=[[1,2,3],[4,5,6]] >>>> col=[('a','f4'),('b','f4'),('c','f4')] >>>> arr=numpy.array(dat,dtype=col) > > Traceback (most recent call last): > File "", line 1, in > arr=numpy.array(dat,dtype=col) > TypeError: expected a readable buffer object > > But this does: > >>>> dat=[(1,2,3),(4,5,6)] >>>> arr=numpy.array(dat,dtype=col) >>>> arr > array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', ' > The only difference that the object is a list of tuples now? I don't know why you're seeing what you're seeing, but if you don't get answer here you could try asking on the numpy list. Good luck Philip From matt.pounsett at gmail.com Sun Sep 18 16:19:24 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Sun, 18 Sep 2011 13:19:24 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <731ee8c8-3f8d-49ad-91a9-4e247f66d252@bl1g2000vbb.googlegroups.com> On Sep 15, 1:54?am, Ryan Kelly wrote: > To be friendlier to others reading your code, I would consider using a > classmethod to create an alternative constructor: I finally got back to looking at this today. As it turns out, un- overriding __new__ in the child class is more complicated than I first expected, and isn't worth the extra effort. So, I ended up using a constructor class method as you suggested. Thanks again! From robert.kern at gmail.com Sun Sep 18 16:31:58 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 18 Sep 2011 15:31:58 -0500 Subject: Numpy.array with dtype works on list of tuples not on list of lists? In-Reply-To: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> References: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Message-ID: On 9/18/11 10:55 AM, Alex van der Spek wrote: > Why does this not work? > >>>> dat=[[1,2,3],[4,5,6]] >>>> col=[('a','f4'),('b','f4'),('c','f4')] >>>> arr=numpy.array(dat,dtype=col) > > Traceback (most recent call last): > File "", line 1, in > arr=numpy.array(dat,dtype=col) > TypeError: expected a readable buffer object >>>> > > But this does: > >>>> dat=[(1,2,3),(4,5,6)] >>>> arr=numpy.array(dat,dtype=col) >>>> arr > array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', ' ('c', '>>> > > The only difference that the object is a list of tuples now? numpy questions are best asked on the numpy mailing list: http://www.scipy.org/Mailing_Lists To answer your question, though, numpy.array() needs to figure out a lot of different things about the input data simultaneously, in particular its shape. Structured arrays (i.e. with elements that have individual fields as above) pose a new problem in that its individual elements are sequences themselves. In order to help it decide whether it should recurse down into a sequence to find its elements or decide that the sequence *is* an element in its own right, we settled on the convention that tuples are to be considered elements and that lists are sequences of elements. -- 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 keymint1498 at gmail.com Sun Sep 18 17:07:22 2011 From: keymint1498 at gmail.com (superhappyfuntime) Date: 18 Sep 2011 21:07:22 GMT Subject: What is wrong with this code? References: <38d9k8-u8t.ln1@satorlaser.homedns.org> Message-ID: On 09-15-2011, Ulrich Eckhardt wrote: > superhappyfuntime wrote: >> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > It's LaTeX, not Python. > Uli no, it's a cap for LaTeX written in python -- I'm trying a new usenet client for Mac, Nemo OS X, since 0 days. You can download it at http://www.malcom-mac.com/nemo From resourts137 at gmail.com Sun Sep 18 17:54:25 2011 From: resourts137 at gmail.com (iqbal iqbal) Date: Sun, 18 Sep 2011 14:54:25 -0700 (PDT) Subject: Booking cheapest airlines Tickets Pakistan world wide Message-ID: Booking cheapest airlines Tickets Pakistan world wide http://karachi-guest-house-5star-hotels.blogspot.com/ From steve+comp.lang.python at pearwood.info Sun Sep 18 18:00:51 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Sep 2011 22:00:51 GMT Subject: What is wrong with this code? References: <38d9k8-u8t.ln1@satorlaser.homedns.org> Message-ID: <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 18 Sep 2011 21:07:22 +0000, superhappyfuntime wrote: > On 09-15-2011, Ulrich Eckhardt wrote: > >> superhappyfuntime wrote: >>> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > >> It's LaTeX, not Python. > >> Uli > > no, it's a cap for LaTeX written in python If it's Python, it's no Python syntax I've ever seen before. >>> here it is: = '\begin{document}' File "", line 1 here it is: = '\begin{document}' ^ SyntaxError: invalid syntax How about if you start off by explaining what you think "a cap for LaTeX" means, or provide a link to something that will explain it? This is a Python list, and we don't necessarily know much about LaTeX. -- Steven From irmen.NOSPAM at xs4all.nl Sun Sep 18 19:05:20 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 19 Sep 2011 01:05:20 +0200 Subject: ANN: Pyro 4.9 released Message-ID: <4e767930$0$2480$e4fe514c@news2.news.xs4all.nl> Hello, Pyro 4.9 has just been released! Get it from Pypi: http://pypi.python.org/pypi/Pyro4/ Documentation: http://packages.python.org/Pyro4/index.html Changes include: * the documentation has finally been completed * changed asyncresult a little in non-compatible ways. * added more examples: gui_eventloop, deadlock, itunes * serialized data is released a bit faster to improve garbage collection * fixed setting several socket options such as SO_REUSEADDR. (See the change log in the documentation for a more detailed list) Pyro = Python Remote Objects. It is a library that enables you to build applications in which objects can talk to each other over the network, with minimal programming effort. You can just use normal Python method calls, with almost every possible parameter and return value type, and Pyro takes care of locating the right object on the right computer to execute the method. It is designed to be very easy to use, and to generally stay out of your way. But it also provides a set of powerful features that enables you to build distributed applications rapidly and effortlessly. Pyro is written in 100% pure Python and therefore runs on many platforms and Python versions, including Python 3.x. Enjoy, Irmen de Jong From ian.g.kelly at gmail.com Mon Sep 19 01:41:29 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 18 Sep 2011 23:41:29 -0600 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 5:38 PM, Chris Angelico wrote: > But if it's done as an exception, all you need is to > catch that exception and reraise it: > > def threadWork(lock, a1, a2, rate): > ? try: > ? ? ? while True: > ? ? ? ? ? ? ? time.sleep(rate) > ? ? ? ? ? ? ? lock.lock() > ? ? ? ? ? ? ? t = a2.balance / 2 > ? ? ? ? ? ? ? a1.balance += t > ? ? ? ? ? ? ? #say a thread.kill kills at this point > ? ? ? ? ? ? ? a2.balance -= t > ? ? ? ? ? ? ? lock.release() > ?except: > ? ? ?# roll back the transaction in some way > ? ? ?lock.release() > ? ? ?raise And what if the thread gets killed a second time while it's in the except block? > It'd require some care in coding, but it could be done. And if the > lock/transaction object can be coded for it, it could even be done > automatically: > > def threadWork(lock, a1, a2, rate): > ? ? ? while True: > ? ? ? ? ? ? ? time.sleep(rate) > ? ? ? ? ? ? ? transaction.begin() > ? ? ? ? ? ? ? t = a2.balance / 2 > ? ? ? ? ? ? ? transaction.apply(a1.balance,t) > ? ? ? ? ? ? ? #say a thread.kill kills at this point > ? ? ? ? ? ? ? transaction.apply(a2.balance,-t) > ? ? ? ? ? ? ? transaction.commit() > > If the transaction object doesn't get its commit() called, it does no > actions at all, thus eliminating all issues of locks. And what if the thread gets killed in the middle of the commit? Getting the code right is going to be a lot more complicated than just adding a couple of try/excepts. Cheers, Ian From greg.ewing at canterbury.ac.nz Mon Sep 19 01:56:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 19 Sep 2011 17:56:42 +1200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <9do3stFtq8U1@mid.individual.net> Ian Kelly wrote: > And what if the thread gets killed a second time while it's in the except block? > And what if the thread gets killed in the middle of the commit? For these kinds of reasons, any feature for raising asynchronous exceptions in another thread would need to come with some related facilites: * A way of blocking asynchronous exceptions around a critical section would be needed. * Once an asynchronous exception has been raised, further asynchronous exceptions should be blocked until explicitly re-enabled. * Asynchronous exceptions should probably be disabled initially in a new thread until it explicitly enables them. Some care would still be required to write code that is robust in the presence of asynchronous exceptions, but given these facilities, it ought to be possible. -- Greg From adam.jorgensen.za at gmail.com Mon Sep 19 02:03:08 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Mon, 19 Sep 2011 08:03:08 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: The point of the Java thread.stop() being deprecated seems to have very little to do with undeclared exceptions being raised and a lot to do with objects being left in a potentially damaged state. As Ian said, it's a lot more complex than just adding try/catches. Killing a thread in the middle of some non-atomic operation with side-effects that propagate beyond the thread is a recipe for trouble. In fact, while a a lot can be written about Java being a poor language the specific article linked to about why Java deprecated thread.stop() gives a pretty damn good explanation as to why Thread.stop() and the like are a bad idea and what a better idea might be (Signalling that a graceful halt should be attempted) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Sep 19 02:25:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 19 Sep 2011 16:25:59 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Mon, Sep 19, 2011 at 3:41 PM, Ian Kelly wrote: > And what if the thread gets killed in the middle of the commit? > Database managers solved this problem years ago. It's not done by preventing death until you're done - death can come from someone brutally pulling out your power cord. There's no "except PowerCordRemoved" to protect you from that! There are various ways, and I'm sure one of them will work for whatever situation is needed. ChrisA From geek.swarup at gmail.com Mon Sep 19 02:38:53 2011 From: geek.swarup at gmail.com (swarupchandra kamerkar) Date: Mon, 19 Sep 2011 12:08:53 +0530 Subject: Need help on using the USB module Message-ID: Hi, I am trying to use Pythoin on windows. I wanted to use the uSB module. I downloaded it and installed it. Still I get the following message. >>> import usb Traceback (most recent call last): File "", line 1, in import usb ImportError: DLL load failed: The specified module could not be found. What is it that I am missing? Regards Swarup -------------- next part -------------- An HTML attachment was scrubbed... URL: From Shambhu.Rajak at kpitcummins.com Mon Sep 19 03:03:10 2011 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Mon, 19 Sep 2011 07:03:10 +0000 Subject: What is wrong with this code? In-Reply-To: <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <38d9k8-u8t.ln1@satorlaser.homedns.org> <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <408F64D89899604FB24015E64E10490C0329A3@KCHJEXMB02.kpit.com> I think you cannnot use "\" as normal string ,it?s a metacharacter, u can use it like this: '\\begin{document}' -Shambhu -----Original Message----- From: Steven D'Aprano [mailto:steve+comp.lang.python at pearwood.info] Sent: Monday, September 19, 2011 3:31 AM To: python-list at python.org Subject: Re: What is wrong with this code? On Sun, 18 Sep 2011 21:07:22 +0000, superhappyfuntime wrote: > On 09-15-2011, Ulrich Eckhardt wrote: > >> superhappyfuntime wrote: >>> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > >> It's LaTeX, not Python. > >> Uli > > no, it's a cap for LaTeX written in python If it's Python, it's no Python syntax I've ever seen before. >>> here it is: = '\begin{document}' File "", line 1 here it is: = '\begin{document}' ^ SyntaxError: invalid syntax How about if you start off by explaining what you think "a cap for LaTeX" means, or provide a link to something that will explain it? This is a Python list, and we don't necessarily know much about LaTeX. -- Steven From chunuan723 at gmail.com Mon Sep 19 05:15:16 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 19 Sep 2011 02:15:16 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <3138b9b7-7b69-411a-a63f-f0c12cfbe56a@1g2000yqm.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From Antoon.Pardon at rece.vub.ac.be Mon Sep 19 06:04:01 2011 From: Antoon.Pardon at rece.vub.ac.be (Antoon Pardon) Date: Mon, 19 Sep 2011 12:04:01 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <20110919100401.GD3410@trout.vub.ac.be> On Sun, Sep 18, 2011 at 07:35:01AM +1000, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: > Forking a thread to discuss threads.... ahem. > > Why is it that threads can't be killed? Do Python threads correspond > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading > library I've seen has some way of killing threads, although I've not > looked in detail into POSIX threads there (there seem to be two > options, pthread_kill and pthread_cancel, that could be used, but I've > not used either). If nothing else, it ought to be possible to > implement a high level kill simply by setting a flag that the > interpreter will inspect every few commands, the same way that > KeyboardInterrupt is checked for. > > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? Python has a half baked solution to this. If you go to http://docs.python.org/release/3.2.2/c-api/init.html You will find the following: int PyThreadState_SetAsyncExc(long id, PyObject *exc) Asynchronously raise an exception in a thread. The id argument is the thread id of the target thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn?t found. If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions. Some recipes can be found at: http://www.google.com/search?ie=UTF-8&oe=utf-8&q=python+recipe+PyThreadState_SetAsyncExc However it this doesn't work 100% correctly. Last time I tried using this, it didn't work with an exception instance but only with an execption class as parameter. There was a discussion at http://mail.python.org/pipermail/python-dev/2006-August/068158.html about this. I don't know how it was finaly resolved. -- Antoon Pardon From hfaber at invalid.net Mon Sep 19 07:11:51 2011 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 19 Sep 2011 13:11:51 +0200 Subject: Operator commutativity Message-ID: Hi there, when I have a python class X which overloads an operator, I can use that operator to do any operation for example with an integer y = X() + 123 however, say I want the "+" operator to be commutative. Then y = 123 + X() should have the same result. However, since it does not call __add__ on an instance of X, but on the int 123, this fails: TypeError: unsupported operand type(s) for +: 'int' and 'X' How can I make this commutative? Best regards, Henrik From arnodel at gmail.com Mon Sep 19 07:17:22 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Mon, 19 Sep 2011 12:17:22 +0100 Subject: Operator commutativity In-Reply-To: References: Message-ID: On 19 September 2011 12:11, Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? Overload X.__radd__() as well HTH -- Arnaud From paul.nospam at rudin.co.uk Mon Sep 19 07:23:48 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 19 Sep 2011 12:23:48 +0100 Subject: Operator commutativity References: Message-ID: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Henrik Faber writes: > How can I make this commutative? Incidentally - this isn't really about commutativity at all - the question is how can you define both left and right versions of add, irrespective of whether they yield the same result. I think __radd__ is what you're after. From duncan.booth at invalid.invalid Mon Sep 19 07:26:08 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Sep 2011 11:26:08 GMT Subject: Operator commutativity References: Message-ID: Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? > By defining __radd__ >>> class X: def __add__(self, other): return "%r + %r" % (self, other) def __radd__(self, other): return "%r + %r" % (other, self) >>> X() + 123 '<__main__.X object at 0x029C45B0> + 123' >>> 123 + X() '123 + <__main__.X object at 0x02101910>' -- Duncan Booth http://kupuguy.blogspot.com From hfaber at invalid.net Mon Sep 19 07:32:00 2011 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 19 Sep 2011 13:32:00 +0200 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: On 19.09.2011 13:23, Paul Rudin wrote: > Henrik Faber writes: > >> How can I make this commutative? > > Incidentally - this isn't really about commutativity at all - the > question is how can you define both left and right versions of add, > irrespective of whether they yield the same result. Right. The operator+ in my case just happens to be commutative and I wanted a language way to express this. > I think __radd__ is what you're after. It is, thank you very much - I knew there was some way to get this done nicely. Perfect! :-) Best regards, Henrik From stars9820 at gmail.com Mon Sep 19 08:09:55 2011 From: stars9820 at gmail.com (star ship) Date: Mon, 19 Sep 2011 05:09:55 -0700 (PDT) Subject: AMAZING WORK AT HOME Message-ID: <2863194c-8fb4-4809-9d50-302ef3e5bbc7@z41g2000yqb.googlegroups.com> Hi this is most power ful earning site. part time job for you refer friends and other people and earn more money. http://www.pswtracker.com/index.php?refid=26536 thanks From roy at panix.com Mon Sep 19 08:10:27 2011 From: roy at panix.com (Roy Smith) Date: Mon, 19 Sep 2011 08:10:27 -0400 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: In article , Henrik Faber wrote: > On 19.09.2011 13:23, Paul Rudin wrote: > > Henrik Faber writes: > > > >> How can I make this commutative? > > > > Incidentally - this isn't really about commutativity at all - the > > question is how can you define both left and right versions of add, > > irrespective of whether they yield the same result. > > Right. The operator+ in my case just happens to be commutative and I > wanted a language way to express this. > > > I think __radd__ is what you're after. > > It is, thank you very much - I knew there was some way to get this done > nicely. Perfect! :-) __radd__() only solves the problem if the left-hand operand has no __add__() method itself. class C1: def __add__(self, other): print "C1.__add__()" def __radd__(self, other): print "C1.__radd__()" class C2: def __add__(self, other): print "C2.__add__()" def __radd__(self, other): print "C2.__radd__()" c1 = C1() c2 = C2() c1 + c2 c2 + c1 $ python radd.py C1.__add__() C2.__add__() From robin at reportlab.com Mon Sep 19 08:42:30 2011 From: robin at reportlab.com (Robin Becker) Date: Mon, 19 Sep 2011 13:42:30 +0100 Subject: help needed on decimal formatting issue Message-ID: <4E7738B6.2080000@chamonix.reportlab.co.uk> I'm not really very used to the decimal module so I'm asking here if any one can help me with a problem in a well known third party web framework The code in question is def format_number(value, max_digits, decimal_places): """ Formats a number into a string with the requisite number of digits and decimal places. """ if isinstance(value, decimal.Decimal): context = decimal.getcontext().copy() context.prec = max_digits return u'%s' % str( value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) else: return u"%.*f" % (decimal_places, value) we have set up decimal fields with max_digits=7 decimal_places=2 and max_digits=10, decimal_places=4. We are getting issues with quantize failing with the message 'quantize result has too many digits for current context'. Anyhow, I believe that we need to adjust the above code so that the precision is actually set to context.prec = max_digits+decimal_places but I'm not certain that is right. Presumably the author thought that the fields could have large values of both max_digits and decimal_places. Initially I thought precision must be to do with decimal_places only, but changing context.prec = decimal_places did not fix the issue. Can someone enlighten me? The failing case for the original code was format_number(Decimal('914146.80'),7,2) with context.prec = decimal_places we failed differently with format_number(Decimal('42.7571'),10,4) so I adopted context.prec = max_digits+decimal_places and that seems to work. If this is indeed a proper fix I will send a bug report to the well known jazz based framework. -- Robin Becker From ethan at stoneleaf.us Mon Sep 19 08:48:07 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 19 Sep 2011 05:48:07 -0700 Subject: Operator commutativity In-Reply-To: References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <4E773A07.6090505@stoneleaf.us> Roy Smith wrote: > In article , > Henrik Faber wrote: > >> On 19.09.2011 13:23, Paul Rudin wrote: >>> Henrik Faber writes: >>> >>>> How can I make this commutative? >>> Incidentally - this isn't really about commutativity at all - the >>> question is how can you define both left and right versions of add, >>> irrespective of whether they yield the same result. >> Right. The operator+ in my case just happens to be commutative and I >> wanted a language way to express this. >> >>> I think __radd__ is what you're after. >> It is, thank you very much - I knew there was some way to get this done >> nicely. Perfect! :-) > > __radd__() only solves the problem if the left-hand operand has no > __add__() method itself. Only true if the left-hand operand is so ill-behaved it doesn't check to see if it makes sense to add itself to the right-hand operand. If it doesn't know how, it should `return NotImplemented` -- Python will then try __radd__ on the left-hand operand. Also, if the right-hand operand is a subclass of the left-hand operand then Python will try right-hand_operand.__radd__ first. Now, if the left-hand operand *does* know how (or thinks it does, which could be another matter entirely), and the right-hand operand is *not* a subclass of the left-hand operand, then you are correct -- the right-hand operand wil not be called. ~Ethan~ From brian.curtin at gmail.com Mon Sep 19 10:00:25 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 19 Sep 2011 09:00:25 -0500 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 13:01, Kevin Walzer wrote: > I have been testing my Python application on the just-released developer > preview of Windows 8 and have noted an error: the application does not > create an app folder in the user's "application data" directory. This causes > the app to crash on startup. Manually creating the directory solves the > problem. Since the app uses an os.mkdir() call to create the directory, and > since the app runs fine on Windows 7, my guess is that the bug lies > somewhere in the interaction between Python (I'm using ActivePython 2.7) and > Windows. > > Here's the relevant code: > > ? ?#make preferences directory if it does not exist > ? ?def makePrefsDir(self): > ? ? ? ?self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], > 'MyApp')) > ? ? ? ?if not os.path.exists(self.appdir): > ? ? ? ? ? ?os.mkdir(self.appdir) > > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do the > Python developers test Python on pre-release versions of Windows? First, is your application actually crashing, or does it just exit due to an unhandled exception? I suspect the latter, so if that's true, what's the exception and message? You said "the application does not create an app folder in the user's 'application data' directory" -- what does this mean, or rather, what is the specific folder you're expecting to have? If Python can't create the directory but you can do it manually, there may be some permission or access differences new to Windows 8. What does "echo %APPDATA%" give you? I haven't installed Windows 8 yet, but I'm planning to get it up and running soon. If you submit issues to http://bugs.python.org, hopefully with specific test cases that we can run and work with, it'll be easier to track and fix. If you do that, add me to the nosy list on the issues - tracker id: brian.curtin, I'm one of the Windows people around there. From torpedoallen at gmail.com Mon Sep 19 11:21:10 2011 From: torpedoallen at gmail.com (Christian Ren) Date: Mon, 19 Sep 2011 08:21:10 -0700 (PDT) Subject: help for the parse of encrypted excel Message-ID: I used xlrd library for the parse of excel before. But now, I encounter a problem that the file has been encrypted for some security reason. On the official website, i found "xlrd will not attempt to decode password-protected (encrypted) files. " :(( And I also tried another library called pyExcelerator, Unfortunately, it failed all the same. Is there anybody can tell me what's the solution to the parse of encrypted excel? Thanks in advance. (PS: for the user experience reason, I don't hope to save this file as another copy) From tjreedy at udel.edu Mon Sep 19 11:25:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Sep 2011 11:25:04 -0400 Subject: Operator commutativity In-Reply-To: <4E773A07.6090505@stoneleaf.us> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <4E773A07.6090505@stoneleaf.us> Message-ID: On 9/19/2011 8:48 AM, Ethan Furman wrote: > Roy Smith wrote: >> __radd__() only solves the problem if the left-hand operand has no >> __add__() method itself. > > Only true if the left-hand operand is so ill-behaved it doesn't check to > see if it makes sense to add itself to the right-hand operand. If it > doesn't know how, it should `return NotImplemented` -- Python will then > try __radd__ on the left-hand operand. > > Also, if the right-hand operand is a subclass of the left-hand operand > then Python will try right-hand_operand.__radd__ first. The builtin classes like int are (should be, sans bug) well-behaved. > Now, if the left-hand operand *does* know how (or thinks it does, which > could be another matter entirely), and the right-hand operand is *not* a > subclass of the left-hand operand, then you are correct -- the > right-hand operand wil not be called. So the potential problems arise with two user classes. -- Terry Jan Reedy From mdickinson at enthought.com Mon Sep 19 12:12:01 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Mon, 19 Sep 2011 09:12:01 -0700 (PDT) Subject: help needed on decimal formatting issue References: Message-ID: <150e2270-84a7-45ae-ae56-681f0b26c62a@1g2000vbu.googlegroups.com> On Sep 19, 1:42?pm, Robin Becker wrote: > I'm not really very used to the decimal module so I'm asking here if any one can > help me with a problem in a well known third party web framework > > The code in question is > > def format_number(value, max_digits, decimal_places): > ? ? ?""" > ? ? ?Formats a number into a string with the requisite number of digits and > ? ? ?decimal places. > ? ? ?""" > ? ? ?if isinstance(value, decimal.Decimal): > ? ? ? ? ?context = decimal.getcontext().copy() > ? ? ? ? ?context.prec = max_digits > ? ? ? ? ?return u'%s' % str( > ? ? ? ? ? value.quantize(decimal.Decimal(".1") ** decimal_places, > ? ? ? ? ? ? ? ? ? ? ? ? context=context)) > ? ? ?else: > ? ? ? ? ?return u"%.*f" % (decimal_places, value) What's the meaning of the 'max_digits' argument here? Are you guaranteed that the incoming value is smaller than 10**max_digits in absolute value? If so, then a precision of max_digits + decimal_places + 1 should be enough. The +1 is there to cover the corner case where a value close to 10**max_digits is rounded up to 10**max_digits by the quantize operation. BTW, that's a fairly horrible way of creating the first argument to the quantize method, too. It would be more efficient to do something like: >>> decimal_places = 2 >>> decimal.Decimal('0.{}1'.format('0'*(decimal_places-1))) Decimal('0.01') (perhaps with suitable special-casing for the case where decimal_places <= 0; not sure whether this applies in your context). -- Mark From shilparani9030 at gmail.com Mon Sep 19 12:14:01 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Mon, 19 Sep 2011 09:14:01 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From anikom15 at gmail.com Mon Sep 19 12:45:53 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 19 Sep 2011 09:45:53 -0700 Subject: Operator commutativity In-Reply-To: References: Message-ID: <20110919164553.GA20521@Smoke> On Mon, Sep 19, 2011 at 01:11:51PM +0200, Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? > > Best regards, > Henri def __radd__(self, other): return self.__add__(self, other) From bahamutzero8825 at gmail.com Mon Sep 19 16:40:00 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 19 Sep 2011 15:40:00 -0500 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: <4E77A8A0.3030104@gmail.com> On 2011.09.19 09:00 AM, Brian Curtin wrote: > You said "the application does not create an app folder in the user's > 'application data' directory" -- what does this mean, or rather, what > is the specific folder you're expecting to have? If Python can't > create the directory but you can do it manually, there may be some > permission or access differences new to Windows 8. What does "echo > %APPDATA%" give you? I booted up the Win8 dev preview in a VM and os.environ['appdata'] gives me the same result it would for Windows 7. Perhaps the problem lies in the os.path.exists() call (that is, Win8 and Win7 react differently to this call). I personally would try to create the directory and then catch either a WindowsError (error 183) or an OSError (error 17) if the directory already exists. I might play around with this later and post some results. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 PGP/GPG Public Key ID: 0xF88E034060A78FCB From nobody at nowhere.com Mon Sep 19 17:54:49 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 19 Sep 2011 22:54:49 +0100 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) References: Message-ID: On Sun, 18 Sep 2011 23:41:29 -0600, Ian Kelly wrote: >> If the transaction object doesn't get its commit() called, it does no >> actions at all, thus eliminating all issues of locks. > > And what if the thread gets killed in the middle of the commit? The essence of a commit is that it involves an atomic operation, for which there is no "middle". From ian.g.kelly at gmail.com Mon Sep 19 18:04:17 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 19 Sep 2011 16:04:17 -0600 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Mon, Sep 19, 2011 at 12:25 AM, Chris Angelico wrote: > On Mon, Sep 19, 2011 at 3:41 PM, Ian Kelly wrote: >> And what if the thread gets killed in the middle of the commit? >> > > Database managers solved this problem years ago. It's not done by > preventing death until you're done - death can come from someone > brutally pulling out your power cord. There's no "except > PowerCordRemoved" to protect you from that! I'm aware of that. I'm not saying it's impossible, just that the example you gave is over-simplified, as writing atomic transactional logic is a rather complex topic. There may be an existing Python library to handle this, but I'm not aware of one. "PowerCordRemoved" is not relevant here, as that would kill the entire process, which renders the issue of broken shared data within a continuing process rather moot. Cheers, Ian From bahamutzero8825 at gmail.com Mon Sep 19 18:38:32 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 19 Sep 2011 17:38:32 -0500 Subject: logging.config and {-style formatting Message-ID: <4E77C468.30709@gmail.com> Is it possible to use {-style formatting with a logging config file? I can add style='{' to a logging.Formatter() call and it works fine, but I see no way of doing this from a config file. I tried adding a style option in the config file, but it has no effect. I see no mention of the {-style in the logging.config docs, so am I right to assume {-style formatting is not implemented in logging.config? -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From mindwalkernine at gmail.com Mon Sep 19 19:13:06 2011 From: mindwalkernine at gmail.com (Jordan Evans) Date: Mon, 19 Sep 2011 18:13:06 -0500 Subject: Dynamically Cause A Function To Return Message-ID: I want dynamically place the 'return' statement in a function via user input or achieve the same through some other means. If some other means, the user must be able initiate this at runtime during a raw_input(). This is what I have so far, this would be an awesome command line debugging tool if I can get it to work. def b(label="", *args): """Used to create breaks for debugging. Will break the function or continue the function it is place within based on user input. Has as a input loop for querying variables and executing code before a break or a continue.""" print label+":", for arg in args: print str(arg), if len(args): print x = "" while x != ".": command = raw_input() try: exec command except: pass -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridharr at activestate.com Mon Sep 19 19:27:40 2011 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Mon, 19 Sep 2011 16:27:40 -0700 Subject: ANN: ActivePython 3.2.2.3 is now available Message-ID: <9643CBF5-DC47-4A59-93B9-1610031E4ACF@activestate.com> ActiveState is pleased to announce ActivePython 3.2.2.3, a complete, ready-to-install binary distribution of Python 3.2. http://www.activestate.com/activepython/downloads What's New in ActivePython-3.2.2.3 ================================== New Features & Upgrades ----------------------- - Upgrade to Python 3.2.2 (`release notes `__) - [Windows] Security upgrade to openssl-1.0.0e - Upgraded the following packages: - Distribute-0.6.21 - virtualenv-1.6.4 What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython also includes a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install numpy [...] C:\>python >>> import numpy.linalg >>> See this page for full details: http://docs.activestate.com/activepython/3.2/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/3.2/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows (x86 and x64) - Mac OS X (x86 and x86_64; 10.5+) - Linux (x86 and x86_64) - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From rosuav at gmail.com Mon Sep 19 20:18:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 20 Sep 2011 10:18:02 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 8:04 AM, Ian Kelly wrote: > "PowerCordRemoved" is not relevant here, as that would kill the entire > process, which renders the issue of broken shared data within a > continuing process rather moot. > Assuming that the "broken shared data" exists only in RAM on one single machine, and has no impact on the state of anything on the hard disk or on any other computer, yes. ChrisA From chunuan723 at gmail.com Mon Sep 19 20:37:31 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 19 Sep 2011 17:37:31 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <7345edb4-a967-4c69-a212-d5072809e360@19g2000vbx.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From greg.ewing at canterbury.ac.nz Mon Sep 19 20:51:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 20 Sep 2011 12:51:42 +1200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <9dq6cvF4ndU1@mid.individual.net> Antoon Pardon wrote: > int PyThreadState_SetAsyncExc(long id, PyObject *exc) > > To prevent > naive misuse, you must write your own C extension to call this. Not if we use ctypes! Muahahahaaa! -- Greg From steve+comp.lang.python at pearwood.info Mon Sep 19 21:22:41 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 11:22:41 +1000 Subject: Operator commutativity References: Message-ID: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > def __radd__(self, other): > return self.__add__(self, other) Which, inside a class, can be simplified to: __radd__ = __add__ -- Steven From roy at panix.com Mon Sep 19 22:26:30 2011 From: roy at panix.com (Roy Smith) Date: Mon, 19 Sep 2011 22:26:30 -0400 Subject: Operator commutativity References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > Westley Mart??nez wrote: > > > def __radd__(self, other): > > return self.__add__(self, other) > > Which, inside a class, can be simplified to: > > __radd__ = __add__ Ooh, I could see that leading to some weird diagnostics. For example: class Foo: def __add__(self, other): raise Exception __radd__ = __add__ f1 = Foo() print 1 + f1 produces: ./add.py Traceback (most recent call last): File "./add.py", line 11, in print 1 + f1 File "./add.py", line 5, in __add__ raise Exception Exception which leaves the user wondering why __add__() was called when clearly __radd__() should have been. The way Westley wrote it (modulo fixing the __add__() call signature) produces: ./add.py Traceback (most recent call last): File "./add.py", line 11, in print 1 + f1 File "./add.py", line 8, in __radd__ return self.__add__(other) File "./add.py", line 5, in __add__ raise Exception Exception which at least is a stack trace that shows that __radd__() was called. From steve+comp.lang.python at pearwood.info Mon Sep 19 22:43:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Sep 2011 02:43:25 GMT Subject: Operator commutativity References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e77fdcd$0$29995$c3e8da3$5496439d@news.astraweb.com> On Mon, 19 Sep 2011 22:26:30 -0400, Roy Smith wrote: > In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >> Westley Mart?nez wrote: >> >> > def __radd__(self, other): >> > return self.__add__(self, other) >> >> Which, inside a class, can be simplified to: >> >> __radd__ = __add__ > > Ooh, I could see that leading to some weird diagnostics. "Weird"? You've lived a sheltered life if you think a function being known under two names is weird. Wait until you discover monkey-patching built-ins for fun and profit! -- Steven From anikom15 at gmail.com Mon Sep 19 22:53:39 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 19 Sep 2011 19:53:39 -0700 Subject: Operator commutativity In-Reply-To: References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110920025339.GA22418@Smoke> On Mon, Sep 19, 2011 at 10:26:30PM -0400, Roy Smith wrote: > In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > > > Westley Mart??nez wrote: > > > > > def __radd__(self, other): > > > return self.__add__(self, other) > > > > Which, inside a class, can be simplified to: > > > > __radd__ = __add__ > > Ooh, I could see that leading to some weird diagnostics. For example: > > class Foo: > def __add__(self, other): > raise Exception > > __radd__ = __add__ > > f1 = Foo() > print 1 + f1 > > produces: > > ./add.py > Traceback (most recent call last): > File "./add.py", line 11, in > print 1 + f1 > File "./add.py", line 5, in __add__ > raise Exception > Exception > > which leaves the user wondering why __add__() was called when clearly > __radd__() should have been. The way Westley wrote it (modulo fixing > the __add__() call signature) produces: > > ./add.py > Traceback (most recent call last): > File "./add.py", line 11, in > print 1 + f1 > File "./add.py", line 8, in __radd__ > return self.__add__(other) > File "./add.py", line 5, in __add__ > raise Exception > Exception > > which at least is a stack trace that shows that __radd__() was called. Calling __radd__ = __add__ simply creates a reference to __add__ named __radd__, it doesn't create a new method. From stars9820 at gmail.com Tue Sep 20 01:34:59 2011 From: stars9820 at gmail.com (star ship) Date: Mon, 19 Sep 2011 22:34:59 -0700 (PDT) Subject: DATA ENTRY JOB Message-ID: hi make money with online work at home so join it and earn more money at home. http://onlinejobforall100.blogspot.com/ thanks From zzzzysilence at gmail.com Tue Sep 20 03:55:20 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Tue, 20 Sep 2011 00:55:20 -0700 (PDT) Subject: red bull hats of http:www.discounthats.net Message-ID: <1dcd1d21-b168-4f73-8411-50903d6fd665@19g2000vbx.googlegroups.com> Welcome to the http:www.discounthats.net.The http:www.discounthats.net is a promotional shop from the red bull hats, monster energy hats, snapback hats.red bull hats: http:www.discounthats.net red bull hats: http://www.discounthats.net/category-2-b0-Red-Bull-Hats.html monster energy hats: http://www.discounthats.net/category-3-b0-Monster-Energy-Hats.html snapback hats: http://www.discounthats.net/category-79-b0-Snapback-Hats.html our site: www.discounthats.net From zzzzysilence at gmail.com Tue Sep 20 04:07:44 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Tue, 20 Sep 2011 01:07:44 -0700 (PDT) Subject: red bull hats of http:www.discounthats.net Message-ID: Welcome to the http:www.discounthats.net.The http:www.discounthats.net is a promotional shop from the red bull hats, monster energy hats, snapback hats.red bull hats: http:www.discounthats.net red bull hats: http://www.discounthats.net/category-2-b0-Red-Bull-Hats.html monster energy hats: http://www.discounthats.net/category-3-b0-Monster-Energy-Hats.html snapback hats: http://www.discounthats.net/category-79-b0-Snapback-Hats.html our site: www.discounthats.net From mateusz at loskot.net Tue Sep 20 06:34:42 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Tue, 20 Sep 2011 11:34:42 +0100 Subject: PyEval_EvalCodeEx return value Message-ID: <4E786C42.3050309@loskot.net> Hi, I'm trying to dig out details about what exactly is the return value the of PyEval_EvalCodeEx function in Python 3.x The documentation is sparse, unfortunately. Perhaps I'm looking at wrong function. My aim is simple, I need to execute Python code using Python interpreter embedded in my C++ application. The Python code is a simple script that always returns single value. For example: #! /usr/bin/env python def foo(a, b): return a + b f = foo(2, 3) But, f can be of different type for different script: one returns numeric value, another returns a sequence, so the type is not possible to be determined in advance. I know how to capture Python stdout/stderr. I also know how to access the "f" attribute using PyObject_GetAttrString and then I can convert "f" value to C++ type depending on PyObject type. However, I guess there shall be a way to access "f" value directly from PyEval_EvalCode return object: PyObject* evalRet = ::PyEval_EvalCode(...); But, I can't find any details what the "evalRet" actually is. Any pointers would be helpful. Best regards, -- Mateusz Loskot, http://mateusz.loskot.net Charter Member of OSGeo, http://osgeo.org Member of ACCU, http://accu.org From alec.taylor6 at gmail.com Tue Sep 20 08:32:53 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 20 Sep 2011 22:32:53 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: <4E77A8A0.3030104@gmail.com> References: <4E77A8A0.3030104@gmail.com> Message-ID: I can confirm that os.mkdir('C:\\h') and os.path.exists('C:\\h') work on Windows 8 Dev x64. On Tue, Sep 20, 2011 at 6:40 AM, Andrew Berg wrote: > On 2011.09.19 09:00 AM, Brian Curtin wrote: >> You said "the application does not create an app folder in the user's >> 'application data' directory" -- what does this mean, or rather, what >> is the specific folder you're expecting to have? If Python can't >> create the directory but you can do it manually, there may be some >> permission or access differences new to Windows 8. What does "echo >> %APPDATA%" give you? > I booted up the Win8 dev preview in a VM and os.environ['appdata'] gives > me the same result it would for Windows 7. Perhaps the problem lies in > the os.path.exists() call (that is, Win8 and Win7 react differently to > this call). I personally would try to create the directory and then > catch either a WindowsError (error 183) or an OSError (error 17) if the > directory already exists. I might play around with this later and post > some results. > > -- > CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 > PGP/GPG Public Key ID: 0xF88E034060A78FCB > -- > http://mail.python.org/mailman/listinfo/python-list > From kw at codebykevin.com Tue Sep 20 08:40:30 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 20 Sep 2011 08:40:30 -0400 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: <4E77A8A0.3030104@gmail.com> Message-ID: On 9/20/11 8:32 AM, Alec Taylor wrote: > I can confirm that os.mkdir('C:\\h') and os.path.exists('C:\\h') work > on Windows 8 Dev x64. OK--looks like I will need to do a bit more digging into my own code. Thanks for clarifying. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mohammedimran115 at gmail.com Tue Sep 20 09:57:08 2011 From: mohammedimran115 at gmail.com (mohammed imran) Date: Tue, 20 Sep 2011 06:57:08 -0700 (PDT) Subject: mohammedimran Message-ID: <6cedda83-32da-4d4d-befa-1b6f89768111@f41g2000yqh.googlegroups.com> http://123maza.com/65/fun564/ From funthyme at gmail.com Tue Sep 20 10:40:06 2011 From: funthyme at gmail.com (John Pinner) Date: Tue, 20 Sep 2011 07:40:06 -0700 (PDT) Subject: PyEval_EvalCodeEx return value References: Message-ID: <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> On Sep 20, 11:34?am, Mateusz Loskot wrote: > Hi, > > I'm trying to dig out details about what exactly is the return > value the of PyEval_EvalCodeEx function in Python 3.x > The documentation is sparse, unfortunately. > > Perhaps I'm looking at wrong function. > My aim is simple, I need to execute Python code using Python interpreter > embedded in my C++ application. > The Python code is a simple script that always returns single value. > For example: > > #! /usr/bin/env python > def foo(a, b): > ? ? return a + b > f = foo(2, 3) > > But, f can be of different type for different script: one returns > numeric value, another returns a sequence, so the type is not > possible to be determined in advance. > > I know how to capture Python stdout/stderr. > > I also know how to access the "f" attribute using > PyObject_GetAttrString and then I can convert "f" value to C++ type > depending on PyObject type. > > However, I guess there shall be a way to access "f" value > directly from PyEval_EvalCode return object: > > PyObject* evalRet = ::PyEval_EvalCode(...); > > But, I can't find any details what the "evalRet" actually is. I assume that you have read the documentation at http://docs.python.org/c-api/veryhigh.html, and I agree that it's sparse, but the entry for the next entry, PyEval_EvalCodeEx, tells you a little more, as does that for PyEval_EvalFrameEx. Obviously, it's returning a pointer to a PyObject, and Looking at the source code, that may be NULL, to throw an exception, or an execution frame, or a generator,etc, etc, depending on the code it's been given. I guess that you should be able to inspect the PyObject to see what it is. What I'm wondering is, why are you eval-ing code ? A favourite device of C programmers coming to Python (and mea culpa in the past), it's fraught with potential problems and even security risks, and is difficult to debug, and maybe you should be using introspection instead. And maybe you should be working in Python, and not C++ at this point, do the dynamic stuff in the language best suited, and then return to C+ + when needed. Best wishes, John -- > Any pointers would be helpful. > > Best regards, > -- > Mateusz Loskot,http://mateusz.loskot.net > Charter Member of OSGeo,http://osgeo.org > Member of ACCU,http://accu.org From jasfreedom at gmail.com Tue Sep 20 11:09:21 2011 From: jasfreedom at gmail.com (jasmine jasmine) Date: Tue, 20 Sep 2011 08:09:21 -0700 (PDT) Subject: techology Message-ID: http://123maza.com/48/doll789/ From yasar11732 at gmail.com Tue Sep 20 12:44:46 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 20 Sep 2011 19:44:46 +0300 Subject: HTMLParser and non-ascii html pages Message-ID: Hi, I am using a simple sublclass of HTMLParser like this: class LinkCollector(HTMLParser): def reset(self): self.links = [] HTMLParser.reset(self) def handle_starttag(self,tag,attr): if tag in ("a","link"): key = "href" elif tag in ("img","script"): key = "src" else: return self.links.extend([v for k,v in attr if k == key]) This gives following error: Traceback (most recent call last): File "downloader.py", line 209, in if __name__ == "__main__": main() File "downloader.py", line 201, in main link_collect.feed(response) File "C:\Python27\lib\HTMLParser.py", line 108, in feed self.goahead(0) File "C:\Python27\lib\HTMLParser.py", line 148, in goahead k = self.parse_starttag(i) File "C:\Python27\lib\HTMLParser.py", line 252, in parse_starttag attrvalue = self.unescape(attrvalue) File "C:\Python27\lib\HTMLParser.py", line 393, in unescape return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s) File "C:\Python27\lib\re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128) Rest of the code available as attachment. Does anyone know how to solve this? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: downloader.py Type: application/octet-stream Size: 6210 bytes Desc: not available URL: From ppearson at nowhere.invalid Tue Sep 20 13:07:35 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 20 Sep 2011 17:07:35 GMT Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <9drvinFngaU1@mid.individual.net> On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman wrote: [snip] > Also, if the right-hand operand is a subclass of the left-hand operand > then Python will try right-hand_operand.__radd__ first. I don't think it works that way for me: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>> class C1(): ... def __add__(self, other): ... print "C1.__add__()" ... >>> class C2(C1): ... def __radd__(self, other): ... print "C2.__radd__()" ... >>> C1() + C2() C1.__add__() >>> -- To email me, substitute nowhere->spamcop, invalid->net. From dreyemi at gmail.com Tue Sep 20 14:13:32 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:13:32 +0100 Subject: Why are my queues empty even though there are items in it? Message-ID: Hello friends, I'm writing some Python app that makes use of the multiprocessing and Queue api to perform transaction jobs. My problem is that, the queue always report empty even though I can confirm that there are items in it. Below is the code I'm working with: import multiprocessing from multiprocessing import Process, Queue from Queue import Empty def process(**kwargs): q = kwargs['q'] # Don't start the process if there's no item in queue if q.empty(): print 'empty queue' multiprocessing.Process() # Process defaults to None else: p = multiprocessing.Process(target=transaction_queue, args=(kwargs)) p.start() def put_in_queue(items={}): print items q = multiprocessing.Queue() try: for k,v in items.iteritems(): data = v #data is a dict timeout = data.get(u'timeout') # Put the transaction item in the queue at a specific timeout # period q.put(data, False, timeout) print "{0} put to queue".format(data) transaction_queue(q, data, timeout, False) except (KeyError, AttributeError, ValueError): print 'Incorrect data format' def transaction_queue(queue, item, timeout, block=False): queue = multiprocessing.Queue() if item is not {} and timeout is not 0: print "Items are {0}".format(item) for i in range(len(item)): try: d = queue.get(block) print d except Empty: print 'Fees queue empty at %s' % (i) else: return process(q=queue, i=d, t=timeout) else: print 'No item in the queue to get' A JSON POST from CURL calls put_in_queue callback: curl -v -H "Content-Type: application/json" -X POST --data 'fees={"fees":{"status":"pending","timeout":5}, "hostel":{"status":"pending","timeout": 3}}' http://127.0.0.1:8000/transaction/add/ > post_data.txt At code run, the output is: {u'status': u'pending', u'timeout': 3} put to queue Items are {u'status': u'pending', u'timeout': 3} Fees queue empty at 0 Fees queue empty at 1 {u'status': u'pending', u'timeout': 5} put to queue Items are {u'status': u'pending', u'timeout': 5} Fees queue empty at 0 Fees queue empty at 1 Q: Why are my queues empty even though there are items in it? Thanks you for the suggestions and answers. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Tue Sep 20 14:29:06 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:29:06 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 12:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user > input or achieve the same through some other means. If some other means, > the user must be able initiate this at runtime during a raw_input(). This > is what I have so far, this would be an awesome command line debugging tool > if I can get it to work. > > def b(label="", *args): > """Used to create breaks for debugging. Will break the function or > continue the function it is place within based on user input. Has as a > input loop for querying variables and executing code before a break or a > continue.""" > print label+":", > for arg in args: > print str(arg), > if len(args): > print > x = "" > while x != ".": > command = raw_input() > try: > exec command > except: > pass > Isn't this "call by reference" ? see http://docs.python.org/faq/programming.html?highlight=kwargs#how-do-i-write-a-function-with-output-parameters-call-by-reference -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Sep 20 14:35:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 21 Sep 2011 04:35:24 +1000 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 9:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user input > or achieve the same through some other means.? If some other means, the user > must be able initiate this at runtime during a raw_input().? This is what I > have so far, this would be an awesome command line debugging tool if I can > get it to work. Not entirely sure what you're trying to accomplish here. You want to pepper your code with calls to b() and then have the user be able to abort the function from there? If so, I can think of two ways: 1) Have b() raise an exception, which you catch at a high level. That'd unwind the stack all the way to the top, which may or may not be what you want. Pretty easy to do though. 2) Pepper your code with: if b(): return and then have b return 0 normally and 1 when the user asks to abort. This isn't truly an interactive debugger, though it does potentially have much value. ChrisA From dreyemi at gmail.com Tue Sep 20 14:35:47 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:35:47 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 12:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user > input or achieve the same through some other means. If some other means, > the user must be able initiate this at runtime during a raw_input(). This > is what I have so far, this would be an awesome command line debugging tool > if I can get it to work. > > def b(label="", *args): > """Used to create breaks for debugging. Will break the function or > continue the function it is place within based on user input. Has as a > input loop for querying variables and executing code before a break or a > continue.""" > print label+":", > for arg in args: > print str(arg), > if len(args): > print > x = "" > while x != ".": > command = raw_input() > try: > exec command > except: > pass > It is also possible to create the function in your loop. for arg in args: def f(args): return args # You can make this a callback function if you want -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Sep 20 14:42:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 20 Sep 2011 19:42:38 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: References: Message-ID: <4E78DE9E.3050100@mrabarnett.plus.com> On 20/09/2011 19:13, Kayode Odeyemi wrote: > Hello friends, > > I'm writing some Python app that makes use of the multiprocessing and > Queue api to perform > transaction jobs. > > My problem is that, the queue always report empty even though I can > confirm that there are items in it. > > Below is the code I'm working with: > [snip] > > def transaction_queue(queue, item, timeout, block=False): > queue = multiprocessing.Queue() This line creates a new empty queue, hiding the one which was passed in. > if item is not {} and timeout is not 0: `not {}` has the value True, so `item is not {}` means `item is True`. The `is` checks for identity, not equality, so this is true only if `item` actually has the value True or 1 (and this is an implementation-dependent behaviour). > print "Items are {0}".format(item) > for i in range(len(item)): You're trying to get as many items from the queue as there are items in the dict `item`, which looks wrong to me. > try: > d = queue.get(block) > print d > except Empty: > print 'Fees queue empty at %s' % (i) > else: > return process(q=queue, i=d, t=timeout) > else: > print 'No item in the queue to get' > > A JSON POST from CURL calls put_in_queue callback: > > curl -v -H "Content-Type: application/json" -X POST --data > 'fees={"fees":{"status":"pending","timeout":5}, > "hostel":{"status":"pending","timeout": 3}}' > http://127.0.0.1:8000/transaction/add/ > post_data.txt > > At code run, the output is: > > {u'status': u'pending', u'timeout': 3} put to queue > Items are {u'status': u'pending', u'timeout': 3} > Fees queue empty at 0 > Fees queue empty at 1 > {u'status': u'pending', u'timeout': 5} put to queue > Items are {u'status': u'pending', u'timeout': 5} > Fees queue empty at 0 > Fees queue empty at 1 > > Q: Why are my queues empty even though there are items in it? > What makes you think there are items in it? You print out `item`, which is not the queue. > Thanks you for the suggestions and answers. > From arnodel at gmail.com Tue Sep 20 15:04:29 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 20 Sep 2011 20:04:29 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On 20 September 2011 00:13, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user input > or achieve the same through some other means.? If some other means, the user > must be able initiate this at runtime during a raw_input().? This is what I > have so far, this would be an awesome command line debugging tool if I can > get it to work. > > def b(label="", *args): > ??? """Used to create breaks for debugging.? Will break the function or > continue the function it is place within based on user input.? Has as a > input loop for querying variables and executing code before a break or a > continue.""" > ??? print label+":", > ??? for arg in args: > ??? ??? print str(arg), > ??? if len(args): > ??? ??? print > ??? x = "" > ??? while x != ".": > ??? ??? command = raw_input() > ??? ??? try: > ??? ??? ??? exec command > ??? ??? except: > ??? ??? ??? pass > I don't really understand your dynamic return idea, but this reminds me of some debugging function I wrote some time ago. It pauses execution and you can evaluate expression in the current stack frame and any of its parents using the following syntax: executes in the stack frame where pause() was inserted . executes it in the parent of this stack frame .. in the grandparent (etc...) ? shows all accessible stack frames def pause(): import sys, inspect, re f = None print "\n*** Entering pause mode (EOF to resume)" try: while True: try: c = raw_input('pause> ') if c == '?': for i, fi in enumerate(inspect.stack()[1:]): print ('%s File "%s", line %s, in %s' % ('.'*i, fi[1], fi[2], fi[3])) continue dots = re.match(r'\.*', c) back = 0 if dots: back = len(dots.group()) f = sys._getframe(back+1) code_name = f.f_code.co_name cmd = c[back:] val = cmd and eval(cmd, f.f_globals, f.f_locals) print "(%s) %r" % (code_name, val) except Exception, e: if isinstance(e, EOFError): del f raise print "%s: %s" % (type(e).__name__, e) except EOFError: pass finally: print "\n*** Leaving pause mode" # Simple example of 'pause' in action: >>> def g(x): ... b = 5 ... pause() ... >>> def f(x, y): ... z = 2 ... g(x) ... print "And we carry on..." ... >>> f('spam', [4, 2]) *** Entering pause mode (EOF to resume) pause> ? File "", line 3, in g . File "", line 3, in f .. File "", line 1, in pause> b (g) 5 pause> b+1 (g) 6 pause> .z (f) 2 pause> .y (f) [4, 2] pause> .x (f) 'spam' pause> ..len () pause> ^D *** Leaving pause mode And we carry on... >>> -- Arnaud From schesis at gmail.com Tue Sep 20 15:09:12 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 20 Sep 2011 15:09:12 -0400 Subject: Why are my queues empty even though there are items in it? In-Reply-To: <4E78DE9E.3050100@mrabarnett.plus.com> References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: : On 20 September 2011 14:42, MRAB wrote: > On 20/09/2011 19:13, Kayode Odeyemi wrote: >> >> ? ? if item is not {} and timeout is not 0: > > `not {}` has the value True, so `item is not {}` means `item is True`. > The `is` checks for identity, not equality, so this is true only if `item` > actually has the value True or 1 (and this is an implementation-dependent > behaviour). Nitpick: "is not" is an operator: >>> "foo" is not {} True >>> "foo" is (not {}) False -[]z. From ethan at stoneleaf.us Tue Sep 20 15:09:15 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 20 Sep 2011 12:09:15 -0700 Subject: Operator commutativity In-Reply-To: <9drvinFngaU1@mid.individual.net> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> Message-ID: <4E78E4DB.4040606@stoneleaf.us> Peter Pearson wrote: > On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman wrote: > [snip] >> Also, if the right-hand operand is a subclass of the left-hand operand >> then Python will try right-hand_operand.__radd__ first. > > I don't think it works that way for me: > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>>> class C1(): > ... def __add__(self, other): > ... print "C1.__add__()" > ... >>>> class C2(C1): > ... def __radd__(self, other): > ... print "C2.__radd__()" > ... >>>> C1() + C2() > C1.__add__() Oh, it has to be a new-style class. Sorry. ~Ethan~ From python at mrabarnett.plus.com Tue Sep 20 15:43:18 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 20 Sep 2011 20:43:18 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: <4E78ECD6.3010705@mrabarnett.plus.com> On 20/09/2011 20:09, Zero Piraeus wrote: > : > > On 20 September 2011 14:42, MRAB wrote: >> On 20/09/2011 19:13, Kayode Odeyemi wrote: >>> >>> if item is not {} and timeout is not 0: >> >> `not {}` has the value True, so `item is not {}` means `item is True`. >> The `is` checks for identity, not equality, so this is true only if `item` >> actually has the value True or 1 (and this is an implementation-dependent >> behaviour). > > Nitpick: "is not" is an operator: > >>>> "foo" is not {} > True >>>> "foo" is (not {}) > False > Oops! True. However, it still doesn't do what the OP intended: >>> {} is {} False >>> {} is not {} True From dreyemi at gmail.com Tue Sep 20 15:51:23 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 20:51:23 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: <4E78DE9E.3050100@mrabarnett.plus.com> References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: On Tue, Sep 20, 2011 at 7:42 PM, MRAB wrote: > On 20/09/2011 19:13, Kayode Odeyemi wrote: > > def transaction_queue(queue, item, timeout, block=False): >> queue = multiprocessing.Queue() >> > > This line creates a new empty queue, hiding the one which was passed in. Removed. > > > if item is not {} and timeout is not 0: >> > > `not {}` has the value True, so `item is not {}` means `item is True`. > The `is` checks for identity, not equality, so this is true only if `item` > actually has the value True or 1 (and this is an implementation-dependent > behaviour). changed to: if item != {} and timeout != None > > > print "Items are {0}".format(item) >> for i in range(len(item)): >> > > You're trying to get as many items from the queue as there are items in > the dict `item`, which looks wrong to me. > > > try: >> d = queue.get(block) >> print d >> except Empty: >> print 'Fees queue empty at %s' % (i) >> else: >> return process(q=queue, i=d, t=timeout) >> else: >> print 'No item in the queue to get' >> >> Effected this. d has a result in the output (output below). So obviously, it is not empty. What I'm trying to do in the initial code is to have all items in the queue evaluated at the same time such that each leaves the queue for processing when its timeout period has elapse. > >> Q: Why are my queues empty even though there are items in it? >> >> What makes you think there are items in it? You print out `item`, which > is not the queue. > I've made these changes but the queue still appears empty None put to queue {u'status': u'pending', u'timeout': 3} empty queue None put to queue {u'status': u'pending', u'timeout': 5} empty queue Why 'empty queue' in process()? Also, why "None put to queue" since d confirms the items in the queue? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Sep 20 15:59:14 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 20 Sep 2011 20:59:14 +0100 Subject: About MAKE_FUNCTION opcode in Python 3 Message-ID: Since Python 3.0 we have keyword only arguments in functions (see PEP 3102). Looking at the documentation for the dis module (where opcodes are documented), I see the following for MAKE_FUNCTION [1] """ MAKE_FUNCTION(argc) Pushes a new function object on the stack. TOS is the code associated with the function. The function object is defined to have argc default parameters, which are found below TOS. """ No mention of default values for keyword only arguments. Now let's try (Python 3.2): >>> def foo(): ... def bar(x, y, *args, z=1, t=2, **kwargs): pass ... >>> dis.dis(foo) 2 0 LOAD_CONST 1 ('z') 3 LOAD_CONST 2 (1) 6 LOAD_CONST 3 ('t') 9 LOAD_CONST 4 (2) 12 LOAD_CONST 5 (", line 2>) 15 MAKE_FUNCTION 512 18 STORE_FAST 0 (bar) 21 LOAD_CONST 0 (None) 24 RETURN_VALUE MAKE_FUNCTION has an argc of 512. So it seems that since Python 3.0: * the number of default values for normal arguments is argc & 0xFF * the number of default values for keyword only arguments is argc >> 8 Can anyone confirm this? I can then open a ticket on bugs.python.org [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION -- Arnaud From __peter__ at web.de Tue Sep 20 16:11:58 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Sep 2011 22:11:58 +0200 Subject: HTMLParser and non-ascii html pages References: Message-ID: Ya?ar Arabac? wrote: > I am using a simple sublclass of HTMLParser like this: > > class LinkCollector(HTMLParser): > > def reset(self): > self.links = [] > HTMLParser.reset(self) > > def handle_starttag(self,tag,attr): > if tag in ("a","link"): > key = "href" > elif tag in ("img","script"): > key = "src" > else: > return > self.links.extend([v for k,v in attr if k == key]) > > This gives following error: > > Traceback (most recent call last): > File "downloader.py", line 209, in > if __name__ == "__main__": main() > File "downloader.py", line 201, in main > link_collect.feed(response) > File "C:\Python27\lib\HTMLParser.py", line 108, in feed > self.goahead(0) > File "C:\Python27\lib\HTMLParser.py", line 148, in goahead > k = self.parse_starttag(i) > File "C:\Python27\lib\HTMLParser.py", line 252, in parse_starttag > attrvalue = self.unescape(attrvalue) > File "C:\Python27\lib\HTMLParser.py", line 393, in unescape > return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, > s) > File "C:\Python27\lib\re.py", line 151, in sub > return _compile(pattern, flags).sub(repl, string, count) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: > ordinal not in range(128) Trying to reproduce the error: >>> from HTMLParser import HTMLParser >>> class P(HTMLParser): ... def handle_starttag(self, tag, attrs): ... key, value = attrs[0] ... print tag, key, "=", value ... >>> def feed(s): ... P().feed(s) ... >>> feed("") a href = yadda >>> feed("") a href = ? yadda >>> feed("") Traceback (most recent call last): File "", line 1, in File "", line 2, in feed File "/usr/local/lib/python2.7/HTMLParser.py", line 108, in feed self.goahead(0) File "/usr/local/lib/python2.7/HTMLParser.py", line 148, in goahead k = self.parse_starttag(i) File "/usr/local/lib/python2.7/HTMLParser.py", line 252, in parse_starttag attrvalue = self.unescape(attrvalue) File "/usr/local/lib/python2.7/HTMLParser.py", line 390, in unescape return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s) File "/usr/local/lib/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) It seems that the exception is triggered by an attribute value that contains both entities and non-ascii bytes. >>> feed(u"") a href = ? ? > Rest of the code available as attachment. Does anyone know how to solve > this? The documentation doesn't mention unicode, but it seems to work anyway: >>> feed(u"") a href = ? ? So one fix might be to convert the data to unicode before passing it to the HTMLParser. From ericsnowcurrently at gmail.com Tue Sep 20 17:56:41 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Tue, 20 Sep 2011 15:56:41 -0600 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 1:59 PM, Arnaud Delobelle wrote: > Since Python 3.0 we have keyword only arguments in functions (see PEP > 3102). ?Looking at the documentation for the dis module (where opcodes > are documented), I see the following for MAKE_FUNCTION [1] > > """ > MAKE_FUNCTION(argc) > Pushes a new function object on the stack. TOS is the code associated > with the function. The function object is defined to have argc default > parameters, which are found below TOS. > """ > > No mention of default values for keyword only arguments. ?Now let's > try (Python 3.2): > >>>> def foo(): > ... ? def bar(x, y, *args, z=1, t=2, **kwargs): pass > ... >>>> dis.dis(foo) > ?2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 1 ('z') > ? ? ? ? ? ? ?3 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > ? ? ? ? ? ? ?6 LOAD_CONST ? ? ? ? ? ? ? 3 ('t') > ? ? ? ? ? ? ?9 LOAD_CONST ? ? ? ? ? ? ? 4 (2) > ? ? ? ? ? ? 12 LOAD_CONST ? ? ? ? ? ? ? 5 ( 0x1005ec8b0, file "", line 2>) > ? ? ? ? ? ? 15 MAKE_FUNCTION ? ? ? ? ?512 > ? ? ? ? ? ? 18 STORE_FAST ? ? ? ? ? ? ? 0 (bar) > ? ? ? ? ? ? 21 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > ? ? ? ? ? ? 24 RETURN_VALUE > > MAKE_FUNCTION has an argc of 512. ?So it seems that since Python 3.0: > > * the number of default values for normal arguments is argc & 0xFF > * the number of default values for keyword only arguments is argc >> 8 > > Can anyone confirm this? ?I can then open a ticket on bugs.python.org You're mostly right. http://hg.python.org/cpython/file/default/Python/ceval.c#l2684 2684 int posdefaults = oparg & 0xff; 2685 int kwdefaults = (oparg>>8) & 0xff; 2686 int num_annotations = (oparg >> 16) & 0x7fff; -eric > > [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Tue Sep 20 21:07:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 21 Sep 2011 11:07:15 +1000 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> Message-ID: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Ethan Furman wrote: > Peter Pearson wrote: >> On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman >> wrote: >> [snip] >>> Also, if the right-hand operand is a subclass of the left-hand operand >>> then Python will try right-hand_operand.__radd__ first. >> >> I don't think it works that way for me: >> >> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>>>> class C1(): >> ... def __add__(self, other): >> ... print "C1.__add__()" >> ... >>>>> class C2(C1): >> ... def __radd__(self, other): >> ... print "C2.__radd__()" >> ... >>>>> C1() + C2() >> C1.__add__() > > Oh, it has to be a new-style class. Sorry. Even so, I still don't think it quite works the way you have suggested. class C1(object): def __add__(self, other): return "__add__(%s, %s)" % (self, other) def __radd__(self, other): return "__radd__(%s, %s)" % (self, other) class C2(C1): pass >>> C1() + C2() '__add__(<__main__.C1 object at 0xb7f79b0c>, <__main__.C2 object at 0xb7f79b6c>)' I've tried that in both Python 2.6 and 3.2 and get the same result. However, consider this slight variation: class D1(object): def __add__(self, other): return "__add__(%s, %s)" % (self, other) class D2(D1): def __radd__(self, other): return "__radd__(%s, %s)" % (self, other) >>> D1() + D2() '__radd__(<__main__.D2 object at 0xb7c2c36c>, <__main__.D1 object at 0xb7c2cb0c>)' After playing around with various combinations of C1, C2, D1 and D2, it seems to me that the rule is: If the right-hand argument is a subclass of the left-hand argument, AND also defines __radd__ directly rather than inheriting it, then its __radd__ method is called before the left-hand argument's __add__ method. which strikes me as a strangely specific and not very useful rule. I suspect it might be an accident of implementation rather than a deliberate feature. -- Steven From rosuav at gmail.com Tue Sep 20 21:31:57 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 21 Sep 2011 11:31:57 +1000 Subject: Operator commutativity In-Reply-To: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 21, 2011 at 11:07 AM, Steven D'Aprano wrote: > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. It makes sense, but in a weird way. (Maybe I understand it because I'm half Dutch? heh) It means that a subclass can override addition for itself - presumably, it'll define __add__ and __radd__ both - and that the only time you'd get a false positive (where a function thinks it can handle the addition but actually there's a better one) is when it's a subclass. So this is probably correct behaviour, but it's a fairly weird and esoteric rule. ChrisA From tjreedy at udel.edu Tue Sep 20 23:09:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 Sep 2011 23:09:30 -0400 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On 9/20/2011 5:56 PM, Eric Snow wrote: > On Tue, Sep 20, 2011 at 1:59 PM, Arnaud Delobelle wrote: >> Since Python 3.0 we have keyword only arguments in functions (see PEP >> 3102). Looking at the documentation for the dis module (where opcodes >> are documented), I see the following for MAKE_FUNCTION [1] >> >> """ >> MAKE_FUNCTION(argc) >> Pushes a new function object on the stack. TOS is the code associated >> with the function. The function object is defined to have argc default >> parameters, which are found below TOS. >> """ >> >> No mention of default values for keyword only arguments. Now let's >> try (Python 3.2): >> >>>>> def foo(): >> ... def bar(x, y, *args, z=1, t=2, **kwargs): pass >> ... >>>>> dis.dis(foo) >> 2 0 LOAD_CONST 1 ('z') >> 3 LOAD_CONST 2 (1) >> 6 LOAD_CONST 3 ('t') >> 9 LOAD_CONST 4 (2) >> 12 LOAD_CONST 5 (> 0x1005ec8b0, file "", line 2>) >> 15 MAKE_FUNCTION 512 >> 18 STORE_FAST 0 (bar) >> 21 LOAD_CONST 0 (None) >> 24 RETURN_VALUE >> >> MAKE_FUNCTION has an argc of 512. So it seems that since Python 3.0: >> >> * the number of default values for normal arguments is argc& 0xFF >> * the number of default values for keyword only arguments is argc>> 8 >> >> Can anyone confirm this? I can then open a ticket on bugs.python.org > > You're mostly right. > > http://hg.python.org/cpython/file/default/Python/ceval.c#l2684 > > 2684 int posdefaults = oparg& 0xff; > 2685 int kwdefaults = (oparg>>8)& 0xff; > 2686 int num_annotations = (oparg>> 16)& 0x7fff; >> [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION I agree that doc should be updated for 3.x. Please suggest a new working if you can, as well as copying the source snippet above. Add me terry.reedy as nosy. -- Terry Jan Reedy From martin at v.loewis.de Wed Sep 21 01:41:50 2011 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 21 Sep 2011 07:41:50 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <4E79791E.7000903@v.loewis.de> > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? I've been considering to implement killing threads several times for the last 15 years (I think about it once every year), and every time I give up because it's too complex and just not implementable. To start with, a simple flag in the thread won't do any good. It will not cancel blocking system calls, so people will complain that the threads they meant to cancel continue to run forever. Instead, you have to use some facility to interrupt blocking system calls. You then have to convince callers of those blocking system calls not to retry when they see that the first attempt to call it was interrupted. And so on. Regards, Martin From vraichur at cisco.com Wed Sep 21 02:42:21 2011 From: vraichur at cisco.com (Vinay) Date: Wed, 21 Sep 2011 12:12:21 +0530 Subject: Tunneling using paramiko to establish tunnel with lab-router Message-ID: <000001cc7829$9d79f6f0$d86de4d0$@com> Hello Friends, I am looking to implement tunneling in python and using "Paramiko" for this.. Sending theTunneling script using Paramiko -Python. It's facing some prob, hangs on running the script..output message it says ".. Missing Handlers". Plz let me know the corrections to be done in this script to making tunneling successful (I hv hard-coded the jump server IP address 10.64.116.34 and password - "Cisco123" in the script to test it once). It's urgent, plz giv me solution ASAP!! Thanks n regards, Vinay -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: create_tunnel.py URL: From k.sahithi2862 at gmail.com Wed Sep 21 05:00:38 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Wed, 21 Sep 2011 02:00:38 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: <41a22645-676f-4f95-852f-a6986d5efea1@h9g2000yqi.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From Antoon.Pardon at rece.vub.ac.be Wed Sep 21 05:25:02 2011 From: Antoon.Pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 21 Sep 2011 11:25:02 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: <4E79791E.7000903@v.loewis.de> References: <4E79791E.7000903@v.loewis.de> Message-ID: <20110921092502.GF3410@trout.vub.ac.be> On Wed, Sep 21, 2011 at 07:41:50AM +0200, Martin v. Loewis wrote: > > Is it just that nobody's implemented it, or is there a good reason for > > avoiding offering this sort of thing? > > I've been considering to implement killing threads several times for the > last 15 years (I think about it once every year), and every time > I give up because it's too complex and just not implementable. > > To start with, a simple flag in the thread won't do any good. I don't agree. Now if you had written that it wouldn't solve all problem, I could understand that. But I have been in circumstances where a simple flag in the thread implementation would have been helpfull. > It will > not cancel blocking system calls, so people will complain that the > threads they meant to cancel continue to run forever. Instead, you > have to use some facility to interrupt blocking system calls. You > then have to convince callers of those blocking system calls not to > retry when they see that the first attempt to call it was interrupted. > And so on. But this is no longer an implementation problem but a use problem. If someone gets an IOError for writing on a closed pipe and he cathes the exception and retries the write in a loop, then this a problem of the author of this loop, not of exceptions. So if one thread throws an exception to an other thread for instance to indicate a timeout for the latter and the latter catches that exception and tries again what it was doing in a loop, that is entirely the problem of the author of that loop and not of the abilty of one thread throwing an exception in an other. Unless of course there may be a lot of such problematic loops within the internal python code. -- Antoon Pardon From csf178 at 163.com Wed Sep 21 05:44:52 2011 From: csf178 at 163.com (=?GBK?B?s8zbv7fH?=) Date: Wed, 21 Sep 2011 17:44:52 +0800 (CST) Subject: Where can I find a lexical spec of python? Message-ID: Hi, everyone, I've found there was several tokens used in python's grammar(http://docs.python.org/reference/grammar.html) but I didn't see their definition anywhere. The tokens listed here: NEWLINE ENDMARKER NAME INDENT DEDENT NUMBER STRING I've got some infomations from the source code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but I'm not sure which feature is only for this specified implementaion. (I saw tabstop could be modified with comments using "tab-width:", ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Wed Sep 21 07:41:33 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 13:41:33 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: References: Message-ID: <4E79CD6D.2030206@jollybox.de> On 21/09/11 11:44, ??? wrote: > Hi, everyone, > I've found there was several tokens used in python's > grammar(http://docs.python.org/reference/grammar.html) but I didn't see > their definition anywhere. The tokens listed here: They should be documented in http://docs.python.org/py3k/reference/lexical_analysis.html - though apparently not using these exact terms. > NEWLINE Trivial: U+000A > ENDMARKER End of file. > NAME documented as "identifier" in 2.3 > INDENT > DEDENT Documented in 2.1.8. > NUMBER Documented in 2.4.3 - 2.4.6 > STRING Documented in 2.4.2 > I've got some infomations from the source > code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but > I'm not sure which feature is only for this specified implementaion. (I > saw tabstop could be modified with comments using "tab-width:", > ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) That sounds like a legacy feature that is no longer used. Somebody familiar with the early history of Python might be able to shed more light on the situation. It is inconsisten with the spec (section 2.1.8): """ Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case. """ - Thomas From info at wingware.com Wed Sep 21 10:15:14 2011 From: info at wingware.com (Wingware) Date: Wed, 21 Sep 2011 10:15:14 -0400 Subject: Wing IDE 4.0.4 released Message-ID: <4E79F172.3070106@wingware.com> Hi, Wingware has released version 4.0.4 of Wing IDE, an integrated development environment designed specifically for the Python programming language. Wing IDE is a cross-platform Python IDE that provides a professional code editor with vi, emacs, and other key bindings, auto-completion, call tips, refactoring, a powerful graphical debugger, version control, unit testing, search, and many other features. **Changes in Version 4.0.4** This is a maintenance release with the following changes: * Shell history operates on whole blocks and filters by entered prefix * Auto-editing (must be enabled with Editor > Auto-Editing preferences): * Auto-enter closing quotes, comments, and parentheses, braces, etc * Tab through auto-entered invocation arguments * Apply quote, comment character, or parenthesis to selection * Use dynamic analysis for goto-definition in the editor, when available * Support ## comments and new block syntax in Mako files * Allow scrolling editor one page below the last line * Refactoring can move symbols to a new file * PyLint panel improvements, including support for version 0.23+ * Commands to copy editor and project file names to clipboard * About 70 other minor features and bug fixes included vi mode improvements See the change log for details. **New Features in Version 4.0** Version 4.0 adds the following new major features: * Refactoring -- Rename/move symbols, extract to function/method, and introduce variable * Find Uses -- Find all points of use of a symbol * Diff/Merge -- Graphical file and repository comparison and merge * Django Support -- Debug Django templates, run Django unit tests, and more * matplotlib Support -- Maintains live-updating plots in shell and debugger * Simplified Licensing -- Includes all OSes and adds Support+Upgrades subscriptions Complete change log: http://wingware.com/pub/wingide/4.0.4/CHANGELOG.txt Details on licensing changes: http://wingware.com/news/2011-02-16 **About Wing IDE** Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful editing, testing, and debugging features that help reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE can be used to develop Python code for web, GUI, and embedded scripting applications. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching beginning programming courses with Python. Version 4.0 of Wing IDE Professional includes the following major features: * Professional quality code editor with vi, emacs, and other keyboard personalities * Code intelligence for Python: Auto-completion, call tips, find uses, goto-definition, error indicators, refactoring, smart indent and rewrapping, and source navigation * Advanced multi-threaded debugger with graphical UI, command line interaction, conditional breakpoints, data value tooltips over code, watch tool, and externally launched and remote debugging * Powerful search and replace options including keyboard driven and graphical UIs, multi-file, wild card, and regular expression search and replace * Version control integration for Subversion, CVS, Bazaar, git, Mercurial, and Perforce * Integrated unit testing with unittest, nose, and doctest frameworks * Django support: Debugs Django templates, provides project setup tools, and runs Django unit tests * Many other features including project manager, bookmarks, code snippets, diff/merge tool, OS command integration, indentation manager, PyLint integration, and perspectives * Extremely configurable and may be extended with Python scripts * Extensive product documentation and How-Tos for Django, matplotlib, Plone, wxPython, PyQt, mod_wsgi, Autodesk Maya, and many other frameworks Please refer to http://wingware.com/wingide/features for a detailed listing of features by product level. System requirements are Windows 2000 or later, OS X 10.3.9 or later (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE supports Python versions 2.0.x through 3.2.x and Stackless Python. For more information, see the http://wingware.com/ **Downloads** Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial can be obtained directly from the product when launched. Wing IDE Pro -- Full-featured product: http://wingware.com/downloads/wingide/4.0 Wing IDE Personal -- A simplified IDE: http://wingware.com/downloads/wingide-personal/4.0 Wing IDE 101 -- For teaching with Python: http://wingware.com/downloads/wingide-101/4.0 **Purchasing and Upgrading** Wing 4.0 requires an upgrade for Wing IDE 2.x and 3.x users at a cost of 1/2 the full product pricing. Upgrade a license: https://wingware.com/store/upgrade Purchase a new license: https://wingware.com/store/purchase Optional Support+Upgrades subscriptions are available for expanded support coverage and free upgrades to new major releases: http://wingware.com/support/agreement Thanks! -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From frank.ruiz at gmail.com Wed Sep 21 11:44:13 2011 From: frank.ruiz at gmail.com (Frank Ruiz) Date: Wed, 21 Sep 2011 08:44:13 -0700 Subject: Graphing Message-ID: I am looking to plot some data points related to system metrics. Benchmarking, etc. Can someone give some recommendations on a good way to graph these datapoints in python. I started looking into matplotlib, however was interested in others experiences. From invalid at invalid.invalid Wed Sep 21 12:27:32 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 21 Sep 2011 16:27:32 +0000 (UTC) Subject: Graphing References: Message-ID: On 2011-09-21, Frank Ruiz wrote: > I am looking to plot some data points related to system metrics. > Benchmarking, etc. Can someone give some recommendations on a good > way to graph these datapoints in python. I started looking into > matplotlib, however was interested in others experiences. I've always liked gnuplot-py, but I was a gnuplot user for 10+ years before I started using Python. If you don't already know how to use gnuplot, then perhaps gnuplot-py might not seem as intuitive. http://gnuplot-py.sourceforge.net/ -- Grant Edwards grant.b.edwards Yow! Hmmm ... an arrogant at bouquet with a subtle gmail.com suggestion of POLYVINYL CHLORIDE ... From ppearson at nowhere.invalid Wed Sep 21 12:28:34 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2011 16:28:34 GMT Subject: Graphing References: Message-ID: <9duhliFopmU1@mid.individual.net> On Wed, 21 Sep 2011 08:44:13 -0700, Frank Ruiz wrote: > I am looking to plot some data points related to system metrics. > Benchmarking, etc. Can someone give some recommendations on a good way > to graph these datapoints in python. I started looking into > matplotlib, however was interested in others experiences. I like biggles. Reasonably straightforward, well defaulted. Simple plots require only simple code. biggles.sourceforge.net -- To email me, substitute nowhere->spamcop, invalid->net. From csf178 at 163.com Wed Sep 21 12:33:03 2011 From: csf178 at 163.com (=?utf-8?B?56iL5Yqt6Z2e?=) Date: Thu, 22 Sep 2011 00:33:03 +0800 (CST) Subject: Where can I find a lexical spec of python? In-Reply-To: <4E79CD6D.2030206@jollybox.de> References: <4E79CD6D.2030206@jollybox.de> Message-ID: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Thanks Thomas. I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html but I worried it might leak some language features like "tab magic". For I'm working on a parser with JavaScript I need a more strictly defined spec. Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html (Also the lexer http://shaofei.name/python/PyLexer.html) As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? Please help me. Thanks a lot. ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >On 21/09/11 11:44, ??? wrote: >> Hi, everyone, >> I've found there was several tokens used in python's >> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >> their definition anywhere. The tokens listed here: > >They should be documented in >http://docs.python.org/py3k/reference/lexical_analysis.html - though >apparently not using these exact terms. > >> NEWLINE >Trivial: U+000A > >> ENDMARKER >End of file. > >> NAME >documented as "identifier" in 2.3 > >> INDENT >> DEDENT >Documented in 2.1.8. > >> NUMBER >Documented in 2.4.3 - 2.4.6 > >> STRING >Documented in 2.4.2 > >> I've got some infomations from the source >> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >> I'm not sure which feature is only for this specified implementaion. (I >> saw tabstop could be modified with comments using "tab-width:", >> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) > >That sounds like a legacy feature that is no longer used. Somebody >familiar with the early history of Python might be able to shed more >light on the situation. It is inconsisten with the spec (section 2.1.8): > >""" >Indentation is rejected as inconsistent if a source file mixes tabs and >spaces in a way that makes the meaning dependent on the worth of a tab >in spaces; a TabError is raised in that case. >""" > >- Thomas >-- >http://mail.python.org/mailman/listinfo/python-list From clp2 at rebertia.com Wed Sep 21 12:53:57 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 09:53:57 -0700 Subject: Where can I find a lexical spec of python? In-Reply-To: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> References: <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: On Wed, Sep 21, 2011 at 9:33 AM, ??? wrote: > Thanks Thomas. > I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html > > but I worried it might leak some language features like "tab magic". > > For I'm working on a parser with JavaScript I need a more strictly defined spec. > > Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html > (Also the lexer ?http://shaofei.name/python/PyLexer.html) > > As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. > > Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? Closest thing would be http://docs.python.org/py3k/reference/grammar.html Cheers, Chris From t at jollybox.de Wed Sep 21 12:55:45 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 18:55:45 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> References: <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: <4E7A1711.8000007@jollybox.de> On 21/09/11 18:33, ??? wrote: > Thanks Thomas. > I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html > > but I worried it might leak some language features like "tab magic". > > For I'm working on a parser with JavaScript I need a more strictly defined spec. > > Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html > (Also the lexer http://shaofei.name/python/PyLexer.html) > > As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. > > Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? I believe the language documentation on docs.python.org is all the documentation of the language there is. It may not be completely formal, and in parts it concentrates not on the actual rules but on the original implementation, but, as far as I can tell, it tells you everything you need to know to write a new parser for the Python language, without any ambiguity. You appear to be anxious about implementing the indentation mechanism correctly. The language documentation describes a behaviour precisely. What is the problem? Thomas > > Please help me. Thanks a lot. > ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >> On 21/09/11 11:44, ??? wrote: >>> Hi, everyone, >>> I've found there was several tokens used in python's >>> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >>> their definition anywhere. The tokens listed here: >> >> They should be documented in >> http://docs.python.org/py3k/reference/lexical_analysis.html - though >> apparently not using these exact terms. >> >>> NEWLINE >> Trivial: U+000A >> >>> ENDMARKER >> End of file. >> >>> NAME >> documented as "identifier" in 2.3 >> >>> INDENT >>> DEDENT >> Documented in 2.1.8. >> >>> NUMBER >> Documented in 2.4.3 - 2.4.6 >> >>> STRING >> Documented in 2.4.2 >> >>> I've got some infomations from the source >>> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >>> I'm not sure which feature is only for this specified implementaion. (I >>> saw tabstop could be modified with comments using "tab-width:", >>> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) >> >> That sounds like a legacy feature that is no longer used. Somebody >> familiar with the early history of Python might be able to shed more >> light on the situation. It is inconsisten with the spec (section 2.1.8): >> >> """ >> Indentation is rejected as inconsistent if a source file mixes tabs and >> spaces in a way that makes the meaning dependent on the worth of a tab >> in spaces; a TabError is raised in that case. >> """ >> >> - Thomas >> -- >> http://mail.python.org/mailman/listinfo/python-list > From dickinsm at gmail.com Wed Sep 21 13:03:15 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 21 Sep 2011 10:03:15 -0700 (PDT) Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> On Sep 21, 2:07?am, Steven D'Aprano wrote: > After playing around with various combinations of C1, C2, D1 and D2, it > seems to me that the rule is: > > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. I'm 99.9% sure it's deliberate rather than an accident of implementation. See the note in the docs at: http://docs.python.org/reference/datamodel.html#emulating-numeric-types Support that you're subclassing int, (class MyInt(int): ...) and you want to intercept additions of the form 3 + MyInt(4) (perhaps because you want MyInt to be 'contagious', so that an arithmetic operation that combines an int and a MyInt returns a MyInt). How would you achieve this without this rule? -- Mark From csf178 at 163.com Wed Sep 21 14:01:14 2011 From: csf178 at 163.com (Shaofei Cheng) Date: Thu, 22 Sep 2011 02:01:14 +0800 (CST) Subject: Where can I find a lexical spec of python? In-Reply-To: <4E7A1711.8000007@jollybox.de> References: <4E7A1711.8000007@jollybox.de> <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> Yes, I'm using this document now but I was wondering if there is a formal spec for lexical grammar? It looks like some part of the doc "http://docs.python.org/py3k/reference/grammar.html" is missing. We can find some replacement in lexical_analysis.html but it seems this document is write for a python user instead of a guy trying to implement python. ? 2011-09-22 00:55:45?"Thomas Jollans" ??? >On 21/09/11 18:33, ??? wrote: >> Thanks Thomas. >> I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html >> >> but I worried it might leak some language features like "tab magic". >> >> For I'm working on a parser with JavaScript I need a more strictly defined spec. >> >> Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html >> (Also the lexer http://shaofei.name/python/PyLexer.html) >> >> As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. >> >> Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? > >I believe the language documentation on docs.python.org is all the >documentation of the language there is. It may not be completely formal, >and in parts it concentrates not on the actual rules but on the original >implementation, but, as far as I can tell, it tells you everything you >need to know to write a new parser for the Python language, without any >ambiguity. > >You appear to be anxious about implementing the indentation mechanism >correctly. The language documentation describes a behaviour precisely. >What is the problem? > >Thomas > >> >> Please help me. Thanks a lot. >> ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >>> On 21/09/11 11:44, ??? wrote: >>>> Hi, everyone, >>>> I've found there was several tokens used in python's >>>> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >>>> their definition anywhere. The tokens listed here: >>> >>> They should be documented in >>> http://docs.python.org/py3k/reference/lexical_analysis.html - though >>> apparently not using these exact terms. >>> >>>> NEWLINE >>> Trivial: U+000A >>> >>>> ENDMARKER >>> End of file. >>> >>>> NAME >>> documented as "identifier" in 2.3 >>> >>>> INDENT >>>> DEDENT >>> Documented in 2.1.8. >>> >>>> NUMBER >>> Documented in 2.4.3 - 2.4.6 >>> >>>> STRING >>> Documented in 2.4.2 >>> >>>> I've got some infomations from the source >>>> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >>>> I'm not sure which feature is only for this specified implementaion. (I >>>> saw tabstop could be modified with comments using "tab-width:", >>>> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) >>> >>> That sounds like a legacy feature that is no longer used. Somebody >>> familiar with the early history of Python might be able to shed more >>> light on the situation. It is inconsisten with the spec (section 2.1.8): >>> >>> """ >>> Indentation is rejected as inconsistent if a source file mixes tabs and >>> spaces in a way that makes the meaning dependent on the worth of a tab >>> in spaces; a TabError is raised in that case. >>> """ >>> >>> - Thomas >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> > From ethan at stoneleaf.us Wed Sep 21 14:15:56 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 21 Sep 2011 11:15:56 -0700 Subject: Operator commutativity In-Reply-To: <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> Message-ID: <4E7A29DC.2060205@stoneleaf.us> Mark Dickinson wrote: > On Sep 21, 2:07 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> After playing around with various combinations of C1, C2, D1 and D2, it >> seems to me that the rule is: >> >> If the right-hand argument is a subclass of the left-hand argument, AND also >> defines __radd__ directly rather than inheriting it, then its __radd__ >> method is called before the left-hand argument's __add__ method. >> >> which strikes me as a strangely specific and not very useful rule. I suspect >> it might be an accident of implementation rather than a deliberate feature. > > I'm 99.9% sure it's deliberate rather than an accident of > implementation. See the note in the docs at: > > http://docs.python.org/reference/datamodel.html#emulating-numeric-types > > Support that you're subclassing int, (class MyInt(int): ...) and you > want to intercept additions of the form 3 + MyInt(4) (perhaps because > you want MyInt to be 'contagious', so that an arithmetic operation > that combines an int and a MyInt returns a MyInt). How would you > achieve this without this rule? I think Steven's objection was in not calling subclass.__radd__ when __radd__ is inherited rather than directly overridden. Interestingly enough, the following works as expected (at least, as I expected ;)... class C1(object): def __add__(self, other): print "C1.__add__(%r, %r)" % (self, other) class C2(C1): def __radd__(self, other): print "C2.__radd__(%r, %r)" % (self, other) class C3(C2): pass C1() + C2() # --> C2.__radd__(<...C2...>, <...C1...) C1() + C3() # --> C2.__radd__(<...C3...>, <...C1...>) C2() + C3() # --> C1.__add__(<...C2...>, <...C3...>) ~Ethan~ From t at jollybox.de Wed Sep 21 14:22:27 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 20:22:27 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> References: <4E7A1711.8000007@jollybox.de> <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> Message-ID: <4E7A2B63.4030505@jollybox.de> On 21/09/11 20:01, Shaofei Cheng wrote: > Yes, I'm using this document now but I was wondering if there is a formal spec for lexical grammar? It looks like some part of the doc "http://docs.python.org/py3k/reference/grammar.html" is missing. > We can find some replacement in lexical_analysis.html but it seems this document is write for a python user instead of a guy trying to implement python. Yes, I understood alright what you were asking. As I said, I don't believe there is any more formal documentation of the Python language than what you have already seen. However, I am of the opinion that it gives you all the information you need, and that a complete formal grammar, while perhaps, for you, easier to interpret, would not add any information. Thomas From ethan at stoneleaf.us Wed Sep 21 15:11:12 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 21 Sep 2011 12:11:12 -0700 Subject: Operator commutativity In-Reply-To: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7A36D0.6030603@stoneleaf.us> Steven D'Aprano wrote: > After playing around with various combinations of C1, C2, D1 and D2, it > seems to me that the rule is: > > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. Update to rule: If the right-hand argument is a subclass of the left-hand argument AND a __radd__ is defined anywhere between the left-hand argument's class up to and including the right-hand argument's class, then __radd__ is called, otherwise the left-hand arguments __add__ is called. And it makes perfect sense -- a + b is, after all, an __add__ function; the only reason to call __radd__ instead is if it has been defined for a subclass, and the only reason to define it is because it needs something different from a + b that a doesn't know about. Probably not a clear explanation -- maybe somebody else can dress it up a bit. ~Ethan~ From arnodel at gmail.com Wed Sep 21 18:04:18 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 21 Sep 2011 23:04:18 +0100 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On 21 September 2011 04:09, Terry Reedy wrote: > I agree that doc should be updated for 3.x. Please suggest a new working if > you can, as well as copying the source snippet above. Add me terry.reedy as > nosy. Done: http://bugs.python.org/issue13026 -- Arnaud From missive at hotmail.com Wed Sep 21 21:35:44 2011 From: missive at hotmail.com (Lee Harr) Date: Thu, 22 Sep 2011 06:05:44 +0430 Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) Message-ID: Pynguin is a python-based turtle graphics application. ??? It combines an editor, interactive interpreter, and ??? graphics display area. It is meant to be an easy environment for introducing ??? some programming concepts to beginning programmers. http://pynguin.googlecode.com/ This release fixes problems which prevented the program ??? from working properly on Windows systems. Pynguin is tested with Python 2.7.1 and PyQt 4.8.3 and ??? will use Pygments syntax highlighting if available. Pynguin is released under GPLv3. Changes in pynguin-0.12: ??? Important fixes ??????? - Fixed menu items and dialogs not working on Windows ??????? - Fixed error on Windows when trying to write backup files ??? Pynguin API ??????? - bgcolor() ??????? - raise exception if using color component outside of 0-255 ??????? - make util.nudge_color() API match util.choose_color() ??? Canvas ??????? - allow setting background color ??????? - fix custom svg avatars to allow any size avatar ??? Integrated Editor ??????? - comment / uncomment line / region ??? Integrated Console ??????? - added command to clear history ??????? - clears line before writing commands selected in menu ??? Examples ??????? - added fractals example file From bahamutzero8825 at gmail.com Wed Sep 21 21:53:04 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 20:53:04 -0500 Subject: Odd behavior with imp.reload and logging Message-ID: <4E7A9500.2070101@gmail.com> When using a logger in a module and then using imp.reload to reload the module, logger messages are repeated in direct proportion to the number of times the modules was loaded. That is, on the first import, the message is written once, but on the second run, each message is written twice, three times on the third run, and so on. With this code: > import logging > > test_logger = logging.getLogger(__name__) > console_handler = logging.StreamHandler() > console_formatter = logging.Formatter('{asctime} - {module} - {funcName} - line {lineno} - {levelname} - {message}', style='{') > console_handler.setFormatter(console_formatter) > test_logger.addHandler(console_handler) > test_logger.setLevel(logging.DEBUG) > > test_logger.info('Test info') I get this in the interpreter: > Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os, imp >>>> import test2 > 2011-09-21 20:51:02,421 - test2 - - line 11 - INFO - Test info >>>> imp.reload(test2) > 2011-09-21 20:51:10,665 - test2 - - line 11 - INFO - Test info > 2011-09-21 20:51:10,665 - test2 - - line 11 - INFO - Test info > What causes this, and how can I fix it (or at least work around it)? Due to the nature of the program, it's much more convenient to reload a module than to restart the entire program (especially when testing). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 PGP/GPG Public Key ID: 0xF88E034060A78FCB From rosuav at gmail.com Wed Sep 21 21:57:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 11:57:42 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7A9500.2070101@gmail.com> References: <4E7A9500.2070101@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 11:53 AM, Andrew Berg wrote: > What causes this, and how can I fix it (or at least work around it)? Due > to the nature of the program, it's much more convenient to reload a > module than to restart the entire program (especially when testing). > Unfortunately, Python doesn't really like modules to be reloaded. Are you able to explicitly close the logger before reloading? ChrisA From bahamutzero8825 at gmail.com Wed Sep 21 22:44:20 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 21:44:20 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4E7A9500.2070101@gmail.com> Message-ID: <4E7AA104.7050009@gmail.com> On 2011.09.21 08:57 PM, Chris Angelico wrote: > Unfortunately, Python doesn't really like modules to be reloaded. Are > you able to explicitly close the logger before reloading? The reload isn't controlled by the module, but I have no problem clearing out any loggers at the beginning. I'm looking through the logging docs, but I don't see what you mean by explicitly closing the logger. Handler.close() doesn't help. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From rosuav at gmail.com Wed Sep 21 22:48:04 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 12:48:04 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7AA104.7050009@gmail.com> References: <4E7A9500.2070101@gmail.com> <4E7AA104.7050009@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 12:44 PM, Andrew Berg wrote: > The reload isn't controlled by the module, but I have no problem > clearing out any loggers at the beginning. I'm thinking more along the lines of closing them in the old module before firing imp.reload() - maybe have a function in the module that cleans itself up and then reloads itself. And yes, I had been thinking of closing the handler, but I don't know the logging module much. ChrisA From atherun at gmail.com Wed Sep 21 23:09:05 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 20:09:05 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate Message-ID: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> This is on windows with python 2.6. I can't seem to remove a possibility of a deadlock in one of my scripts at the moment. Its not a constant deadlock but it appears from time to time. The code is below: try: process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) NotDone = True data = [] while NotDone: NotDone = False result = process.poll() if result == None: NotDone = True if NotDone: out, err = process.communicate() Log(out) I was able to get the program to write out the stack trace for my threads and it is usually deadlocked on sys.stdout.read or _internal_poll of subproceess. I've even tried the above, with using "with tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but it still deadlocks. In the past I work around this by running fewer processes asynchronously but I would really like to get this solved so I don't have to wait to see if it'll be caused with any changes I make. Any tips would be appreciated. From roy at panix.com Wed Sep 21 23:32:19 2011 From: roy at panix.com (Roy Smith) Date: Wed, 21 Sep 2011 23:32:19 -0400 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: In article <098f3d78-85f5-44e7-ba72-f2270a24d1b0 at o9g2000vbo.googlegroups.com>, Atherun wrote: > This is on windows with python 2.6. > I can't seem to remove a possibility of a deadlock in one of my > scripts at the moment. Its not a constant deadlock but it appears > from time to time. The code is below: > > try: > > process = > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > NotDone = True > data = [] > while NotDone: > NotDone = False > > result = process.poll() > if result == None: > NotDone = True > if NotDone: > out, err = process.communicate() > Log(out) > > I was able to get the program to write out the stack trace for my > threads and it is usually deadlocked on sys.stdout.read or > _internal_poll of subproceess. > > I've even tried the above, with using "with > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > it still deadlocks. In the past I work around this by running fewer > processes asynchronously but I would really like to get this solved so > I don't have to wait to see if it'll be caused with any changes I > make. > > Any tips would be appreciated. My reading of the docs (http://docs.python.org/release/2.6.7/library/subprocess.html#popen-objec ts) says that Popen.poll() doesn't return a value, it sets the object's return code attribute, which you can then interrogate. More than that, your loop logic looks amazingly complicated for what's basically a simple thing. I suggest something along the lines of: # assuming process.returncode is initially None while process.returncode is None: out, err = process.communicate() Log(out) I haven't tested that, but I think (from reading the docs) that's the right idea. From clp2 at rebertia.com Wed Sep 21 23:33:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 20:33:37 -0700 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: On Wed, Sep 21, 2011 at 8:09 PM, Atherun wrote: > This is on windows with python 2.6. > I can't seem to remove a possibility of a ?deadlock in one of my > scripts at the moment. ?Its not a constant deadlock but it appears > from time to time. ?The code is below: > > try: > > ? ? ? ?process = > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > ? ? ? ?NotDone = True > ? ? ? ?data = [] > ? ? ? ?while NotDone: > ? ? ? ? ? ?NotDone = False > > ? ? ? ? ? ?result = process.poll() > ? ? ? ? ? ?if result == None: > ? ? ? ? ? ? ? ?NotDone = True > ? ? ? ? ? ?if NotDone: > ? ? ? ? ? ? ? ?out, err = process.communicate() > ? ? ? ? ? ? ? ?Log(out) > > I was able to get the program to write out the stack trace for my > threads and it is usually deadlocked on sys.stdout.read or > _internal_poll of subproceess. > > I've even tried the above, with using "with > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > it still deadlocks. ?In the past I work around this by running fewer > processes asynchronously but I would really like to get this solved so > I don't have to wait to see if it'll be caused with any changes I > make. > > Any tips would be appreciated. Your polling loop is completely pointless. The code can be simplified to: process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) out, err = process.communicate() log(out) Depending on the particular program you're running in a subprocess, you may need to take heed of the Note in the communicate() docs: "Note: The data read is buffered in memory, so *do not use this method* if the data size is large or unlimited." [Emphasis added] Cheers, Chris -- http://rebertia.com From atherun at gmail.com Wed Sep 21 23:42:53 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 20:42:53 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> On Sep 21, 8:33?pm, Chris Rebert wrote: > On Wed, Sep 21, 2011 at 8:09 PM, Atherun wrote: > > This is on windows with python 2.6. > > I can't seem to remove a possibility of a ?deadlock in one of my > > scripts at the moment. ?Its not a constant deadlock but it appears > > from time to time. ?The code is below: > > > try: > > > ? ? ? ?process = > > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > > ? ? ? ?NotDone = True > > ? ? ? ?data = [] > > ? ? ? ?while NotDone: > > ? ? ? ? ? ?NotDone = False > > > ? ? ? ? ? ?result = process.poll() > > ? ? ? ? ? ?if result == None: > > ? ? ? ? ? ? ? ?NotDone = True > > ? ? ? ? ? ?if NotDone: > > ? ? ? ? ? ? ? ?out, err = process.communicate() > > ? ? ? ? ? ? ? ?Log(out) > > > I was able to get the program to write out the stack trace for my > > threads and it is usually deadlocked on sys.stdout.read or > > _internal_poll of subproceess. > > > I've even tried the above, with using "with > > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > > it still deadlocks. ?In the past I work around this by running fewer > > processes asynchronously but I would really like to get this solved so > > I don't have to wait to see if it'll be caused with any changes I > > make. > > > Any tips would be appreciated. > > Your polling loop is completely pointless. The code can be simplified to: > > process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > out, err = process.communicate() > log(out) > > Depending on the particular program you're running in a subprocess, > you may need to take heed of the Note in the communicate() docs: > "Note: The data read is buffered in memory, so *do not use this > method* if the data size is large or unlimited." [Emphasis added] > > Cheers, > Chris > --http://rebertia.com I'm pretty sure thats the problem, this is a generic catch all function for running subprocesses. It can be anything to a simple command to a complex command with a ton of output. I'm looking for a better solution to handle the case of running subprocesses that have an undetermined amount of output. (i.e. p4 edit's or tools that have an excessive amount of logging) I'll definitely simplify the loop, thanks for the tip on that part. From clp2 at rebertia.com Wed Sep 21 23:52:02 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 20:52:02 -0700 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: On Wed, Sep 21, 2011 at 8:32 PM, Roy Smith wrote: > My reading of the docs > (http://docs.python.org/release/2.6.7/library/subprocess.html#popen-objec > ts) says that Popen.poll() doesn't return a value, it sets the object's > return code attribute, which you can then interrogate. Popen.poll(): Check if child process has terminated. Set **and return** returncode attribute. [Direct quote from the docs; emphasis added] > More than that, your loop logic looks amazingly complicated for what's > basically a simple thing. ?I suggest something along the lines of: > > ? # assuming process.returncode is initially None > ? while process.returncode is None: > ? ? ?out, err = process.communicate() > ? ? ?Log(out) > > I haven't tested that, but I think (from reading the docs) that's the > right idea. There is no point in communicate()-ing multiple times; communicate() reads until EOF and only returns after subprocess termination! Cheers, Chris From roy at panix.com Wed Sep 21 23:58:19 2011 From: roy at panix.com (Roy Smith) Date: Wed, 21 Sep 2011 23:58:19 -0400 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: In article , Chris Rebert wrote: > Popen.poll(): > Check if child process has terminated. Set **and return** > returncode attribute. > [Direct quote from the docs; emphasis added] Doh. I read right past that and didn't see it. Thanks for the correction. From steve+comp.lang.python at pearwood.info Thu Sep 22 00:22:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 04:22:39 GMT Subject: Odd behavior with imp.reload and logging References: Message-ID: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> On Wed, 21 Sep 2011 20:53:04 -0500, Andrew Berg wrote: > When using a logger in a module and then using imp.reload to reload the > module, logger messages are repeated in direct proportion to the number > of times the modules was loaded. That is, on the first import, the > message is written once, but on the second run, each message is written > twice, three times on the third run, and so on. [...] > What causes this, and how can I fix it (or at least work around it)? Due > to the nature of the program, it's much more convenient to reload a > module than to restart the entire program (especially when testing). You unconditionally add a handler every time you reload the module, regardless of whether or not the old handler is still there. You could try something like this (untested): import logging test_logger = logging.getLogger(__name__) if not test_logger.handlers: console_handler = logging.StreamHandler() console_formatter = logging.Formatter( '{asctime} - {module} - {funcName} - line {lineno} - ' '{levelname} - {message}', style='{' ) console_handler.setFormatter(console_formatter) test_logger.addHandler(console_handler) test_logger.setLevel(logging.DEBUG) test_logger.info('Test info') -- Steven From bahamutzero8825 at gmail.com Thu Sep 22 00:47:55 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 23:47:55 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7ABDFB.5020509@gmail.com> On 2011.09.21 11:22 PM, Steven D'Aprano wrote: > You could > try something like this (untested): That works. Thanks! This makes me wonder what else stays around after a reload and what side effects there are, though. I would really like to purge everything from the previous import. The main program has no dependence on the module whatsoever. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From atherun at gmail.com Thu Sep 22 00:52:42 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 21:52:42 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: <56b9526d-fdd5-4f9d-bd39-d17b84f12141@h7g2000yqm.googlegroups.com> On Sep 21, 8:58?pm, Roy Smith wrote: > In article , > ?Chris Rebert wrote: > > > Popen.poll(): > > ? ? Check if child process has terminated. Set **and return** > > returncode attribute. > > [Direct quote from the docs; emphasis added] > > Doh. ?I read right past that and didn't see it. ?Thanks for the > correction. I removed the loop and changed it to a single communicate now, still get a deadlock. All threads just stop, even threads that have nothing to do with the ongoing subprocesses. I specifically created a thread that dumps the stack trace of all threads so I can try and view the deadlocks, but that stops responding at the same time as the deadlock. This wasn't happening before so not sure why it changed suddenly. From rosuav at gmail.com Thu Sep 22 01:09:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 15:09:49 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7ABDFB.5020509@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 2:47 PM, Andrew Berg wrote: > This makes me wonder what else stays around after a reload and what side > effects there are, though. I would really like to purge everything from > the previous import. The main program has no dependence on the module > whatsoever. > On-the-fly reloading of modules isn't really one of Python's strengths. Everyone who asks about it seems to be doing rapid development/debugging and wanting to save on startup time (as opposed to, say, running a server and updating code in it while it's active and serving clients), so the question becomes: Which is more of a problem, startup delay or the risk that it's not the same as a clean start? Python doesn't guarantee that your debugging session is going to be useful - if you reload that module and weird things happen, it could be because of reload(), not because of a module bug. Ranting Rick will probably expect me to mention Pike here, but I won't. Muahahahaha..... oh. I just did. Oh well! ChrisA From yves at zioup.com Thu Sep 22 01:24:03 2011 From: yves at zioup.com (yves at zioup.com) Date: Wed, 21 Sep 2011 23:24:03 -0600 Subject: with statements does not delete the object Message-ID: Is this the expected behaviour: with mylib.token() as t: do_something dir() In the last dir(), after the with "loop" is finished, t still shows up... I expected it to be unreferenced by then. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ From bahamutzero8825 at gmail.com Thu Sep 22 01:54:10 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 00:54:10 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> Message-ID: <4E7ACD82.4080302@gmail.com> On 2011.09.22 12:09 AM, Chris Angelico wrote: > On-the-fly reloading of modules isn't really one of Python's > strengths. Everyone who asks about it seems to be doing rapid > development/debugging and wanting to save on startup time (as opposed > to, say, running a server and updating code in it while it's active > and serving clients), so the question becomes: Which is more of a > problem, startup delay or the risk that it's not the same as a clean > start? Python doesn't guarantee that your debugging session is going > to be useful - if you reload that module and weird things happen, it > could be because of reload(), not because of a module bug. The main program is an IRC bot, which could potentially be in use by many people in several channels on a network. As it is, the bot can only connect to one server, but it could probably be set up to connect to any number of networks. Making a number of quick fixes or changes to one module could be very irritating to users if the bot has to terminate each time, especially if those users don't know or care about that specific module. Startup time is an issue because it must connect to a network before it can take any input. Also, many disconnects/reconnects could easily cause problems (like the network refusing the connection as a DoS prevention measure). I'm not tied to any particular solution, and it's quite possible I'm missing something since I am still a beginner. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From ben+python at benfinney.id.au Thu Sep 22 02:01:05 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 16:01:05 +1000 Subject: with statements does not delete the object References: Message-ID: <871uv92k0u.fsf@benfinney.id.au> yves at zioup.com writes: > Is this the expected behaviour: You can learn the expected behaviour for ?with? in the documentation . > with mylib.token() as t: > do_something > > dir() > > In the last dir(), after the with "loop" is finished, t still shows up... I > expected it to be unreferenced by then. What gives you that expectation, when it's not the case for any of ?if?, ?for?, ?while?, ?try?, and so on? The set of statements which introduce a new scope is small, and ?with? is not one of them. -- \ ?No smoothen the lion.? ?lion cage, zoo, Czech Republic | `\ | _o__) | Ben Finney From steve+comp.lang.python at pearwood.info Thu Sep 22 02:12:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 06:12:01 GMT Subject: Environment variables not visible from Python Message-ID: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> I don't understand why some environment variables are not visible from Python. [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM 30 140 xterm [steve at wow-wow ~]$ python2.6 Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) (None, None, 'xterm') -- Steven From airween at gmail.com Thu Sep 22 02:37:22 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Thu, 22 Sep 2011 08:37:22 +0200 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110922063721.GA3655@arxnet.hu> hello, On Thu, Sep 22, 2011 at 06:12:01AM +0000, Steven D'Aprano wrote: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') I think TERM is inherited from parent shell, but LINES and COLUMNS are re-created every child shell. IMHO it's normally, cause TERM will not change in child, but another variables should changed... Look at this: airween at sebulba:~$ export LINES COLUMNS TERM airween at sebulba:~$ python2.6 Python 2.6.6 (r266:84292, Mar 25 2011, 19:24:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) ('65', '210', 'rxvt-256color') a. From kushal.kumaran+python at gmail.com Thu Sep 22 02:40:08 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 22 Sep 2011 12:10:08 +0530 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Sep 22, 2011 at 11:42 AM, Steven D'Aprano wrote: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') > > I have this: $ python Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getenv('LINES') >>> $ python -S Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 >>> import os >>> os.getenv('LINES') '35' >>> I hope it helps narrow things down somewhat. -- regards, kushal From rosuav at gmail.com Thu Sep 22 02:46:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 16:46:59 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7ACD82.4080302@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 3:54 PM, Andrew Berg wrote: > The main program is an IRC bot, which could potentially be in use by > many people in several channels on a network. As it is, the bot can only > connect to one server, but it could probably be set up to connect to any > number of networks. Making a number of quick fixes or changes to one > module could be very irritating to users if the bot has to terminate > each time, especially if those users don't know or care about that > specific module. > Startup time is an issue because it must connect to a network before it > can take any input. Also, many disconnects/reconnects could easily cause > problems (like the network refusing the connection as a DoS prevention > measure). Playing with networking and the desire to reload without restarting? I think Pike may be a good choice for you. It has a C-like syntax but Python-like guts; you use braces to delimit blocks of code, but arrays and mappings and such are first-class objects that you can pass around and use. It's a favorite of mine, but quite off-topic for this mailing list; I'd be happy to help you get started with it. Chris Angelico From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 03:21:59 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 09:21:59 +0200 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 22.09.2011 08:12 schrieb Steven D'Aprano: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') > They are no environment variables, but merely shell variables. You can turn them into environment variables with the shell command "export". After exporting them, they are visible by Python. The environment can be obtained with env. So try: $ python -c 'import os; print "\n".join(sorted("%s=%s" % (k,v) for k,v in os.environ.iteritems()))' | diff -u - <(env|LANG=C sort) @@ -61,4 +61,4 @@ XDG_DATA_DIRS=/usr/share XKEYSYMDB=/usr/share/X11/XKeysymDB XNLSPATH=/usr/share/X11/nls -_=/usr/bin/python +_=/usr/bin/env and you see that they (nearly) match. Try as well $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' linux $ export LINES $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' 24 linux $ export COLUMNS $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' 24 80 linux $ HTH, Thomas From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 03:24:53 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 09:24:53 +0200 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: Am 22.09.2011 05:42 schrieb Atherun: > I'm pretty sure thats the problem, this is a generic catch all > function for running subprocesses. It can be anything to a simple > command to a complex command with a ton of output. I'm looking for a > better solution to handle the case of running subprocesses that have > an undetermined amount of output. Just handle process.stdout/stderr by yourself - read it out until EOF and then wait() for the process. Thomas From ericsnowcurrently at gmail.com Thu Sep 22 03:45:20 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 22 Sep 2011 01:45:20 -0600 Subject: static statements and thread safety Message-ID: A recent thread on the python-ideas list got me thinking about the possibility of a static statement (akin to global and nonlocal). I am wondering if an implementation would have to address thread safety concerns. I would expect that static variables would work pretty much the same way as default arguments, with a list of names on the code object and a list of values on the function object. And I would guess that the values from the static variables would get updated on the function object at the end of the call. If multiple threads are executing the function at the same time won't there be a problem with that end-of-call update? -eric p.s. It probably shows that I haven't done a lot of thread-related programming, so perhaps this is not a hard question. From bahamutzero8825 at gmail.com Thu Sep 22 03:59:42 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 02:59:42 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> Message-ID: <4E7AEAEE.20504@gmail.com> On 2011.09.22 01:46 AM, Chris Angelico wrote: > I think Pike may be a good choice for you. That's quite unappealing for a few reasons. First, that would likely require writing an entirely new bot (I'm not even that familiar with the current one; I've only been writing a module for it). Also, I don't really enjoy programming (I'm aware I'm likely in the minority on this list); I tolerate it enough to get certain things done, so learning another language, especially when I'm still learning Python, is not something I want to do. Python is probably not the best tool for this particular job, but I am not nearly dedicated to this project enough to learn another programming language. So, is there any way to at least monitor what happens after a reload? I haven't noticed anything odd until I came across this logging issue. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From rosuav at gmail.com Thu Sep 22 04:06:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:06:45 +1000 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow wrote: > I would expect that static variables would work pretty much the same > way as default arguments Could you just abuse default arguments to accomplish this? def accumulate(n,statics={'sum':0}): statics['sum']+=n return statics['sum'] >>> accumulate(1) 1 >>> accumulate(10) 11 >>> accumulate(20) 31 >>> accumulate(14) 45 This eliminates any sort of "end of function write-back" by writing to static storage immediately. Of course, syntactic assistance would make this look cleaner, for instance: def accumulate(n): static sum=0 sum+=n return sum Both of these would, of course, have thread-safety issues. But these can be resolved by figuring out exactly what you're trying to accomplish with your static data, and what it really means when two threads are affecting it at once. ChrisA From rosuav at gmail.com Thu Sep 22 04:12:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:12:49 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7AEAEE.20504@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> <4E7AEAEE.20504@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 5:59 PM, Andrew Berg wrote: > That's quite unappealing for a few reasons. First, that would likely > require writing an entirely new bot (I'm not even that familiar with the > current one; I've only been writing a module for it). Ah, then yeah, it's probably not a good idea to change languages. But you may end up finding other issues with reload() as well. I wonder whether this would work... modules=[] # instead of 'import mymodule' use: modules.append(__import__('mymodule')); mymodule=modules[-1] In theory, this should mean that you load it fresh every time - I think. If not, manually deleting entries from sys.modules might help, either with or without the list of modules. ChrisA From ladasky at my-deja.com Thu Sep 22 04:13:12 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 22 Sep 2011 01:13:12 -0700 (PDT) Subject: Graphing References: Message-ID: I'm using matplotlib and I'm happy with it. Quick plotting is easy using the pyplot interface, which resembles the popular software package MATLAB. As your ambitions grow, matplotlib has many sophisticated tools waiting for you. From ericsnowcurrently at gmail.com Thu Sep 22 04:16:11 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 22 Sep 2011 02:16:11 -0600 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 2:06 AM, Chris Angelico wrote: > On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow wrote: >> I would expect that static variables would work pretty much the same >> way as default arguments > > Could you just abuse default arguments to accomplish this? > > def accumulate(n,statics={'sum':0}): > ? ?statics['sum']+=n > ? ?return statics['sum'] > >>>> accumulate(1) > 1 >>>> accumulate(10) > 11 >>>> accumulate(20) > 31 >>>> accumulate(14) > 45 > > This eliminates any sort of "end of function write-back" by writing to > static storage immediately. Of course, syntactic assistance would make > this look cleaner, for instance: > > def accumulate(n): > ? ?static sum=0 > ? ?sum+=n > ? ?return sum > > Both of these would, of course, have thread-safety issues. But these > can be resolved by figuring out exactly what you're trying to > accomplish with your static data, and what it really means when two > threads are affecting it at once. That's a good point. So, isn't the default arguments hack in the same boat with regards to threads? Maybe I'm just misunderstanding the thread concept in Python. Threads have separate execution stacks but share interpreter global state, right? -eric > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Thu Sep 22 04:18:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:18:28 +1000 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 6:16 PM, Eric Snow wrote: > That's a good point. ?So, isn't the default arguments hack in the same > boat with regards to threads? > > Maybe I'm just misunderstanding the thread concept in Python. ?Threads > have separate execution stacks but share interpreter global state, > right? I would say it probably is, but others on this list will know more of threading in Python. I tend not to write multithreaded programs in Python - the main reason for me to use Python is rapid scriptwriting, which usually doesn't demand threads. ChrisA From steve+comp.lang.python at pearwood.info Thu Sep 22 04:25:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 08:25:39 GMT Subject: Odd behavior with imp.reload and logging References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> On Wed, 21 Sep 2011 23:47:55 -0500, Andrew Berg wrote: > On 2011.09.21 11:22 PM, Steven D'Aprano wrote: >> You could >> try something like this (untested): > That works. Thanks! > This makes me wonder what else stays around after a reload Practically everything. A reload doesn't delete anything, except as a side-effect of running the module again. Don't think of reloading as: * Revert anything the module is responsible for. * Delete the module object from the import cache. * Import the module in a fresh environment. Instead, think of it as: * Re-import the module in the current environment. In practice, you won't often see such side-effects, because most modules don't store state outside of themselves. If they store state *inside* themselves, then they will (almost always) overwrite that state. E.g. this will work as expected: state = [something] But this leaves state hanging around in other modules and will be surprising: import another_module another_module.state.append(something) My guess is that the logging module uses a cache to save the logger, hence there is state inadvertently stored outside your module. Another place where reload() doesn't work as expected: >>> import module >>> a = module.MyClass() >>> reload(module) >>> b = module.MyClass() >>> type(a) is type(b) False Objects left lying around from before the reload will keep references open to the way things were before the reload. This often leads to confusion when modules are edited, then reloaded. (Been there, done that.) -- Steven From bahamutzero8825 at gmail.com Thu Sep 22 05:02:48 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 04:02:48 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7AF9B8.7020802@gmail.com> On 2011.09.22 03:25 AM, Steven D'Aprano wrote: > Objects left lying around from before the reload will keep references > open to the way things were before the reload. This often leads to > confusion when modules are edited, then reloaded. (Been there, done that.) I'll keep that in mind. My module does have a class, but instances are kept inside dictionaries, which are explicitly set to {} at the beginning (can't use the update() method for dictionaries that don't exist). Also, class instances get pickled after creation and unpickled when the module is imported. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From chris at simplistix.co.uk Thu Sep 22 05:27:36 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 22 Sep 2011 10:27:36 +0100 Subject: python install on locked down windows box? Message-ID: <4E7AFF88.2040308@simplistix.co.uk> Hi All, Is there a way to install python on a locked down Windows desktop? (ie: no compilers, no admin rights, etc) cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From ben+python at benfinney.id.au Thu Sep 22 06:16:47 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 20:16:47 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wrd0286o.fsf@benfinney.id.au> Steven D'Aprano writes: > I don't understand why some environment variables are not visible from > Python. Not all variables are environment variables. Variables only become environment variables if exported to the environment; the ?export? command is one way to do that. -- \ ?As far as the laws of mathematics refer to reality, they are | `\ not certain, and as far as they are certain, they do not refer | _o__) to reality.? ?Albert Einstein, 1983 | Ben Finney From zondo42 at gmail.com Thu Sep 22 06:19:05 2011 From: zondo42 at gmail.com (Glenn Hutchings) Date: Thu, 22 Sep 2011 03:19:05 -0700 (PDT) Subject: python install on locked down windows box? In-Reply-To: References: Message-ID: <13828134.867.1316686745332.JavaMail.geo-discussion-forums@yqbr29> You could try Portable Python (http://www.portablepython.com). No need to install anything! From zondo42 at gmail.com Thu Sep 22 06:19:05 2011 From: zondo42 at gmail.com (Glenn Hutchings) Date: Thu, 22 Sep 2011 03:19:05 -0700 (PDT) Subject: python install on locked down windows box? In-Reply-To: References: Message-ID: <13828134.867.1316686745332.JavaMail.geo-discussion-forums@yqbr29> You could try Portable Python (http://www.portablepython.com). No need to install anything! From gavinpanella at gmail.com Thu Sep 22 06:21:28 2011 From: gavinpanella at gmail.com (Gavin Panella) Date: Thu, 22 Sep 2011 03:21:28 -0700 (PDT) Subject: Context manager with class methods Message-ID: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Hi, On Python 2.6 and 3.1 the following code works fine: class Foo(object): @classmethod def __enter__(cls): print("__enter__") @classmethod def __exit__(cls, exc_type, exc_value, traceback): print("__exit__") with Foo: pass However, in 2.7 and 3.2 I get: Traceback (most recent call last): File "", line 1, in AttributeError: __exit__ Is this a regression or a deliberate change? Off the top of my head I can't think that this pattern is particularly useful, but it seems like something that ought to work. Gavin. From vs at it.uu.se Thu Sep 22 06:25:30 2011 From: vs at it.uu.se (Virgil Stokes) Date: Thu, 22 Sep 2011 12:25:30 +0200 Subject: Execute code after Shut Down command given --- How? Message-ID: <4E7B0D1A.7040306@it.uu.se> I would like to execute some Python code (popup message to be displayed) when Windows Vista/7 is shut down. That is, this code should execute after "Shut Down" is given from the "Shut Down Windows" popup, but before the actual shut down sequence starts. How to write Python code to accomplish this task? From yasar11732 at gmail.com Thu Sep 22 06:43:48 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 22 Sep 2011 13:43:48 +0300 Subject: httplib's HEAD request, and https protocol Message-ID: Hi, I wrote a function to get thorugh redirections and find a final page for a given web-page. But following function gives maximum recursion error for any https pages I tried. Do you know what might be the problem here? def getHeadResponse(url,response_cache = {}): try: return response_cache[url] except KeyError: url = urlparse.urlparse(url) conn = httplib.HTTPConnection(url.netloc) try: conn.request("HEAD",url.path) except: # Anything can happen, this is SPARTA! return None response = conn.getresponse() response_cache[url.geturl()] = response return response def getFinalUrl(url): "Navigates through redirections to get final url." response = getHeadResponse(url) try: if str(response.status).startswith("3"): return getFinalUrl(response.getheader("location")) except AttributeError: pass return url -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From shilparani9030 at gmail.com Thu Sep 22 06:48:47 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Thu, 22 Sep 2011 03:48:47 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From steve+comp.lang.python at pearwood.info Thu Sep 22 07:07:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 21:07:31 +1000 Subject: Execute code after Shut Down command given --- How? References: Message-ID: <4e7b16f4$0$29979$c3e8da3$5496439d@news.astraweb.com> Virgil Stokes wrote: > I would like to execute some Python code (popup message to be displayed) > when > Windows Vista/7 is shut down. That is, this code should execute after > "Shut Down" is given from the "Shut Down Windows" popup, but before the > actual shut down sequence starts. > > How to write Python code to accomplish this task? Exactly the same way you would write it in any other language. This is not a Python question. It is a Windows question: "How do I execute code after the user calls Shut Down Windows, but before the shut down sequence starts?" Find out how to do that, and then do it using Python instead of another language. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 22 07:09:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 21:09:00 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: <4e7b174c$0$29979$c3e8da3$5496439d@news.astraweb.com> Ben Finney wrote: > Steven D'Aprano writes: > >> I don't understand why some environment variables are not visible from >> Python. > > Not all variables are environment variables. Variables only become > environment variables if exported to the environment; the ?export? > command is one way to do that. I see. Thank you to everyone who answered. -- Steven From joni8135 at gmail.com Thu Sep 22 07:16:34 2011 From: joni8135 at gmail.com (joni) Date: Thu, 22 Sep 2011 04:16:34 -0700 (PDT) Subject: Negativ nearest interger? Message-ID: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Have a simple question in the Integer calculator in Python 2.65 and also 2.7.. The consol showing: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 7.0/3 #fist to show floiting-point calculation 2.3333333333333335 >>> -7.0/3 -2.3333333333333335 >>> -7/-3 #Rounding to nearest interger. 2 >>> 7/3 2 >>> 7/-3 #Now to the problem with interger rounding with negative anwser. -3 >>> -7/3 -3 >>> -3 are more wrong than -2. Negativ number seems not to round to nearest interger, but the integer UNDER the anwser!! Or? Why? From yasar11732 at gmail.com Thu Sep 22 07:42:12 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 22 Sep 2011 14:42:12 +0300 Subject: httplib's HEAD request, and https protocol In-Reply-To: References: Message-ID: Ok, nevermind. Appereantly there is such a thing as HTTPSConnection. I thought httplib auto-handled https connections.. 22 Eyl?l 2011 13:43 tarihinde Ya?ar Arabac? yazd?: > Hi, > > I wrote a function to get thorugh redirections and find a final page for a > given web-page. But following function gives maximum recursion error for any > https pages I tried. Do you know what might be the problem here? > > def getHeadResponse(url,response_cache = {}): > try: > return response_cache[url] > except KeyError: > url = urlparse.urlparse(url) > conn = httplib.HTTPConnection(url.netloc) > try: > conn.request("HEAD",url.path) > except: > # Anything can happen, this is SPARTA! > return None > response = conn.getresponse() > response_cache[url.geturl()] = response > return response > > def getFinalUrl(url): > "Navigates through redirections to get final url." > > response = getHeadResponse(url) > try: > if str(response.status).startswith("3"): > return getFinalUrl(response.getheader("location")) > except AttributeError: > pass > return url > -- > http://yasar.serveblog.net/ > > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 07:43:52 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 13:43:52 +0200 Subject: Environment variables not visible from Python In-Reply-To: <87wrd0286o.fsf@benfinney.id.au> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: Am 22.09.2011 12:16 schrieb Ben Finney: > -- > \ ?As far as the laws of mathematics refer to reality, they are | > `\ not certain, and as far as they are certain, they do not refer | > _o__) to reality.? ?Albert Einstein, 1983 | > Ben Finney So, he said what in 1983? Wow. From jpiitula at ling.helsinki.fi Thu Sep 22 07:44:15 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 22 Sep 2011 14:44:15 +0300 Subject: Negativ nearest interger? References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: joni writes: > Have a simple question in the Integer calculator in Python 2.65 and > also 2.7.. > > The consol showing: > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) ... > >>> -7/3 > -3 > >>> > > -3 are more wrong than -2. Negativ number seems not to round to > nearest interger, but the integer UNDER the anwser!! Or? > > Why? It simply does not round to the nearest integer. It floors. This has nicer mathematical properties. In particular, it allows the remainder (notated as "per cent") operation (n % m) to return a number that differs from n by a multiple of m ("is congruent to n modulo m"). These two operations go together. From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 07:47:15 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 13:47:15 +0200 Subject: Context manager with class methods In-Reply-To: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Am 22.09.2011 12:21 schrieb Gavin Panella: > Hi, > > On Python 2.6 and 3.1 the following code works fine: > > class Foo(object): > > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass > > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ Same here. But with Foo(): pass works, and that is more important and more logical. Thomas From ben+python at benfinney.id.au Thu Sep 22 08:26:15 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 22:26:15 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: <87r538226w.fsf@benfinney.id.au> Thomas Rachel writes: > Am 22.09.2011 12:16 schrieb Ben Finney: > > -- > > \ ?As far as the laws of mathematics refer to reality, they are | > > `\ not certain, and as far as they are certain, they do not refer | > > _o__) to reality.? ?Albert Einstein, 1983 | > > Ben Finney > > So, he said what in 1983? Wow. Or at least, in a work of his published in 1983: ?Sidelights on Relativity?. According to Wikiquote, anyway . -- \ ?[Entrenched media corporations will] maintain the status quo, | `\ or die trying. Either is better than actually WORKING for a | _o__) living.? ?ringsnake.livejournal.com, 2007-11-12 | Ben Finney From mwilson at the-wire.com Thu Sep 22 08:45:18 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 22 Sep 2011 08:45:18 -0400 Subject: Context manager with class methods References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Gavin Panella wrote: > Hi, > > On Python 2.6 and 3.1 the following code works fine: > > class Foo(object): > > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass > > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ > > Is this a regression or a deliberate change? Off the top of my head I > can't think that this pattern is particularly useful, but it seems > like something that ought to work. This seems to work: class MetaWith (type): @classmethod def __enter__(cls): print("__enter__") @classmethod def __exit__(cls, exc_type, exc_value, traceback): print("__exit__") class With (object): __metaclass__ = MetaWith with With: pass Mel. From mwilson at the-wire.com Thu Sep 22 08:53:21 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 22 Sep 2011 08:53:21 -0400 Subject: Context manager with class methods References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Mel wrote: > This seems to work: > > > > class MetaWith (type): > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > class With (object): > __metaclass__ = MetaWith > > with With: > pass It seems to work equally well without the `@classmethod`s Mel. From steve+comp.lang.python at pearwood.info Thu Sep 22 08:58:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 22:58:00 +1000 Subject: python install on locked down windows box? References: Message-ID: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Chris Withers wrote: > Hi All, > > Is there a way to install python on a locked down Windows desktop? > (ie: no compilers, no admin rights, etc) (1) Bribe or blackmail the fascist system administrator. (2) Hack into the system with any of dozens of unpatched vulnerabilities that will give you admin rights. (3) Sneak into the office at 3 in the morning and replace the desktop with an identical machine which you have admin rights to. (4) Guess the admin password -- it's not hard, most fascist system administrators can't remember words with more than four letters, so the password is probably something like "passw" or, if he's being especially cunning, "drows". (5) "Accidentally" install Linux on the machine and use that instead. (6) Take hostages. (7) If all else fails, as an absolute last resort, simply run the Windows installer as a regular, unprivileged user, after selecting the option for a Non-Admin Install under Advanced Options first. You could also try the ActivePython installer. http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ http://diveintopython.org/installing_python/windows.html -- Steven From joni8135 at gmail.com Thu Sep 22 10:13:54 2011 From: joni8135 at gmail.com (joni) Date: Thu, 22 Sep 2011 07:13:54 -0700 (PDT) Subject: Negativ nearest interger? References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: On Sep 22, 1:44?pm, Jussi Piitulainen wrote: > joni writes: > > Have a simple question in the Integer calculator in Python 2.65 and > > also 2.7.. > > > The consol showing: > > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) > ... > > >>> -7/3 > > -3 > > > -3 are more wrong than -2. Negativ number seems not to round to > > nearest interger, but the integer UNDER the anwser!! Or? > > > Why? > > It simply does not round to the nearest integer. It floors. This has > nicer mathematical properties. In particular, it allows the remainder > (notated as "per cent") operation (n % m) to return a number that > differs from n by a multiple of m ("is congruent to n modulo m"). > These two operations go together. Thanx. See if I can understand it.... /Cheers From ian at excess.org Thu Sep 22 11:05:00 2011 From: ian at excess.org (Ian Ward) Date: Thu, 22 Sep 2011 11:05:00 -0400 Subject: ANN: Urwid 1.0.0 - Console UI Library Message-ID: <4E7B4E9C.7060704@excess.org> Announcing Urwid 1.0.0 ---------------------- Urwid home page: http://excess.org/urwid/ Manual: http://excess.org/urwid/wiki/UrwidManual Tarball: http://excess.org/urwid/urwid-1.0.0.tar.gz About this release: =================== This is a major feature release for Urwid: It's the first official release that has support for Python 3. There's a new experimental Terminal widget so you can terminal while you terminal or write a screen-clone. There's a new example showing how to serve Urwid interfaces to many users simultaneously over ssh with Twisted. There are new classes to help with creating dynamic tree views of anything you have that's tree-like. There are new widgets for working with pop-ups so you can now have all the menu bars, drop-downs and combo-boxes you can write. The old requirement to sprinkle draw_screen() calls around your callbacks is gone. Urwid now updates the screen automatically after everything else is done. There's a new simple MainLoop method for catching updates from other threads and processes. No need to manually fumble with os.pipe() and event loops. And lots more... Happy 1.0 Urwid! It's been a great nearly-seven years since our first release. Huge thanks to everyone that's contributed code, docs, bug reports and help on the mailing list and IRC. New in this release: ==================== * New support for Python 3.2 from the same 2.x code base, requires distribute instead of setuptools (by Kirk McDonald, Wendell, Marien Zwart) everything except TwistedEventLoop and GLibEventLoop is supported * New experimental Terminal widget with xterm emulation and terminal.py example program (by aszlig) * Edit widget now supports a mask (for passwords), has a insert_text_result() method for full-field validation and normalizes input text to Unicode or bytes based on the caption type used * New TreeWidget, TreeNode, ParentNode, TreeWalker and TreeListBox classes for lazy expanding/collapsing tree views factored out of browse.py example program, with new treesample.py example program (by Rob Lanphier) * MainLoop now calls draw_screen() just before going idle, so extra calls to draw_screen() in user code may now be removed * New MainLoop.watch_pipe() method for subprocess or threaded communication with the process/thread updating the UI, and new subproc.py example demonstrating its use * New PopUpLauncher and PopUpTarget widgets and MainLoop option for creating pop-ups and drop-downs, and new pop_up.py example program * New twisted_serve_ssh.py example (by Ali Afshar) that serves multiple displays over ssh from the same application using Twisted and the TwistedEventLoop * ListBox now includes a get_cursor_coords() method, allowing nested ListBox widgets * Columns widget contents may now be marked to always be treated as flow widgets for mixing flow and box widgets more easily * New lcd_display module with support for CF635 USB LCD panel and lcd_cf635.py example program with menus, slider controls and a custom font * Shared command_map instance is now stored as Widget._command_map class attribute and may be overridden in subclasses or individual widgets for more control over special keystrokes * Overlay widget parameters may now be adjusted after creation with set_overlay_parameters() method * New WidgetPlaceholder widget useful for swapping widgets without having to manipulate a container widget's contents * LineBox widgets may now include title text * ProgressBar text content and alignment may now be overridden * Use reactor.stop() in TwistedEventLoop and document that Twisted's reactor is not designed to be stopped then restarted * curses_display now supports AttrSpec and external event loops (Twisted or GLib) just like raw_display * raw_display and curses_display now support the IBMPC character set (currently only used by Terminal widget) * Fix for a gpm_mev bug preventing user input when on the console * Fix for leaks of None objects in str_util extension * Fix for WidgetWrap and AttrMap not working with fixed widgets * Fix for a lock up when attempting to wrap text containing wide characters into a single character column About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, Unicode support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From python at mrabarnett.plus.com Thu Sep 22 11:19:04 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 22 Sep 2011 16:19:04 +0100 Subject: static statements and thread safety In-Reply-To: References: Message-ID: <4E7B51E8.10200@mrabarnett.plus.com> On 22/09/2011 08:45, Eric Snow wrote: > A recent thread on the python-ideas list got me thinking about the > possibility of a static statement (akin to global and nonlocal). I am > wondering if an implementation would have to address thread safety > concerns. > > I would expect that static variables would work pretty much the same > way as default arguments, with a list of names on the code object and > a list of values on the function object. And I would guess that the > values from the static variables would get updated on the function > object at the end of the call. If multiple threads are executing the > function at the same time won't there be a problem with that > end-of-call update? > It's no different from using a global, except that it's not in the global (module) namespace, but attached to a function object. > -eric > > > p.s. It probably shows that I haven't done a lot of thread-related > programming, so perhaps this is not a hard question. From atherun at gmail.com Thu Sep 22 11:55:40 2011 From: atherun at gmail.com (Atherun) Date: Thu, 22 Sep 2011 08:55:40 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Sep 22, 12:24?am, Thomas Rachel wrote: > Am 22.09.2011 05:42 schrieb Atherun: > > > I'm pretty sure thats the problem, this is a generic catch all > > function for running subprocesses. ?It can be anything to a simple > > command to a complex command with a ton of output. ?I'm looking for a > > better solution to handle the case of running subprocesses that have > > an undetermined amount of output. > > Just handle process.stdout/stderr by yourself - read it out until EOF > and then wait() for the process. > > Thomas Thats what confuses me though, the documentation says process.stdout.read()/stderr.read() can deadlock and apparently so can communicate, how do you read the stdout/stderr on yourself if its documented using them can cause a deadlock? From navkirat.py at gmail.com Thu Sep 22 12:00:18 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Thu, 22 Sep 2011 21:30:18 +0530 Subject: Decision on python technologies Message-ID: Hi Guys, I have been a python developer for a bit now and for the life of me I am not being able to decide something. I am trying to develop a web based application in python. I am torn between using python 2 or 3. All the good frameworks are still in 2.x. Now, cherrypy, sqlalchemy and jinja2 support python 3. But do I really want to do all the boilerplate work again? I have this strong urge to use python 3 and call it my indecisiveness , I am somehow not wanting to use 2.x, though it has everything I need to build my app. Hence, I finally decided to turn to the community for helping me make this decision. Please help. Regards, Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Thu Sep 22 12:28:52 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 22 Sep 2011 09:28:52 -0700 (PDT) Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) In-Reply-To: References: Message-ID: <19309769.959.1316708932280.JavaMail.geo-discussion-forums@prdy8> Thank you! My kids *love* it. From miki.tebeka at gmail.com Thu Sep 22 12:28:52 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 22 Sep 2011 09:28:52 -0700 (PDT) Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) In-Reply-To: References: Message-ID: <19309769.959.1316708932280.JavaMail.geo-discussion-forums@prdy8> Thank you! My kids *love* it. From ppearson at nowhere.invalid Thu Sep 22 12:51:39 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 22 Sep 2011 16:51:39 GMT Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9e17crFamfU1@mid.individual.net> On Thu, 22 Sep 2011 09:21:59 +0200, Thomas Rachel wrote: [snip] > $ python -c 'import os; print "\n".join(sorted("%s=%s" % (k,v) for k,v > in os.environ.iteritems()))' | diff -u - <(env|LANG=C sort) [standing ovation] -- To email me, substitute nowhere->spamcop, invalid->net. From rosuav at gmail.com Thu Sep 22 13:39:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 03:39:54 +1000 Subject: random.randint() slow, esp in Python 3 Message-ID: The standard library function random.randint() seems to be quite slow compared to random.random(), and worse in Python 3 than Python 2 (specifically that's 3.3a0 latest from Mercurial, and 2.6.6 that came default on my Ubuntu install). My test involves building a list of one million random integers between 0 and ten million (for tinkering with sorting algorithms), using a list comprehension: import random import time sz=1000000 start=time.time() a=[random.randint(0,sz*10-1) for i in range(sz)] print("Time taken: ",time.time()-start) The code works fine in either version of Python (although the display looks a bit odd in Py2). But on my test system, it takes about 5 seconds to run in Py2, and about 10 seconds for Py3. (The obvious optimization of breaking sz*10-1 out and storing it in a variable improves both times, but leaves the dramatic difference.) Replacing randint with random(): a=[int(random.random()*top) for i in range(sz)] cuts the times down to about 1.5 secs for Py2, and 1.8 secs for Py3. I suspect that the version difference is (at least in part) due to the merging of the 'int' and 'long' types in Py3. This is supported experimentally by rerunning the second list comp but using int() in place of long() - the time increases to about 1.7-1.8 secs, matching Py3. But this still doesn't explain why randint() is so much slower. In theory, randint() should be doing basically the same thing that I've done here (multiply by the top value, truncate the decimal), only it's in C instead of Python - if anything, it should be faster than doing it manually, not slower. A minor point of curiosity, nothing more... but, I think, a fascinating one. ChrisA From nobody at nowhere.com Thu Sep 22 13:44:09 2011 From: nobody at nowhere.com (Nobody) Date: Thu, 22 Sep 2011 18:44:09 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Thu, 22 Sep 2011 08:55:40 -0700, Atherun wrote: >> Just handle process.stdout/stderr by yourself - read it out until EOF >> and then wait() for the process. > > Thats what confuses me though, the documentation says > process.stdout.read()/stderr.read() can deadlock and apparently so can > communicate, how do you read the stdout/stderr on yourself if its > documented using them can cause a deadlock? If you try to read/write two or more of stdin/stdout/stderr via the "naive" approach, you run the risk of the child process writing more than a pipe's worth of data to one stream (and thus blocking) while the parent is performing a blocking read/write on another stream, resulting in deadlock. The .communicate() method avoids the deadlock by either: 1. On Unix, using non-blocking I/O and select(), or 2. On Windows, creating a separate thread for each stream. Either way, the result is that it can always read/write whichever streams are ready, so the child will never block indefinitely while waiting for the parent. If .communicate() is blocking indefinitely, it suggests that the child process never terminates. There are many reasons why this might happen, and most of them depend upon exactly what the child process is doing. I suggest obtaining a copy of Process Explorer, and using it to investigate the state of both processes (but especially the child) at the point that the "deadlock" seems to occur. From steve+comp.lang.python at pearwood.info Thu Sep 22 14:14:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 23 Sep 2011 04:14:16 +1000 Subject: random.randint() slow, esp in Python 3 References: Message-ID: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > The standard library function random.randint() seems to be quite slow > compared to random.random(), and worse in Python 3 than Python 2 [...] > But this still doesn't explain why randint() is so much slower. In > theory, randint() should be doing basically the same thing that I've > done here (multiply by the top value, truncate the decimal), only it's > in C instead of Python - if anything, it should be faster than doing > it manually, not slower. What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the random module is mostly Python. There is an import of _random, which presumably is in C, but it doesn't have a randint method: >>> import _random >>> _random.Random.randint Traceback (most recent call last): File "", line 1, in AttributeError: type object '_random.Random' has no attribute 'randint' I'm not seeing any significant difference in speed between 2.6 and 3.2: [steve at sylar ~]$ python2.6 -m timeit -s "from random import randint" "randint(0, 1000000)" 100000 loops, best of 3: 4.29 usec per loop [steve at sylar ~]$ python3.2 -m timeit -s "from random import randint" "randint(0, 1000000)" 100000 loops, best of 3: 4.98 usec per loop (The times are quite variable: the above are the best of three attempts.) -- Steven From emile at fenx.com Thu Sep 22 14:16:05 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 22 Sep 2011 11:16:05 -0700 Subject: Decision on python technologies In-Reply-To: References: Message-ID: On 9/22/2011 9:00 AM Navkirat Singh said... > Hi Guys, > > I have been a python developer for a bit now and for the life of me I am > not being able to decide something. I am trying to develop a web based > application in python. I am torn between using python 2 or 3. All the > good frameworks are still in 2.x. Now, cherrypy, sqlalchemy and jinja2 > support python 3. But do I really want to do all the boilerplate work > again? I have this strong urge to use python 3 and call it my > indecisiveness , I am somehow not wanting to use 2.x, though it has > everything I need to build my app. Hence, I finally decided to turn to > the community for helping me make this decision. > I'd consider the development timeframe -- if it'll still be under development within the timeframe of migration and availability of desired tools then I'd start with 3 and focus on those parts that can be worked on. If your development timeframe is measured in weeks instead of quarters or years, I'd just get it done with 2. Emile From atherun at gmail.com Thu Sep 22 14:19:28 2011 From: atherun at gmail.com (Atherun) Date: Thu, 22 Sep 2011 11:19:28 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Sep 22, 10:44?am, Nobody wrote: > On Thu, 22 Sep 2011 08:55:40 -0700, Atherun wrote: > >> Just handle process.stdout/stderr by yourself - read it out until EOF > >> and then wait() for the process. > > > Thats what confuses me though, the documentation says > > process.stdout.read()/stderr.read() can deadlock and apparently so can > > communicate, how do you read the stdout/stderr on yourself if its > > documented using them can cause a deadlock? > > If you try to read/write two or more of stdin/stdout/stderr via the > "naive" approach, you run the risk of the child process writing more than > a pipe's worth of data to one stream (and thus blocking) while the > parent is performing a blocking read/write on another stream, resulting in > deadlock. > > The .communicate() method avoids the deadlock by either: > > 1. On Unix, using non-blocking I/O and select(), or > 2. On Windows, creating a separate thread for each stream. > > Either way, the result is that it can always read/write whichever > streams are ready, so the child will never block indefinitely while > waiting for the parent. > > If .communicate() is blocking indefinitely, it suggests that the child > process never terminates. There are many reasons why this might happen, > and most of them depend upon exactly what the child process is doing. > > I suggest obtaining a copy of Process Explorer, and using it to > investigate the state of both processes (but especially the child) at the > point that the "deadlock" seems to occur. In the one case I can easily reproduce, its in a p4.exe call that I'm making both python and p4.exe have nearly the same stack for their threads: python: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!__misaligned_access+0xba4 ntoskrnl.exe!__misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!NtWaitForSingleObject+0xde ntoskrnl.exe!KeSynchronizeExecution+0x3a43 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x6c0 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x4a8 wow64.dll!Wow64SystemServiceEx+0x1ce wow64.dll!Wow64LdrpInitialize+0x429 ntdll.dll!RtlUniform+0x6e6 ntdll.dll!RtlCreateTagHeap+0xa7 ntdll.dll!LdrInitializeThunk+0xe ntdll.dll!ZwWaitForSingleObject+0x15 kernel32.dll!WaitForSingleObjectEx+0x43 kernel32.dll!WaitForSingleObject+0x12 python26.dll!_Py_svnversion+0xcf8 p4: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForSingleObject+0x19f ntoskrnl.exe!_misaligned_access+0xba4 ntoskrnl.exe!_misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForSingleObject+0x19f ntoskrnl.exe!NtCreateFile+0x4c9 ntoskrnl.exe!NtWriteFile+0x7e3 ntoskrnl.exe!KeSynchronizeExecution+0x3a43 ntdll.dll!ZwWriteFile+0xa KERNELBASE.dll!WriteFile+0x7b kernel32.dll!WriteFile+0x36 p4.exe+0x42d4b p4.exe+0x42ed8 To me it looks like they're both waiting on each other. From mattj.morrison at gmail.com Thu Sep 22 17:14:39 2011 From: mattj.morrison at gmail.com (Matt) Date: Thu, 22 Sep 2011 14:14:39 -0700 (PDT) Subject: Python Mixins Message-ID: I'm curious about what people's opinions are about using mixins in Python. I really like, for example, the way that class based views were implemented in Django 1.3 using mixins. It makes everything extremely customizable and reusable. I think this is a very good practice to follow, however, in Python mixins are achieved by using (or perhaps misusing) inheritance and often multiple inheritance. Inheritance is a very powerful tool, and multiple inheritance is an even more powerful tool. These tools have their uses, but I feel like "mixing in" functionality is not one of them. There are much different reasons and uses for inheriting functionality from a parent and mixing in functionality from elsewhere. As a person, you learn certain things from your parents, you learn other things from your peers all of those things put together becomes you. Your peers are not your parents, that would not be possible. You have completely different DNA and come from a completely different place. In terms of code, lets say we have the following classes: class Animal class Yamlafiable class Cat(Animal, Yamlafiable) class Dog(Animal, Yamlafiable) I've got an Animal that does animal things, a Cat that does cat things and a Dog that does dog things. I've also got a Yamlafiable class that does something clever to generically convert an object into Yaml in some way. Looking at these classes I can see that a Cat is an Animal, a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a Yamlafiable? and a Cat is a Yamlafiable? Is that really true? If my objects are categorized correctly, in the correct inheritance hierarchy shouldn't that make more sense? Cats and Dogs aren't Yamlafiable, that doesn't define what they are, rather it defines something that they can do because of things that they picked up from their friend the Yamlafile. This is just a ridiculous example, but I think it is valid to say that these things shouldn't be limited to inherit functionality only from their parents, that they can pick other things up along the way as well. Which is easy to do, right? Dog.something_new = something_new (I wish my stupid dog would learn that easily) Ideally, what I would like to see is something like Ruby's mixins. It seems to me like Ruby developed this out of necessity due to the fact that it does not support multiple inheritance, however I think the implementation is much more pure than inheriting from things that aren't your parents. (although having only a single parent doesn't make much sense either, I believe there are very few actual documented cases of that happening). Here is a Ruby snippet: module ReusableStuff def one_thing "something cool" end end class MyClass < MyParent include ReusableStuff end x = MyClass.new x.one_thing == "something cool" MyClass.superclass == Object So I'm inheriting from MyParent and mixing in additional functionality from ReusableStuff without affecting who my Parents are. This, to me, makes much more sense than using inheritance to just grab a piece of functionality that I want to reuse. I wrote a class decorator for Python that does something similar (https://gist.github.com/1233738) here is a snippet from that: class MyMixin(object): def one_thing(self): return "something cool" @mixin(MyMixin) class MyClass(object): pass x = MyClass() x.one_thing() == 'something cool' x.__class__.__bases__ == (object,) To me, this is much more concise. By looking at this I can tell what MyClass IS, who it's parents are and what else it can do. I'm very interested to know if there are others who feel as dirty as I do when using inheritance for mixins or if there are other things that Python developers are doing to mix in functionality without using inheritance or if the general populous of the Python community disagrees with me and thinks that this is a perfectly valid use of inheritance. I look forward to hearing back. Thanks, Matthew J Morrison www.mattjmorrison.com P.S. - This is a good article about not using inheritance as a code reuse tool: http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/ From rantingrick at gmail.com Thu Sep 22 17:44:03 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 22 Sep 2011 14:44:03 -0700 (PDT) Subject: Python Mixins References: Message-ID: <1b1998c1-150c-49d5-b42b-56fe117e7ad6@eb1g2000vbb.googlegroups.com> On Sep 22, 4:14?pm, Matt wrote: > (although having only a single parent doesn't > make much sense either, I believe there are very few actual documented > cases of that happening). There is nothing wrong with an object having only one parent. Most times the reasons are for maintainability. I might have a TextEditor that exposes all the generic functionality that are ubiquitous to text editors and then a FancyTextEditor(TextEditor) that exposes functionality that is unique to a confined set of text editing uses. A silly example, but proves the point. Do not judge an object by the number of prodigy. From t at jollybox.de Thu Sep 22 18:09:08 2011 From: t at jollybox.de (Thomas Jollans) Date: Fri, 23 Sep 2011 00:09:08 +0200 Subject: Python Mixins In-Reply-To: References: Message-ID: <4E7BB204.90902@jollybox.de> On 2011-09-22 23:14, Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. > > Inheritance is a very powerful tool, and multiple inheritance is an > even more powerful tool. These tools have their uses, but I feel like > "mixing in" functionality is not one of them. There are much different > reasons and uses for inheriting functionality from a parent and mixing > in functionality from elsewhere. > > As a person, you learn certain things from your parents, you learn > other things from your peers all of those things put together becomes > you. Your peers are not your parents, that would not be possible. You > have completely different DNA and come from a completely different > place. > > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > I think this is an excellent use of multiple inheritance. One could also have a construction like this: class Dog (Animal) class YamlafialbleDog (Dog, Yamlafiable) ... which you may be more comfortable with. In you above example, yes, a Dog object is a Yamlafiable object. If you need a Yamlafiable object, you can use a Cat or Dog. That's what inheritance is about. In Python or Ruby, this way of doing things is not all that different from the one you present below. Here, it doesn't really matter. In strictly typed languages, it makes a world of difference. What if you don't care what kind of object you're dealing with, as long as it supports the interface a certain mixin provides? In Python, true, duck typing will do the trick. In C++, for example, where you could use the C preprocessor to do something like Ruby mixins, multiple inheritance is a lot more useful for mixing in something that has a public interface. The Vala language, and, I suppose the GObject type system, actually allows interfaces to act as mixins. This is really a more formalised way of doing just this: using multiple inheritance (which, beyond interfaces, Vala does not support) to mix in functionality. Oh and your thing looks kind of neat. Thomas > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. > > This is just a ridiculous example, but I think it is valid to say that > these things shouldn't be limited to inherit functionality only from > their parents, that they can pick other things up along the way as > well. Which is easy to do, right? > > Dog.something_new = something_new > > (I wish my stupid dog would learn that easily) > > Ideally, what I would like to see is something like Ruby's mixins. It > seems to me like Ruby developed this out of necessity due to the fact > that it does not support multiple inheritance, however I think the > implementation is much more pure than inheriting from things that > aren't your parents. (although having only a single parent doesn't > make much sense either, I believe there are very few actual documented > cases of that happening). Here is a Ruby snippet: > > module ReusableStuff > def one_thing > "something cool" > end > end > class MyClass < MyParent > include ReusableStuff > end > > x = MyClass.new > x.one_thing == "something cool" > MyClass.superclass == Object > > So I'm inheriting from MyParent and mixing in additional functionality > from ReusableStuff without affecting who my Parents are. This, to me, > makes much more sense than using inheritance to just grab a piece of > functionality that I want to reuse. I wrote a class decorator for > Python that does something similar (https://gist.github.com/1233738) > here is a snippet from that: > > class MyMixin(object): > def one_thing(self): > return "something cool" > > @mixin(MyMixin) > class MyClass(object): > pass > > x = MyClass() > x.one_thing() == 'something cool' > x.__class__.__bases__ == (object,) > > To me, this is much more concise. By looking at this I can tell what > MyClass IS, who it's parents are and what else it can do. I'm very > interested to know if there are others who feel as dirty as I do when > using inheritance for mixins or if there are other things that Python > developers are doing to mix in functionality without using inheritance > or if the general populous of the Python community disagrees with me > and thinks that this is a perfectly valid use of inheritance. > > I look forward to hearing back. > > Thanks, > Matthew J Morrison > www.mattjmorrison.com > > > P.S. - This is a good article about not using inheritance as a code > reuse tool: http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/ From tjreedy at udel.edu Thu Sep 22 18:56:54 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Sep 2011 18:56:54 -0400 Subject: Context manager with class methods In-Reply-To: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: On 9/22/2011 6:21 AM, Gavin Panella wrote: > On Python 2.6 and 3.1 the following code works fine: > class Foo(object): > @classmethod > def __enter__(cls): > print("__enter__") > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass This could be regarded as a bug, see below. > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ type(Foo) == type and type has no such attribute. Unless otherwise specified, 'method' typically means 'instance method'. In particular, the '__xxx__' special methods are (all?) (intended to be) instance methods, which is to say, functions that are attributes of an object's class. So it is normal to look for special methods on the class (and superclasses) of an object rather than starting with the object itself. For instance, when executing 'a+b', the interpreter never looks for __add__ as an attribute of a itself (in a.__dict__) but starts the search looking for with type(a).__add__ > Is this a regression or a deliberate change? Off the top of my head I > can't think that this pattern is particularly useful, but it seems > like something that ought to work. I suspect there was a deliberate change to correct an anomaly, though this might have been done as part of some other change. As Thomas noted, *instances* of Foo work and as Mei noted, making Foo an instance of a (meta)class with the needed methods also works. -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 22 19:14:42 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Sep 2011 19:14:42 -0400 Subject: Negativ nearest interger? In-Reply-To: References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: On 9/22/2011 7:44 AM, Jussi Piitulainen wrote: > joni writes: >> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) > ... >>>>> -7/3 >> -3 In late Python 2 you *can* and in Python 3 you *must* use // rather than / to get an int result. >> -3 are more wrong than -2. Negativ number seems not to round to >> nearest interger, but the integer UNDER the anwser!! Or? >> Why? > > It simply does not round to the nearest integer. It floors. This has > nicer mathematical properties. In particular, it allows the remainder > (notated as "per cent") operation (n % m) to return a number that > differs from n by a multiple of m ("is congruent to n modulo m"). > These two operations go together. The Python doc set has a FAQ collection. I recommend you read the questions for those you might be interested in. In the Programming FAQ: "Why does -22 // 10 return -3? It?s primarily driven by the desire that i % j have the same sign as j. If you want that, and also want: i == (i // j) * j + (i % j) then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate i // j need to make i % j have the same sign as i. There are few real use cases for i % j when j is negative. When j is positive, there are many, and in virtually all of them it?s more useful for i % j to be >= 0. If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite." -- Terry Jan Reedy From rosuav at gmail.com Thu Sep 22 19:22:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 09:22:44 +1000 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 23, 2011 at 4:14 AM, Steven D'Aprano wrote: > What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the > random module is mostly Python. There is an import of _random, which > presumably is in C, but it doesn't have a randint method: True. It seems to be defined in cpython/lib/random.py as a reference to randrange, which does a pile of error checking and calls _randbelow... which does a whole lot of work as well as calling random(). Guess I should have checked the code before asking! There's probably good reasons for using randint(), but if you just want a pile of more-or-less random integers, int(random.random()*top) is the best option. > I'm not seeing any significant difference in speed between 2.6 and 3.2: > > [steve at sylar ~]$ python2.6 -m timeit -s "from random import > randint" "randint(0, 1000000)" > 100000 loops, best of 3: 4.29 usec per loop > > [steve at sylar ~]$ python3.2 -m timeit -s "from random import > randint" "randint(0, 1000000)" > 100000 loops, best of 3: 4.98 usec per loop That might be getting lost in the noise. Try the list comp that I had above and see if you can see a difference - or anything else that calls randint that many times. Performance-testing with a heapsort (and by the way, it's _ridiculously_ slower implementing it in Python instead of just calling a.sort(), but we all knew that already!) shows a similar difference in performance. As far as I know, everything's identical between the two (I use // division so there's no floating point getting in the way, for instance), but what takes 90 seconds on Py2 takes 150 seconds on Py3. As with the randint test, I switched int() to long() to test Py2, and that slowed it down a little, but still far far below the Py3 time. I've pasted the code I'm using here: http://pastebin.com/eQPHQhD0 Where's the dramatic performance difference? Or doesn't it matter, since anything involving this sort of operation needs to be done in C anyway? ChrisA From skippy.hammond at gmail.com Thu Sep 22 19:47:12 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 23 Sep 2011 09:47:12 +1000 Subject: PyEval_EvalCodeEx return value In-Reply-To: <4E786C42.3050309@loskot.net> References: <4E786C42.3050309@loskot.net> Message-ID: <4E7BC900.9010103@gmail.com> On 20/09/2011 8:34 PM, Mateusz Loskot wrote: > Hi, > > I'm trying to dig out details about what exactly is the return > value the of PyEval_EvalCodeEx function in Python 3.x > The documentation is sparse, unfortunately. > > Perhaps I'm looking at wrong function. > My aim is simple, I need to execute Python code using Python interpreter > embedded in my C++ application. > The Python code is a simple script that always returns single value. > For example: > > #! /usr/bin/env python > def foo(a, b): > return a + b > f = foo(2, 3) > > But, f can be of different type for different script: one returns > numeric value, another returns a sequence, so the type is not > possible to be determined in advance. > > I know how to capture Python stdout/stderr. > > I also know how to access the "f" attribute using > PyObject_GetAttrString and then I can convert "f" value to C++ type > depending on PyObject type. > > However, I guess there shall be a way to access "f" value > directly from PyEval_EvalCode return object: > > PyObject* evalRet = ::PyEval_EvalCode(...); > > But, I can't find any details what the "evalRet" actually is. Eval is to eval an expression. If you simply eval the expression "f" in the context of the module you should get the result returned. Obviously though it is designed to eval more complex expressions and in your specific example, doing the getattr thing will also work fine. Mark From jesus.ramirez.utexas at gmail.com Thu Sep 22 20:36:45 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Thu, 22 Sep 2011 17:36:45 -0700 (PDT) Subject: Python 2.5 zlib trouble Message-ID: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Hello, I am trying to deploy an app on google app engine using bottle, a micro-framework, similar to flask. I am running on ubuntu which comes with python 2.7 installed but GAE needs version 2.5, so I installed 2.5. I then realized I didn't use make altinstall so I may have a default version problem now. But my real problem is that when I try to use the gae server to test locally I get the following error: Traceback (most recent call last): File "/opt/google/appengine/dev_appserver.py", line 77, in run_file(__file__, globals()) File "/opt/google/appengine/dev_appserver.py", line 73, in run_file execfile(script_path, globals_) File "/opt/google/appengine/google/appengine/tools/ dev_appserver_main.py", line 156, in from google.appengine.tools import dev_appserver File "/opt/google/appengine/google/appengine/tools/ dev_appserver.py", line 94, in import zlib ImportError: No module named zlib Can you help me with this? From anacrolix at gmail.com Fri Sep 23 01:44:25 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Fri, 23 Sep 2011 15:44:25 +1000 Subject: python install on locked down windows box? In-Reply-To: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: 5 is the best solution, followed by 2 and 3. On Sep 22, 2011 11:02 PM, "Steven D'Aprano" < steve+comp.lang.python at pearwood.info> wrote: > Chris Withers wrote: > >> Hi All, >> >> Is there a way to install python on a locked down Windows desktop? >> (ie: no compilers, no admin rights, etc) > > (1) Bribe or blackmail the fascist system administrator. > > (2) Hack into the system with any of dozens of unpatched vulnerabilities > that will give you admin rights. > > (3) Sneak into the office at 3 in the morning and replace the desktop with > an identical machine which you have admin rights to. > > (4) Guess the admin password -- it's not hard, most fascist system > administrators can't remember words with more than four letters, so the > password is probably something like "passw" or, if he's being especially > cunning, "drows". > > (5) "Accidentally" install Linux on the machine and use that instead. > > (6) Take hostages. > > (7) If all else fails, as an absolute last resort, simply run the Windows > installer as a regular, unprivileged user, after selecting the option for a > Non-Admin Install under Advanced Options first. You could also try the > ActivePython installer. > > http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ > http://diveintopython.org/installing_python/windows.html > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Fri Sep 23 01:59:12 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 23 Sep 2011 06:59:12 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Thu, 22 Sep 2011 11:19:28 -0700, Atherun wrote: >> I suggest obtaining a copy of Process Explorer, and using it to >> investigate the state of both processes (but especially the child) at the >> point that the "deadlock" seems to occur. > > In the one case I can easily reproduce, its in a p4.exe call that I'm > making both python and p4.exe have nearly the same stack for their > threads: > python: > kernel32.dll!WaitForSingleObject+0x12 > python26.dll!_Py_svnversion+0xcf8 I haven't a clue how this happens. _Py_svnversion just returns a string: _Py_svnversion(void) { /* the following string can be modified by subwcrev.exe */ static const char svnversion[] = SVNVERSION; if (svnversion[0] != '$') return svnversion; /* it was interpolated, or passed on command line */ return "Unversioned directory"; } It doesn't even From rosuav at gmail.com Fri Sep 23 03:08:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 17:08:39 +1000 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > It doesn't even > You intrigue me, sir. Does it odd? What is the remainder of this aborted sentence? ChrisA From chris at simplistix.co.uk Fri Sep 23 03:46:41 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 08:46:41 +0100 Subject: TestFixtures 2.0.0 Released! Message-ID: <4E7C3961.8020107@simplistix.co.uk> Hi All, I'm happy to announce a new release major release of TestFixtures. This release is 99% backwards compatible, but a lot has changed under the hood and there's some major new functionality, so thought it was time for a bump. The big changes are: - compare now uses a registry of comparers in the same way that unitest2's assertEquals does. You can register your own globally, register the default comparers for your own types and use a specific registry for a specific call to compare. - The handling of timezones has been reworked in `test_datetime` again. (did anyone ever mention that timezones are hard ;-) ) It feels more intuitive now, but it is backwards incompatible in the case where the `tzinfo` parameter to the `test_datetime` constructor was used. For details, read: http://packages.python.org/testfixtures/datetime.html#timezones The full list of changes can be found here: http://packages.python.org/testfixtures/changes.html The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From steve+comp.lang.python at pearwood.info Fri Sep 23 04:11:03 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 23 Sep 2011 18:11:03 +1000 Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> Jesramz wrote: > Hello, > > I am trying to deploy an app on google app engine using bottle, a > micro-framework, similar to flask. [...] > ImportError: No module named zlib What happens if you explicitly launch Python2.5 and then try to import zlib? -- Steven From andrea.crotti.0 at gmail.com Fri Sep 23 05:12:10 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 10:12:10 +0100 Subject: extending class Message-ID: <4E7C4D6A.8050107@gmail.com> I wanted to add a couple of parameters to a class from a given library (paste-script), but without changing the original code. So I thought, I create a wrapper class which adds what I need, and then dispatch all the calls to the super class. My following attempt gives, however, a recursion error, but why? class PSIVar(object): """Extend var implementation from the paste-script, to add the ability of correlating variables >>> v = var("name", "desc") >>> v.name == 'name' True >>> v1 = PSIVar(v) >>> v1.name == 'name' True """ def __init__(self, first_var, other=None, fun=None): # this is of type defined there self.first_var = first_var if other is not None: self.other = other self.fun = fun assert callable(self.fun) # now try to dispatch every method call to the other class # must probably call the super class def __getattribute__(self, attr): return self.first_var.__getattribute__(attr) From duncan.booth at invalid.invalid Fri Sep 23 05:19:09 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Sep 2011 09:19:09 GMT Subject: Python Mixins References: Message-ID: Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. > I think Mixins are great, in moderation, but wait until you have to debug code on an object with 70 base classes. Reinout van Rees wrote a very insightful article recently about Django's use of multiple inheritance: http://reinout.vanrees.org/weblog/2011/08/23/class-based-views.html He points out the problems that arise from overuse of mixins; why Zope went through so much upheaval to get away from mixins everywhere and switched to a component architecture instead; and suggests that Django will do the same in a few years time. -- Duncan Booth http://kupuguy.blogspot.com From __peter__ at web.de Fri Sep 23 05:31:30 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Sep 2011 11:31:30 +0200 Subject: extending class References: <4E7C4D6A.8050107@gmail.com> Message-ID: Andrea Crotti wrote: > I wanted to add a couple of parameters to a class from a given library > (paste-script), but without changing the original code. > So I thought, I create a wrapper class which adds what I need, and then > dispatch all the calls to the super class. > > My following attempt gives, however, a recursion error, but why? Inside __getattribute__() you ask for self.first_var which triggers another __getattribute__() call that once again trys to determine the first_var attribute before it returns... Try using __getattr__() instead which is only triggered for non-existent attributes def __getattr__(self, name): return getattr(self.first_var, name) or check for the attributes you don't want to delegate explicitly: def __getattribute__(self, name): if name == "first_var": return super(PSIVar, self).__getattribute__(name) return getattr(self.first_var, name) > class PSIVar(object): > """Extend var implementation from the paste-script, to add the > ability of correlating variables > >>> v = var("name", "desc") > >>> v.name == 'name' > True > >>> v1 = PSIVar(v) > >>> v1.name == 'name' > True > """ > def __init__(self, first_var, other=None, fun=None): > # this is of type defined there > self.first_var = first_var > if other is not None: > self.other = other > self.fun = fun > assert callable(self.fun) > > # now try to dispatch every method call to the other class > # must probably call the super class > def __getattribute__(self, attr): > return self.first_var.__getattribute__(attr) From andrea.crotti.0 at gmail.com Fri Sep 23 05:35:49 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 10:35:49 +0100 Subject: extending class In-Reply-To: References: <4E7C4D6A.8050107@gmail.com> Message-ID: <4E7C52F5.5060301@gmail.com> On 09/23/2011 10:31 AM, Peter Otten wrote: > > Inside __getattribute__() you ask for self.first_var which triggers another > __getattribute__() call that once again trys to determine the first_var > attribute before it returns... > > Try using __getattr__() instead which is only triggered for non-existent > attributes > > def __getattr__(self, name): > return getattr(self.first_var, name) > > or check for the attributes you don't want to delegate explicitly: > > def __getattribute__(self, name): > if name == "first_var": > return super(PSIVar, self).__getattribute__(name) > Right thanks a lot it works perfectly. I don't like too much, however, to mess around in this way, maybe it's better if I just fork the project and patch the original code. In this way maybe I can also contribute to it with patches (if they are accepted)... From mateusz at loskot.net Fri Sep 23 05:54:43 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Fri, 23 Sep 2011 10:54:43 +0100 Subject: PyEval_EvalCodeEx return value In-Reply-To: <4E7BC900.9010103@gmail.com> References: <4E786C42.3050309@loskot.net> <4E7BC900.9010103@gmail.com> Message-ID: <4E7C5763.3060106@loskot.net> On 23/09/11 00:47, Mark Hammond wrote: > On 20/09/2011 8:34 PM, Mateusz Loskot wrote: >> >> I'm trying to dig out details about what exactly is the return >> value the of PyEval_EvalCodeEx function in Python 3.x >> The documentation is sparse, unfortunately. >> >> Perhaps I'm looking at wrong function. >> My aim is simple, I need to execute Python code using Python interpreter >> embedded in my C++ application. >> The Python code is a simple script that always returns single value. >> For example: >> >> #! /usr/bin/env python >> def foo(a, b): >> return a + b >> f = foo(2, 3) >> >> But, f can be of different type for different script: one returns >> numeric value, another returns a sequence, so the type is not >> possible to be determined in advance. >> >> I know how to capture Python stdout/stderr. >> >> I also know how to access the "f" attribute using >> PyObject_GetAttrString and then I can convert "f" value to C++ type >> depending on PyObject type. >> >> However, I guess there shall be a way to access "f" value >> directly from PyEval_EvalCode return object: >> >> PyObject* evalRet = ::PyEval_EvalCode(...); >> >> But, I can't find any details what the "evalRet" actually is. > > Eval is to eval an expression. If you simply eval the expression "f" in > the context of the module you should get the result returned. Obviously > though it is designed to eval more complex expressions and in your > specific example, doing the getattr thing will also work fine. Hi Mark, So, the result of PyEval_EvalCode strictly depends on the code being evaluated. It makes sense. Thanks for help! Best regards, -- Mateusz Loskot, http://mateusz.loskot.net Charter Member of OSGeo, http://osgeo.org Member of ACCU, http://accu.org From gelonida at gmail.com Fri Sep 23 06:23:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Fri, 23 Sep 2011 12:23:57 +0200 Subject: cProfile and name spaces. Message-ID: Hi I have following piece of code in file f1.py ##### f1.py starts here ####### def f(): pass def main(): import profile profile.run('f()') if __name__ == '__main__': main() # ------ end of f1.py ---- executing f1.py works as expected. Now I have a file f2.py ##### f2.py starts here ####### import f1 f1.main() # ------ end of f2.py ---- If I run f2.py I get the error message: . . . . > File "C:\Python26\lib\profile.py", line 70, in run > prof = prof.run(statement) > File "C:\Python26\lib\profile.py", line 456, in run > return self.runctx(cmd, dict, dict) > File "C:\Python26\lib\profile.py", line 462, in runctx > exec cmd in globals, locals > File "", line 1, in > NameError: name 'f' is not defined So cProfile doesn't find my function f any more. I can fix this by changing the code in f1.py to profile.run('f1.f()') However now I can't run f1.py anymore. Is it intentional, that cProfile always uses the name space of the initial module? I consider it surprising especially as I did not find any mentioning of this particularity in the documentation, which states: > cProfile.run(command[, filename]) > > This function takes a single argument that can be passed to the exec > statement, and an optional file name. In all cases this routine attempts > to exec its first argument, and gather profiling statistics from the > execution. If no file name is present, then this function automatically > prints a simple profiling report, sorted by the standard name string > (file/line/function-name) that is presented in each line. The following > is a typical output from such a call: I'm using python 2.6.5 The reason why I don't profile at the top level is, that I do not want to profile some parts of the code and as I want to conditionally profile a cetain function within different contexts / applications WI have also difficulties implementing something like this in a module, which is not the main module. arg1 = f(1) arg2 = f2() if do_profile: CProfile('result = function_name(arg1, arg2)', fname) else: result = function_name(arg1, arg2) Any tips / suggestions?? From andrea.crotti.0 at gmail.com Fri Sep 23 07:02:00 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 12:02:00 +0100 Subject: Develop inter-dependent eggs Message-ID: <4E7C6728.7040500@gmail.com> Develop inter-dependent eggs: On a Linux machine I have many eggs to develop, for example - egg1 - egg2 ... Now the eggs depend from each other, so running "python setup.py develop" in order, doesn't work, because if the dependency required is not already installed then easy_install tries to fetch it from PyPi. I looked around everywhere, but I can't find any feasible option, how do I tell easy_install to install the dependencies needed from a filesystem position and not from the PyPi server? From yasar11732 at gmail.com Fri Sep 23 07:44:27 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Fri, 23 Sep 2011 14:44:27 +0300 Subject: Need help with file encoding-decoding Message-ID: Hi, I'am trying to write a mass html downloader, and it processes files after it downloaded them. I have problems with encodings, and decodings. Sometimes I get UnicodeDecodeErrors, or I get half-pages in after processing part. Or more generally, some things don't feel right. Can you check my approach, and provide me some feedback please? Here is what I am doing. 1) send a HEAD request to file's source to get file encoding, set encoding variable accordingly. 2) if server doesn't provide an encoding, set encoding variable as utf-8 3) read html page from internet, read it to a variable let's say content. 4) in this step, I need to parse the content I get, because I will search for further links \ I feed content to parser (subclass of HTMLParser.HTMLParser) like this -> content.decode(encoding) 5) open a file in binary mod open(file_path,"wb") 6) I write as I read without modifing. ########## # After processing part.... ########## (Note: encoding variable is same as the downloading part) 1) open local file in binary mod for reading file_name = open(file_path,"rb") 2) decode the file contents into a variable => decoded_content = file_name.read().decode(encoding) 3) send decoded content to a parser, parser contstruct new html content. (as str) 4) open same file for writing, in binary mod, write parsers output like this: file_name.write(parser.output.encode(encoding)) -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Fri Sep 23 07:52:40 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 12:52:40 +0100 Subject: [TIP] TestFixtures 2.0.0 Released! In-Reply-To: <4E7C3961.8020107@simplistix.co.uk> References: <4E7C3961.8020107@simplistix.co.uk> Message-ID: <4E7C7308.7020709@simplistix.co.uk> On 23/09/2011 08:46, Chris Withers wrote: > I'm happy to announce a new release major release of TestFixtures. > This release is 99% backwards compatible, but a lot has changed under > the hood and there's some major new functionality, so thought it was > time for a bump. Of course, a 2.0.0 release wouldn't be complete without a fairly show-stopping lack of backwards compatibility... Thankfully, I've managed to return the case (comparison of generators with iterators) to its previous state with the 2.0.1 release I've just pushed out... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From python at bdurham.com Fri Sep 23 08:09:40 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 23 Sep 2011 08:09:40 -0400 Subject: python install on locked down windows box? In-Reply-To: References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1316779780.12406.140258146888625@webmail.messagingengine.com> Hi Matt, Enjoyed your list options :) I'm a consultant and have to do what your subject line asks at most clients I work at. Here's the technique I recommend: Install Python for the ***current user*** on another workstation with the appropriate priviledges. Then xcopy this Python folder to a USB drive. Then xcopy this folder from your USB drive to a matching folder on your locked down workstation. The xcopy-ed version of Python will run without problems when you start the python.exe executable from a command line with a python script as a command line parameter. The only thing you won't be able to do is click on .py* files and have them automatically invoke the Python interpreter because file associations require admin rights to update the registery. I don't consider this a big deal. Good luck! Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Fri Sep 23 09:14:15 2011 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 23 Sep 2011 09:14:15 -0400 Subject: Need help with file encoding-decoding In-Reply-To: References: Message-ID: <6CE93FA9-E24F-4FB7-ABA2-24F2F611978A@semanchuk.com> On Sep 23, 2011, at 7:44 AM, Ya?ar Arabac? wrote: > Hi, > > I'am trying to write a mass html downloader, and it processes files after it > downloaded them. I have problems with encodings, and decodings. Sometimes I > get UnicodeDecodeErrors, or > I get half-pages in after processing part. Or more generally, some things > don't feel right. Can you check my approach, and provide me some feedback > please? Here is what I am doing. > > 1) send a HEAD request to file's source to get file encoding, set encoding > variable accordingly. Hi Ya?ar This is a pretty optimistic algorithm, at least by the statistics from 2008 (see below). > 2) if server doesn't provide an encoding, set encoding variable as utf-8 This is statistically a good guess but it doesn't follow the HTTP specification. > 4) in this step, I need to parse the content I get, because I will search > for further links \ > I feed content to parser (subclass of HTMLParser.HTMLParser) like Does HTMLParser.HTMLParser handle broken HTML? Because there's lots of it out there. I used to run an automated site validator, and I wrote a couple of articles you might find interesting. One is about how to get the encoding of a Web page: http://NikitaTheSpider.com/articles/EncodingDivination.html I also wrote an article examining the statistics I'd seen run through the crawler/validator. One thing I saw was that almost 2/3 of Web pages specified the encoding in the META HTTP-EQUIV Content-Type tag rather than in the HTTP Content-Type header. Mind you, this was three years ago so the character of the Web has likely changed since then, but probably not too dramatically. http://NikitaTheSpider.com/articles/ByTheNumbers/fall2008.html You can also do some straightforward debugging. Save the raw bytes you get from each site, and when you encounter a decode error, check the raw bytes. Are they really in the encoding specified? Webmasters make all kinds of mistakes. Hope this helps Philip > this -> content.decode(encoding) > 5) open a file in binary mod open(file_path,"wb") > 6) I write as I read without modifing. > > ########## > # After processing part.... > ########## > > (Note: encoding variable is same as the downloading part) > > 1) open local file in binary mod for reading file_name = > open(file_path,"rb") > 2) decode the file contents into a variable => decoded_content = > file_name.read().decode(encoding) > 3) send decoded content to a parser, parser contstruct new html content. (as > str) > 4) open same file for writing, in binary mod, write parsers output like > this: file_name.write(parser.output.encode(encoding)) > -- > http://yasar.serveblog.net/ > -- > http://mail.python.org/mailman/listinfo/python-list From jeanmichel at sequans.com Fri Sep 23 09:17:53 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 23 Sep 2011 15:17:53 +0200 Subject: extending class In-Reply-To: <4E7C52F5.5060301@gmail.com> References: <4E7C4D6A.8050107@gmail.com> <4E7C52F5.5060301@gmail.com> Message-ID: <4E7C8701.5020302@sequans.com> Andrea Crotti wrote: > On 09/23/2011 10:31 AM, Peter Otten wrote: >> >> Inside __getattribute__() you ask for self.first_var which triggers >> another >> __getattribute__() call that once again trys to determine the first_var >> attribute before it returns... >> >> Try using __getattr__() instead which is only triggered for non-existent >> attributes >> >> def __getattr__(self, name): >> return getattr(self.first_var, name) >> >> or check for the attributes you don't want to delegate explicitly: >> >> def __getattribute__(self, name): >> if name == "first_var": >> return super(PSIVar, self).__getattribute__(name) >> > > Right thanks a lot it works perfectly. > I don't like too much, however, to mess around in this way, maybe it's > better if I just fork the project > and patch the original code. > > In this way maybe I can also contribute to it with patches (if they > are accepted)... Did you consider subclassing your Var class ? This is how you extend a class behavior in OOP. class PSIVar(var): def __init__(self, name, desc, other=None, fun=None): var.__init__(self, name, desc) if other is not None: self.other = other self.fun = fun assert callable(self.fun) v1 = PSIVar('name', 'desc') that's it. By the way, don't create instance attribute conditionally. Your PSIVar instance should always have a 'other' attribute, its value can be None though. JM From bahamutzero8825 at gmail.com Fri Sep 23 09:57:32 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Fri, 23 Sep 2011 08:57:32 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> <4E7AEAEE.20504@gmail.com> Message-ID: <4E7C904C.3020604@gmail.com> On 2011.09.22 03:12 AM, Chris Angelico wrote: > In theory, this should mean that you load it fresh every time - I > think. If not, manually deleting entries from sys.modules might help, > either with or without the list of modules. I've played around with sys.modules, and it seems there are issues with logging being reloaded (not sure if it's fair to call it a bug), not my module. The only reliable way I've found to start fresh is to delete at least logging from sys.modules (I can even do this from within my module). Even if the module that imports logging is deleted, things in logging persist (I can confirm at least handlers and handles to log files; the latter requiring garbage collection as well to free up). However, this would probably wreak havoc on other code that uses logging (although, I could always import logging as something else). On a side note, this actually gives me a good way to detect that the module is reloaded (I can't think of any other way to detect it, at least not off the top of my head). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From andrea.crotti.0 at gmail.com Fri Sep 23 09:59:56 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 14:59:56 +0100 Subject: extending class In-Reply-To: <4E7C8701.5020302@sequans.com> (Jean-Michel Pichavant's message of "Fri, 23 Sep 2011 15:17:53 +0200") References: <4E7C4D6A.8050107@gmail.com> <4E7C52F5.5060301@gmail.com> <4E7C8701.5020302@sequans.com> Message-ID: <87pqirnyub.fsf@gmail.com> Jean-Michel Pichavant writes: > Did you consider subclassing your Var class ? This is how you extend a > class behavior in OOP. > > class PSIVar(var): > def __init__(self, name, desc, other=None, fun=None): > var.__init__(self, name, desc) > if other is not None: > self.other = other > self.fun = fun > assert callable(self.fun) > > v1 = PSIVar('name', 'desc') > > that's it. > > By the way, don't create instance attribute conditionally. Your PSIVar > instance should always have a 'other' attribute, its value can be None > though. > > > > JM Yes thanks, first I tried that, but I didn't want to have to change my class definition if the one from the library changes. So I started to mess with *args and **kwargs and it was really not beautiful ;) Anyway since I want to other and more deep changes I just forked the project and start work on that... From gmszone at gmail.com Fri Sep 23 10:01:27 2011 From: gmszone at gmail.com (gmszone) Date: Fri, 23 Sep 2011 07:01:27 -0700 (PDT) Subject: Could anybody tell me how to make a version of Nokia Symbian os Message-ID: <9e03e15b-4d1e-4af7-8e80-751ab9e2f35f@f12g2000yqi.googlegroups.com> I like the Python in my mobile phone.But a don't have the enough money to buy a new phone.And my mobile type is Nokia N72 which is a part of S60v2.And I could program in some boring classes.But the version of my mobile's python is to old.So I hope I coule learn how to compile it for my N72.My notebook has the Windows 7 and Ubuntu GNU/Linux.Ask for help..... From steve+comp.lang.python at pearwood.info Fri Sep 23 10:21:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 00:21:53 +1000 Subject: extending class References: Message-ID: <4e7c9602$0$30000$c3e8da3$5496439d@news.astraweb.com> Andrea Crotti wrote: > I wanted to add a couple of parameters to a class from a given library > (paste-script), but without changing the original code. > So I thought, I create a wrapper class which adds what I need, and then > dispatch all the calls to the super class. You don't need to use a wrapper class if all you want is to add additional attributes to an instance. >>> class Spam(object): ... def __init__(self): ... self.x = 1 ... >>> s = Spam() >>> s.name = "Fred" >>> s.name 'Fred' > My following attempt gives, however, a recursion error, but why? Here is an old recipe showing how to do automatic delegation correctly: http://code.activestate.com/recipes/52295/ -- Steven From w.g.sneddon at gmail.com Fri Sep 23 10:25:55 2011 From: w.g.sneddon at gmail.com (python) Date: Fri, 23 Sep 2011 07:25:55 -0700 (PDT) Subject: pyWin build 216 Message-ID: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> I have used pyWin for several years now with out issue. I recently installed build 216 for python 2.7 on windows XP pro. The program crashes every time I exit a wxPython program and has crashed a few other times. I does not seem that pyWin has been updated since February of this year. Is there a direction change for the windows extensions? Is it time I make the move to 3.x? Mark Hammond has given much to the Python community and I do not intend for this post to be negative in any way. From atherun at gmail.com Fri Sep 23 10:58:07 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 07:58:07 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: <5bd0c088-0f46-4e4a-b5c5-9d8de668b50d@v18g2000yqj.googlegroups.com> On Sep 23, 12:08?am, Chris Angelico wrote: > On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > > It doesn't even > > You intrigue me, sir. Does it odd? > > What is the remainder of this aborted sentence? > > ChrisA That is odd, I also find it odd that it deadlocks the entire python system, even threads that have nothing to do with the subprocess stop working, the entire thing just stops. I may not have pasted the full stack trace looking at it again, I'll double check in a few. I was able to repro this on a tool I have the source for, when I attach to it to debug visual studio tells me the threads are deadlocked and the only stack trace I have available to me is a low level os call to a WriteFile function. From brian.curtin at gmail.com Fri Sep 23 11:01:04 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Fri, 23 Sep 2011 10:01:04 -0500 Subject: pyWin build 216 In-Reply-To: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: On Fri, Sep 23, 2011 at 09:25, python wrote: > I have used pyWin for several years now with out issue. ? I recently > installed build 216 for python 2.7 on windows XP pro. ? The program > crashes every time I exit a wxPython program and has crashed a few > other times. ?I does not seem that pyWin has been updated since > February of this year. ? Is there a direction change for the windows > extensions? ?Is it time I make the move to 3.x? ?Mark Hammond has > given much to the Python community and I do not intend for this post > to be negative in any way. pywin32 has been available for 3.x for some time, but you wouldn't be able to use it since you're currently using wxPython. You may want to post a more detailed question to http://mail.python.org/mailman/listinfo/python-win32 -- Mark hangs out there and there are plenty of pywin32 experts around who could help as well. From jesus.ramirez.utexas at gmail.com Fri Sep 23 11:41:59 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 08:41:59 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Python 2.5.6 (r256:88840, Sep 22 2011, 13:45:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import zlib Traceback (most recent call last): File "", line 1, in ImportError: No module named zlib >>> But if I run Python2.7 I get: Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import zlib >>> It seems to work. From chris at simplistix.co.uk Fri Sep 23 13:06:19 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 18:06:19 +0100 Subject: python install on locked down windows box? In-Reply-To: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7CBC8B.8000501@simplistix.co.uk> Hi Steve On 22/09/2011 13:58, Steven D'Aprano wrote: > (7) If all else fails, as an absolute last resort, simply run the Windows > installer as a regular, unprivileged user, after selecting the option for a > Non-Admin Install under Advanced Options first. Thanks for this, will send on to my friend in need... Hadn't seen this before, but it's a long time since I've run the Windows installer ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From atherun at gmail.com Fri Sep 23 13:07:56 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 10:07:56 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <5bd0c088-0f46-4e4a-b5c5-9d8de668b50d@v18g2000yqj.googlegroups.com> Message-ID: <7133358a-3fd0-4dfd-8af7-d8afaa9c6597@z7g2000vbp.googlegroups.com> On Sep 23, 7:58?am, Atherun wrote: > On Sep 23, 12:08?am, Chris Angelico wrote: > > > On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > > > It doesn't even > > > You intrigue me, sir. Does it odd? > > > What is the remainder of this aborted sentence? > > > ChrisA > > That is odd, I also find it odd that it deadlocks the entire python > system, even threads that have nothing to do with the subprocess stop > working, the entire thing just stops. I may not have pasted the full > stack trace looking at it again, I'll double check in a few. > > I was able to repro this on a tool I have the source for, when I > attach to it to debug visual studio tells me the threads are > deadlocked and the only stack trace I have available to me is a low > level os call to a WriteFile function. Ya heres the full python stack: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!__misaligned_access+0xba4 ntoskrnl.exe!__misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!NtWaitForSingleObject+0xde ntoskrnl.exe!KeSynchronizeExecution+0x3a43 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x6c0 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x4a8 wow64.dll!Wow64SystemServiceEx+0x1ce wow64.dll!Wow64LdrpInitialize+0x429 ntdll.dll!RtlUniform+0x6e6 ntdll.dll!RtlCreateTagHeap+0xa7 ntdll.dll!LdrInitializeThunk+0xe ntdll.dll!ZwWaitForSingleObject+0x15 kernel32.dll!WaitForSingleObjectEx+0x43 kernel32.dll!WaitForSingleObject+0x12 python26.dll!_Py_svnversion+0xcf8 python26.dll!PyObject_AsReadBuffer+0x46d python26.dll!PyEval_EvalCodeEx+0x738 python26.dll!PyEval_EvalFrameEx+0x467 python26.dll!PyObject_Realloc+0x90 python26.dll!PyEval_EvalCodeEx+0x8ef python26.dll!PyEval_EvalFrameEx+0x467 From msoulier at digitaltorque.ca Fri Sep 23 13:15:25 2011 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Fri, 23 Sep 2011 13:15:25 -0400 Subject: ANN: Urwid 1.0.0 - Console UI Library In-Reply-To: <4E7B4E9C.7060704@excess.org> References: <4E7B4E9C.7060704@excess.org> Message-ID: <20110923171525.GH2703@digitaltorque.ca> On 22/09/11 Ian Ward said: > Announcing Urwid 1.0.0 > ---------------------- Congrats. From nobody at nowhere.com Fri Sep 23 13:47:20 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 23 Sep 2011 18:47:20 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: >> kernel32.dll!WaitForSingleObject+0x12 >> python26.dll!_Py_svnversion+0xcf8 > > I haven't a clue how this happens. _Py_svnversion just returns a string: In retrospect, I think that's a red herring. 0xcf8 seems like too large an offset for such a small function. I think that it's more likely to be in a non-exported function, and _Py_svnversion just happens to be the last exported symbol prior to that point in the code. From atherun at gmail.com Fri Sep 23 13:59:27 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 10:59:27 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> On Sep 23, 10:47?am, Nobody wrote: > On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: > >> kernel32.dll!WaitForSingleObject+0x12 > >> python26.dll!_Py_svnversion+0xcf8 > > > I haven't a clue how this happens. _Py_svnversion just returns a string: > > In retrospect, I think that's a red herring. 0xcf8 seems like too large an > offset for such a small function. I think that it's more likely to be in a > non-exported function, and _Py_svnversion just happens to be the last > exported symbol prior to that point in the code. I have the call stacks for each python thread running up until the dead lock: # ThreadID: 992 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 5516 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) # ThreadID: 2668 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in run self.stacktraces() File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in stacktraces fout.write(stacktraces()) File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in stacktraces for filename, lineno, name, line in traceback.extract_stack(stack): # ThreadID: 3248 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 7700 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) # ThreadID: 8020 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 4252 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) The StackTracer thread freezes trying to update my output file, and yes I'm trying to 3 tasks in parallel which each one starts by creating a changelist in perforce. This is just an easy repro case for me, it happens with commands other then p4. This almost looks like a threading issue more then the output deadlock. From luch at ank-sia.com Fri Sep 23 14:21:56 2011 From: luch at ank-sia.com (Alexey Luchko) Date: Fri, 23 Sep 2011 21:21:56 +0300 Subject: comments on runpy module Message-ID: <4E7CCE44.8030508@ank-sia.com> Hi! I've just had fun with the runpy module in Python 2.7. I'm writing to share it :) What I've tried is to "load" a python script using runpy.run_path(), take a function from the resulting namespace and call it with arbitrary arguments. All the functions in the namespace seem to be ok. repr(namespace["f"]) gives "". But if the f() is referring the modules namespace (I supposed it is the same as the returned one), all the values appear to be None. Example script.py: """ def f(arg): return g(arg) def g(arg): return arg """ Then running main.py: """ import runpy namespace = runpy.run_path("./script.py") print namespace["f"] print namespace["g"] print namespace["f"]("abc") """ gives such an output """ Traceback (most recent call last): File "main.py", line 7, in print namespace["f"]("abc") File "./script.py", line 2, in f return g(arg) TypeError: 'NoneType' object is not callable """ Reading the Lib/runpy.py I've found, that the temporary module created inside the run_path() calls, is destroyed right after the script.py code executed in the resulting namespace. I suppose that it is ether an issue or a feature that should be documented :) -- Have a good time and a good mood! Alex. From luch at ank-sia.com Fri Sep 23 14:38:36 2011 From: luch at ank-sia.com (Alexey Luchko) Date: Fri, 23 Sep 2011 21:38:36 +0300 Subject: comments on runpy module In-Reply-To: <4E7CCE44.8030508@ank-sia.com> References: <4E7CCE44.8030508@ank-sia.com> Message-ID: <4E7CD22C.5040308@ank-sia.com> > Example script.py: """ > def f(arg): > return g(arg) > > def g(arg): > return arg > """ > Reading the Lib/runpy.py I've found, that the temporary module created > inside the run_path() calls, is destroyed right after the script.py code > executed in the resulting namespace. I've got an idea. It would be nice if there existed such a way to use it: with runpy.run_path("script.py") as a_namespace: a_namespace["f"]("abc") -- Regards, Alex. From Phillip.M.Feldman at gmail.com Fri Sep 23 16:09:32 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 23 Sep 2011 13:09:32 -0700 (PDT) Subject: strange behavior from recursive generator Message-ID: <32503886.post@talk.nabble.com> A few weeks ago, I wrote a class that creates an iterator for solving the general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert converted my code to a generator, which made the code cleaner, and I subsequently simplified it somewhat further. My problem is the following: All of these versions of the code work fine for very small problems, but do not produce the full set of occupancy distributions for larger problems. The following sample input and output show what happens with two balls and two boxes (to keep things simple, I've made the boxes large enough so that each box can hold both balls). In [6]: x= balls_in_labeled_boxes(2,[2,2]) In [7]: list(x) balls=2, box_sizes=[2, 2] About to make recursive call. balls_in_other_boxes=0, box_sizes=[2] i=0, distribution_other=(0,) About to make recursive call. balls_in_other_boxes=1, box_sizes=[2] i=0, distribution_other=(1,) About to make recursive call. balls_in_other_boxes=2, box_sizes=[2] i=0, distribution_other=(2,) Out[7]: [(2, 0), (1, 1), (0, 2)] Note that Out[7] above gives the correct result, showing all three possible distributions. Now lets try the same thing with three boxes. In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) In [9]: list(x) balls=2, box_sizes=[2, 2, 2] About to make recursive call. balls_in_other_boxes=0, box_sizes=[2, 2] i=0, distribution_other=(0, 0) About to make recursive call. balls_in_other_boxes=1, box_sizes=[2, 2] i=0, distribution_other=(1, 0) About to make recursive call. balls_in_other_boxes=2, box_sizes=[2, 2] i=0, distribution_other=(2, 0) i=1, distribution_other=(1, 1) Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] When there are no balls in the initial box, the recursive call should produce the same three occupancy distributions that we saw above, but one of them is now missing. If someone can shed light on why this is happening, I'd be grateful. Phillip http://old.nabble.com/file/p32503886/balls_in_labeled_boxes.py balls_in_labeled_boxes.py -- View this message in context: http://old.nabble.com/strange-behavior-from-recursive-generator-tp32503886p32503886.html Sent from the Python - python-list mailing list archive at Nabble.com. From arnodel at gmail.com Fri Sep 23 16:26:13 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 23 Sep 2011 21:26:13 +0100 Subject: strange behavior from recursive generator In-Reply-To: <32503886.post@talk.nabble.com> References: <32503886.post@talk.nabble.com> Message-ID: On 23 September 2011 21:09, Dr. Phillip M. Feldman wrote: > > A few weeks ago, I wrote a class that creates an iterator for solving the > general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert > converted my code to a generator, which made the code cleaner, and I > subsequently simplified it somewhat further. > > My problem is the following: All of these versions of the code work fine for > very small problems, but do not produce the full set of occupancy > distributions for larger problems. The following sample input and output > show what happens with two balls and two boxes (to keep things simple, I've > made the boxes large enough so that each box can hold both balls). > > In [6]: x= balls_in_labeled_boxes(2,[2,2]) > > In [7]: list(x) > balls=2, box_sizes=[2, 2] > About to make recursive call. ?balls_in_other_boxes=0, box_sizes=[2] > i=0, distribution_other=(0,) > About to make recursive call. ?balls_in_other_boxes=1, box_sizes=[2] > i=0, distribution_other=(1,) > About to make recursive call. ?balls_in_other_boxes=2, box_sizes=[2] > i=0, distribution_other=(2,) > Out[7]: [(2, 0), (1, 1), (0, 2)] > > Note that Out[7] above gives the correct result, showing all three possible > distributions. Now lets try the same thing with three boxes. > > In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) > > In [9]: list(x) > balls=2, box_sizes=[2, 2, 2] > About to make recursive call. ?balls_in_other_boxes=0, box_sizes=[2, 2] > i=0, distribution_other=(0, 0) > About to make recursive call. ?balls_in_other_boxes=1, box_sizes=[2, 2] > i=0, distribution_other=(1, 0) > About to make recursive call. ?balls_in_other_boxes=2, box_sizes=[2, 2] > i=0, distribution_other=(2, 0) > i=1, distribution_other=(1, 1) > Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] > > When there are no balls in the initial box, the recursive call should > produce the same three occupancy distributions that we saw above, but one of > them is now missing. If someone can shed light on why this is happening, I'd > be grateful. Line 46: for distribution_other in _balls_in_unlabeled_boxes( Should be: for distribution_other in _balls_in_labeled_boxes( HTH -- Arnaud From lists at cheimes.de Fri Sep 23 17:20:44 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 23 Sep 2011 23:20:44 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Message-ID: Am 23.09.2011 17:41, schrieb Jesramz: > Python 2.5.6 (r256:88840, Sep 22 2011, 13:45:58) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import zlib > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named zlib Are you running a self-compiled installation of Python 2.5 on recent Debian or Ubuntu? Check out my blog http://lipyrary.blogspot.com/2011/05/how-to-compile-python-on-ubuntu-1104.html Christian From jesus.ramirez.utexas at gmail.com Fri Sep 23 17:34:16 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 14:34:16 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Message-ID: <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Thank You Christian Im running on Ubuntu Natty and I am not running a self-compiled install, its a regular release. In order to do this: $ make distclean $ export LDFLAGS="-L/usr/lib/$(dpkg-architecture - qDEB_HOST_MULTIARCH)" $ ./configure $ make $ make install $ unset LDFLAGS If you can, can you explain the steps for this, can I run this in a regular release of Python2.5? From phillip.m.feldman at gmail.com Fri Sep 23 19:42:13 2011 From: phillip.m.feldman at gmail.com (Phillip Feldman) Date: Fri, 23 Sep 2011 16:42:13 -0700 Subject: strange behavior from recursive generator In-Reply-To: References: <32503886.post@talk.nabble.com> Message-ID: I don't know how many times I stared at that code without seeing the error. Thanks so much! Phillip On Fri, Sep 23, 2011 at 1:26 PM, Arnaud Delobelle wrote: > On 23 September 2011 21:09, Dr. Phillip M. Feldman > wrote: > > > > A few weeks ago, I wrote a class that creates an iterator for solving the > > general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert > > converted my code to a generator, which made the code cleaner, and I > > subsequently simplified it somewhat further. > > > > My problem is the following: All of these versions of the code work fine > for > > very small problems, but do not produce the full set of occupancy > > distributions for larger problems. The following sample input and output > > show what happens with two balls and two boxes (to keep things simple, > I've > > made the boxes large enough so that each box can hold both balls). > > > > In [6]: x= balls_in_labeled_boxes(2,[2,2]) > > > > In [7]: list(x) > > balls=2, box_sizes=[2, 2] > > About to make recursive call. balls_in_other_boxes=0, box_sizes=[2] > > i=0, distribution_other=(0,) > > About to make recursive call. balls_in_other_boxes=1, box_sizes=[2] > > i=0, distribution_other=(1,) > > About to make recursive call. balls_in_other_boxes=2, box_sizes=[2] > > i=0, distribution_other=(2,) > > Out[7]: [(2, 0), (1, 1), (0, 2)] > > > > Note that Out[7] above gives the correct result, showing all three > possible > > distributions. Now lets try the same thing with three boxes. > > > > In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) > > > > In [9]: list(x) > > balls=2, box_sizes=[2, 2, 2] > > About to make recursive call. balls_in_other_boxes=0, box_sizes=[2, 2] > > i=0, distribution_other=(0, 0) > > About to make recursive call. balls_in_other_boxes=1, box_sizes=[2, 2] > > i=0, distribution_other=(1, 0) > > About to make recursive call. balls_in_other_boxes=2, box_sizes=[2, 2] > > i=0, distribution_other=(2, 0) > > i=1, distribution_other=(1, 1) > > Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] > > > > When there are no balls in the initial box, the recursive call should > > produce the same three occupancy distributions that we saw above, but one > of > > them is now missing. If someone can shed light on why this is happening, > I'd > > be grateful. > > Line 46: > > for distribution_other in _balls_in_unlabeled_boxes( > > Should be: > > > for distribution_other in _balls_in_labeled_boxes( > > HTH > > -- > Arnaud > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Fri Sep 23 20:07:54 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 24 Sep 2011 12:07:54 +1200 Subject: Context manager with class methods In-Reply-To: References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: <9e4lasFv7sU1@mid.individual.net> Terry Reedy wrote: > it is normal to look for special methods on the class (and superclasses) > of an object rather than starting with the object itself. > I suspect there was a deliberate change to correct an anomaly, though > this might have been done as part of some other change. It's a necessary consequence of the fact that new-style classes are also instances. Without it, there would be an ambiguity as to whether a special method defined the behaviour of instances of a class or of the class object itself. It also increases efficiency, because for those special methods that correspond to C-level type slots, you only have to look in the type slot to find an implementation of the method, rather than having to look in the instance dict first. -- Greg From alec.taylor6 at gmail.com Fri Sep 23 20:53:06 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 24 Sep 2011 10:53:06 +1000 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: No idea, as I said before, if you ask for it they might put in the alpha. On Sat, Sep 24, 2011 at 8:30 AM, Jesse Ramirez wrote: > > Thanks Alec, might you know when the 2.7 support might come? From jesus.ramirez.utexas at gmail.com Fri Sep 23 21:19:39 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 18:19:39 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: <5f064e18-57ab-4a7a-b855-e212bb84711d@l4g2000vbz.googlegroups.com> Thank You Christian Im running on Ubuntu Natty and I am not running a self-compiled install, its a regular release. In order to do this: $ make distclean $ export LDFLAGS="-L/usr/lib/$(dpkg-architecture - qDEB_HOST_MULTIARCH)" $ ./configure $ make $ make install $ unset LDFLAGS If you can, can you explain the steps for this, can I run this in a regular release of Python2.5? From ricky85.phone at gmail.com Fri Sep 23 21:42:44 2011 From: ricky85.phone at gmail.com (Ricardo) Date: Fri, 23 Sep 2011 20:42:44 -0500 Subject: can't load an script from html... Message-ID: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Hi everyone I'm trying to use the cgi library to create a python script and loading it from a web page. I have already done the necessary imports, and the default commands to receive data from "html" are written too. The final version is something like this: #!/usr/bin/python import subprocess import cgi import cgitb cgitb.enable() input = cgi.FieldStorage() ?. my code (do something with input)?. #printing the response print "Content-Type: text/html" print print "My title:" print "" print "" print ?.. bla bla ? print "%s"%theoutput print "" Besides, my call from my index.html is like this:


well, the thing is that when i do the call from the browser: http://localhost/index.html | V put the data and click on the "accept" button | V http:/localhost/scripts/python_script.py I only get the python_script.py as a plain test by response (the script printed on my browser). I have already changed the permissions for python_script.py. I have checked the import cgi,cgitb in the python shell (i am using v2.7) and they work fine. So, i don't know what it is going wrong here. A little help please? any idea? Thanks anyway for your time. From python at mrabarnett.plus.com Fri Sep 23 21:57:37 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 02:57:37 +0100 Subject: can't load an script from html... In-Reply-To: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> References: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Message-ID: <4E7D3911.9030803@mrabarnett.plus.com> On 24/09/2011 02:42, Ricardo wrote: > Hi everyone > I'm trying to use the cgi library to create a python script and loading it from a web page. I have already done the necessary imports, and the default commands to receive data from "html" are written too. The final version is something like this: > > #!/usr/bin/python > > import subprocess > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > ?. my code (do something with input)?. > > > #printing the response > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print ?.. bla bla ? > print "%s"%theoutput > print "" > > Besides, my call from my index.html is like this: > >
>

> >
> > well, the thing is that when i do the call from the browser: > > http://localhost/index.html > | > V > put the data and click on the "accept" button > | > V > http:/localhost/scripts/python_script.py > > I only get the python_script.py as a plain test by response (the script printed on my browser). > I have already changed the permissions for python_script.py. I have checked the import cgi,cgitb in the python shell (i am using v2.7) and they work fine. So, i don't know what it is going wrong here. > > A little help please? any idea? > Thanks anyway for your time. > If it helps, the responses on my home-make stuff start something like this: From anacrolix at gmail.com Fri Sep 23 22:03:01 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Sat, 24 Sep 2011 12:03:01 +1000 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> Message-ID: how do you get the call stacks like this? On Sat, Sep 24, 2011 at 3:59 AM, Atherun wrote: > On Sep 23, 10:47?am, Nobody wrote: >> On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: >> >> kernel32.dll!WaitForSingleObject+0x12 >> >> python26.dll!_Py_svnversion+0xcf8 >> >> > I haven't a clue how this happens. _Py_svnversion just returns a string: >> >> In retrospect, I think that's a red herring. 0xcf8 seems like too large an >> offset for such a small function. I think that it's more likely to be in a >> non-exported function, and _Py_svnversion just happens to be the last >> exported symbol prior to that point in the code. > > I have the call stacks for each python thread running up until the > dead lock: > > # ThreadID: 992 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > # ThreadID: 5516 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > # ThreadID: 2668 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in > run > ?self.stacktraces() > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in > stacktraces > ?fout.write(stacktraces()) > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in > stacktraces > ?for filename, lineno, name, line in traceback.extract_stack(stack): > > # ThreadID: 3248 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > > # ThreadID: 7700 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > # ThreadID: 8020 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > # ThreadID: 4252 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > The StackTracer thread freezes trying to update my output file, and > yes I'm trying to 3 tasks in parallel which each one starts by > creating a changelist in perforce. ?This is just an easy repro case > for me, it happens with commands other then p4. ?This almost looks > like a threading issue more then the output deadlock. > -- > http://mail.python.org/mailman/listinfo/python-list > From flt.johnson at gmail.com Fri Sep 23 23:36:05 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 23 Sep 2011 20:36:05 -0700 (PDT) Subject: Why is the shutil module called shutil? Message-ID: The topic says it all: Why is shutil named shutil? What does it stand for? This is just a mild curiosity of mine. The shutil module for reference: http://docs.python.org/library/shutil.html#module-shutil From skippy.hammond at gmail.com Fri Sep 23 23:43:45 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 24 Sep 2011 13:43:45 +1000 Subject: pyWin build 216 In-Reply-To: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: <4E7D51F1.7010209@gmail.com> On 24/09/2011 12:25 AM, python wrote: > I have used pyWin for several years now with out issue. I recently > installed build 216 for python 2.7 on windows XP pro. The program > crashes every time I exit a wxPython program and has crashed a few > other times. There are a number of issues using Pythonwin to run a program which uses a different UI toolkit (eg, wx, Tkinter) and while these have been around for many years I don't plan on trying to fix it. IOW, "don't do that" :) > I does not seem that pyWin has been updated since > February of this year. Is there a direction change for the windows > extensions? Is it time I make the move to 3.x? Mark Hammond has > given much to the Python community and I do not intend for this post > to be negative in any way. No problem. There have been no updates as there is very little to update (ie, the code hasn't change a huge amount in hg since then). There will probably be a new version in the next month or so, but that is quite orthogonal to whether you should move to 3.x - the 3.x version of Pythonwin hasn't been updated in the same period and is built from the same source tree, so is likely to have exactly the same problems (infact is likely to have a few more - there are probably a few 3.x specific issues still hiding away). Mark From clp2 at rebertia.com Fri Sep 23 23:58:41 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 23 Sep 2011 20:58:41 -0700 Subject: Why is the shutil module called shutil? In-Reply-To: References: Message-ID: On Fri, Sep 23, 2011 at 8:36 PM, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. "sh" is short for "shell", in line with Unix convention, where the default shell is located at /bin/sh. http://en.wikipedia.org/wiki/Shell_(computing) http://en.wikipedia.org/wiki/Unix_shell "util" is short for "utilities". shutil is a utility module used to accomplish tasks which one often does when in the shell, such as copying, moving, or removing directory trees. But shutil (to my knowledge) is not implemented using shell commands or by running external programs, so it thus avoids a whole host of shell-related issues. It's not the best name, but what with backwards compatibility and all, it's unlikely to change any time soon. Cheers, Chris -- http://rebertia.com From 1248283536 at qq.com Sat Sep 24 00:11:17 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Sat, 24 Sep 2011 12:11:17 +0800 Subject: parse html:strange tr problem Message-ID: here is my code: import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() t = root.xpath("//table[@class='yfnc_datamodoutline1']")[0] trs=t.xpath(".//tr") for i, tr in enumerate(trs): print (i, len(tr),tr.text_content()) the output is: 0 1 StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 1 8 StrikeSymbolLastChgBidAskVolOpen Int 2 8 25.00A111022C0002500010.70 0.007.007.45315 3 8 28.00A111022C000280004.35 0.004.654.75201210 4 8 29.00A111022C000290003.80 0.003.954.05426425 5 8 30.00A111022C000300003.110.013.253.355597 6 8 31.00A111022C000310002.700.162.662.717407 7 8 32.00A111022C000320002.110.082.122.172364 8 8 33.00A111022C000330001.870.311.651.7029568 9 8 34.00A111022C000340001.360.151.261.3026649 10 8 35.00A111022C000350000.960.040.940.9845477 11 8 36.00A111022C000360000.720.120.690.7243786 12 8 37.00A111022C000370000.510.030.490.52511,435 13 8 38.00A111022C000380000.35 0.000.340.3544293 14 8 39.00A111022C000390000.16 0.000.220.269149 15 8 40.00A111022C000400000.180.030.150.1853301 16 8 41.00A111022C000410000.33 0.000.100.142184 17 8 42.00A111022C000420000.08 0.000.060.103147 18 8 45.00A111022C000450000.10 0.000.010.05200243 i want to know why i=0 the tr.text_content()'s value is : StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 it's strannge thing for me to understand. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contropinion at gmail.com Sat Sep 24 00:49:10 2011 From: contropinion at gmail.com (contro opinion) Date: Sat, 24 Sep 2011 12:49:10 +0800 Subject: parse html to get tr content Message-ID: here is my code: import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() t = root.xpath("//table[@class='yfnc_datamodoutline1']")[0] trs=t.xpath(".//tr") for i, tr in enumerate(trs): print (i, len(tr),tr.text_content()) the output is: 0 1 StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 1 8 StrikeSymbolLastChgBidAskVolOpen Int 2 8 25.00A111022C0002500010.70 0.007.007.45315 3 8 28.00A111022C000280004.35 0.004.654.75201210 4 8 29.00A111022C000290003.80 0.003.954.05426425 5 8 30.00A111022C000300003.110.013.253.355597 6 8 31.00A111022C000310002.700.162.662.717407 7 8 32.00A111022C000320002.110.082.122.172364 8 8 33.00A111022C000330001.870.311.651.7029568 9 8 34.00A111022C000340001.360.151.261.3026649 10 8 35.00A111022C000350000.960.040.940.9845477 11 8 36.00A111022C000360000.720.120.690.7243786 12 8 37.00A111022C000370000.510.030.490.52511,435 13 8 38.00A111022C000380000.35 0.000.340.3544293 14 8 39.00A111022C000390000.16 0.000.220.269149 15 8 40.00A111022C000400000.180.030.150.1853301 16 8 41.00A111022C000410000.33 0.000.100.142184 17 8 42.00A111022C000420000.08 0.000.060.103147 18 8 45.00A111022C000450000.10 0.000.010.05200243 i want to know why i=0 the tr.text_content()'s value is : StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 it's strannge thing for me to understand. -------------- next part -------------- An HTML attachment was scrubbed... URL: From flt.johnson at gmail.com Sat Sep 24 00:58:58 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 23 Sep 2011 21:58:58 -0700 (PDT) Subject: Why is the shutil module called shutil? References: Message-ID: On Sep 23, 11:58?pm, Chris Rebert wrote: > On Fri, Sep 23, 2011 at 8:36 PM, Fletcher Johnson wrote: > > The topic says it all: > > Why is shutil named shutil? What does it stand for? This is just a > > mild curiosity of mine. > > "sh" is short for "shell", in line with Unix convention, where the > default shell is located at /bin/sh.http://en.wikipedia.org/wiki/Shell_(computing)http://en.wikipedia.org/wiki/Unix_shell > > "util" is short for "utilities". > > shutil is a utility module used to accomplish tasks which one often > does when in the shell, such as copying, moving, or removing directory > trees. But shutil (to my knowledge) is not implemented using shell > commands or by running external programs, so it thus avoids a whole > host of shell-related issues. > > It's not the best name, but what with backwards compatibility and all, > it's unlikely to change any time soon. > > Cheers, > Chris > --http://rebertia.com I had a hunch it might have been that. From atherun at gmail.com Sat Sep 24 02:00:34 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 23:00:34 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> Message-ID: <15570090-f674-46e6-8c2e-747b68da5672@n12g2000yqh.googlegroups.com> On Sep 23, 7:03?pm, Matt Joiner wrote: > how do you get the call stacks like this? > > > > > > > > On Sat, Sep 24, 2011 at 3:59 AM, Atherun wrote: > > On Sep 23, 10:47?am, Nobody wrote: > >> On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: > >> >> kernel32.dll!WaitForSingleObject+0x12 > >> >> python26.dll!_Py_svnversion+0xcf8 > > >> > I haven't a clue how this happens. _Py_svnversion just returns a string: > > >> In retrospect, I think that's a red herring. 0xcf8 seems like too large an > >> offset for such a small function. I think that it's more likely to be in a > >> non-exported function, and _Py_svnversion just happens to be the last > >> exported symbol prior to that point in the code. > > > I have the call stacks for each python thread running up until the > > dead lock: > > > # ThreadID: 992 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 5516 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > # ThreadID: 2668 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in > > run > > ?self.stacktraces() > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in > > stacktraces > > ?fout.write(stacktraces()) > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in > > stacktraces > > ?for filename, lineno, name, line in traceback.extract_stack(stack): > > > # ThreadID: 3248 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 7700 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > # ThreadID: 8020 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 4252 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > The StackTracer thread freezes trying to update my output file, and > > yes I'm trying to 3 tasks in parallel which each one starts by > > creating a changelist in perforce. ?This is just an easy repro case > > for me, it happens with commands other then p4. ?This almost looks > > like a threading issue more then the output deadlock. > > -- > >http://mail.python.org/mailman/listinfo/python-list I found the code for it here: http://code.activestate.com/recipes/577334-how-to-debug-deadlocked-multi-threaded-programs/ There is some bugs in the code given but its pretty straight forward to fix it. From __peter__ at web.de Sat Sep 24 02:48:29 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 24 Sep 2011 08:48:29 +0200 Subject: can't load an script from html... References: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Message-ID: Ricardo wrote: > Hi everyone > I'm trying to use the cgi library to create a python script and loading it > from a web page. I have already done the necessary imports, and the > default commands to receive data from "html" are written too. The final > version is something like this: > > #!/usr/bin/python > > import subprocess > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > ?. my code (do something with input)?. > > > #printing the response > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print ?.. bla bla ? > print "%s"%theoutput > print "" > > Besides, my call from my index.html is like this: > >
>

> >
> > well, the thing is that when i do the call from the browser: > > http://localhost/index.html > | > V > put the data and click on the "accept" button > | > V > http:/localhost/scripts/python_script.py > > I only get the python_script.py as a plain test by response (the script > printed on my browser). I have already changed the permissions for > python_script.py. I have checked the import cgi,cgitb in the python shell > (i am using v2.7) and they work fine. So, i don't know what it is going > wrong here. > > A little help please? any idea? Is your webserver configured to allow cgi scripts? In the scripts directory? For Apache see http://httpd.apache.org/docs/current/howto/cgi.html Python also comes with a CGI Server. A quick-and-dirty setup goes like this: $ cat cgi-bin/script.py #!/usr/bin/python # -*- coding: utf-8 -*- import cgi import cgitb cgitb.enable() input = cgi.FieldStorage() print "Content-Type: text/html" print print "My title:" print "" print "" print "Hello world" print "" $ chmod a+x cgi-bin/script.py $ python -m CGIHTTPServer Serving HTTP on 0.0.0.0 port 8000 ... If you then point your browser to http://localhost:8000/cgi-bin/script.py you should see Hello world in the browser and (something like) localhost - - [24/Sep/2011 08:41:27] "GET /cgi-bin/script.py HTTP/1.1" 200 - in the shell. Note that the script must be in cgi-bin (or htbin) unless you start the server with a custom script that modifies CGIHTTPRequestHandler.cgi_directories accordingly. From steve+comp.lang.python at pearwood.info Sat Sep 24 02:55:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 16:55:18 +1000 Subject: random.randint() slow, esp in Python 3 References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Fri, Sep 23, 2011 at 4:14 AM, Steven D'Aprano > wrote: >> What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the >> random module is mostly Python. There is an import of _random, which >> presumably is in C, but it doesn't have a randint method: > > True. It seems to be defined in cpython/lib/random.py as a reference > to randrange, which does a pile of error checking and calls > _randbelow... which does a whole lot of work as well as calling > random(). Guess I should have checked the code before asking! > > There's probably good reasons for using randint(), If you want unbiased, random (or at least pseudo-random) integers chosen from an uniform distribution with proper error checking, you should use randint or randrange. > but if you just > want a pile of more-or-less random integers, int(random.random()*top) > is the best option. "I only need random-ish ints, but I need 'em yesterday!!!" If you want biased, not-quite-uniformly distributed integers with no error checking, then the above will save you a few nanoseconds per call. So if your application needs a million such ints, you might save a full five seconds or so. Sounds like premature optimization to me, but what do I know? If you have an application where the quality of randomness is unimportant and generating random ints is a genuine performance bottleneck, then go right ahead. >> I'm not seeing any significant difference in speed between 2.6 and 3.2: >> >> [steve at sylar ~]$ python2.6 -m timeit -s "from random import >> randint" "randint(0, 1000000)" >> 100000 loops, best of 3: 4.29 usec per loop >> >> [steve at sylar ~]$ python3.2 -m timeit -s "from random import >> randint" "randint(0, 1000000)" >> 100000 loops, best of 3: 4.98 usec per loop > > That might be getting lost in the noise. Try the list comp that I had > above and see if you can see a difference - or anything else that > calls randint that many times. If you want to measure the speed of randint, you should measure the speed of randint. That's what the timeit call does: it calls randint 100000 times. You can't measure the speed of: [random.randint(0,sz*10-1) for i in range(sz)] and draw conclusions about randint alone. Roughly speaking, you are measuring the time taken to: lookup range lookup sz, twice call range, possibly generating a massive list iterate over the list/range object lookup random lookup random.randint multiply sz by 10 and subtract 1 build a list of the results, repeatedly resizing it as you go (in no particular order) There is MUCH more noise in your suggestion, not my version. But for what it's worth, I get these results: [steve at sylar ~]$ python3.2 -m timeit -s "import random" -s "sz = 1000000" "[random.randint(0,sz*10-1) for i in range(sz)]" 10 loops, best of 3: 6.09 sec per loop [steve at sylar ~]$ python2.6 -m timeit -s "import random" -s "sz = 1000000" "[random.randint(0,sz*10-1) for i in range(sz)]" 10 loops, best of 3: 4.67 sec per loop So Python 3.2 is about 30% slower for the whole mess. (I would, however, give little confidence in those results: at 4-6 seconds per loop, I expect that OS-level noise will be significant.) For what (little) it's worth, it seems that Python 3.2 should be a bit faster than 2.6, at least if you consider the Pystone benchmark to mean anything. http://www.levigross.com/post/2340736877/pystone-benchmark-on-2-6-2-7-3-2 > Performance-testing with a heapsort (and by the way, it's > _ridiculously_ slower implementing it in Python instead of just > calling a.sort(), but we all knew that already!) shows a similar > difference in performance. You do know that Python's heap implementation is written in C? Don't be fooled by the heapq module being in Python. About 2/3rds of the way down, there's a sneaky little trick: # If available, use C implementation try: from _heapq import * except ImportError: pass -- Steven From Phillip.M.Feldman at gmail.com Sat Sep 24 03:06:01 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 24 Sep 2011 00:06:01 -0700 (PDT) Subject: multinomial combinations Message-ID: <32503896.post@talk.nabble.com> I wrote a small generator function that produces multinomial combinations. (Python's itertools module does ordinary combinations, but not multinomial combinations). The code essentially works, except that the the last combination in each tuple is not enclosed in a nested tuple: In [2]: x= multinomial_combinations(range(7),[2,1,2]) In [3]: x.next() Out[3]: ((0, 1), (2,), 3, 4) (The 3 and 4 should be enclosed in a nested tuple). Any suggestions as to what I'm doing wrong will be appreciated. My code follows: def multinomial_combinations(items, ns): if len(ns) == 1: for c in itertools.combinations(items, ns[0]): yield c else: for c_first in itertools.combinations(items, ns[0]): items_remaining= set(items) - set(c_first) for c_other in multinomial_combinations(items_remaining, ns[1:]): yield (c_first,) + c_other -- View this message in context: http://old.nabble.com/multinomial-combinations-tp32503896p32503896.html Sent from the Python - python-list mailing list archive at Nabble.com. From clp2 at rebertia.com Sat Sep 24 03:35:42 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 24 Sep 2011 00:35:42 -0700 Subject: multinomial combinations In-Reply-To: <32503896.post@talk.nabble.com> References: <32503896.post@talk.nabble.com> Message-ID: On Sat, Sep 24, 2011 at 12:06 AM, Dr. Phillip M. Feldman wrote: > > I wrote a small generator function that produces multinomial combinations. > (Python's itertools module does ordinary combinations, but not multinomial > combinations). ?The code essentially works, except that the the last > combination in each tuple is not enclosed in a nested tuple: > > In [2]: x= multinomial_combinations(range(7),[2,1,2]) > > In [3]: x.next() > Out[3]: ((0, 1), (2,), 3, 4) > > (The 3 and 4 should be enclosed in a nested tuple). > > Any suggestions as to what I'm doing wrong will be appreciated. ?My code > follows: > > def multinomial_combinations(items, ns): > > ? if len(ns) == 1: > ? ? ?for c in itertools.combinations(items, ns[0]): > ? ? ? ? yield c FWIW, changing the base case to: if not ns: yield () appears to fix the issue. (Disclaimer: Have not done additional testing.) Cheers, Chris > ? else: > ? ? ?for c_first in itertools.combinations(items, ns[0]): > ? ? ? ? items_remaining= set(items) - set(c_first) > ? ? ? ? for c_other in multinomial_combinations(items_remaining, ns[1:]): > ? ? ? ? ? ?yield (c_first,) + c_other From arnodel at gmail.com Sat Sep 24 03:43:17 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 08:43:17 +0100 Subject: multinomial combinations In-Reply-To: <32503896.post@talk.nabble.com> References: <32503896.post@talk.nabble.com> Message-ID: (sorry about the top posting) Change yield c to yield (c,) HTH Arnaud PS: you could also change the if ... To If not ns: Yield ((),) Else: ... On Sep 24, 2011 8:06 AM, "Dr. Phillip M. Feldman" < Phillip.M.Feldman at gmail.com> wrote: > > I wrote a small generator function that produces multinomial combinations. > (Python's itertools module does ordinary combinations, but not multinomial > combinations). The code essentially works, except that the the last > combination in each tuple is not enclosed in a nested tuple: > > In [2]: x= multinomial_combinations(range(7),[2,1,2]) > > In [3]: x.next() > Out[3]: ((0, 1), (2,), 3, 4) > > (The 3 and 4 should be enclosed in a nested tuple). > > Any suggestions as to what I'm doing wrong will be appreciated. My code > follows: > > def multinomial_combinations(items, ns): > > if len(ns) == 1: > for c in itertools.combinations(items, ns[0]): > yield c > > else: > for c_first in itertools.combinations(items, ns[0]): > items_remaining= set(items) - set(c_first) > for c_other in multinomial_combinations(items_remaining, ns[1:]): > yield (c_first,) + c_other > -- > View this message in context: http://old.nabble.com/multinomial-combinations-tp32503896p32503896.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From iamforufriends at gmail.com Sat Sep 24 04:34:26 2011 From: iamforufriends at gmail.com (hot girl) Date: Sat, 24 Sep 2011 01:34:26 -0700 (PDT) Subject: want to meet a new girlfriend for free Message-ID: <7f26bf3c-5fa9-4514-a5f3-0f4acbc57720@i9g2000yqe.googlegroups.com> want to meet a new girlfriend for free http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3v24v6e From steve+comp.lang.python at pearwood.info Sat Sep 24 04:57:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 18:57:01 +1000 Subject: Python Mixins References: Message-ID: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. Mixins considered harmful: http://www.artima.com/weblogs/viewpost.jsp?thread=246341 http://www.artima.com/weblogs/viewpost.jsp?thread=246483 Mixins are much too easy to abuse, but there are uses for them. I have found mixins useful for testing. If I have a bunch of functions that take mostly similar unit tests, I create a mixin for the common unit tests, then apply them to the tests. Suppose I have two functions, ham and spam, which are unrelated but do share some common behaviours. Since they are unrelated, I don't want the spam test suite to inherit from the ham test suite, or vice versa, but I don't want to write the same tests multiple times. (Especially when I add cheese, egg and tomato functions.) So I put the common behaviours in a mixin class: class StandardTestMixin: def test_requires_one_argument(self): self.assertRaises(TypeError, self.func) def test_has_docstring(self): self.assertTrue(self.func.__doc__) class TestHam(unittest.TestCase, StandardTestMixin): ... class TestSpam(unittest.TestCase, StandardTestMixin): ... In this case, I simply don't care that the use of a mixin implies that TestHam is a StandardTestMixin. I treat that as an accident of implementation: it makes no practical difference, since I write no code that depends on isinstance(instance, StandardTestMixin). [...] > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? That depends on what you want. Python says is that issubclass(Cat, Yamlafiable) will return True. The *interpretation* of that fact is entirely up to you. If you want to interpret it as meaning that cats are Yamlafiables, go right ahead. If you want to interpret it as a technical result with no semantic meaning, that's fine too. After all, just because "ram" in "programming" returns True doesn't actually mean anything about male sheep and computing. The map is not the territory, and object-oriented ancestor/descendant relationships are not the same as real life relationships. It's a tool, nothing more, and if the metaphor starts to creak at the edges, oh well, so much for the metaphor. In fact, even in real life, the ancestor/descendant metaphor creaks. What should we make of bacteria which exchange DNA with other species of bacteria? Which is the ancestor and which is the descendant? How about symbionts like lichen? What about when we splice genes from one species into another? So even in real life, there are multiple inheritance and mixins. > If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. The standard metaphor for inheritance in OOP doesn't include "learning things from a friend". It is a very simple metaphor: everything is either "is-a" or "has-a". If you inherit from a class, the is-a relationship holds. If you don't want that, you can use composition instead: class Cat(Animal): def __init__(self, yamlifier): self.yamlifier = yamlifier def make_yaml(self): self.yamlifier.make_yaml(self, self.spam) Now we say that a Cat has-a Yamlafiable. > This is just a ridiculous example, but I think it is valid to say that > these things shouldn't be limited to inherit functionality only from > their parents, that they can pick other things up along the way as > well. Which is easy to do, right? > > Dog.something_new = something_new And that works in Python. But the thing is, which would you rather write? #1 class Dog(Animal, Yamlafiable): pass or this? #2 class Dog(Animal): pass Dog.__dict__.update(Yamlafiable.__dict__) But wait! The two aren't the same. There are quite big differences in behaviour between inheritance and attribute injection: * In the case of inheritance, attributes defined by Animal take precedence over those defined by Yamlafiable. In the case of injection, the opposite is the case. * In the case of inheritance, attributes defined by Yamlafiable's superclasses are reachable. In the case of injection, they aren't (at least not without more work). * Inheritance is late-binding, injection is early-binding: if you dynamically add a new method to Yamlafiable, Dog will see the change in the first case but not the second. That's not to say that one is right and the other is wrong. They're just different. Use whichever tool you prefer. Another option is straits: http://www.artima.com/weblogs/viewpost.jsp?thread=246488 -- Steven From chris at simplistix.co.uk Sat Sep 24 05:27:07 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Sat, 24 Sep 2011 10:27:07 +0100 Subject: MailingLogger 3.5.0 Released! Message-ID: <4E7DA26B.5090202@simplistix.co.uk> I'm pleased to announce a new release of Mailinglogger. Mailinglogger provides two handlers for the standard python logging framework that enable log entries to be emailed either as the entries are logged or as a summary at the end of the running process. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with a configurable headers for easy filtering - flood protection to ensure the number of emails sent is not excessive - support for SMTP servers that require authentication - fully documented and tested The only change for this release was to add an X-Log-Level header to emails sent. For MailingLogger, this is the level of the log message being emailed. For SummarisingLogger this is the highest level of any of the messages handled. Full docs can be found here: http://packages.python.org/mailinglogger/ For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger or http://pypi.python.org/pypi/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From ian.g.kelly at gmail.com Sat Sep 24 05:38:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 24 Sep 2011 03:38:14 -0600 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 12:55 AM, Steven D'Aprano wrote: > If you want unbiased, random (or at least pseudo-random) integers chosen > from an uniform distribution with proper error checking, you should use > randint or randrange. > > >> but if you just >> want a pile of more-or-less random integers, int(random.random()*top) >> is the best option. > > "I only need random-ish ints, but I need 'em yesterday!!!" > > If you want biased, not-quite-uniformly distributed integers with no error > checking, then the above will save you a few nanoseconds per call. So if > your application needs a million such ints, you might save a full five > seconds or so. Sounds like premature optimization to me, but what do I > know? If you have an application where the quality of randomness is > unimportant and generating random ints is a genuine performance bottleneck, > then go right ahead. Peeking under the hood, after all the error-checking and extra features, randrange basically just does int(random.random() * top). Any bias present in the latter will also be present in the former. Cheers, Ian From pavlovevidence at gmail.com Sat Sep 24 05:58:37 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 Sep 2011 02:58:37 -0700 (PDT) Subject: Python Mixins In-Reply-To: References: Message-ID: <20110522.2658.1316858317611.JavaMail.geo-discussion-forums@prfb12> On Thursday, September 22, 2011 2:14:39 PM UTC-7, Matt wrote: [snip] > class MyMixin(object): > def one_thing(self): > return "something cool" > > @mixin(MyMixin) > class MyClass(object): > pass > > x = MyClass() > x.one_thing() == 'something cool' > x.__class__.__bases__ == (object,) > > To me, this is much more concise. By looking at this I can tell what > MyClass IS, who it's parents are and what else it can do. I'm very > interested to know if there are others who feel as dirty as I do when > using inheritance for mixins Not me. Inheritance perfectly encompasses the mixin relationship, and because inheritance is so thoroughly ingrained in Python, it makes sense not to create a completely different mechanism to share behavior just for the case of mixins. I know that, as someone who reads code, I would rather coders stick to well-known mechanisms than to create their own ad hoc mechanisms that don't actually add any new capability. Take your MyClass example above. If you had stuck to inheritance I could have seen what classes all the behavior was implemented by listing the __bases__. But since you used an ad hoc mechanism, now I have to track down where the hell that one_thing() method is coming from. No mechanism is ever perfect, and Python's MI is very far from perfect, but sticking to well-known and understood methods is usually more important than whatever little improvement you can make. (And it is little; best as I can tell, your main objection is that mixins make it harder to see what the "main" parent is. I'd say that's a dubious justification to spring a new behavior-sharing mechanism on a reader.) > or if there are other things that Python > developers are doing to mix in functionality without using inheritance > or if the general populous of the Python community disagrees with me > and thinks that this is a perfectly valid use of inheritance. I'd guess the majority just use inheritance, although I can't say I've seen enough code out there to gauge it. But there is something else a lot of Pythonistas will do in many cases: just define regular functions. In your example, instead of defining one_thing() as a method of a mixin, define it as a function. Personally, I find that I almost never use mixins, though I have absolutely nothing against them and I use MI and metaclasses all the time. It's just that for most things I'd use a mixin for, I find that one or two regular functions work perfectly well. Carl Banks From pavlovevidence at gmail.com Sat Sep 24 06:23:11 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 Sep 2011 03:23:11 -0700 (PDT) Subject: Python Mixins In-Reply-To: References: Message-ID: <16852897.463.1316859791599.JavaMail.geo-discussion-forums@prng5> On Thursday, September 22, 2011 2:14:39 PM UTC-7, Matt wrote: > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? Yes. I hope you are not confusing Cats with cats. > If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. The whole point of OOP is that objects are defined by their behavior. A Cat is whatever it can do. A Dog is whatever it can do. If a Cat is yamlafiable, then it's coorect to say that a Cat is a Yamlafible (even if a cat isn't). Carl Banks From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sat Sep 24 07:48:29 2011 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sat, 24 Sep 2011 13:48:29 +0200 Subject: pyWin build 216 References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: <4e7dc38c$0$18801$ba4acef3@reader.news.orange.fr> Hi! Me, because some bugs in 216, I come back to 214... (215 has another bugs). @-salutations -- MCi From rosuav at gmail.com Sat Sep 24 08:33:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 24 Sep 2011 22:33:50 +1000 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 4:55 PM, Steven D'Aprano wrote: > Chris Angelico wrote: > > If you want unbiased, random (or at least pseudo-random) integers chosen > from an uniform distribution with proper error checking, you should use > randint or randrange. > > "I only need random-ish ints, but I need 'em yesterday!!!" All I want is some data to sort, so that I can verify that my implementation is doing the same thing in every language that I write it in. Doesn't have to be casino-level purity of randomness. > You can't measure the speed of: > > [random.randint(0,sz*10-1) for i in range(sz)] > > and draw conclusions about randint alone. Sure, but by comparing the two lines of code (one with randint and one with random()), the other aspects can be cancelled out. > For what (little) it's worth, it seems that Python 3.2 should be a bit > faster than 2.6, at least if you consider the Pystone benchmark to mean > anything. > > http://www.levigross.com/post/2340736877/pystone-benchmark-on-2-6-2-7-3-2 That's what I would normally expect, that the new version outperforms the old - regardless of the program and the context. Exceptions need justification (as in the case of int/long vs just int - Py2 often outperforms Py3 when all the numbers fit inside machine int). > You do know that Python's heap implementation is written in C? Don't be > fooled by the heapq module being in Python. I didn't know, but it doesn't surprise me. But my purpose wasn't to sort the integers, it was to play with a particular hand-rolled implementation of a heap sort in multiple languages and make sure it was producing consistent results. ChrisA From dickinsm at gmail.com Sat Sep 24 08:53:41 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 05:53:41 -0700 (PDT) Subject: random.randint() slow, esp in Python 3 References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <94662e3d-5551-4ead-a067-9a381a402b43@i28g2000yqn.googlegroups.com> On Sep 24, 10:38?am, Ian Kelly wrote: > On Sat, Sep 24, 2011 at 12:55 AM, Steven D'Aprano > > > > > > > > > > wrote: > > If you want unbiased, random (or at least pseudo-random) integers chosen > > from an uniform distribution with proper error checking, you should use > > randint or randrange. > > >> but if you just > >> want a pile of more-or-less random integers, int(random.random()*top) > >> is the best option. > > > "I only need random-ish ints, but I need 'em yesterday!!!" > > > If you want biased, not-quite-uniformly distributed integers with no error > > checking, then the above will save you a few nanoseconds per call. So if > > your application needs a million such ints, you might save a full five > > seconds or so. Sounds like premature optimization to me, but what do I > > know? If you have an application where the quality of randomness is > > unimportant and generating random ints is a genuine performance bottleneck, > > then go right ahead. > > Peeking under the hood, after all the error-checking and extra > features, randrange basically just does int(random.random() * top). > Any bias present in the latter will also be present in the former. > > Cheers, > Ian In Python 2.x that's true, and indeed randrange has some fairly bad behaviour for large arguments ( see http://bugs.python.org/issue9025 ). In Python 3.2 and up, randrange is more careful: it doesn't introduce any extra bias beyond that already present in the random source (Mersenne Twister). If you look at the source, you'll see that Python 2.x only calls _getrandbits for large arguments, while Python 3.2+ calls _getrandbits for *every* invocation of randrange. (All assuming that we're using the default MT random number generator.) This may well explain the difference in timings observed by the OP. -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 09:53:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 23:53:26 +1000 Subject: Generating equally-spaced floats with least rounding error Message-ID: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> I'm trying to generate a sequence of equally-spaced numbers between a lower and upper limit. Given arbitrary limits, what is the best way to generate a list of equally spaced floats with the least rounding error for each point? For example, suppose I want to divide the range 0 to 2.1 into 7 equal intervals, then the end-points of each interval are: (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) and I'd like to return the values in the brackets. Using Decimal or Fraction is not an option, I must use floats. If the exact value isn't representable as a float, I'm okay with returning the nearest possible float. The width of each interval is: width = (2.1 - 0.0)/7 The relevant points can be calculated in either of two methods: #1 add multiples of the width to the starting value, 0. #2 subtract multiples of width from the ending value, 2.1. (Repeated addition or subtraction should be avoided, as it increases the amount of rounding error.) Mathematically the two are equivalent, but due to rounding, they may not be. Here's a run using Python 3.2: >>> [0.0 + i*width for i in range(8)] [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] The 4th and 7th values have rounding errors, the rest are exact. >>> [2.1 - (7-i)*width for i in range(8)] [0.0, 0.30000000000000027, 0.6000000000000001, 0.9000000000000001, 1.2000000000000002, 1.5, 1.8, 2.1] The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th value is exact here, but not above. Is there a way to pick between methods #1 and #2 (or some combination of the two) without human intervention so as to minimise the rounding error? Or is there some other way to generate equally-spaced floats? My efforts at googling have not been helpful. -- Steven From rosuav at gmail.com Sat Sep 24 09:58:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 24 Sep 2011 23:58:32 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano wrote: > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. #3, go half and half - generate the lower half by adding to the lower bound, and the upper half by subtracting from the upper bound. Not sure if it'll help or not but it might be worth a shot. ChrisA From vlastimil.brom at gmail.com Sat Sep 24 10:17:40 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 24 Sep 2011 16:17:40 +0200 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/24 Chris Angelico : > On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano > wrote: >> #1 add multiples of the width to the starting value, 0. >> >> #2 subtract multiples of width from the ending value, 2.1. > > #3, go half and half - generate the lower half by adding to the lower > bound, and the upper half by subtracting from the upper bound. Not > sure if it'll help or not but it might be worth a shot. > > ChrisA > -- Just a naive way: #4 compute the values in both directions and use the average of the results (of, course, given, there isn't a better way to distinguish the values showing rounding errors automatically). (I guess dealing manually with values obtained by .as_integer_ratio() doesn't count as pure float operation...) vbr From arnodel at gmail.com Sat Sep 24 10:18:44 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 15:18:44 +0100 Subject: Generating equally-spaced floats with least rounding error Message-ID: On Sep 24, 2011 2:59 PM, "Chris Angelico" wrote: > > On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano > wrote: > > #1 add multiples of the width to the starting value, 0. > > > > #2 subtract multiples of width from the ending value, 2.1. > > #3, go half and half - generate the lower half by adding to the lower > bound, and the upper half by subtracting from the upper bound. Not #4 the barycentric approach. ((n-i)*a + i*b)/n for i in range(n+1) Gives you n+1 equally spaced values between a and b inclusive Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Sat Sep 24 10:26:08 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 24 Sep 2011 10:26:08 -0400 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a > lower and upper limit. Given arbitrary limits, what is the best way to > generate a list of equally spaced floats with the least rounding error for > each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or > Fraction is not an option, I must use floats. If the exact value isn't > representable as a float, I'm okay with returning the nearest possible > float. > > The width of each interval is: > > width = (2.1 - 0.0)/7 > > The relevant points can be calculated in either of two methods: > > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. > > (Repeated addition or subtraction should be avoided, as it increases the > amount of rounding error.) > > Mathematically the two are equivalent, but due to rounding, they may not > be. Here's a run using Python 3.2: > >>>> [0.0 + i*width for i in range(8)] > [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] > > The 4th and 7th values have rounding errors, the rest are exact. > > >>>> [2.1 - (7-i)*width for i in range(8)] > [0.0, 0.30000000000000027, 0.6000000000000001, 0.9000000000000001, > 1.2000000000000002, 1.5, 1.8, 2.1] > > The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th > value is exact here, but not above. > > Is there a way to pick between methods #1 and #2 (or some combination of > the two) without human intervention so as to minimise the rounding error? > Or is there some other way to generate equally-spaced floats? My efforts > at googling have not been helpful. When I've done this with ints (usually in small embedded systems) I've always preferred low_limit + (total_width * i) / intervals since it does the rounding on the biggest numbers where proportional error will be least, and it's guaranteed to hit the low_limit and high_limit exactly (as exactly as they can be represented, anyway.) Mel. From lists at cheimes.de Sat Sep 24 10:56:59 2011 From: lists at cheimes.de (Christian Heimes) Date: Sat, 24 Sep 2011 16:56:59 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Message-ID: Am 23.09.2011 23:34, schrieb Jesramz: > Im running on Ubuntu Natty and I am not running a self-compiled > install, its a regular release. Ubuntu Natty doesn't come with Python 2.5. How did you install Python 2.5 on Natty? If you used some sort of installer or 3rd party repository, there is a big chance that the installer doesn't understand multiarch. Christian From dickinsm at gmail.com Sat Sep 24 11:17:49 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 08:17:49 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> On Sep 24, 2:53?pm, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. Can you explain why you're constrained not to use Fraction? Speed? Using Fraction for intermediate calculations actually works perfectly for this, since conversions from float to Fraction are exact, while conversions from Fraction to float are correctly rounded. So if you're using Python, you're not too bothered about efficiency, and you want provably correctly-rounded results, why not use Fraction? >>> from fractions import Fraction >>> start, stop, n = 0.0, 2.1, 7 >>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 12:46:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 02:46:39 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> Message-ID: <4e7e0971$0$30000$c3e8da3$5496439d@news.astraweb.com> Mark Dickinson wrote: > On Sep 24, 2:53?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> I'm trying to generate a sequence of equally-spaced numbers between a >> lower and upper limit. Given arbitrary limits, what is the best way to >> generate a list of equally spaced floats with the least rounding error >> for each point? >> >> For example, suppose I want to divide the range 0 to 2.1 into 7 equal >> intervals, then the end-points of each interval are: >> >> (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) >> >> and I'd like to return the values in the brackets. Using Decimal or >> Fraction is not an option, I must use floats. If the exact value isn't >> representable as a float, I'm okay with returning the nearest possible >> float. > > Can you explain why you're constrained not to use Fraction? Speed? Speed is important, but secondary to correctness. To be honest, I never even thought of using fractions as an intermediate result -- I was thinking of generating lists of Fractions. I think I can use this approach. But out of curiosity, how would you do it using nothing but floats? Is there a way? -- Steven From dickinsm at gmail.com Sat Sep 24 12:55:35 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 09:55:35 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0971$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <44c72615-2455-469c-964f-6aacedeb705f@d17g2000yqa.googlegroups.com> On Sep 24, 5:46?pm, Steven D'Aprano wrote: > Speed is important, but secondary to correctness. To be honest, I never even > thought of using fractions as an intermediate result -- I was thinking of > generating lists of Fractions. I think I can use this approach. Speed could be improved greatly by using integer arithmetic (with some help from the float.as_integer_ratio method) instead of using Fraction directly, though it would require writing quite a lot more code; Fraction's many and slow gcd calls for normalization are a problem here, and since all denominators will be powers of 2 they're largely unnecessary. > But out of curiosity, how would you do it using nothing but floats? Is there > a way? Hmm. Beyond writing my own multiple-precision integer library using floats as the base type, I can't think of anything obvious. :-) -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 13:01:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 03:01:47 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> Message-ID: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Mark Dickinson wrote: > Using Fraction for intermediate calculations actually works perfectly > for this, since conversions from float to Fraction are exact, while > conversions from Fraction to float are correctly rounded. So if > you're using Python, you're not too bothered about efficiency, and you > want provably correctly-rounded results, why not use Fraction? > >>>> from fractions import Fraction >>>> start, stop, n = 0.0, 2.1, 7 >>>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) >>>> [for i in range(n+1)] > [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] Ah, I knew it was too easy! >>> from fractions import Fraction as F >>> start, stop, n = 1, 3.1, 7 >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>> >>> start, stop, n = -1, 1.1, 7 >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] -- Steven From rosuav at gmail.com Sat Sep 24 13:03:14 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 03:03:14 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 12:26 AM, Mel wrote: > low_limit + (total_width * i) / intervals > Definite improvement, if the range is comparatively small. Multiply first, then divide. ChrisA From rosuav at gmail.com Sat Sep 24 13:19:34 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 03:19:34 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:01 AM, Steven D'Aprano wrote: > Mark Dickinson wrote: > >> Using Fraction for intermediate calculations actually works perfectly >> for this, since conversions from float to Fraction are exact, while >> conversions from Fraction to float are correctly rounded. ?So if >> you're using Python, you're not too bothered about efficiency, and you >> want provably correctly-rounded results, why not use Fraction? >> > Ah, I knew it was too easy! Try using Fraction for the start and stop too: >>> from fractions import Fraction as F >>> start,stop,n = F(0),F(21,10),7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] (Tested in Py 3.2 for Win) ChrisA From passiday at gmail.com Sat Sep 24 13:31:21 2011 From: passiday at gmail.com (Passiday) Date: Sat, 24 Sep 2011 10:31:21 -0700 (PDT) Subject: Suggested coding style Message-ID: Hello, I have started to code random stuff in Python only recently, still lots to learn. So please bear with me if my question sounds like rant. I have been coding in many other languages, most of the time it was Java and C#. I don't like the function mess of PHP (ie, loads and loads of functions without any namespaces etc), but I'd like to think that Python is different. In my brief coding experience I have stumbled upon Python zfill(width) method, and I thought, really, do you have to include such a narrow- purpose method in the basic method set? Perhaps there are more such methods that are nice when you need them, but then again, you don't put all the possible methods in the standard set. Perhaps there is reason such method is in the basic library, and my complaints are unbased? Or, perhaps the language is on course to bloat out and get filled with tens and hundreds of special-purpose methods that render the language structure chaotic? Passiday From dickinsm at gmail.com Sat Sep 24 14:23:21 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 11:23:21 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 24, 6:01?pm, Steven D'Aprano wrote: > Ah, I knew it was too easy! > > >>> from fractions import Fraction as F > >>> start, stop, n = 1, 3.1, 7 > >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > > [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] I believe that's still giving correctly-rounded results. Note that the stop value of 3.1 isn't exactly 3.1 here: it's 3.100000000000000088817841970012523233890533447265625 So the 4th value above is the closest float to 4/7 * 1.0 + 3/7 * 3.100000000000000088817841970012523233890533447265625. -- Mark From rick.mansilla at gmail.com Sat Sep 24 14:50:26 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Sat, 24 Sep 2011 13:50:26 -0500 Subject: Python-list Digest, Vol 96, Issue 137 In-Reply-To: References: Message-ID: <201109241350.27066.rick.mansilla@gmail.com> On Saturday 24 September 2011 01:48:29 you wrote: > Ricardo wrote: > > Hi everyone > > I'm trying to use the cgi library to create a python script and loading > > it from a web page. I have already done the necessary imports, and the > > default commands to receive data from "html" are written too. The final > > version is something like this: > > > > #!/usr/bin/python > > > > import subprocess > > import cgi > > import cgitb > > > > cgitb.enable() > > > > input = cgi.FieldStorage() > > > > ?. my code (do something with input)?. > > > > > > #printing the response > > > > print "Content-Type: text/html" > > print > > print "My title:" > > print "" > > print "" > > print ?.. bla bla ? > > print "%s"%theoutput > > print "" > > > > Besides, my call from my index.html is like this: > >
> > > >

> > > > > > > >
> > > > well, the thing is that when i do the call from the browser: > > > > http://localhost/index.html > > > > V > > > > put the data and click on the "accept" button > > > > V > > > > http:/localhost/scripts/python_script.py > > > > I only get the python_script.py as a plain test by response (the script > > printed on my browser). I have already changed the permissions for > > python_script.py. I have checked the import cgi,cgitb in the python shell > > (i am using v2.7) and they work fine. So, i don't know what it is going > > wrong here. > > > > A little help please? any idea? > > Is your webserver configured to allow cgi scripts? In the scripts > directory? For Apache see > > http://httpd.apache.org/docs/current/howto/cgi.html > > Python also comes with a CGI Server. A quick-and-dirty setup goes like > this: > > $ cat cgi-bin/script.py > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print "Hello world" > print "" > $ chmod a+x cgi-bin/script.py > $ python -m CGIHTTPServer > Serving HTTP on 0.0.0.0 port 8000 ... > > If you then point your browser to http://localhost:8000/cgi-bin/script.py > you should see > > Hello world > > in the browser and (something like) > > localhost - - [24/Sep/2011 08:41:27] "GET /cgi-bin/script.py HTTP/1.1" 200 > - > > in the shell. Note that the script must be in cgi-bin (or htbin) unless you > start the server with a custom script that modifies > CGIHTTPRequestHandler.cgi_directories accordingly. Thanks a lot, for your answer. Yes, i can run scripts from /cgi-bin/. Actually I follow you example and it works really well. I didn't know at all about this CGI server. I am doing the hole thing over python now, it's nice. Thanks again. -- (...)Also, since that same law states that any system able to prove its consistency to itself must be inconsistent; any mind that believes it can prove its own sanity is, therefore, insane.(...) Kurt G?del. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Sep 24 15:03:31 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 20:03:31 +0100 Subject: Suggested coding style In-Reply-To: References: Message-ID: <4E7E2983.10506@mrabarnett.plus.com> On 24/09/2011 18:31, Passiday wrote: > Hello, > > I have started to code random stuff in Python only recently, still > lots to learn. So please bear with me if my question sounds like rant. > > I have been coding in many other languages, most of the time it was > Java and C#. I don't like the function mess of PHP (ie, loads and > loads of functions without any namespaces etc), but I'd like to think > that Python is different. > > In my brief coding experience I have stumbled upon Python zfill(width) > method, and I thought, really, do you have to include such a narrow- > purpose method in the basic method set? Perhaps there are more such > methods that are nice when you need them, but then again, you don't > put all the possible methods in the standard set. > > Perhaps there is reason such method is in the basic library, and my > complaints are unbased? Or, perhaps the language is on course to bloat > out and get filled with tens and hundreds of special-purpose methods > that render the language structure chaotic? > Considering that Python has been around for 20 years, there's not much bloat. Most of the risk of that was early on, when any interest in the language might have been welcomed. Now that its use has grown, it can be more choosy. .zfill does have its uses: >>> "-1".rjust(4, "0") '00-1' >>> "-1".zfill(4) '-001' From tim at akwebsoft.com Sat Sep 24 15:10:48 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sat, 24 Sep 2011 11:10:48 -0800 Subject: Suggested coding style In-Reply-To: References: Message-ID: <20110924191048.GH19422@johnsons-web.com> * Passiday [110924 09:47]: <...> > I have been coding in many other languages, most of the time it was > Java and C#. I don't like the function mess of PHP (ie, loads and > loads of functions without any namespaces etc), but I'd like to think > that Python is different. It is ... > In my brief coding experience I have stumbled upon Python zfill(width) > method, and I thought, really, do you have to include such a narrow- > purpose method in the basic method set? Perhaps there are more such > methods that are nice when you need them, but then again, you don't > put all the possible methods in the standard set. I think that you have raised an interesting question here. I've been coding in python for 9 years and I have never used it. > Perhaps there is reason such method is in the basic library, and my > complaints are unbased? It could be some sort of legacy. I imagine we will hear from some more senior pythonists on this matter. > Or, perhaps the language is on course to bloat > out and get filled with tens and hundreds of special-purpose methods > that render the language structure chaotic? From my observance, python has developed with care and prudence. I have a feeling (instinctive of course), that Guido van Rossum is/was more likely to say 'no' to a request for a new implementation that Rasmus Lerdorf. MTCW -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From python at mrabarnett.plus.com Sat Sep 24 15:34:36 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 20:34:36 +0100 Subject: Suggested coding style In-Reply-To: <20110924191048.GH19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> Message-ID: <4E7E30CC.3040402@mrabarnett.plus.com> On 24/09/2011 20:10, Tim Johnson wrote: > * Passiday [110924 09:47]: > <...> >> I have been coding in many other languages, most of the time it was >> Java and C#. I don't like the function mess of PHP (ie, loads and >> loads of functions without any namespaces etc), but I'd like to think >> that Python is different. > It is ... > >> In my brief coding experience I have stumbled upon Python zfill(width) >> method, and I thought, really, do you have to include such a narrow- >> purpose method in the basic method set? Perhaps there are more such >> methods that are nice when you need them, but then again, you don't >> put all the possible methods in the standard set. > I think that you have raised an interesting question here. I've > been coding in python for 9 years and I have never used it. > >> Perhaps there is reason such method is in the basic library, and my >> complaints are unbased? > > It could be some sort of legacy. I imagine we will hear from some > more senior pythonists on this matter. > The documentation says "New in version 2.2.2". >> Or, perhaps the language is on course to bloat >> out and get filled with tens and hundreds of special-purpose methods >> that render the language structure chaotic? > > From my observance, python has developed with care and prudence. I > have a feeling (instinctive of course), that Guido van Rossum > is/was more likely to say 'no' to a request for a new > implementation that Rasmus Lerdorf. > From arnodel at gmail.com Sat Sep 24 15:54:28 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 20:54:28 +0100 Subject: Suggested coding style In-Reply-To: <4E7E30CC.3040402@mrabarnett.plus.com> References: <20110924191048.GH19422@johnsons-web.com> <4E7E30CC.3040402@mrabarnett.plus.com> Message-ID: On 24 September 2011 20:34, MRAB wrote: >>> In my brief coding experience I have stumbled upon Python zfill(width) >>> method, [...] >> ? It could be some sort of legacy. I imagine we will hear from some >> ? more senior pythonists on this matter. >> > The documentation says "New in version 2.2.2". But zfill has been in the string module for a lot longer. -- Arnaud From arnodel at gmail.com Sat Sep 24 15:55:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 20:55:34 +0100 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24 September 2011 18:01, Steven D'Aprano wrote: > Mark Dickinson wrote: > >> Using Fraction for intermediate calculations actually works perfectly >> for this, since conversions from float to Fraction are exact, while >> conversions from Fraction to float are correctly rounded. ?So if >> you're using Python, you're not too bothered about efficiency, and you >> want provably correctly-rounded results, why not use Fraction? >> >>>>> from fractions import Fraction >>>>> start, stop, n = 0.0, 2.1, 7 >>>>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) >>>>> [for i in range(n+1)] >> [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] > > > Ah, I knew it was too easy! > >>>> from fractions import Fraction as F >>>> start, stop, n = 1, 3.1, 7 >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>> start, stop, n = 1, 3.1, 7 >>> [((n-i)*start + i*stop)/n for i in range(n+1)] [1.0, 1.3, 1.5999999999999999, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>>> start, stop, n = -1, 1.1, 7 >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, > 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] >>> start, stop, n = -1, 1.1, 7 >>> [((n-i)*start + i*stop)/n for i in range(n+1)] [-1.0, -0.7000000000000001, -0.39999999999999997, -0.09999999999999996, 0.20000000000000004, 0.5, 0.8, 1.1] On these examples, using fractions is no better than what I suggested in my previous post. -- Arnaud From stefan-usenet at bytereef.org Sat Sep 24 16:30:45 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Sat, 24 Sep 2011 22:30:45 +0200 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110924203045.GA2014@sleipnir.bytereef.org> Arnaud Delobelle wrote: > >>>> start, stop, n = -1, 1.1, 7 > >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > > [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, > > 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] > > >>> start, stop, n = -1, 1.1, 7 > >>> [((n-i)*start + i*stop)/n for i in range(n+1)] > [-1.0, -0.7000000000000001, -0.39999999999999997, > -0.09999999999999996, 0.20000000000000004, 0.5, 0.8, 1.1] > > On these examples, using fractions is no better than what I suggested > in my previous post. Why not use Decimal if one needs exact endpoints? Something like: def drange(start, stop, step=1): if (step == 0): raise ValueError("step must be != 0") with localcontext() as ctx: ctx.traps[Inexact] = True x = start cmp = -1 if step > 0 else 1 while x.compare(stop) == cmp: yield float(x) x += step >>> list(drange(Decimal(1), Decimal("3.1"), Decimal("0.3"))) [1.0, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal("0.3"))) [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal("0.1823612873"))) [-1.0, -0.8176387127, -0.6352774254, -0.4529161381, -0.2705548508, -0.0881935635, 0.0941677238, 0.2765290111, 0.4588902984, 0.6412515857, 0.823612873, 1.0059741603] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal(1)/3)) Traceback (most recent call last): File "", line 1, in File "", line 10, in drange File "/usr/lib/python3.2/decimal.py", line 1178, in __add__ ans = ans._fix(context) File "/usr/lib/python3.2/decimal.py", line 1652, in _fix context._raise_error(Inexact) File "/usr/lib/python3.2/decimal.py", line 3836, in _raise_error raise error(explanation) decimal.Inexact: None Stefan Krah From mateusz at loskot.net Sat Sep 24 16:52:46 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Sat, 24 Sep 2011 13:52:46 -0700 (PDT) Subject: PyEval_EvalCodeEx return value In-Reply-To: <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> References: <4E786C42.3050309@loskot.net> <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> Message-ID: <32503908.post@talk.nabble.com> John Pinner-3 wrote: > > I assume that you have read the documentation at > http://docs.python.org/c-api/veryhigh.html, > and I agree that it's sparse, but the entry for the next entry, > PyEval_EvalCodeEx, tells you a little more, as does that for > PyEval_EvalFrameEx. > It does help, but only a bit. John Pinner-3 wrote: > > Obviously, it's returning a pointer to a PyObject, and Looking at the > source code, that may be NULL, to throw an exception, or an execution > frame, or a generator,etc, etc, depending on the code it's been given. > I guess that you should be able to inspect the PyObject to see what it is. > Yes, that's one possibility. I tried to investigate others. John Pinner-3 wrote: > > What I'm wondering is, why are you eval-ing code ? A favourite device > of C programmers coming to Python (and mea culpa in the past), it's > fraught with potential problems and even security risks, and is > difficult to debug, and maybe you should be using introspection instead. > My application accepts Python scripts from user and executes using embedded Python interpreter. So, I use this particular API. Could you elaborate on the "using introspection"? John Pinner-3 wrote: > > And maybe you should be working in Python, and not C++ at this point, > do the dynamic stuff in the language best suited, and then return to C++ > when needed. > My application in C++ interacts with Python programs provided by users. Depending on what these programs request, various PyObject objects are created and returned back, etc. I understand it's difficult to discuss it without long essays or without providing the code, etc. So, I can only discuss and investigate building blocks I use. Anyway, thanks for your comments. Best regards, ----- -- Mateusz Loskot http://mateusz.loskot.net -- View this message in context: http://old.nabble.com/PyEval_EvalCodeEx-return-value-tp32501833p32503908.html Sent from the Python - python-list mailing list archive at Nabble.com. From f.derainville at gmail.com Sat Sep 24 16:54:16 2011 From: f.derainville at gmail.com (f.derainville at gmail.com) Date: Sat, 24 Sep 2011 13:54:16 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <16897112.251.1316897656322.JavaMail.geo-discussion-forums@yqmw31> >>> import numpy >>> numpy.arange(0, 3, 0.3) array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7]) From rantingrick at gmail.com Sat Sep 24 17:05:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 14:05:36 -0700 (PDT) Subject: Python Mixins References: Message-ID: <210c9d0b-d0f0-4fec-9d7b-11ef32127d6e@q26g2000vby.googlegroups.com> On Sep 22, 4:14?pm, Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. Have a look at this article also. Even though he uses java source code anyone can follow along: http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/ From tim at akwebsoft.com Sat Sep 24 17:09:35 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sat, 24 Sep 2011 13:09:35 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4E7E30CC.3040402@mrabarnett.plus.com> Message-ID: <20110924210935.GI19422@johnsons-web.com> * Arnaud Delobelle [110924 12:04]: > On 24 September 2011 20:34, MRAB wrote: > > >>> In my brief coding experience I have stumbled upon Python zfill(width) > >>> method, > [...] > >> ? It could be some sort of legacy. I imagine we will hear from some > >> ? more senior pythonists on this matter. > >> > > The documentation says "New in version 2.2.2". > > But zfill has been in the string module for a lot longer. :) Like I said. See timestamp. http://mail.python.org/pipermail/python-bugs-list/1999-July/000035.html I was coding C/C++ and ASM back then.... -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From tjreedy at udel.edu Sat Sep 24 18:10:29 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 18:10:29 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/24/2011 9:53 AM, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. > > The width of each interval is: > > width = (2.1 - 0.0)/7 Calculating width is the fundamental problem. .3 cannot be exactly represented in binary, and higher multiples with multiply the error. > > The relevant points can be calculated in either of two methods: > > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. > > (Repeated addition or subtraction should be avoided, as it increases the > amount of rounding error.) > > Mathematically the two are equivalent, but due to rounding, they may not be. > Here's a run using Python 3.2: > >>>> [0.0 + i*width for i in range(8)] > [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] > > The 4th and 7th values have rounding errors, the rest are exact No they are not. Their errors are just smaller and not visible with 16 digits. >>> width = (2.1 - 0.0)/7 >>> ['%20.18f' % x for x in [0.0 + i*width for i in range(8)]] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.899999999999999911', '1.199999999999999956', '1.500000000000000000', '1.799999999999999822', '2.100000000000000089'] On 9/24/2011 10:18 AM, Arnaud Delobelle wrote: > ((n-i)*a + i*b)/n for i in range(n+1) >>> ['%20.18f' % x for x in [((7-i)*0.0 + i*2.1)/7 for i in range(8)]] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000133', '1.199999999999999956', '1.500000000000000000', '1.800000000000000266', '2.100000000000000089'] In the two places where this disagrees with the previous result, I believe it is worse. The *0.0 adds nothing. You are still multiplying an inexactly represented 2.1 by increasingly large numbers. Even 7*2.1/7 is not exact! My answer is the same as Mark's. Do exact calculation with fractions (whether using Fraction or not) and convert to float. I believe the least common multiple of a.as_integer_ratio[1], b.as_integer_ratio[1], and n is the common denominator needed to convert the numerators to a range() output. For the current problem, that is lcm(10,7) = 70. The best you can do for this example is >>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', '1.800000000000000044', '2.100000000000000089'] Notice that the last place errors are all less than 50, so printing to 16 places will make them appear 'exact'. Without being fancy (to see than you can cancel 7), you get the same output with >>> ['%20.18f' % (i/70 ) for i in range(0, 148, 21)] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', '1.800000000000000044', '2.100000000000000089'] In the two places where these disagree with the first (your original) they are *better*, with absolute error in the last places of 22 versus 89 and 44 versus 178 for .9 and 1.8. The last place errors greater than 50 gave you the 'inexact' answers in your post, and indeed, they are not the best possible. -- Terry Jan Reedy From rantingrick at gmail.com Sat Sep 24 18:36:44 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 15:36:44 -0700 (PDT) Subject: Why is the shutil module called shutil? References: Message-ID: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> On Sep 23, 10:36?pm, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. > The shutil module for reference:http://docs.python.org/library/shutil.html#module-shutil Because even after 20 freaking years of evolution Python "heads of state" (or states of head) cannot be bi-partisan enough to agree on a freaking File and/or path object; remind you of any "body" we know? From rantingrick at gmail.com Sat Sep 24 18:41:22 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 15:41:22 -0700 (PDT) Subject: Python Mixins References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> On Sep 24, 3:57?am, Steven D'Aprano wrote: > class StandardTestMixin: > ? ? def test_requires_one_argument(self): > ? ? ? ? self.assertRaises(TypeError, self.func) > ? ? def test_has_docstring(self): > ? ? ? ? self.assertTrue(self.func.__doc__) And this is another example of why we need doc-string reforms. Here we have a well know "pythonista" (for lack of better word) who needs to write a test for doc-string inclusion because he refuses to get in the habit of writing them. People, EVERY method and function MUST have a doc-string! What is the purpose of having doc-strings if we are too lazy to use them! From jesus.ramirez.utexas at gmail.com Sat Sep 24 19:08:21 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Sat, 24 Sep 2011 16:08:21 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Message-ID: <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> I installed it from here: http://www.python.org/getit/releases/2.5.6/ What do you think a solution might be? From benjamin.kaplan at case.edu Sat Sep 24 19:33:35 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 24 Sep 2011 19:33:35 -0400 Subject: Python 2.5 zlib trouble In-Reply-To: <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: On Sat, Sep 24, 2011 at 7:08 PM, Jesramz wrote: > > I installed it from here: http://www.python.org/getit/releases/2.5.6/ > > What do you think a solution might be? > There is no binary installer on that page. That means you downloaded the source code and compiled it yourself. Yes, you didn't patch it. But it's still a self-compiled version of Python. In order to get zlib in a self-compiled version of Python, you need to install the appropriate -dev package. From a quick look at the repository, I think it's zlib1g-dev but I'm not sure. On Ubuntu, the development headers are in a different package than the libraries themselves. The development headers aren't needed when you're installing a binary that someone else compiled (for instance, anything you get from the package manager) but are needed if you're trying to build anything that uses the library. Since a good chunk of the Python stdlib isn't actually necessary to run Python, you can successfully build Python without getting a good chunk of the modules. ./configure will give you a list of the modules that won't get built at the end of its output. From python.list at tim.thechases.com Sat Sep 24 19:36:56 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 24 Sep 2011 18:36:56 -0500 Subject: Python Mixins In-Reply-To: <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> Message-ID: <4E7E6998.80102@tim.thechases.com> On 09/24/11 17:41, rantingrick wrote: > On Sep 24, 3:57 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> class StandardTestMixin: >> def test_requires_one_argument(self): >> self.assertRaises(TypeError, self.func) >> def test_has_docstring(self): >> self.assertTrue(self.func.__doc__) > > And this is another example of why we need doc-string reforms. Here we > have a well know "pythonista" (for lack of better word) who needs to > write a test for doc-string inclusion because he refuses to get in the > habit of writing them. People, EVERY method and function MUST have a > doc-string! What is the purpose of having doc-strings if we are too > lazy to use them! http://www.python.org/dev/peps/pep-0257/ """ The aim of this PEP is to standardize the high-level structure of docstrings: what they should contain, and how to say it (without touching on any markup syntax within docstrings). The PEP contains conventions, not laws or syntax. """ You keep saying the word "MUST". I do not think it means what you think it means. Just for the record [1], [2], [3], [4] all in my first page of search Google search results. Pot, meet kettle. -tkc [1] http://mail.python.org/pipermail/python-list/2009-September/1220068.html [2] http://mail.python.org/pipermail//python-list/2011-July/1276021.html [3] http://mail.python.org/pipermail/python-list/2010-March/1237898.html [4] http://mail.python.org/pipermail/python-list/2010-June/1246305.html From tjreedy at udel.edu Sat Sep 24 20:31:06 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 20:31:06 -0400 Subject: Python Mixins In-Reply-To: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/24/2011 4:57 AM, Steven D'Aprano wrote: > Python says is that issubclass(Cat, Yamlafiable) will return True. The > *interpretation* of that fact is entirely up to you. If you want to > interpret it as meaning that cats are Yamlafiables, go right ahead. If you > want to interpret it as a technical result with no semantic meaning, that's > fine too. After all, just because "ram" in "programming" returns True > doesn't actually mean anything about male sheep and computing. Today's comics had a strip in which girl A suggests to girl B that they go to a disco to disco-ver someone interesting. > In fact, even in real life, the ancestor/descendant metaphor creaks. What > should we make of bacteria which exchange DNA with other species of > bacteria? That the human concept of 'species' does not really apply to bacteria. And similarly, that the CompSci concept of 'class' may also not always fit what we want to model. > Which is the ancestor and which is the descendant? How about > symbionts like lichen? What about when we splice genes from one species > into another? So even in real life, there are multiple inheritance and > mixins. Good point. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 24 20:40:36 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 20:40:36 -0400 Subject: Why is the shutil module called shutil? In-Reply-To: References: Message-ID: On 9/23/2011 11:36 PM, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. > The shutil module for reference: http://docs.python.org/library/shutil.html#module-shutil I think it would be nice if the doc explained. Feel free to open a doc issue to add '(sh-ell util-ities)' or something after "The shutil " and add me, terry.reedy, as nosy. -- Terry Jan Reedy From lists at cheimes.de Sat Sep 24 20:51:28 2011 From: lists at cheimes.de (Christian Heimes) Date: Sun, 25 Sep 2011 02:51:28 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: Am 25.09.2011 01:33, schrieb Benjamin Kaplan: > There is no binary installer on that page. That means you downloaded > the source code and compiled it yourself. Yes, you didn't patch it. > But it's still a self-compiled version of Python. > > In order to get zlib in a self-compiled version of Python, you need to > install the appropriate -dev package. From a quick look at the > repository, I think it's zlib1g-dev but I'm not sure. > > On Ubuntu, the development headers are in a different package than the > libraries themselves. The development headers aren't needed when > you're installing a binary that someone else compiled (for instance, > anything you get from the package manager) but are needed if you're > trying to build anything that uses the library. Since a good chunk of > the Python stdlib isn't actually necessary to run Python, you can > successfully build Python without getting a good chunk of the modules. > ../configure will give you a list of the modules that won't get built > at the end of its output. On recent Ubuntu and Debian versions, the dev packages aren't enough for old versions of Python. Anything older than Python 2.7.2 requires a tweak in order to make Python find the shared libraries. It's all explained in my blog posting. Debian's new multiarch features has broken Python's main setup.py because it tries to find the libraries itself instead of relying on ld.so and gcc. Barry has already fixed the issue for 2.7.2 and recent 3.2. Christian PS: Linux 3.x is going to cause trouble with older versions of Python, too. Wanna know more? Have a look: http://lipyrary.blogspot.com/ From steve+comp.lang.python at pearwood.info Sat Sep 24 22:13:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 12:13:26 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7e8e47$0$29966$c3e8da3$5496439d@news.astraweb.com> Arnaud Delobelle wrote: > On these examples, using fractions is no better than what I suggested > in my previous post. I'm sorry, I can't see your previous post. Perhaps it isn't available on my news provider? -- Steven From steve+comp.lang.python at pearwood.info Sat Sep 24 22:36:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 12:36:42 +1000 Subject: Suggested coding style References: <20110924191048.GH19422@johnsons-web.com> Message-ID: <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> MRAB wrote: > On 24/09/2011 20:10, Tim Johnson wrote: >> * Passiday [110924 09:47]: >> <...> >>> I have been coding in many other languages, most of the time it was >>> Java and C#. I don't like the function mess of PHP (ie, loads and >>> loads of functions without any namespaces etc), but I'd like to think >>> that Python is different. >> It is ... >> >>> In my brief coding experience I have stumbled upon Python zfill(width) >>> method, and I thought, really, do you have to include such a narrow- >>> purpose method in the basic method set? Perhaps there are more such >>> methods that are nice when you need them, but then again, you don't >>> put all the possible methods in the standard set. >> I think that you have raised an interesting question here. I've >> been coding in python for 9 years and I have never used it. >> >>> Perhaps there is reason such method is in the basic library, and my >>> complaints are unbased? >> >> It could be some sort of legacy. I imagine we will hear from some >> more senior pythonists on this matter. >> > The documentation says "New in version 2.2.2". Which is about nine years old, so roughly half as old as Python itself. It's hardly a new feature. Just because Passiday and Tim don't use zfill doesn't mean it's not useful to some people. Here are examples of it in use, or people asking how to format numbers with leading zeroes: http://www.ruby-forum.com/topic/67378 http://stackoverflow.com/questions/134934/display-number-with-leading-zeros http://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros http://msdn.microsoft.com/en-us/library/dd260048.aspx http://www.ozgrid.com/forum/showthread.php?t=64193&page=1 http://www.google.com/codesearch#algXCqBNNP0/utils/zip2rep.py&q=lang:%5Epython$%20zfill%20case:yes&ct=rc&cd=7 http://www.google.com/codesearch#Wnd3W7C0RPM/lives_guide.tar.bz2%7C0MIk12cLwTg/desub.py&q=lang:%5Epython$%20zfill%20case:yes Padding numbers with leading zeroes is very common. I'm surprised that more languages don't make it a string method. -- Steven From jeanpierreda at gmail.com Sat Sep 24 22:55:10 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 24 Sep 2011 22:55:10 -0400 Subject: Suggested coding style In-Reply-To: <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: > Padding numbers with leading zeroes is very common. I'm surprised that > more languages don't make it a string method. By making it a string method, instead of a function, we force all implementations of strings to implement that method. That sort of sucks, and it's a reason not to include it as a method. It can, after all, be implemented as a function, and in doing so (with the appropriate operator overloading) that function could work with multiple implementations of strings. Instead any implementation of a string must implement that method. That's a waste. Of course, one could argue that there are very few string implementations. On the other hand, there were three in the stdlib in 2.x, and there are other concepts of strings (like ropes) that are more efficient for different use-cases. The third string in the stdlib, mmap, didn't even bother implementing the full string interface. It's just so damned big. (Also some methods didn't apply, like zfill, but hey!) At the very least, it's sort of ugly from my perspective to tack on trivial things like this to be string methods. But sure, yeah, as a bonus you get to do fewer imports. That's pretty great too, I guess. Devin On Sat, Sep 24, 2011 at 10:36 PM, Steven D'Aprano wrote: > MRAB wrote: > >> On 24/09/2011 20:10, Tim Johnson wrote: >>> * Passiday ?[110924 09:47]: >>> <...> >>>> I have been coding in many other languages, most of the time it was >>>> Java and C#. I don't like the function mess of PHP (ie, loads and >>>> loads of functions without any namespaces etc), but I'd like to think >>>> that Python is different. >>> ? ?It is ... >>> >>>> In my brief coding experience I have stumbled upon Python zfill(width) >>>> method, and I thought, really, do you have to include such a narrow- >>>> purpose method in the basic method set? Perhaps there are more such >>>> methods that are nice when you need them, but then again, you don't >>>> put all the possible methods in the standard set. >>> ? ?I think that you have raised an interesting question here. I've >>> ? ?been coding in python for 9 years and I have never used it. >>> >>>> Perhaps there is reason such method is in the basic library, and my >>>> complaints are unbased? >>> >>> ? ?It could be some sort of legacy. I imagine we will hear from some >>> ? ?more senior pythonists on this matter. >>> >> The documentation says "New in version 2.2.2". > > Which is about nine years old, so roughly half as old as Python itself. > It's hardly a new feature. > > Just because Passiday and Tim don't use zfill doesn't mean it's not useful > to some people. Here are examples of it in use, or people asking how to > format numbers with leading zeroes: > > http://www.ruby-forum.com/topic/67378 > http://stackoverflow.com/questions/134934/display-number-with-leading-zeros > http://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros > http://msdn.microsoft.com/en-us/library/dd260048.aspx > http://www.ozgrid.com/forum/showthread.php?t=64193&page=1 > > http://www.google.com/codesearch#algXCqBNNP0/utils/zip2rep.py&q=lang:%5Epython$%20zfill%20case:yes&ct=rc&cd=7 > > http://www.google.com/codesearch#Wnd3W7C0RPM/lives_guide.tar.bz2%7C0MIk12cLwTg/desub.py&q=lang:%5Epython$%20zfill%20case:yes > > Padding numbers with leading zeroes is very common. I'm surprised that > more languages don't make it a string method. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From anacrolix at gmail.com Sun Sep 25 00:56:15 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Sun, 25 Sep 2011 14:56:15 +1000 Subject: Why is the shutil module called shutil? In-Reply-To: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> Message-ID: Please continue On Sun, Sep 25, 2011 at 8:36 AM, rantingrick wrote: > On Sep 23, 10:36?pm, Fletcher Johnson wrote: >> The topic says it all: >> Why is shutil named shutil? What does it stand for? This is just a >> mild curiosity of mine. >> The shutil module for reference:http://docs.python.org/library/shutil.html#module-shutil > > Because even after 20 freaking years of evolution Python "heads of > state" (or states of head) cannot be bi-partisan enough to agree on a > freaking File and/or path object; remind you of any "body" we know? > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Sun Sep 25 01:21:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 15:21:31 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > On 9/24/2011 9:53 AM, Steven D'Aprano wrote: [...] >>>>> [0.0 + i*width for i in range(8)] >> [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] >> >> The 4th and 7th values have rounding errors, the rest are exact > > No they are not. Their errors are just smaller and not visible with 16 > digits. Pardon. I meant that they were as close to exact as is possible in binary floats. With the exception of 0.8999... and 1.7999... I don't believe any other float can be closer to the exact value. I did mention that "If the exact value isn't representable as a float, I'm okay with returning the nearest possible float." :) -- Steven From steve+comp.lang.python at pearwood.info Sun Sep 25 01:31:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 15:31:14 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Sun, Sep 25, 2011 at 3:01 AM, Steven D'Aprano > wrote: >> Mark Dickinson wrote: >> >>> Using Fraction for intermediate calculations actually works perfectly >>> for this, since conversions from float to Fraction are exact, while >>> conversions from Fraction to float are correctly rounded. ?So if >>> you're using Python, you're not too bothered about efficiency, and you >>> want provably correctly-rounded results, why not use Fraction? >>> >> Ah, I knew it was too easy! > > Try using Fraction for the start and stop too: If you look again at the code I used, I did. I just did it inside the list comp. >>>> from fractions import Fraction as F >>>> start,stop,n = F(0),F(21,10),7 >>>> [float(start+i*(stop-start)/n) for i in range(n+1)] > [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>>> [float(start+i*(stop-start)/n) for i in range(n+1)] > [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] Something looks a tad suspicious here... the two list comps are identical, but give completely different results, even though you don't re-assign start and stop between calls. You're not editing your results are you? But seriously, you were freaking me out there for a bit. I couldn't see why pulling the conversion to fraction outside of the list comp was giving different results. And then it hit me... >>> 2.1 == F(21, 10) False You're testing different numbers from me. Try again with F(2.1) as the stop value. -- Steven From ladasky at my-deja.com Sun Sep 25 01:38:14 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 24 Sep 2011 22:38:14 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 24, 6:53?am, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. Use numpy. >>> from numpy import mgrid >>> seq = mgrid[0.0:2.1:8j] >>> seq array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1]) >>> for x in seq: print repr(x) 0.0 0.29999999999999999 0.59999999999999998 0.89999999999999991 1.2 1.5 1.7999999999999998 2.1000000000000001 From rosuav at gmail.com Sun Sep 25 02:02:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 16:02:47 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:31 PM, Steven D'Aprano wrote:>> If you look again at the code I used, I did. I just did it inside the list> comp. You did, but you created a Fraction from a float; my version used Fraction(21,10) instead of (effectively) Fraction(2.1). My description was a little sloppy, but what I meant was to use Fraction for the actual arguments to the "function" that this is implementing. > Something looks a tad suspicious here... the two list comps are identical, > but give completely different results, even though you don't re-assign > start and stop between calls. You're not editing your results are you? > Whooops! I had a whole lot of other commands in the scrollback (displaying intermediate results and such), and elided the rather crucial reassignment of parameters along with them! Fortunately, thanks to my reiplophobia, I still have the original session up in IDLE. This is even the most recent thing in it. >>> sys.version '3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]' >>> from fractions import Fraction as F >>> start,stop,n = F(0),F(21,10),7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>> start, stop, n = F(-1), F(11,10), 7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] There, now it's honest. Sorry about that!! ChrisA From tjreedy at udel.edu Sun Sep 25 02:07:25 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 Sep 2011 02:07:25 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/25/2011 1:21 AM, Steven D'Aprano wrote: > Terry Reedy wrote: > >> On 9/24/2011 9:53 AM, Steven D'Aprano wrote: > [...] >>>>>> [0.0 + i*width for i in range(8)] >>> [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] >>> >>> The 4th and 7th values have rounding errors, the rest are exact >> >> No they are not. Their errors are just smaller and not visible with 16 >> digits. > > Pardon. I meant that they were as close to exact as is possible in binary > floats. With the exception of 0.8999... and 1.7999... I don't believe any > other float can be closer to the exact value. > > I did mention that "If the exact value isn't representable as a float, I'm > okay with returning the nearest possible float." :) I do hope you did not stop with my lead-in sentence, and read to the end, where I gave you most of the answer you were looking for, without using the fractions module. -- Terry Jan Reedy From rosuav at gmail.com Sun Sep 25 02:09:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 16:09:01 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:31 PM, Steven D'Aprano wrote: >>>> 2.1 == F(21, 10) > False > Ahh, but that may just mean that Fraction doesn't implement an == that compares with floats. >>> 2.1==float(F(21,10)) True This may be because one oughtn't to use == with floats anyway. >>> F(2.1)==F(21,10) False >>> F(2.1) Fraction(4728779608739021, 2251799813685248) That denominator is a power of 2 (2**51 as it happens), which is unsurprising for something created from an IEEE floating point value. Rounding F(21,10) off to fit into float produces this same value. ChrisA From jialiuonlineshoe01 at 163.com Sun Sep 25 02:42:44 2011 From: jialiuonlineshoe01 at 163.com (amy) Date: Sat, 24 Sep 2011 23:42:44 -0700 (PDT) Subject: paypal wholesale NBA shoes (paypal payment)( http://www.24hour-buy.com/ ) Message-ID: <400cec1f-767d-4f99-9f2d-2188105f6d2b@k10g2000vbn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale lv shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale NBA shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale antick jeans (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale artful dudger (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hour-buy.com/) paypal wholesale clothing (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Prada (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Puma (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Sand (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Shox (paypal payment)( http://www.24hour-buy.com/) paypal wholesale soccer (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Versace (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Y-3 (paypal payment)( http://www.24hour-buy.com/ ) From ramapraba2653 at gmail.com Sun Sep 25 02:57:09 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 24 Sep 2011 23:57:09 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: <31d837d8-5274-4b9a-a1e8-f11cfc7779b1@i9g2000yqe.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From arnodel at gmail.com Sun Sep 25 03:36:23 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 25 Sep 2011 08:36:23 +0100 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24 September 2011 23:10, Terry Reedy wrote: > On 9/24/2011 10:18 AM, Arnaud Delobelle wrote: >> ? ? ?((n-i)*a + i*b)/n for i in range(n+1) > >>>> ['%20.18f' % x for x in [((7-i)*0.0 + i*2.1)/7 for i in range(8)]] > ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', > '0.900000000000000133', '1.199999999999999956', '1.500000000000000000', > '1.800000000000000266', '2.100000000000000089'] > > In the two places where this disagrees with the previous result, I believe > it is worse. The *0.0 adds nothing. You are still multiplying an inexactly > represented 2.1 by increasingly large numbers. Even 7*2.1/7 is not exact! Of course *0.0 adds nothing in this case. I was suggesting a general solution to the problem of partitioning the interval (a, b) into n subintervals of equal length. As for 7*2.1/7 it is exactly the same as 21/10 to 18 decimal places as the output of your own solution shows below. [...] > The best you can do for this example is >>>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] > ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', > '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', > '1.800000000000000044', '2.100000000000000089'] Can you give an implementation for any interval (a, b) where a, b are floats and any partition size n where n is a positive int? My suggestion was a simple answer which tries to avoid the obvious pitfalls that the naive approaches may fall into, as shown >>> def bary(start, stop, n): ... return [((n-i)*start + i*stop)/n for i in range(n+1)] ... >>> def width(start, stop, n): ... width = stop - start ... return [start + i*width/n for i in range(n+1)] ... Here is where the 'width' approach will fail: >>> width(-1.0, 1e-20, 4) [-1.0, -0.75, -0.5, -0.25, 0.0] >>> bary(-1.0, 1e-20, 4) [-1.0, -0.75, -0.5, -0.25, 1e-20] -- Arnaud From steve+comp.lang.python at pearwood.info Sun Sep 25 05:30:03 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 19:30:03 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7ef49b$0$29987$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > I do hope you did not stop with my lead-in sentence, and read to the > end, where I gave you most of the answer you were looking for, without > using the fractions module. Yes, I read your entire post, thank you, and for my purposes I'm happy with the fractions module. -- Steven From t.omahony.dublin at gmail.com Sun Sep 25 08:31:50 2011 From: t.omahony.dublin at gmail.com (Timmy O'Mahony) Date: Sun, 25 Sep 2011 05:31:50 -0700 (PDT) Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server Message-ID: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Hey, I have a question on Stackoverflow at the moment that I thought I would put up here as it might get some more eyes (It has a bounty so feel free to answer there if you have a SO account!) ---- I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: - Log in to a remote website (this works) - Move to another page (this works) - Perform a POST by filling in a form (read on ...!) I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with different versions of python but the exact same packages (via pip requirements file), and the code only works on the two virtualenvs on my local development machine(2.6.1 and 2.7.2) - it won't work on either of my production VPSs :( In the failing cases, I can log in successfully, move to the correct page but when I submit the form, the remote server replies telling me that there has been an error - it's an application server error page ('we couldn't complete your request') and not a webserver error. - because I can successfully log in and maneuver to a second page, this doesn't seem to be a session or a cookie problem - it's particular to the final POST - because I can perform the operation on a particular machine with the EXACT same headers and data, this doesn't seem to be a problem with what I am requesting/posting - because I am trying the code on two separate VPS rented from different companies, this doesn't seem to be a problem with the VPS physical environment - because the code works on 2 different python versions, I can't imagine it being an incompabilty problem I'm completely lost at this stage as to why this wouldn't work. I've even 'turned-it-off-and-turn-it-on-again' because I just can't see what the problem could be. I've tried everything I can think of to get this working. I've been through all of the headers of the requests & responses and they are all the same between machines. The server I am trying to contact is a Tomcat server. It gives me a cookie called JSESSIONID and it also requires an apache.struct.token in the POST data which I am succesfully extracting with BeautifulSoup/lxml. Again, this works on 2 machines, so I don't think it's an ommision on my behalf, I think it's a compatibility or an encoding error. Any ideas welcome! From eaglebalti at gmail.com Sun Sep 25 09:47:43 2011 From: eaglebalti at gmail.com (Ashraf Ali) Date: Sun, 25 Sep 2011 06:47:43 -0700 (PDT) Subject: Information About Bollywood Famous Actresses Just For You Message-ID: <353fde50-2433-4cae-84b0-73b36871c95d@q26g2000vby.googlegroups.com> Just Visit and know about bollywood beautiful actresses http://bollywoodhotwallpaperz.blogspot.com/ From jeanpierreda at gmail.com Sun Sep 25 11:53:59 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 11:53:59 -0400 Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server In-Reply-To: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> References: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Message-ID: It might help to give more information about the machines. In particular, what versions of Python are on the production machines? Devin On Sun, Sep 25, 2011 at 8:31 AM, Timmy O'Mahony wrote: > Hey, I have a question on Stackoverflow at the moment that I thought I would put up here as it might get some more eyes (It has a bounty so feel free to answer there if you have a SO account!) > > ---- > > I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: > > - Log in to a remote website (this works) > - Move to another page (this works) > - Perform a POST by filling in a form (read on ...!) > > I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with different versions of python but the exact same packages (via pip requirements file), and the code only works on the two virtualenvs on my local development machine(2.6.1 and 2.7.2) - it won't work on either of my production VPSs :( > > In the failing cases, I can log in successfully, move to the correct page but when I submit the form, the remote server replies telling me that there has been an error - it's an application server error page ('we couldn't complete your request') and not a webserver error. > > - because I can successfully log in and maneuver to a second page, this doesn't seem to be a session or a cookie problem - it's particular to the final POST > > - because I can perform the operation on a particular machine with the EXACT same headers and data, this doesn't seem to be a problem with what I am requesting/posting > > - because I am trying the code on two separate VPS rented from different companies, this doesn't seem to be a problem with the VPS physical environment > > - because the code works on 2 different python versions, I can't imagine it being an incompabilty problem > I'm completely lost at this stage as to why this wouldn't work. I've even 'turned-it-off-and-turn-it-on-again' because I just can't see what the problem could be. > > I've tried everything I can think of to get this working. I've been through all of the headers of the requests & responses and they are all the same between machines. > > The server I am trying to contact is a Tomcat server. It gives me a cookie called JSESSIONID and it also requires an apache.struct.token in the POST data which I am succesfully extracting with BeautifulSoup/lxml. Again, this works on 2 machines, so I don't think it's an ommision on my behalf, I think it's a compatibility or an encoding error. > > Any ideas welcome! > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From t.omahony.dublin at gmail.com Sun Sep 25 12:48:22 2011 From: t.omahony.dublin at gmail.com (Timmy O'Mahony) Date: Sun, 25 Sep 2011 09:48:22 -0700 (PDT) Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server In-Reply-To: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> References: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Message-ID: <21653630.520.1316969302334.JavaMail.geo-discussion-forums@yqjw35> Good point. The two machines that the code works with are running python 2.6.1 and 2.7.2 and are running on my Mac (Snow Leopard) The two non-working machines are running python 2.6.6 and 2.7.1 and are on Debian 6 and Debian 5 respectively. They are VPSs managed by different providers. All of the installs are on separate virtuaenvs. From tim at akwebsoft.com Sun Sep 25 14:46:14 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 10:46:14 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110925184614.GK19422@johnsons-web.com> * Devin Jeanpierre [110924 19:07]: > > Padding numbers with leading zeroes is very common. I'm surprised that > > more languages don't make it a string method. > > By making it a string method, instead of a function, we force all > implementations of strings to implement that method. That sort of > sucks, and it's a reason not to include it as a method. Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) Just answer the first question, the second is rhetorical. I think that your answer, regardless of whether I agree with it may edify me serendipitously. > It can, after all, be implemented as a function, and in doing so > (with the appropriate operator overloading) that function could > work with multiple implementations of strings. Instead any > implementation of a string must implement that method. That's a > waste. I'm not sure what you mean. I've written my own `split' function. I don't believe that there would be any conflict if you wrote your own `zfill' function. Or if there would be, I'd want to know before I hurt myself. regards -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From petite.abeille at gmail.com Sun Sep 25 14:54:28 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Sun, 25 Sep 2011 20:54:28 +0200 Subject: Suggested coding style In-Reply-To: <20110925184614.GK19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> Message-ID: <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) It's a technical term: http://www.osnews.com/images/comics/wtfm.jpg From rantingrick at gmail.com Sun Sep 25 16:30:41 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 13:30:41 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> Message-ID: <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> On Sep 24, 11:56?pm, Matt Joiner wrote: > Please continue Well specifically we should have a look over the Ruby API's of "File", "Dir", and "IO". I don't believe we should copy them verbatim --as the Ruby API is not Pythonic-- however, it may be a good starting point for something that has been decades overdue within this community. There was the rejected Path object from PEP 355: http://www.python.org/dev/peps/pep-0355/ But it seems the "Anointed One" tossed the idea due to it's "versatility" and it being a subclass of string... is he joking? o_O First of all, what the hell is wrong with versatility Mr Van Rossum? Where else would you put these methods? True it may be a large collection, however, can YOU offer any suggestions as to where else we would put them or are YOU just going to latch on to your prejudices of path objects like your irrational fears of functional programming? Do you remember the map and lambda fiasco? We need you to get on board and push something through. When you hide your head in the sand and imagine everything is "peachy cream" you expose your backside for a swift kicking. [References:] Ruby File Object: http://www.ruby-doc.org/core/classes/File.html Ruby Dir Object: http://ruby-doc.org/core/classes/Dir.html Ruby IO Object: http://www.ruby-doc.org/core/classes/IO.html From rosuav at gmail.com Sun Sep 25 17:48:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 07:48:29 +1000 Subject: Suggested coding style In-Reply-To: <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille wrote: > > On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > >> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) > > It's a technical term: > > http://www.osnews.com/images/comics/wtfm.jpg Also, because technical people are opinionated windbags. Goes with the territory. :) Actually, it's partly because it's so easy to create standards. You don't like X? Create your own language in which it doesn't exist! You absolutely detest Y? Ignore it and use something else! But since we can't ignore _everything_ we dislike, there ends up a happy medium in which we all use the things that we dislike least, all the while ranting about those aspects of them that "absolutely, totally suck", and vowing that we could have done way better if we'd been in the position of Some Famous Guy back when he had that perfect opportunity to create a new and perfect standard, but he *blew it* by having a small and narrow view, etc, etc, etc... Of course, some of us manage to still be courteous and objective when discussing the things that suck, while others just go off on lengthy rants. And if you're willing to learn, it's not uncommon to start off complaining and end up appreciating. :) Chris Angelico From jeanpierreda at gmail.com Sun Sep 25 17:52:35 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 17:52:35 -0400 Subject: Why is the shutil module called shutil? In-Reply-To: <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: > Well specifically we should have a look over the Ruby API's of "File", > "Dir", and "IO". I don't believe we should copy them verbatim --as the > Ruby API is not Pythonic-- however, it may be a good starting point > for something that has been decades overdue within this community. Perhaps you would be interested in one of the recent threads on Python-Ideas. http://mail.python.org/pipermail/python-ideas/2011-September/011559.html Also please stop being abrasive and personally attacking other members of the Python community. Devin On Sun, Sep 25, 2011 at 4:30 PM, rantingrick wrote: > On Sep 24, 11:56?pm, Matt Joiner wrote: >> Please continue > > Well specifically we should have a look over the Ruby API's of "File", > "Dir", and "IO". I don't believe we should copy them verbatim --as the > Ruby API is not Pythonic-- however, it may be a good starting point > for something that has been decades overdue within this community. > > There was the rejected Path object from PEP 355: > ? ?http://www.python.org/dev/peps/pep-0355/ > > But it seems the "Anointed One" tossed the idea due to it's > "versatility" and it being a subclass of string... is he joking? o_O > > First of all, what the hell is wrong with versatility Mr Van Rossum? > Where else would you put these methods? True it may be a large > collection, however, can YOU offer any suggestions as to where else we > would put them or are YOU just going to latch on to your prejudices of > path objects like your irrational fears of functional programming? Do > you remember the map and lambda fiasco? > > We need you to get on board and push something through. When you hide > your head in the sand and imagine everything is "peachy cream" you > expose your backside for a swift kicking. > > [References:] > > Ruby File Object: > ? ? http://www.ruby-doc.org/core/classes/File.html > > Ruby Dir Object: > ? ?http://ruby-doc.org/core/classes/Dir.html > > Ruby IO Object: > ? ?http://www.ruby-doc.org/core/classes/IO.html > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at gmail.com Sun Sep 25 18:39:47 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 25 Sep 2011 23:39:47 +0100 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Sep 25, 2011 10:49 PM, "Chris Angelico" wrote: > And if you're willing to learn, it's not uncommon to start off > complaining and end up appreciating. :) +1 QOTW -- Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Sun Sep 25 18:50:17 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 15:50:17 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: Here is a *very* rough outline of my ideas. There are probably a few mistakes in there. I've decided on three main main objects. A File object, a Path object, and a Dir object. ## START ENLIGHTENMENT ## class Path: def __init__(self, path): # # Properties about the path: drive => str directory => str filename => str extension => str uncshare[1]=> ??? # # Mutations. def coerce(self) => File or Dir def normalize(self): => ip or Path? #normcase/normpath def expand_user(self): => ip or Path? def expand_vars(self): => ip or Path? def absolute(self) => ip or Path? #realpath/abspath def strip(self) => ip => remove one extension. def chmod(self, mode) => None def chown(self, uid, gid) => None [1] def rename(self, newname) => None def access(self, mode): => None #access def chroot(self) => None # # Introspection. def is_valid(self): # exists def is_absolute(self): #isabs def is_directory(self): #isdir def is_file(self): #isfile def is_link(self): #islnk def is_mount(self): #ismount def is_identical(self, other): #issamefile def time_accessed(self): #atime def time_modified(self): #mtime def time_changed(self): #ctime ## def utime(self, times) => None # # Inspection. def info_stat(self): #stat def info_lstat(self): #lstat def info_statvfs(self): #statvfs # # Extraction. def basename(self): => str #Do we need basename when properties exist? def partition(self) => (drive, path, filename, extension) #Do we need partition when properties exist? def splitunc(self): ??? def splitall(self): ??? def relpathto(self, dest): => ??? def pathconf(self, name): #pathconfig # # Modifying operations on links def link(self, newpath): ... def symlink(self, newlink): ... def readlink(self): ... def readlinkabs(self): ... class File: def new(path) (...All existing file methods here...) # # Mutate, Clone, Destroy. def rename(self, newname) => ip or File? def delete(self, overwrites=3) => None def copy(self, dst) => File def unlink(self) => None # # # Attribute mutation. def update(self) => None #touch def copy_mode(src) => None #copymode def copy_stat(src) => None #copystat def update_mode(dst) => None def update_stat(dst) => None # # Other def bytes(self): => int => 1292894 def size(self, fmtstr="{0:0.2f}") => str => "1.23 MB" def backup(self) => filename.bak{count} class Dir: def new(path) def open(path) # # Mutate, Clone, Destroy. def delete(self, onerror=None): => None def copy(self, dst, symlinks=True): => Dir # # Introspection. def get_paths(self, pattern=None): [Path, Path, ...] def get_dirs(self, pattern=None): => [Dir, Dir, ...] def get_files(self, pattern=None): => [File, File, ...] # def walk_paths(self, pattern=None): itereach->PathObj def walk_dirs(self, pattern=None): itereach->DirObj def walk_files(self, pattern=None): itereach->FileObj # def match(self, pattern) => bool def glob(self, pattern): => [Path, Path, ...] ####################################### # Not sure what to do with these yet. ####################################### def startfile(self) # startfile should part of os anyway. ## END ENLIGHTENMENT ## From rantingrick at gmail.com Sun Sep 25 19:50:13 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 16:50:13 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: <605ac6e9-0a83-4658-9240-8889980b1862@8g2000yqm.googlegroups.com> Oh the creative juices are flowing now!!! class Path: def __init__(self, path): def __coerce__(self) => File or Dir # # Properties about the path: drive => str directory => str filename => str extension => str ## uncshare[1]=> ??? # # Mutations. def expand_user(self): => ip or Path? def expand_vars(self): => ip or Path? def to_normpath(self): => ip #normcase/normpath def to_abspath(self) => ip #realpath/abspath def set_access(self, mode) => None def set_owner(self, uid, gid) => None def set_root(self, path) => None # # Introspection. def is_accessable(self, mode) => bool #access def is_valid(self) => bool # exists def is_absolute(self) => bool #isabs def is_directory(self) => bool #isdir def is_file(self) => bool #isfile def is_link(self) => bool #islnk def is_mount(self) => bool #ismount def is_same(self, path_Dir_or_File) => bool #issamefile # # Inspection, Extraction def get_abspath(self)=> Path def get_normpath(self) => Path ## def get_atime(self) => str #atime ## def get_mtime(self) => str #mtime ## def get_ctime(self) => str #ctime def get_stat(self) => stat #stat,lstat ## def get_statvfs(self) => stat #statvfs ## # do we really need this antiquity? ############################################################ # Question # ############################################################ # Should all the stat stuff like get_mtime, get_ctime, # # get_atime, etc... be accessed only under get_stat? I # # believe so! # ############################################################ def get_drive(self): => str def get_directory(self): => str def get_filename(self): => str (empty if is_dir) def get_extension(self): => str (empty if is_dir) # def split(self) => (drive, path, filename, extension) ## def splitunc(self): ??? ## def splitall(self): ??? ## def relpathto(self, dest): => ??? ## def pathconf(self, name): #pathconfig # # Modifying operations on links def link_new(self, newpath, symbolic=False): ... def link_read(self): ... def link_readabs(self): ... class File: def new(path) (...All existing file methods here...) # # Mutate, Clone, Destroy. def rename(self, newname) => ip or File? def delete(self, overwrites=3) => None def copy(self, dst) => File def unlink(self) => None # # # Attribute mutation. def update(self) => None #touch def copy_mode(src) => None #copymode def copy_stat(src) => None #copystat def update_mode(dst) => None def update_stat(dst) => None # # Other def get_bytes(self): => int => 1292894 def get_size(self, fmtstr="{0:0.2f}") => str => "1.23 MB" def backup(self) => filename.bak{count} class Dir: def new(path) def open(path) # # Mutate, Clone, Destroy. def delete(self, onerror=None): => None def copy(self, dst, symlinks=True): => Dir # # Introspection. def get_paths(self, pattern=None): [Path, Path, ...] def get_dirs(self, pattern=None): => [Dir, Dir, ...] def get_files(self, pattern=None): => [File, File, ...] def walk_paths(self, pattern=None): itereach->PathObj def walk_dirs(self, pattern=None): itereach->DirObj def walk_files(self, pattern=None): itereach->FileObj ############################################################ # Question # ############################################################ # Do we really need "get_*" AND "walk_*"? I believe we # # should choose one set of three # ############################################################ def match(self, pattern) => bool # Do we need match when re would suffice? def glob(self, pattern): => [Path, Path, ...] ############################################################ # Excommunicated Methods. ############################################################ def startfile(self) # startfile should part of os anyway. From jeanpierreda at gmail.com Sun Sep 25 20:23:47 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 20:23:47 -0400 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: > Why does it suck? The gist of what I was saying is that it's possible to define functions that do this "generically" so that one implementation of zfill can work with multiple implementations of strings. Having to reimplement every time when one implementation would do is bothersome and generally isn't done unless it has to be (thus why mmap lacks a zfill method). Having to do more work than necessary "sucks", as does having partial str implementations that don't do everything str does. Ideally, I would claim that if some interface will have multiple implementations, it should have as few methods as possible to make implementation as easy as possible, and move as much as possible _away_ from methods and into functions that work with arbitrary implementations of the interface. This minimizes the amount of work that must be done for implementors and thus makes life better. It's also true that it's "bad practice" to have objects with large APIs, not for convenience reasons but because it increases object coupling, something that "good" object oriented design seeks to eliminate. The idea there is that the less ways you can have your object interacted with / interact with other objects, the easier it is to think of the way state flows. I agree with this in principle, but it doesn't really matter for strings. The situation I see with something like zfill as-a-method is that it has nearly negligible benefit (less imports vs function?) and some detriment. So I would conclude it should not exist. Other people look at this differently. > Also, because technical people are opinionated windbags. Pardon? Devin On Sun, Sep 25, 2011 at 5:48 PM, Chris Angelico wrote: > On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille > wrote: >> >> On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: >> >>> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) >> >> It's a technical term: >> >> http://www.osnews.com/images/comics/wtfm.jpg > > Also, because technical people are opinionated windbags. Goes with the > territory. :) Actually, it's partly because it's so easy to create > standards. You don't like X? Create your own language in which it > doesn't exist! You absolutely detest Y? Ignore it and use something > else! But since we can't ignore _everything_ we dislike, there ends up > a happy medium in which we all use the things that we dislike least, > all the while ranting about those aspects of them that "absolutely, > totally suck", and vowing that we could have done way better if we'd > been in the position of Some Famous Guy back when he had that perfect > opportunity to create a new and perfect standard, but he *blew it* by > having a small and narrow view, etc, etc, etc... > > Of course, some of us manage to still be courteous and objective when > discussing the things that suck, while others just go off on lengthy > rants. And if you're willing to learn, it's not uncommon to start off > complaining and end up appreciating. :) > > Chris Angelico > -- > http://mail.python.org/mailman/listinfo/python-list > From python at mrabarnett.plus.com Sun Sep 25 20:47:58 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 26 Sep 2011 01:47:58 +0100 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <4E7FCBBE.4070806@mrabarnett.plus.com> On 26/09/2011 01:23, Devin Jeanpierre wrote: >> Why does it suck? > > The gist of what I was saying is that it's possible to define > functions that do this "generically" so that one implementation of > zfill can work with multiple implementations of strings. Having to > reimplement every time when one implementation would do is bothersome > and generally isn't done unless it has to be (thus why mmap lacks a > zfill method). Having to do more work than necessary "sucks", as does > having partial str implementations that don't do everything str does. > > Ideally, I would claim that if some interface will have multiple > implementations, it should have as few methods as possible to make > implementation as easy as possible, and move as much as possible > _away_ from methods and into functions that work with arbitrary > implementations of the interface. This minimizes the amount of work > that must be done for implementors and thus makes life better. > [snip] I would have thought that a better solution would be to specify a minimal set of methods in an abstract superclass and write the additional methods using that minimal set. The concrete string implementations would be descended from the superclass and would still be able to override the additional methods with more efficient code were desired, such as in the 'str' class. From tjreedy at udel.edu Sun Sep 25 20:58:57 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 Sep 2011 20:58:57 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/25/2011 3:36 AM, Arnaud Delobelle wrote: > On 24 September 2011 23:10, Terry Reedy wrote: >> The best you can do for this example is >>>>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] >> ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', >> '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', >> '1.800000000000000044', '2.100000000000000089'] > > Can you give an implementation for any interval (a, b) where a, b are > floats and any partition size n where n is a positive int? I was leaving that as an exercise for Stephen ;-) but since he is satisfied with using Franctions ... I accepted the challenge and (I believe) did it. I first separated float-fractions conversions from generating equally spaced fractions. While this does not make much if any difference if and when one converts back to floats, testing with (21,10), for instance, as input is much easier than with (2.1).as_integer_ratio() == (4728779608739021, 2251799813685248). In some applications, small integer ratios are wanted anyway instead of floats. The main complication in the code is getting all outputs to have the smallest possible common denominator across the entire series. #! python3 -- frange.py # Copyright 2011 Terry Jan Reedy: use with acknowledgement '''Generate n+1 equally spaced fractions or float given two endpoints and the number n of intervals''' from fractions import gcd def floatrange(a, b, n): '''Yield floats a, b, and n-1 equally spaced floats in between.''' for num,dem in fracrange(a.as_integer_ratio(), b.as_integer_ratio(), n): yield num/dem def fracrange(frac1, frac2, n): '''Yield fractions frac1, frac2 and n-1 equally spaced fractions in between. Fractions are represented as (numerator, denominator > 0) pairs. For output, use the smallest common denominator of the inputs that makes the numerator range an even multiple of n. ''' n1, d1 = frac1 n2, d2 = frac2 dem = d1 * d2 // gcd(d1, d2) start = n1 * (dem // d1) stop = n2 * (dem // d2) rang = stop - start q, r = divmod(rang, n) if r: gcd_r_n = gcd(r, n) m = n // gcd_r_n dem *= m start *= m stop *= m step = rang // gcd_r_n # rang * m // n else: step = q # if r==0: gcd(r,n)==n, m==1, rang//n == q for num in range(start, stop+1, step): yield num,dem for (i,j), x in zip(fracrange((0,1), (21,10), 7), floatrange(0.0, 2.1, 7)): print((i,j), '%20.18f' % (i/j ), '%20.18f' % x ) print() for i,j in fracrange((1,10), (22,10), 7): print(i,j) print() for i,j in fracrange((1,5), (1,1), 6): print(i,j) # output (0, 10) 0.000000000000000000 0.000000000000000000 (3, 10) 0.299999999999999989 0.299999999999999989 (6, 10) 0.599999999999999978 0.599999999999999978 (9, 10) 0.900000000000000022 0.900000000000000022 (12, 10) 1.199999999999999956 1.199999999999999956 (15, 10) 1.500000000000000000 1.500000000000000000 (18, 10) 1.800000000000000044 1.800000000000000044 (21, 10) 2.100000000000000089 2.100000000000000089 1 10 4 10 7 10 10 10 13 10 16 10 19 10 22 10 3 15 5 15 7 15 9 15 11 15 13 15 15 15 -- Terry Jan Reedy From jeanpierreda at gmail.com Sun Sep 25 21:15:49 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 21:15:49 -0400 Subject: Suggested coding style In-Reply-To: <4E7FCBBE.4070806@mrabarnett.plus.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <4E7FCBBE.4070806@mrabarnett.plus.com> Message-ID: > I would have thought that a better solution would be to specify a > minimal set of methods in an abstract superclass and write the > additional methods using that minimal set. > > The concrete string implementations would be descended from the > superclass and would still be able to override the additional methods > with more efficient code were desired, such as in the 'str' class. This does sound better to me too! Devin On Sun, Sep 25, 2011 at 8:47 PM, MRAB wrote: > On 26/09/2011 01:23, Devin Jeanpierre wrote: >>> >>> ?Why does it suck? >> >> The gist of what I was saying is that it's possible to define >> functions that do this "generically" so that one implementation of >> zfill can work with multiple implementations of strings. Having to >> reimplement every time when one implementation would do is bothersome >> and generally isn't done unless it has to be (thus why mmap lacks a >> zfill method). Having to do more work than necessary "sucks", as does >> having partial str implementations that don't do everything str does. >> >> Ideally, I would claim that if some interface will have multiple >> implementations, it should have as few methods as possible to make >> implementation as easy as possible, and move as much as possible >> _away_ from methods and into functions that work with arbitrary >> implementations of the interface. This minimizes the amount of work >> that must be done for implementors and thus makes life better. >> > [snip] > I would have thought that a better solution would be to specify a > minimal set of methods in an abstract superclass and write the > additional methods using that minimal set. > > The concrete string implementations would be descended from the > superclass and would still be able to override the additional methods > with more efficient code were desired, such as in the 'str' class. > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Sun Sep 25 21:42:55 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 11:42:55 +1000 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Mon, Sep 26, 2011 at 10:23 AM, Devin Jeanpierre wrote: >> Also, because technical people are opinionated windbags. > > Pardon? No offense intended; just look at this list and you'll see how opinionated people can be, and how willing to express those opinions in many words! Frank and courteous exchange of views, one of the best ways to learn about the subject matter... and about the other programmers too. ChrisA From tim at akwebsoft.com Sun Sep 25 22:55:26 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 18:55:26 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <20110926025526.GN19422@johnsons-web.com> * Devin Jeanpierre [110925 16:37]: > > Why does it suck? > > The gist of what I was saying is that it's possible to define > functions that do this "generically" so that one implementation of > zfill can work with multiple implementations of strings. That is kind of 'spot on' for me. Before I started using python, I worked in rebol - where (at that time), there was a limited number of function names available because of limited namespacing (and the binary was a fraction the size of python). So I learned to take that approach. > Having to > reimplement every time when one implementation would do is bothersome > and generally isn't done unless it has to be (thus why mmap lacks a > zfill method). Having to do more work than necessary "sucks", as does > having partial str implementations that don't do everything str does. > > Ideally, I would claim that if some interface will have multiple > implementations, it should have as few methods as possible to make > implementation as easy as possible, and move as much as possible > _away_ from methods and into functions that work with arbitrary > implementations of the interface. This minimizes the amount of work > that must be done for implementors and thus makes life better. > > It's also true that it's "bad practice" to have objects with large > APIs, not for convenience reasons but because it increases object > coupling, something that "good" object oriented design seeks to > eliminate. The idea there is that the less ways you can have your > object interacted with / interact with other objects, the easier it is > to think of the way state flows. I agree with this in principle, but > it doesn't really matter for strings. > > The situation I see with something like zfill as-a-method is that it > has nearly negligible benefit (less imports vs function?) and some > detriment. So I would conclude it should not exist. Other people look > at this differently. Good response. Thank you. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From tim at akwebsoft.com Sun Sep 25 22:59:20 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 18:59:20 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <20110926025920.GO19422@johnsons-web.com> * Chris Angelico [110925 13:50]: > On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille > wrote: > > > > On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > > > >> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) > > > > It's a technical term: > > > > http://www.osnews.com/images/comics/wtfm.jpg > > Also, because technical people are opinionated windbags. Goes with the > territory. :) I always felt that to be courteous, to the point and reserved cost me less typing time. And since I'm self-employed and only charge for productive time for clients, that's being cost-conscious for me. Of course I've been known to get a little crazy about PHP. So don't let me get started... BTW: If you like ranting as a spectator sport, I have found the Common Lisp newsgroup to be among the most spectacular. But that's just me. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From rosuav at gmail.com Sun Sep 25 23:41:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 13:41:29 +1000 Subject: Suggested coding style In-Reply-To: <20110926025920.GO19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <20110926025920.GO19422@johnsons-web.com> Message-ID: On Mon, Sep 26, 2011 at 12:59 PM, Tim Johnson wrote: > BTW: If you like ranting as a spectator sport, I have found the > ?Common Lisp newsgroup to be among the most spectacular. But that's > ?just me. > I do, actually, but I don't need to add another newsgroup. Rick provides plenty of material here, and I can easily sate myself in just a few other places that I frequent. It's quite amusing to watch those holy wars erupt... And every once in a while, they actually prove quite educative. I'm not sure how it happens, nor how to trigger it - hmm, perhaps this should be the subject of a scientific paper. "On ranting newsgroups and how to make them productive". ChrisA From wuwei23 at gmail.com Mon Sep 26 00:18:27 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 25 Sep 2011 21:18:27 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> <605ac6e9-0a83-4658-9240-8889980b1862@8g2000yqm.googlegroups.com> Message-ID: <098aa3ae-070f-46c5-99e4-f8b712561029@i33g2000yqm.googlegroups.com> On Sep 26, 9:50?am, rantingrick wrote: > Oh the creative juices are flowing now!!! It's a pity they won't flow into a PyPI project to aggregate interest in such replacement objects. But please, spam us some more with your code stubs. It's a nice change from invective. From bmacinnis at comcast.net Mon Sep 26 03:45:11 2011 From: bmacinnis at comcast.net (bmacinnis at comcast.net) Date: Mon, 26 Sep 2011 03:45:11 -0400 Subject: Counting bits in large string / bit vector Message-ID: In Perl I can create a large bit vector as follows: vec($bitmap,10000000,1) = 0; # this will create a bit string of all zeros To set bits I may using commands like: vec($bitmap,1000, 1) = 1 # turn on bit 1000 vec($bitmap,10000, 1) = 1 # turn on bit 10000 vec($bitmap,1000000, 1) = 1 # turn on bit 10000000 which would set three bits in the string $bitmap - Note: in perl I don't even have to declare $bitmap until I use it in the vec command. Anyway there is a very cool perl command which return the number of bits set in a large bitmap string instantly. The command is: $setbits = unpack("%32b*", $bitmap); Which in this case would store the number 3 in $setbits Is there an equivalent command in python that would immediately provide the number of set bits in a large bit vector/string I know I could loop through but when you have 10,000,000 or 100,000,000 bits, the looping takes quite a while the perl unpack is instant. Thanks for any help you could provide -------------- next part -------------- An HTML attachment was scrubbed... URL: From nizamov.shawkat at gmail.com Mon Sep 26 03:56:56 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Mon, 26 Sep 2011 09:56:56 +0200 Subject: Counting bits in large string / bit vector In-Reply-To: References: Message-ID: > Is there an equivalent command in python that would immediately provide the > number of set bits in a large bit vector/string > You might be able to achieve this using numpy boolean array and, e.g, the arithmetic sum function or something similar. There is also another library http://pypi.python.org/pypi/bitarray which resembles numpy's bit array. Hope it helps, S.Nizamov From gelonida at gmail.com Mon Sep 26 04:55:42 2011 From: gelonida at gmail.com (Gelonida N) Date: Mon, 26 Sep 2011 10:55:42 +0200 Subject: Hierarchical commnd line parsing / help texts Message-ID: Hi, So far I used optparse.OptionParser for parsing command line arguments for my python scripts. So far I was happy, with a one level approach, where I get only one help text Now I'd like to create a slightly different python script and wondered which approach / module might be best for implementing the parsing and generation of help texts. Please look at my example (let's emulate a shell in python) $ ./sh.py or $ ./sh.py -h Should create the top level help text and list possible commands .e.g. ls rm cat and list some commands with potential sub commands .e.g. net db then if I typed ./sh.py -h I'd like to get the helptext for the specified command. For some more complex commands I'd even like to be able to type /sh.py -h Ideally, I would like to be able to parse generic options before commands / sub commands and less generic options after the commands ./sh.py -v ls -a Thanks in advance for suggestions From clp2 at rebertia.com Mon Sep 26 05:10:17 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 26 Sep 2011 02:10:17 -0700 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 1:55 AM, Gelonida N wrote: > Hi, > > So far I used optparse.OptionParser for parsing command line arguments > for my python scripts. So far I was happy, with a one level approach, > where I get only one help text > > Now I'd like to create a slightly different python script and wondered > which approach / module might be best for implementing the parsing and > generation of help texts. > then if I typed ./sh.py -h > I'd like to get the helptext for the specified command. http://docs.python.org/library/argparse.html It is capable of handling sub-commands and the display of subcommand-specific help text. Cheers, Chris From __peter__ at web.de Mon Sep 26 05:11:07 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Sep 2011 11:11:07 +0200 Subject: Counting bits in large string / bit vector References: Message-ID: bmacinnis at comcast.net wrote: > In Perl I can create a large bit vector as follows: > vec($bitmap,10000000,1) = 0; # this will create a bit string of all > zeros > To set bits I may using commands like: > vec($bitmap,1000, 1) = 1 # turn on bit 1000 > vec($bitmap,10000, 1) = 1 # turn on bit 10000 > vec($bitmap,1000000, 1) = 1 # turn on bit 10000000 > which would set three bits in the string $bitmap - Note: in perl I don't > even have to declare $bitmap until I use it in the vec command. > Anyway there is a very cool perl command which return the number of bits > set in a large bitmap string instantly. > The command is: > $setbits = unpack("%32b*", $bitmap); > Which in this case would store the number 3 in $setbits > Is there an equivalent command in python that would immediately provide > the number of set bits in a large bit vector/string > I know I could loop through but when you have 10,000,000 or 100,000,000 > bits, the looping takes quite a while the perl unpack is instant. With numpy: >>> b = numpy.zeros(10**7, dtype=bool) >>> for x in 3, 4, 6: b[10**x] = True ... >>> b.sum() 3 I don't know how it's implemented, but it seems to be quite fast. From gelonida at gmail.com Mon Sep 26 05:28:59 2011 From: gelonida at gmail.com (Gelonida N) Date: Mon, 26 Sep 2011 11:28:59 +0200 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: On 09/26/2011 11:10 AM, Chris Rebert wrote: > On Mon, Sep 26, 2011 at 1:55 AM, Gelonida N wrote: >> Hi, >> >> So far I used optparse.OptionParser for parsing command line arguments >> for my python scripts. So far I was happy, with a one level approach, >> where I get only one help text >> >> Now I'd like to create a slightly different python script and wondered >> which approach / module might be best for implementing the parsing and >> generation of help texts. > >> then if I typed ./sh.py -h >> I'd like to get the helptext for the specified command. > > http://docs.python.org/library/argparse.html > > It is capable of handling sub-commands and the display of > subcommand-specific help text. > Thanks a lot. It seems it's time to start reading about argparse From arnodel at gmail.com Mon Sep 26 06:02:02 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Mon, 26 Sep 2011 11:02:02 +0100 Subject: Counting bits in large string / bit vector In-Reply-To: References: Message-ID: >>>> b = numpy.zeros(10**7, dtype=bool) >>>> for x in 3, 4, 6: b[10**x] = True > ... >>>> b.sum() > 3 Without numpy: >>> counts = [bin(i).count('1') for i in range(256)] >>> bytes = b"hello python"*100000 >>> len(bytes)*8 9600000 >>> sum(map(counts.__getitem__, bytes)) 4800000 Pretty fast as well. -- Arnaud From taleinat at gmail.com Mon Sep 26 07:23:04 2011 From: taleinat at gmail.com (Tal Einat) Date: Mon, 26 Sep 2011 04:23:04 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! Message-ID: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> The library is called RunningCalcs and is useful for running several calculations on a single iterable of values. https://bitbucket.org/taleinat/runningcalcs/ http://pypi.python.org/pypi/RunningCalcs/ I'd like some input on how this could be made more useful and how to spread the word about it. The library contains the base RunningCalc class and implementations of sub-classes for common calculations: sum, min/max, average, variance & standard deviation, n-largest & n-smallest. Additionaly a utility function apply_in_parallel() is supplied which makes running several calculations on an iterable easy (and fast!). Straight-forward example: mean_rc, stddev_rc = RunningMean(), RunningStdDev() for x in values: mean_rc.feed(x) stddev_rc.feed(x) mean, stddev = mean_rc.value, stddev_rc.value Examples using apply_in_parallel(): mean, stddev = apply_in_parallel(values, [RunningMean(), RunningStdDev()]) five_smallest, five_largest = apply_in_parallel(values, [RunningNSmallest(5), RunningNLargest(5)]) Comments and suggestions would be highly appreciated! From casevh at gmail.com Mon Sep 26 11:38:57 2011 From: casevh at gmail.com (casevh) Date: Mon, 26 Sep 2011 08:38:57 -0700 (PDT) Subject: Counting bits in large string / bit vector References: Message-ID: On Sep 26, 12:56?am, Nizamov Shawkat wrote: > > Is there an equivalent command in python that would immediately provide the > > number of set bits in a large bit vector/string > > You might be able to achieve this using numpy boolean array and, e.g, > the arithmetic sum function or something similar. > There is also another library ?http://pypi.python.org/pypi/bitarray > which resembles numpy's bit array. > > Hope it helps, > S.Nizamov You can also use gmpy or gmpy2. >>> a=gmpy2.mpz(123) >>> bin(a) '0b1111011' >>> gmpy2.hamdist(a,0) 6 >>> casevh From magguru.appalakonda at gmail.com Mon Sep 26 11:43:39 2011 From: magguru.appalakonda at gmail.com (Hot Hot) Date: Mon, 26 Sep 2011 08:43:39 -0700 (PDT) Subject: MY HOT BEAUTIFUL VIDEOS Message-ID: <980d6317-f747-498f-bb22-dd8432bf50be@i33g2000yqm.googlegroups.com> Mallika sharawath bolly wood bad sexy seens, Katrina Kaif very bad videos,Bipasa basu hot expose videos with John Abraham,Bollywood star Aishwarya rai romantic videos with Abhishek,At http://starsbikinihotshow140.co.cc/ Due to high sex cantest,I have hidden more details, click on right side of my website do not tell another person. From ian.g.kelly at gmail.com Mon Sep 26 12:39:16 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 26 Sep 2011 10:39:16 -0600 Subject: Counting bits in large string / bit vector Message-ID: On Sep 26, 2011 1:49 AM, wrote: > Is there an equivalent command in python that would immediately provide the number of set bits in a large bit vector/string Besides what others have said, if you expect the number of bits set to be small, you might just use a set. bits = set() # set bit 1000 bits.add(1000) # clear bit 2000000 bits.discard(2000000) # test bit 1000 if 1000 in bits: pass # get number of bits set len(bits) All of these operations are O(1), but if you expect to set a very large number of bits, then the space trade-off may not be practical. Cheers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From rahul_g_chaudhary at yahoo.com Mon Sep 26 13:45:42 2011 From: rahul_g_chaudhary at yahoo.com (Rahul) Date: Mon, 26 Sep 2011 10:45:42 -0700 (PDT) Subject: Python Weekly Message-ID: <13c6df6c-7ab5-4cf6-b82b-9e7631226a8b@i9g2000yqe.googlegroups.com> Hi Everyone, I have started a free weekly newsletter called Python Weekly which includes curated news, articles, new releases, software & tools, events, jobs etc about Python and related technologies. It's a great way to keep abreast of what's happening in Python land. You can subscribe to it here, http://www.pythonweekly.com/ Regards Rahul Chaudhary From jesus.ramirez.utexas at gmail.com Mon Sep 26 14:16:08 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Mon, 26 Sep 2011 11:16:08 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> I appreciate all the help, but I am still a little confused. Sorry, I'm a lay person. Should I download zlib1g-dev and install it to get the zlib module? and Alter the configure script to avoid future issues? Also about getting zlib I found the following: "I was able to recompile zlib $./configure --shared then recompile Python 2.5.1; I am now able to import the zlib module. cheers -sg" Does this mean that while in the zlib folder run ./configure shared and then install python? From ramit.prasad at jpmorgan.com Mon Sep 26 14:57:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 26 Sep 2011 14:57:52 -0400 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> > It seems it's time to start reading about argparse FYI, it only appears on Python 2.7+ Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From benjamin.kaplan at case.edu Mon Sep 26 15:04:45 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 26 Sep 2011 15:04:45 -0400 Subject: Python 2.5 zlib trouble In-Reply-To: <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> Message-ID: On Mon, Sep 26, 2011 at 2:16 PM, Jesramz wrote: > > I appreciate all the help, but I am still a little confused. Sorry, > I'm a lay person. > > Should I download zlib1g-dev and install it to get the zlib module? > > and Alter the configure script to avoid future issues? > > Also about getting zlib I found the following: > > "I was able to recompile zlib > > $./configure --shared > > then recompile Python 2.5.1; I am now able to import the zlib module. > > cheers > > -sg" > > Does this mean that while in the zlib folder run ./configure shared > and then install python? > -- Not quite. This person was talking about configuring zlib, not Python. Just about every Linux program out there has a ./configure file- it's part of GNU Autotools, which many programs use as an easy way to compile and install their software. Since the version of zlib on Ubuntu Natty doesn't work for Python 2.5, this person just compiled their own zlib (calling ./configure --shared; make; make install from the zlib *source* folder that they downloaded) and then compiled their own Python version (from the Python source folder that they downloaded) > http://mail.python.org/mailman/listinfo/python-list > From paul.nospam at rudin.co.uk Mon Sep 26 15:44:02 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 26 Sep 2011 20:44:02 +0100 Subject: Hierarchical commnd line parsing / help texts References: Message-ID: <874nzz3x8d.fsf@no-fixed-abode.cable.virginmedia.net> "Prasad, Ramit" writes: > This email is confidential... Probably a bad idea to post it to a world readable mailing list then :) From joncle at googlemail.com Mon Sep 26 16:07:43 2011 From: joncle at googlemail.com (Jon Clements) Date: Mon, 26 Sep 2011 13:07:43 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> Message-ID: On Sep 26, 12:23?pm, Tal Einat wrote: > The library is called RunningCalcs and is useful for running several > calculations on a single iterable of values. > > https://bitbucket.org/taleinat/runningcalcs/http://pypi.python.org/pypi/RunningCalcs/ > > I'd like some input on how this could be made more useful and how to > spread the word about it. > > The library contains the base RunningCalc class and implementations of > sub-classes for common calculations: sum, min/max, average, variance & > standard deviation, n-largest & n-smallest. Additionaly a utility > function apply_in_parallel() is supplied which makes running several > calculations on an iterable easy (and fast!). > > Straight-forward example: > > mean_rc, stddev_rc = RunningMean(), RunningStdDev() > for x in values: > ? ? mean_rc.feed(x) > ? ? stddev_rc.feed(x) > mean, stddev = mean_rc.value, stddev_rc.value > > Examples using apply_in_parallel(): > > mean, stddev = apply_in_parallel(values, [RunningMean(), > RunningStdDev()]) > five_smallest, five_largest = apply_in_parallel(values, > [RunningNSmallest(5), RunningNLargest(5)]) > > Comments and suggestions would be highly appreciated! You may not of heard of it, but the SAS language has something called PROC FREQ... I'm imagining that maybe this is where you should be taking this. Sorry I can't comment on the code, as I haven't really got time, but have a look! (I'd be willing to invest sometime with you, if you agree that's where something like this should be going...) Cheers, Jon. From python.list at tim.thechases.com Mon Sep 26 16:11:44 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Sep 2011 15:11:44 -0500 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E80DC80.8090808@tim.thechases.com> On 09/26/11 13:57, Prasad, Ramit wrote: >> It seems it's time to start reading about argparse > FYI, it only appears on Python 2.7+ However I believe it can be uneventfully copied and run under several versions earlier (likely back to 2.5, perhaps to 2.4 -- I no longer have 2.4 at my fingertips to test). -tkc From ian.g.kelly at gmail.com Mon Sep 26 16:33:54 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 26 Sep 2011 14:33:54 -0600 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: <4E80DC80.8090808@tim.thechases.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> <4E80DC80.8090808@tim.thechases.com> Message-ID: On Mon, Sep 26, 2011 at 2:11 PM, Tim Chase wrote: > On 09/26/11 13:57, Prasad, Ramit wrote: >>> >>> It seems it's time to start reading about argparse >> >> FYI, it only appears on Python 2.7+ > > However I believe it can be uneventfully copied and run under several > versions earlier (likely back to 2.5, perhaps to 2.4 -- I no longer have 2.4 > at my fingertips to test). For older versions it would be best to use the Google project, which I think is still maintained and backported: http://code.google.com/p/argparse/ From jabba.laci at gmail.com Mon Sep 26 16:39:28 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Mon, 26 Sep 2011 16:39:28 -0400 Subject: install packages with pip to older Python versions Message-ID: Hi, I have Python 2.7 on my system. Today I wanted to try Google App Engine but it runs on Python 2.5 at Google so I installed this version on my machine next to v2.7 to avoid compatibility problems. However, when I start the Python shell v2.5 and try to import something from the GAE SDK (for instance "from google.appengine.ext import webapp"), I get an error: "ImportError: No module named webob". (Note that with v2.7 I don't have this problem.) So, how can I install packages for a specific version of Python (here, v2.5)? With 2.7 I use "sudo pip install ". Thanks, Laszlo From tgugger at bex.net Mon Sep 26 16:56:51 2011 From: tgugger at bex.net (TOM) Date: Mon, 26 Sep 2011 13:56:51 -0700 (PDT) Subject: QA Engineering/ Python/ Contract/ Austin, TX Message-ID: Tom Gugger Independent Recruiter tgugger at bex.net US Citizens or Greencard On Site QA Engineering/ Python/ Contract/ Austin, TX This is an immediate start, such as next week. I need three contractors for a 4--6 month contract in Austin, TX for Quality Assurance Engineers. The location is Austin, TX. This is an automation project. Must Have ? Good Network domain knowledge such as TCP/IP. Must Have --- experience testing Data, Voice, and IPTV traffic. Must Have --- Strong Python A Plus --- Fanfare Please make sure all the required skills show on the resume. If interested and qualified, email resume to tgugger at bex.net. From clp2 at rebertia.com Mon Sep 26 17:03:49 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 26 Sep 2011 14:03:49 -0700 Subject: QA Engineering/ Python/ Contract/ Austin, TX In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 1:56 PM, TOM wrote: > Tom Gugger > Independent Recruiter > tgugger at bex.net > > US Citizens or Greencard > On Site > > > QA Engineering/ Python/ Contract/ Austin, TX > > This is an immediate start, such as next week. I need three > contractors Such postings belong on the Python jobs board (http://www.python.org/community/jobs/ ), not python-list/comp.lang.python. Cheers, Chris From atherun at gmail.com Mon Sep 26 21:07:31 2011 From: atherun at gmail.com (Atherun) Date: Mon, 26 Sep 2011 18:07:31 -0700 (PDT) Subject: Race condition deadlock in communicate when threading? Message-ID: In python 2.6.4 I have a fairly complex system running (copying and pasting it would be quite difficult). At its core there are builders that inherit from threading.Thread. I have some builders that run external tasks via popen and read output using communicate. I have the ability to run any number of builders in parallel. All of this uses logging as well, where each builder has their own logger they create from the base logger i.e. logging.getLogger("Logger. %s"%self.Name). When running several threads in parallel that each call popen and communicate functions, python just hangs, about 95% of the time. All of it, parent threads, any threads I started before I got to this step, it just stops responding. Stepping through it with pdb trying to find the deadlock will always make it work, killing the external app I called via popen, after it has hung, will make it move along as well. Looking at the stack traces using the code found http://code.activestate.com/recipes/577334-how-to-debug-deadlocked-multi-threaded-programs/ the threads stop running with the following stacks, this is the last output from the tracer before it stops responding.: File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) And out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() I'm trying to track this down so I can eliminate it for good as it pops up in multiple places from time to time. Any tips would be appreciated. From wuwei23 at gmail.com Mon Sep 26 23:11:13 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 26 Sep 2011 20:11:13 -0700 (PDT) Subject: install packages with pip to older Python versions References: Message-ID: On Sep 27, 6:39?am, Jabba Laci wrote: > So, how can I install packages for a specific version of Python (here, > v2.5)? With 2.7 I use "sudo pip install ". It's amazing what you can find when you look at the documentation: http://www.pip-installer.org/en/latest/index.html "You can use pip install --upgrade SomePackage to upgrade to a newer version, or pip install SomePackage==1.0.4 to install a very specific version." However, if you're not using virtualenv, I'd recommend looking at it as well: http://pypi.python.org/pypi/virtualenv From devplayer at gmail.com Tue Sep 27 02:45:21 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 26 Sep 2011 23:45:21 -0700 (PDT) Subject: Suggested coding style References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <20110926025920.GO19422@johnsons-web.com> Message-ID: <492cb266-01df-493c-86d2-1a994933e570@p11g2000yqe.googlegroups.com> On Sep 25, 11:41?pm, Chris Angelico wrote: > On Mon, Sep 26, 2011 at 12:59 PM, Tim Johnson wrote: > > BTW: If you like ranting as a spectator sport, I have found the > > ?Common Lisp newsgroup to be among the most spectacular. But that's > > ?just me. > > I do, actually, but I don't need to add another newsgroup. Rick > provides plenty of material here, and I can easily sate myself in just > a few other places that I frequent. It's quite amusing to watch those > holy wars erupt... > > And every once in a while, they actually prove quite educative. I'm > not sure how it happens, nor how to trigger it - hmm, perhaps this > should be the subject of a scientific paper. "On ranting newsgroups > and how to make them productive". > > ChrisA I think intellectual growth from rants works like this: Ranter: Bla bla, bad logic, poor facts, some point. Others: Bla bla you rant Mr Ranter, some logic, few facts, same point. Ranter: bad mouthing Others: bad mouthing back Ranter: Bla Bla, I don't rant, better logic counter facts, lots of opinion (to not get called a ranter) Others: Bla bla, You do rant Ranter, good counter logic and facts, same point (some reason needs to put Ranter "in his place") Ranter: Super Bla, long winded logic with some strong points, random but accurate facts out the wazzu (tries to save face) Others: Acknowleges Ranters point are accurate but claims they don't apply Ranter: makes case his points do. Others: agrees to disagree, silently picks mute Ranter, Ranter: picks a new topic and starts over. From devplayer at gmail.com Tue Sep 27 02:51:08 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 26 Sep 2011 23:51:08 -0700 (PDT) Subject: Suggested coding style References: Message-ID: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> By the way OP Passiday the title of the topic is "Suggested coding style". Are you suggesting a coding style or asking for a Python coding style or are you asking what IS the Python coding style. If you are asking what is the Python coding style. Google The Zen of Python. It's pretty much the dictum of coding style and referred to alot by many Pythoneers. From pavlovevidence at gmail.com Tue Sep 27 03:17:50 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 27 Sep 2011 00:17:50 -0700 (PDT) Subject: Race condition deadlock in communicate when threading? In-Reply-To: References: Message-ID: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> There's really not enough information for us to debug this, but one possibility is that your subprocess is using buffered I/O; you're expecting the external task to write a string, but it doesn't actually write that string because it's sitting in a buffer. First thing to try is to see if the program accepts some kind of command line argument to run in unbuffered mode (for instance, if you are calling a Python interpreter you can pass it the -u switch to force unbuffered I/O). If (like most programs) it doesn't have an option to disable buffering, you can try running it on a pty device (if you're on Unix). If worse comes to worst, see if there's a way to get the external task to print lots of extra output (a verbosity setting, for instance); that could work in a pinch until you can debug it more thoroughly. Carl Banks From r32813 at freescale.com Tue Sep 27 05:08:54 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 09:08:54 +0000 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 In-Reply-To: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> Message-ID: <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Hello all, I encounter this issue whereby I am not able to load cPickle module into the python I newly built. There is no issue when I load it right from the folder where the python executable and libpython2.7.so is built. However, it gives me this error when I load the same module using the installed files (python and all its modules, shared library from default /use/local folder that contains bin, lib, include sub-folders) from "make install" command. Does anyone know why? Here is the error:- $ python Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import cPickle Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '_extension_registry' From r32813 at freescale.com Tue Sep 27 05:28:31 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 09:28:31 +0000 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> Message-ID: <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. $ python Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import random Traceback (most recent call last): File "", line 1, in File "random.py", line 49, in import hashlib as _hashlib File "hashlib.py", line 136, in globals()[__func_name] = __get_hash(__func_name) File "hashlib.py", line 74, in __get_builtin_constructor import _sha256 ImportError: No module named _sha256 >>> From clp2 at rebertia.com Tue Sep 27 05:51:30 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 27 Sep 2011 02:51:30 -0700 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 In-Reply-To: <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Tue, Sep 27, 2011 at 2:28 AM, Wong Wah Meng-R32813 wrote: > I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. > ?File "hashlib.py", line 74, in __get_builtin_constructor > ? ?import _sha256 > ImportError: No module named _sha256 Did you get a message along the lines of "Python build finished, but the necessary bits to build these modules were not found:" when you built Python? Cheers, Chris From r32813 at freescale.com Tue Sep 27 06:04:50 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 10:04:50 +0000 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F59485@039-SN1MPN1-003.039d.mgd.msft.net> Yes I did. In fact earlier "make test" failed to execute due to _sha256 not found in one of the module testing. Earlier I ignored these failures from the build and make test as I thought they are not needed by my application. Now I can't use "random" module in my application. So I need to solve this issue. Here is the output of the build. Python build finished, but the necessary bits to build these modules were not found: _bsddb _curses _curses_panel _sqlite3 _ssl bsddb185 bz2 dl gdbm imageop linuxaudiodev ossaudiodev readline spwd sunaudiodev zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _ctypes termios Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Tuesday, September 27, 2011 5:52 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Error 'No module named _sha256' when importing random in python 2.7.1 On Tue, Sep 27, 2011 at 2:28 AM, Wong Wah Meng-R32813 wrote: > I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. > ?File "hashlib.py", line 74, in __get_builtin_constructor > ? ?import _sha256 > ImportError: No module named _sha256 Did you get a message along the lines of "Python build finished, but the necessary bits to build these modules were not found:" when you built Python? Cheers, Chris From yixuan178 at gmail.com Tue Sep 27 06:48:07 2011 From: yixuan178 at gmail.com (yixuan) Date: Tue, 27 Sep 2011 03:48:07 -0700 (PDT) Subject: error when use portable python 2.7.2 Message-ID: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Hello, I copy python 2.7.2 folder from other machine to my new installed Windows XP. If I run python.exe it would say side by side error, it is caused by crt environment. I copy msvc90 runtime and manifest into my folder, python.exe seems working now. But when I used 'import FixTk', it would say "dll load failed", actually, it also a side by side error, if I paste crt libraries into Dlls folder, it can be solved. But I don't think it is a good solution. How can I set it to prevent above error? w/o install any microsoft package. I want to user can use my package when they unpack it. Thanks, Eugene From alec.taylor6 at gmail.com Tue Sep 27 07:01:32 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 27 Sep 2011 21:01:32 +1000 Subject: error when use portable python 2.7.2 In-Reply-To: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Message-ID: You're looking for this: http://www.portablepython.com/wiki/PortablePython2.7.2.1 On Tue, Sep 27, 2011 at 8:48 PM, yixuan wrote: > Hello, > I copy python 2.7.2 folder from other machine to my new installed > Windows XP. > If I run python.exe it would say side by side error, it is caused by > crt environment. > I copy msvc90 runtime and manifest into my folder, python.exe seems > working now. > But when I used 'import FixTk', it would say "dll load failed", > actually, it also a side by side error, if I paste crt libraries into > Dlls folder, it can be solved. But I don't think it is a good > solution. > How can I set it to prevent above error? w/o install any microsoft > package. I want to user can use my package when they unpack it. > > Thanks, > Eugene > -- > http://mail.python.org/mailman/listinfo/python-list > From mikehulluk at googlemail.com Tue Sep 27 07:54:10 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 04:54:10 -0700 (PDT) Subject: atexit handlers - getting the return code Message-ID: Hi, I work in neuroscience modelling and use python for lots of my work. One problem I have is management of scripts and results. To that end, I have written code that make its easier to keep track of scripts, to see which ones have run, or need to be rerun, to see output errors and generally organise running of scripts better. The way i have implemented it is that I register a function to the atexit module, which takes care of recording information about the script run; such as whether an exception was raised and not caught, and how long it took to run and the stdout/stderr streams; which can then be uploaded into a database. One thing I am struggling to get though is the 'return code' that the is going to be returned after my atexit handlers have finished. Could anyone tell me how it get at this!? Thanks Mike From yixuan178 at gmail.com Tue Sep 27 08:00:30 2011 From: yixuan178 at gmail.com (yixuan) Date: Tue, 27 Sep 2011 05:00:30 -0700 (PDT) Subject: error when use portable python 2.7.2 References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Message-ID: <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> On Sep 27, 7:01?pm, Alec Taylor wrote: > You're looking for this:http://www.portablepython.com/wiki/PortablePython2.7.2.1 > > > > > > > > On Tue, Sep 27, 2011 at 8:48 PM, yixuan wrote: > > Hello, > > I copy python 2.7.2 folder from other machine to my new installed > > Windows XP. > > If I run python.exe it would say side by side error, it is caused by > > crt environment. > > I copy msvc90 runtime and manifest into my folder, python.exe seems > > working now. > > But when I used 'import FixTk', it would say "dll load failed", > > actually, it also a side by side error, if I paste crt libraries into > > Dlls folder, it can be solved. But I don't think it is a good > > solution. > > How can I set it to prevent above error? w/o install any microsoft > > package. I want to user can use my package when they unpack it. > > > Thanks, > > Eugene > > -- > >http://mail.python.org/mailman/listinfo/python-list Alec, Thanks for your information. But in that site, it seems how to rebuild python for another use. My issue is that, when I install python 2.7.2 in one windows, then I want to copy that folder to my new installed windows, and try to run python. It will ask CRT environment. Why I need that scenario, i want to package python in my package, so I want it to run one new installed windows which w/o any crt runtime installed. For more convenience, my issue seems like that in DLLs folder, there has some dlls, python would load them when needed, but when run application, it couldn't find crt files which stored in python root folder. So how to set that all dll can find that folder? Thanks, Eugene From drobinow at gmail.com Tue Sep 27 08:15:10 2011 From: drobinow at gmail.com (David Robinow) Date: Tue, 27 Sep 2011 08:15:10 -0400 Subject: install packages with pip to older Python versions In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 4:39 PM, Jabba Laci wrote: > Hi, > > I have Python 2.7 on my system. Today I wanted to try Google App > Engine but it runs on Python 2.5 at Google so I installed this version > on my machine next to v2.7 to avoid compatibility problems. However, > when I start the Python shell v2.5 and try to import something from > the GAE SDK (for instance "from google.appengine.ext import webapp"), > I get an error: "ImportError: No module named webob". (Note that with > v2.7 I don't have this problem.) > > So, how can I install packages for a specific version of Python (here, > v2.5)? With 2.7 I use "sudo pip install ". sudo pip-2.5 install (You may need to install pip in your 2.5) From nizamov.shawkat at gmail.com Tue Sep 27 08:35:38 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Tue, 27 Sep 2011 14:35:38 +0200 Subject: error when use portable python 2.7.2 In-Reply-To: <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> Message-ID: I bet that the difference is in the environment settings (PYTHONPATH). Look here for details how to set it manually: http://docs.python.org/using/windows.html Hope it helps, S.Nizamov From g.rodola at gmail.com Tue Sep 27 08:55:17 2011 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 27 Sep 2011 14:55:17 +0200 Subject: atexit handlers - getting the return code In-Reply-To: References: Message-ID: You mean the registered function return value or the process return code? In the first case you can do something such as: import atexit @atexit.register def cleanup(): def actual_function(): ... return something ret = actual_function() # do something with ret In the latter case you can use sys.exit(code). --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ 2011/9/27 Mike Hull : > Hi, > I work in neuroscience modelling and use python for lots of my work. > One problem I have is management of scripts and results. To that end, > I have > written code that make its easier to keep track of scripts, to see > which ones > have run, or need to be rerun, to see output errors and generally > organise running of scripts better. > > The way i have implemented it is that I register a function to the > atexit module, > which takes care of recording information about the script run; such > as whether an > exception was raised and not caught, and how long it took to run and > the > stdout/stderr streams; which can then be uploaded into a database. > > One thing I am struggling to get though is the 'return code' that the > is going to be returned after my > atexit handlers have finished. Could anyone tell me how it get at > this!? > > > Thanks > > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > From mikehulluk at googlemail.com Tue Sep 27 09:37:10 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 06:37:10 -0700 (PDT) Subject: atexit handlers - getting the return code References: Message-ID: Hi Giampaolo, Sorry, I didn't explain very clearly. I have a python file, 'simulation_logger.py', (given below). Then, in my scripts, I add the following lines to the top, #simulation1.py: ################### from simulation_logger import SimulationDecorator SimulationDecorator.Init() # Rest of the simulation script.... ##################### and at the end of the simulation, it should write the stdout/stderr, the return code and any top level exception details into a database. This is working except I can't work out how to get the return code the script is going to return. Any help would be gratefully appreciated, Thanks! Mike # simulation_logger.py ######################## import atexit import sys import os import cStringIO import time import traceback import datetime import inspect class SimulationRunInfo(object): def __init__(self, script_name ): self.return_code = None self.time_taken = None self.time_out = None self.std_out = None self.std_err = None self.exception_details = None,None self.script_name = script_name class IOStreamDistributor(object): def __init__(self, outputs): self.outputs = outputs def write(self, *args, **kwargs): for op in self.outputs: op.write(*args, **kwargs) class SimulationDecorator(object): start_time = None time_out = None is_initialised = False exception_details = None,None std_out = None std_err = None script_name = None @classmethod def exit_handler(cls, *args, **kwargs): print 'Exit Handler' print 'Args', args print 'KwArgs', kwargs info = SimulationRunInfo( cls.script_name) # Read and restore the StdOut/Err info.std_out = cls.std_out.getvalue() sys.stdout = sys.__stdout__ info.std_err = cls.std_err.getvalue() sys.stderr = sys.__stderr__ # Get the return value: info.return_code = 0 # Get the timing: info.time_taken = int( time.time() - cls.start_time ) # Has thier been an exception? info.exception_details = cls.exception_details if info.exception_details != (None,None): print 'Exception details', info.exception_details info.return_code = -1 # Write to SimulationDataBase # Save the information to a database: SimulationDBWriter.write_to_database(info) @classmethod def top_level_exception_handler(cls, exception_type, exception, traceback, *args): print 'TopLevel Exception Handler' cls.exception_details = exception_type, exception, traceback @classmethod def Init(cls, time_out=None): assert not cls.is_initialised if 'MF_TIMEOUT' in os.environ: timeout = int( os.environ['MF_TIMEOUT'] ) # Filename of the Simulation script cwd = os.getcwd() cls.script_name = os.path.join( cwd, traceback.extract_stack() [0][0] ) #cls.script_name = traceback.extract_stack()[0][2]. #cls.script_name = inspect.stack()[-1][1] #Intercept StdOut and StdErr: cls.std_out = cStringIO.StringIO() sys.stdout = IOStreamDistributor( [cls.std_out, sys.stdout] ) cls.std_err = cStringIO.StringIO() sys.stderr = IOStreamDistributor( [cls.std_err, sys.stderr] ) # Set an exit handler and a top level exception-handler # Set a top level exception handler: atexit.register( cls.exit_handler ) sys.excepthook = cls.top_level_exception_handler # Set a time-out alarm cls.start_time = time.time() cls.time_out = time_out From wescpy at gmail.com Tue Sep 27 10:00:55 2011 From: wescpy at gmail.com (wesley chun) Date: Tue, 27 Sep 2011 11:00:55 -0300 Subject: ANN: Intro+Intermediate Python course, SF, Oct 18-20 In-Reply-To: References: Message-ID: ** FINAL CALL ** http://sfbay.craigslist.org/sfc/cls/2495963854.html ---------- Forwarded message ---------- From: wesley chun Date: Mon, Jul 25, 2011 at 12:32 PM Subject: ANN: Intro+Intermediate Python course, SF, Oct 18-20 Need to get up-to-speed with Python as quickly and as in-depth as possible? Already coding Python but still have areas of uncertainty you need to fill? Then come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python" for a comprehensive intro/intermediate course coming up this May in Northern California, then enjoy a beautiful Fall weekend afterwards in San Francisco, the beautiful city by the bay. Please pass on this note to whomever you think may be interested. I look forward to meeting you and your colleagues! Feel free to pass around the PDF flyer linked down below. Write if you have questions. Since I hate spam, I'll only send out one reminder as the date gets closer. (Comprehensive) Intro+Intermediate Python Tue-Thu, 2011 Oct 18-20, 9am-5pm Hope to meet you soon! -Wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRO+INTERMEDIATE PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! PREVIEW 1: you will find (and can download) a video clip of a class session recorded live to get an idea of my lecture style and the interactive classroom environment (as well as sign-up) at: http://cyberwebconsulting.com PREVIEW 2: Partnering with O'Reilly and Pearson, Safari Books Online has asked me to deliver a 1-hour webcast a couple of years ago called "What is Python?". This was an online seminar based on a session that I've delivered at numerous conferences in the past. It will give you an idea of lecture style as well as an overview of the material covered in the course. info:http://www.safaribooksonline.com/events/WhatIsPython.html download (reg req'd): http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcastInfo.php?page=WhatIsPython - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com FLYER: http://cyberwebconsulting.com/flyerPP1.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. There is a significant discounts available for full-time students, secondary teachers, and others. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From taleinat at gmail.com Tue Sep 27 10:24:12 2011 From: taleinat at gmail.com (Tal Einat) Date: Tue, 27 Sep 2011 07:24:12 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> Message-ID: <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> I don't work with SAS so I have no reason to invest any time developing for it. Also, as far as I can tell, SAS is far from free or open-source, meaning I definitely am not interested in developing for it. My library solves a problem for which there is no existing solution in the world of Python programming, AFAIK. I'm certainly not surprised such solutions already exist in other computing environments, but that's not relevant for me. From robert.kern at gmail.com Tue Sep 27 11:49:47 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:49:47 -0400 Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> Message-ID: On 9/27/11 10:24 AM, Tal Einat wrote: > I don't work with SAS so I have no reason to invest any time developing for it. > > Also, as far as I can tell, SAS is far from free or open-source, meaning I definitely am not interested in developing for it. I don't think he's suggesting that you drop what you are doing in Python and start working with SAS. He is suggesting that you look at the similar procedures that exist in the SAS standard library for inspiration. -- 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 robert.kern at gmail.com Tue Sep 27 11:52:13 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:52:13 -0400 Subject: QA Engineering/ Python/ Contract/ Austin, TX In-Reply-To: References: Message-ID: On 9/26/11 5:03 PM, Chris Rebert wrote: > On Mon, Sep 26, 2011 at 1:56 PM, TOM wrote: >> Tom Gugger >> Independent Recruiter >> tgugger at bex.net >> >> US Citizens or Greencard >> On Site >> >> >> QA Engineering/ Python/ Contract/ Austin, TX >> >> This is an immediate start, such as next week. I need three >> contractors > > Such postings belong on the Python jobs board > (http://www.python.org/community/jobs/ ), not > python-list/comp.lang.python. While he should definitely also post to the Jobs Board, job postings have usually been welcomed on python-list provided that they are relevant and not too spammy. Using [JOB] in the Subject line also helps. -- 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 robert.kern at gmail.com Tue Sep 27 11:59:09 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:59:09 -0400 Subject: atexit handlers - getting the return code In-Reply-To: References: Message-ID: On 9/27/11 9:37 AM, Mike Hull wrote: > Hi Giampaolo, > Sorry, I didn't explain very clearly. > I have a python file, 'simulation_logger.py', (given below). > Then, in my scripts, I add the following lines to the top, > > > > #simulation1.py: > ################### > from simulation_logger import SimulationDecorator > SimulationDecorator.Init() > > # Rest of the simulation script.... > > ##################### > > and at the end of the simulation, it should write the stdout/stderr, > the return code and any top level exception details into a database. > This is working except I can't work out how to get the return code > the script is going to return. I don't think that's available inside the process. You may want to use a "runner" script that records this information. Additionally, the runner script could record the stdout/stderr information more cleanly than stubbing out sys.stdout/sys.stderr. For example, if you have C or Fortran modules that use their own mechanisms to print things directly to the STDOUT/STDERR file descriptors, your sys.stdout/sys.stderr stubs will never be informed about it. However, if the runner script directs stdout/stderr to a pipe, it can read every bit of text that gets printed. Timing is probably also best recorded by the runner script to record the startup overhead of the Python interpreter. Continue to use the SimulationDecorator to record the traceback information, though. -- 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 sakthi92 at gmail.com Tue Sep 27 13:21:24 2011 From: sakthi92 at gmail.com (sakthi) Date: Tue, 27 Sep 2011 10:21:24 -0700 (PDT) Subject: Multiplication error in python Message-ID: In the following code, >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... >>> t 45 Python gives an answer as 45. But i am getting 30 when i execute manually. Is there any different multiplication pattern in python? Thank yu. From steve+comp.lang.python at pearwood.info Tue Sep 27 13:33:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 28 Sep 2011 03:33:13 +1000 Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Robert Kern wrote: > On 9/27/11 10:24 AM, Tal Einat wrote: >> I don't work with SAS so I have no reason to invest any time developing >> for it. >> >> Also, as far as I can tell, SAS is far from free or open-source, meaning >> I definitely am not interested in developing for it. > > I don't think he's suggesting that you drop what you are doing in Python > and start working with SAS. He is suggesting that you look at the similar > procedures that exist in the SAS standard library for inspiration. Yeah, inspiration on what *not* to do. I googled on "SAS PROC FREQ" and found this: http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm All the words are in English, but I have no idea what the function does, how you would call it, and what it returns. Would it have been so hard to show a couple of examples? Documentation like that really makes me appreciate the sterling work done on Python's docs. This tutorial: http://www2.sas.com/proceedings/sugi30/263-30.pdf is much clearer. -- Steven From gherron at digipen.edu Tue Sep 27 13:41:02 2011 From: gherron at digipen.edu (Gary Herron) Date: Tue, 27 Sep 2011 10:41:02 -0700 Subject: Multiplication error in python In-Reply-To: References: Message-ID: <4E820AAE.2000405@digipen.edu> On 09/27/2011 10:21 AM, sakthi wrote: > In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: > ... p=2*a > ... t=p+i > ... i=t > ... >>>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. I think it's most likely you've made an error here. Running your exact lines in Python gives the expected result: >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... >>> t 30 Please try again. If you can reproduce the incorrect result -- then we have a real bug. However, the chance of that is really really tiny. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From pruebauno at latinmail.com Tue Sep 27 13:42:02 2011 From: pruebauno at latinmail.com (nn) Date: Tue, 27 Sep 2011 10:42:02 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <4082eb5c-9374-4409-a007-1133eb13bb36@i28g2000yqn.googlegroups.com> On Sep 27, 1:21?pm, sakthi wrote: > In the following code,>>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ...>>> t > > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. You must be doing something different than these steps: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: p=2*a t=p+i i=t >>> t 30 >>> From contato at abruno.com Tue Sep 27 13:42:20 2011 From: contato at abruno.com (Alysson Bruno (WebSite)) Date: Tue, 27 Sep 2011 14:42:20 -0300 Subject: Multiplication error in python In-Reply-To: References: Message-ID: In my python 3.2, no problem: >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... print("p={}, t={}, i={}".format(p,t,i)) ... p=2, t=2, i=2 p=4, t=6, i=6 p=6, t=12, i=12 p=8, t=20, i=20 p=10, t=30, i=30 >>> t 30 >>> paz e amor (love and peace), Alysson Bruno Palmas(TO) Brasil http://abruno.com Leia: Heo Sargila: Hist?ria da Cria??o: http://heosargila.blogspot.com/2011/09/historia-da-criacao.html 2011/9/27 sakthi > In the following code, > >>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > ... p=2*a > ... t=p+i > ... i=t > ... > >>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bex.lewis at gmail.com Tue Sep 27 13:43:00 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 10:43:00 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <4dfd3a08-d5df-48a2-91d1-95a2a0f79c3e@j19g2000yqc.googlegroups.com> I tried running your code in ipython: In [1]: l = [1,2,3,4,5] In [2]: i = 0 In [3]: for a in l: ...: p = 2 * a ...: t = p + i ...: i = t ...: In [4]: In [4]: t Out[4]: 30 The output from Python was 30, not 45. What Python version are you running? On Sep 27, 6:21?pm, sakthi wrote: > In the following code,>>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ...>>> t > > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. From clp2 at rebertia.com Tue Sep 27 13:43:22 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 27 Sep 2011 10:43:22 -0700 Subject: Multiplication error in python In-Reply-To: References: Message-ID: On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: > In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ... >>>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. My Python gives 30; methinks perhaps you've elided some important part of your code. Also, I note that your loop body can be significantly simplified to just: i += 2*a Cheers, Chris -- http://rebertia.com From sakthi92 at gmail.com Tue Sep 27 13:50:23 2011 From: sakthi92 at gmail.com (sakthi) Date: Tue, 27 Sep 2011 10:50:23 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> On Sep 27, 1:43?pm, Chris Rebert wrote: > On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: > > In the following code, > >>>> l=[1,2,3,4,5] > >>>> i=0 > >>>> for a in l: > > ... ? ? p=2*a > > ... ? ? t=p+i > > ... ? ? i=t > > ... > >>>> t > > 45 > > > Python gives an answer as 45. But i am getting 30 when i execute > > manually. Is there any different multiplication pattern in python? > > Thank yu. > > My Python gives 30; methinks perhaps you've elided some important part > of your code. > Also, I note that your loop body can be significantly simplified to > just: i += 2*a > > Cheers, > Chris > --http://rebertia.com if i put i += 2*a it returns 155. From bex.lewis at gmail.com Tue Sep 27 14:51:06 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 11:51:06 -0700 (PDT) Subject: Multiplication error in python References: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> Message-ID: I think you may be doing something wrong. If I run: >>> l = [1, 2, 3, 4, 5] >>> i = 0 >>> for a in l: ... i += 2 * a ... >>> i 30 The result is 30 as expected. Nowhere near the 155 that you are getting. :/ Again, could you state which version of python are you using (and what OS) so that we can run the code in the same environment as you. Becky Lewis > > > > Python gives an answer as 45. But i am getting 30 when i execute > > > manually. Is there any different multiplication pattern in python? > > > Thank yu. > > > My Python gives 30; methinks perhaps you've elided some important part > > of your code. > > Also, I note that your loop body can be significantly simplified to > > just: i += 2*a > > > Cheers, > > Chris > > --http://rebertia.com > > if i put i += 2*a it returns 155. From mikehulluk at googlemail.com Tue Sep 27 15:12:09 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 12:12:09 -0700 (PDT) Subject: atexit handlers - getting the return code References: Message-ID: <662ee8e4-34af-42aa-b01b-edace3af133d@20g2000yqq.googlegroups.com> On Sep 27, 4:59?pm, Robert Kern wrote: > On 9/27/11 9:37 AM, Mike Hull wrote: > > > > > > > > > > > Hi Giampaolo, > > Sorry, I didn't explain very clearly. > > I have a python file, 'simulation_logger.py', (given below). > > Then, in my scripts, I add the following lines to the top, > > > #simulation1.py: > > ################### > > from simulation_logger ?import SimulationDecorator > > SimulationDecorator.Init() > > > # Rest of the simulation script.... > > > ##################### > > > and at the end of the simulation, it should write the stdout/stderr, > > the return code and any top level exception details into a database. > > This is working except I can't work out how to get the return code > > the script is going to return. > > I don't think that's available inside the process. You may want to use a > "runner" script that records this information. Additionally, the runner script > could record the stdout/stderr information more cleanly than stubbing out > sys.stdout/sys.stderr. For example, if you have C or Fortran modules that use > their own mechanisms to print things directly to the STDOUT/STDERR file > descriptors, your sys.stdout/sys.stderr stubs will never be informed about it. > However, if the runner script directs stdout/stderr to a pipe, it can read every > bit of text that gets printed. Timing is probably also best recorded by the > runner script to record the startup overhead of the Python interpreter. Continue > to use the SimulationDecorator to record the traceback information, though. > > -- > 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 Hi Robert, Thanks for this. The return code is not super important at this stage, but I thought I would try and get everything working neatly. Creating a separate runner script is probably the way to go. If i get some time I will implement it like that. My reason for wanting to do it 'in the same script' was that I also have another library that intercepts calls to matplotlib's show(), so I could ultimately create a pdf containing the script with figures interjected at the right place. Anyway, I will have to think about that some more. Thanks again! Mike From mwilson at the-wire.com Tue Sep 27 15:12:20 2011 From: mwilson at the-wire.com (Mel) Date: Tue, 27 Sep 2011 15:12:20 -0400 Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm > > All the words are in English, but I have no idea what the function does, > how you would call it, and what it returns. Would it have been so hard to > show a couple of examples? Hmm. Yeah. Very much so. That's the kind of documentation I call "syntax happy". It tells you how to create a well-formed PROC STAT without ever saying what would happen if you did, or why you might want that, whatever it was, to happen. I see that kind of documentation way too often. By comparison, even this might seem good. At least they try. "Does things to the stuff. By default, the most recent stuff is done things to." Mel. From tundra at tundraware.com Tue Sep 27 15:12:33 2011 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 27 Sep 2011 14:12:33 -0500 Subject: Multiplication error in python In-Reply-To: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> References: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> Message-ID: <1qj9l8-t6b.ln1@ozzie.tundraware.com> On 9/27/2011 12:50 PM, sakthi said this: > On Sep 27, 1:43 pm, Chris Rebert wrote: >> On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: >>> In the following code, >>>>>> l=[1,2,3,4,5] >>>>>> i=0 >>>>>> for a in l: >>> ... p=2*a >>> ... t=p+i >>> ... i=t >>> ... >>>>>> t >>> 45 >> >>> Python gives an answer as 45. But i am getting 30 when i execute >>> manually. Is there any different multiplication pattern in python? >>> Thank yu. >> >> My Python gives 30; methinks perhaps you've elided some important part >> of your code. >> Also, I note that your loop body can be significantly simplified to >> just: i += 2*a >> >> Cheers, >> Chris >> --http://rebertia.com > > if i put i += 2*a it returns 155. Are you sure you don't have something indented incorrectly? How about a plain text copy of your program (without the interactive stuff) so we can run it independently... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From joncle at googlemail.com Tue Sep 27 15:54:22 2011 From: joncle at googlemail.com (Jon Clements) Date: Tue, 27 Sep 2011 12:54:22 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <65466670-d990-4d7c-9cca-0ac3ec9881a6@db5g2000vbb.googlegroups.com> On Sep 27, 6:33?pm, Steven D'Aprano wrote: > Robert Kern wrote: > > On 9/27/11 10:24 AM, Tal Einat wrote: > >> I don't work with SAS so I have no reason to invest any time developing > >> for it. > > >> Also, as far as I can tell, SAS is far from free or open-source, meaning > >> I definitely am not interested in developing for it. > > > I don't think he's suggesting that you drop what you are doing in Python > > and start working with SAS. He is suggesting that you look at the similar > > procedures that exist in the SAS standard library for inspiration. > > Yeah, inspiration on what *not* to do. > > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/defau... > > All the words are in English, but I have no idea what the function does, how > you would call it, and what it returns. Would it have been so hard to show > a couple of examples? > > Documentation like that really makes me appreciate the sterling work done on > Python's docs. > > This tutorial: > > http://www2.sas.com/proceedings/sugi30/263-30.pdf > > is much clearer. > > -- > Steven Yes - I definitely do not like the SAS docs - in fact, when I last had to "buy" the product, it was something like ?5k for the "BASE" system, then if I wanted ODBC it was another ?900, and the "proper" manuals were something stupid like another ?1k (and only in hard copy) - this was a good 5/6 years ago though... (oh, and for a very basic course, it was ?1.2k a day for staff to train) *sighs* [oh, and if I wanted a 'site' licence, we were talking 6 digits] Anyway, Robert Kern correctly interpreted me. I was not suggesting to the OP that he move to SAS (heaven forbid), I was indeed suggesting that he look into what similar systems have (that I have experience with and appreciate), and he acknowledges that is not present in Python, and ummm, take inspiration and quite possibly "rip 'em off". A decent tabulate/cross-tabulation and statistics related there-to library is something I'd be willing to assist with and put time into. Cheers, Jon. From rantingrick at gmail.com Tue Sep 27 16:45:52 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 27 Sep 2011 13:45:52 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> Message-ID: <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> On Sep 27, 1:51?am, DevPlayer wrote: > By the way OP Passiday the title of the topic is "Suggested coding > style". > > Are you suggesting a coding style or asking for a Python coding style > or are you asking what IS the Python coding style. > > If you are asking what is the Python coding style. Google The Zen of > Python. It's pretty much the dictum of coding style and referred to > alot by many Pythoneers. The Python zen is a very general outline of our collective religious beliefs concerning programming (and it could be applied to many fields). Every Python programmer should know the zen by heart. Which can be very beneficial in a war of words when some smart mouth decides to quote the zen in an attempt to defeat you. Since, like the bible the zen is self contradicting, any argument utilizing the zen can be defeated utilizing the zen. If however you want to learn about the accepted rules for formatting code then you need to read "PEP-8"! PEP 8 is our style guide. It is not perfect as i have pointed out on many occasions HOWEVER it is the only thing we have that keeps multiplicity from reproducing like leporidae. http://www.python.org/dev/peps/pep-0008/ From wanderer at dialup4less.com Tue Sep 27 16:54:48 2011 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 27 Sep 2011 13:54:48 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows Message-ID: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says "Python 2.6.6 has been replaced by a newer security-fix only source release of Python. Please download Python 2.6.7 instead." But there is no windows installer on the 2.6.7 page. Do I install 2.6.6 first and then update to 2.6.7? Thanks From arnodel at gmail.com Tue Sep 27 17:11:58 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 27 Sep 2011 22:11:58 +0100 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: On 27 September 2011 21:54, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? I don't know if it would suite your needs but there's ActivePython - they provide an installer for 2.6.7 http://www.activestate.com/activepython/downloads HTH -- Arnaud From brian.curtin at gmail.com Tue Sep 27 17:17:45 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 16:17:45 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: On Tue, Sep 27, 2011 at 15:54, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? As the text states, 2.6.7 is only a source code release. 2.6.6 is the last binary package available, but if you need what's in 2.6.7, you will have to compile the source yourself. Alternatively, you could upgrade to 2.7 as 2.6 will continue to only receive security fixes, or as Arnaud states, you could use an alternative distribution to get 2.6.6. From bex.lewis at gmail.com Tue Sep 27 17:19:33 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 14:19:33 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> On Sep 27, 9:54?pm, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? > > Thanks Hi, is there any reason that you specifically need the 2.6 branch or would it be possible to update to 2.7? As someone else already pointed out, there's the ActivePython route if you really need 2.6.7. From wanderer at dialup4less.com Tue Sep 27 17:32:43 2011 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 27 Sep 2011 14:32:43 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> Message-ID: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> On Sep 27, 5:19?pm, becky_lewis wrote: > On Sep 27, 9:54?pm, Wanderer wrote: > > > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > > "Python 2.6.6 has been replaced by a newer security-fix only source > > release of Python. Please download Python 2.6.7 instead." > > > But there is no windows installer on the 2.6.7 page. Do I install > > 2.6.6 first and then update to 2.6.7? > > > Thanks > > Hi, > > is there any reason that you specifically need the 2.6 branch or would > it be possible to update to 2.7? > > As someone else already pointed out, there's the ActivePython route if > you really need 2.6.7. I need to stay in sink with the rest of the company which is still using 2.6 flavors. There was some investigation into going to Python 3 but not enough of the libraries we use were available. I'll install 2.6.6. I don't think the security stuff really effects me. I think it is strange to release a security update but not really expect people to use it. From iamforufriends at gmail.com Tue Sep 27 18:02:21 2011 From: iamforufriends at gmail.com (hot girl) Date: Tue, 27 Sep 2011 15:02:21 -0700 (PDT) Subject: hai date with girl for free Message-ID: <1239dc58-6fcd-4f7d-8795-1907e08af831@j10g2000vbb.googlegroups.com> want a gf for dating http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas From aljosa.mohorovic at gmail.com Tue Sep 27 18:54:37 2011 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Tue, 27 Sep 2011 15:54:37 -0700 (PDT) Subject: oauth2 server implementation Message-ID: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> i'm looking for oauth2 server implementation but other than https://github.com/simplegeo/python-oauth2 (oauth v1 implementation) it doesn't seem that people are using v2 implementations. anybody using some oauth2 implementation and can share some info? Aljosa Mohorovic From brian.curtin at gmail.com Tue Sep 27 18:59:35 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 17:59:35 -0500 Subject: PyCon 2012 Proposals Due October 12 Message-ID: The deadline for PyCon 2012 tutorial, talk, and poster proposals is under 15 days away, so be sure to get your submissions in by October 12, 2011. Whether you?re a first-timer or an experienced veteran, PyCon is depends on you, the community, coming together to build the best conference schedule possible. Our call for proposals (http://us.pycon.org/2012/cfp/) lays out the details it takes to be included in the lineup for the conference in Santa Clara, CA on March 7-15, 2012. If you?re unsure of what to write about, our recent survey yielded a large list of potential talk topics (http://pycon.blogspot.com/2011/09/need-talk-ideas.html), and plenty of ideas for tutorials (INSERT TUTORIAL POST). We?ve also come up with general tips on proposal writing at http://pycon.blogspot.com/2011/08/writing-good-proposal.html to ensure everyone has the most complete proposal when it comes time for review. As always, the program committee wants to put together an incredible conference, so they?ll be working with submitters to fine tune proposal details and help you produce the best submissions. We?ve had plenty of great news to share since we first announced the call for proposals. Paul Graham of Y Combinator was recently announced as a keynote speaker (http://pycon.blogspot.com/2011/09/announcing-first-pycon-2012-keynote.html), making his return after a 2003 keynote. David Beazley, famous for his mind-blowing talks on CPython?s Global Interpreter Lock, was added to the plenary talk series (http://pycon.blogspot.com/2011/09/announcing-first-pycon-2012-plenary.html). Sponsors can now list their job openings on the ?Job Fair? section of the PyCon site (http://pycon.blogspot.com/2011/09/announcing-pycon-2012-fair-page-sponsor.html). We?re hard at work to bring you the best conference yet, so stay tuned to PyCon news at http://pycon.blogspot.com/ and on Twitter at https://twitter.com/#!/pycon. We recently eclipsed last year?s sponsorship count of 40 and are currently at a record 52 organizations supporting PyCon. If you or your organization are interested in sponsoring PyCon, we?d love to hear from you, so check out our sponsorship page (http://us.pycon.org/2012/sponsors/). A quick thanks to all of our awesome PyCon 2012 Sponsors: - Diamond Level: Google and Dropbox. - Platinum Level: New Relic, SurveyMonkey, Microsoft, Eventbrite, Nasuni and Gondor.io - Gold Level: Walt Disney Animation Studios, CCP Games, Linode, Enthought, Canonical, Dotcloud, Loggly, Revsys, ZeOmega, Bitly, ActiveState, JetBrains, Caktus, Disqus, Spotify, Snoball, Evite, and PlaidCloud - Silver Level: Imaginary Landscape, WiserTogether, Net-ng, Olark, AG Interactive, Bitbucket, Open Bastion, 10Gen, gocept, Lex Machina, fwix, github, toast driven, Aarki, Threadless, Cox Media, myYearBook, Accense Technology, Wingware, FreshBooks, and BigDoor - Lanyard: Dreamhost - Sprints: Reddit - FLOSS: OSU/OSL, OpenHatch The PyCon Organizers - http://us.pycon.org/2012 Jesse Noller - Chairman - jnoller at python.org Brian Curtin - Publicity Coordinator - brian at python.org From gagsl-py2 at yahoo.com.ar Tue Sep 27 19:52:55 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 Sep 2011 20:52:55 -0300 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813 escribi?: > Hello all, > > I encounter this issue whereby I am not able to load cPickle module into > the python I newly built. There is no issue when I load it right from > the folder where the python executable and libpython2.7.so is built. > However, it gives me this error when I load the same module using the > installed files (python and all its modules, shared library from default > /use/local folder that contains bin, lib, include sub-folders) from > "make install" command. > > Does anyone know why? Here is the error:- > > $ python > Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import cPickle > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '_extension_registry' Looking at cPickle.c, it imports the copy_reg module and then looks for its "_extension_registry" attribute. Maybe your copy_reg.py is broken, or you have another copy_reg.py hiding the standard one. -- Gabriel Genellina From roy at panix.com Tue Sep 27 20:17:01 2011 From: roy at panix.com (Roy Smith) Date: Tue, 27 Sep 2011 20:17:01 -0400 Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> Message-ID: In article <4c93ff75-1d85-48ec-b6d1-b71f216c61ce at g33g2000yqc.googlegroups.com>, Aljosa Mohorovic wrote: > i'm looking for oauth2 server implementation but other than > https://github.com/simplegeo/python-oauth2 (oauth v1 implementation) > it doesn't seem that people are using v2 implementations. > anybody using some oauth2 implementation and can share some info? > > > Aljosa Mohorovic We rolled our own oauth2 client on top of basic urllib calls. It's not terribly difficult. Other than Twitter, I'm not aware of anybody still using oauth1. From brian.curtin at gmail.com Tue Sep 27 20:52:07 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 19:52:07 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: On Tue, Sep 27, 2011 at 16:32, Wanderer wrote: > I think it is strange to release a security update but not really expect > people > to use it. We expect that people who need 2.6 but won't move to 2.7, and at the same time are vulnerable to the security issue(s), would be able to compile Python for themselves. Shortly after 2.7 was released, 2.6 went into security-fix mode, and that's true of any X.Y and X.Y-1 pair. For a look at how busy the release schedule has been at times, I wrote about all of the releases we were up to in June at http://blog.python.org/2011/06/june-releases-267-272-314.html. Consider the fact that the person creating the installer usually creates at least three installers for any release (usually two candidates, and the final - add in alphas for a new X.Y), for each branch, of which three branches were having binary installers produced. For the specifics on the 2.6.7 fix, http://blog.python.org/2011/04/urllib-security-vulnerability-fixed.html covers it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Sep 27 20:56:49 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 Sep 2011 20:56:49 -0400 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: On 9/27/2011 5:32 PM, Wanderer wrote: > I need to stay in sink with the rest of the company which is still > using 2.6 flavors. There was some investigation into going to Python 3 > but not enough of the libraries we use were available. I'll install > 2.6.6. I don't think the security stuff really effects me. I think it > is strange to release a security update but not really expect people > to use it. It is used most, I presume, by security-conscious server people, especially *nix people, who expect to compile their own binary. The ordinary user is hardly affected by most of these issues. -- Terry Jan Reedy From wuwei23 at gmail.com Tue Sep 27 22:22:49 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 27 Sep 2011 19:22:49 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <553f821c-58c1-4b81-817e-078c148af209@j19g2000yqc.googlegroups.com> Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/defau... > > All the words are in English, but I have no idea what the function does, how > you would call it, and what it returns. Would it have been so hard to show > a couple of examples? I'm currently arms deep in converting a handful of randomisation algorithms written in SAS into Python. Pretty much ALL of the magic happens behind cryptic SAS calls like this. I'm having more success reverse-engineering the _results_ they produce and building something Pythonic and comprehensible. From wuwei23 at gmail.com Tue Sep 27 22:25:48 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 27 Sep 2011 19:25:48 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: rantingrick wrote: > Since, like the bible > the zen is self contradicting, any argument utilizing the zen can be > defeated utilizing the zen. And like the Bible, the Zen was created by humans as a joke. If you're taking it too seriously, that's your problem. > If however you want to learn about the accepted rules for formatting > code then you need to read "PEP-8"! PEP 8 is our style guide. PEP 8 is the _standard library style guide_. There's a difference. > It is > not perfect as i have pointed out on many occasions HOWEVER it is the > only thing we have that keeps multiplicity from reproducing like > leporidae. Yes, save us from multiplicity, variety and difference. Nothing good comes from them anyway. From steve+comp.lang.python at pearwood.info Wed Sep 28 00:25:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Sep 2011 04:25:05 GMT Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> On Tue, 27 Sep 2011 14:32:43 -0700, Wanderer wrote: > I need to stay in sink with the rest of the company which is still using > 2.6 flavors. There was some investigation into going to Python 3 but not > enough of the libraries we use were available. I'll install 2.6.6. I > don't think the security stuff really effects me. I think it is strange > to release a security update but not really expect people to use it. More likely the person who builds the Windows installers just hasn't made a new release yet. The Python development team is relatively small and chronically busy: too much to do and not enough time to do it. As I understand it, most of them use Linux, so I'm afraid that Windows sometimes takes a back seat. (At least it's not Mac OS, which is stuck riding in the boot of the car, or the other semi-supported OSes, which are on a skateboard desperately hanging onto the bumper trying not to be left behind.) You could try installing from source, if you have the appropriate Windows development environment. -- Steven From timr at probo.com Wed Sep 28 02:28:32 2011 From: timr at probo.com (Tim Roberts) Date: Tue, 27 Sep 2011 23:28:32 -0700 Subject: Multiplication error in python References: Message-ID: sakthi wrote: >In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: >... p=2*a >... t=p+i >... i=t >... >>>> t >45 > >Python gives an answer as 45. But i am getting 30 when i execute >manually. Is there any different multiplication pattern in python? My guess is that you actually typed p=3*a instead of p=2*a That produces 45. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From r32813 at freescale.com Wed Sep 28 02:37:56 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 06:37:56 +0000 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F598F9@039-SN1MPN1-003.039d.mgd.msft.net> Thanks Gabriel, Indeed, there is corrupted copy_reg.py file residing in my $PYTHONPATH folder, as opposed to the standard one from the installed package. Thanks a lot for your helps! Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Gabriel Genellina Sent: Wednesday, September 28, 2011 7:53 AM To: python-list at python.org Subject: Re: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813 escribi?: > Hello all, > > I encounter this issue whereby I am not able to load cPickle module into > the python I newly built. There is no issue when I load it right from > the folder where the python executable and libpython2.7.so is built. > However, it gives me this error when I load the same module using the > installed files (python and all its modules, shared library from default > /use/local folder that contains bin, lib, include sub-folders) from > "make install" command. > > Does anyone know why? Here is the error:- > > $ python > Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import cPickle > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '_extension_registry' Looking at cPickle.c, it imports the copy_reg module and then looks for its "_extension_registry" attribute. Maybe your copy_reg.py is broken, or you have another copy_reg.py hiding the standard one. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From 1248283536 at qq.com Wed Sep 28 03:24:13 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 28 Sep 2011 15:24:13 +0800 Subject: how to run in xp? Message-ID: #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'w') url='http://www.nasdaq.com/screening/companies- \ by-industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print ('ok',down) myfile.close() it can run in ubuntu+python2.6 ,when it run in window xp+python32,the output is Traceback (most recent call last): File "C:\Python32\getcode.py", line 8, in file=urllib.urlopen(url).read() AttributeError: 'module' object has no attribute 'urlopen' i change it into: #coding:utf-8 import urllib.request exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'w') url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print ('ok',down) myfile.close() the output is : Traceback (most recent call last): File "C:\Python32\getcode.py", line 9, in myfile.write(file) TypeError: must be str, not bytes how to make it run in xp+python32? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Sep 28 03:31:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 17:31:16 +1000 Subject: Multiplication error in python In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 4:28 PM, Tim Roberts wrote: > My guess is that you actually typed > ? ?p=3*a > instead of > ? ?p=2*a > > That produces 45. > Or alternatively, that you used an interactive Python environment and didn't clear i between runs. ChrisA From __peter__ at web.de Wed Sep 28 04:04:46 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Sep 2011 10:04:46 +0200 Subject: how to run in xp? References: Message-ID: =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX From r32813 at freescale.com Wed Sep 28 04:37:13 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 08:37:13 +0000 Subject: python 2.7.1 built not supporting thread? In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F59952@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I couldn't detect this problem until I run my application that utilizes thread module in python that I just built on HP-UX 11.31 ia64 using aCC. Could it be the build did not include enable thread option? _REENTRANT as stated in the README file? If yes, it looks like threading may not work "out of the box". >>> thread.start_new_thread(testing, ()) Traceback (most recent call last): File "", line 1, in thread.error: can't start new thread >>> Excerpts from README file for python 2.7 build HP-UX: When using threading, you may have to add -D_REENTRANT to the OPT variable in the top-level Makefile; reported by Pat Knight, this seems to make a difference (at least for HP-UX 10.20) even though pyconfig.h defines it. This seems unnecessary when using HP/UX 11 and later - threading seems to work "out of the box". From xahlee at gmail.com Wed Sep 28 05:28:38 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 02:28:38 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or Message-ID: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> curious question. suppose you have 300 different strings and they need all be replaced to say "aaa". is it faster to replace each one sequentially (i.e. replace first string to aaa, then do the 2nd, 3rd,...) , or is it faster to use a regex with ?or? them all and do replace one shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) let's say the sourceString this replacement to be done on is 500k chars. Anyone? i suppose the answer will be similar for perl, python, ruby. btw, the origin of this question is about writing a emacs lisp function that replace ~250 html named entities to unicode char. Xah From aljosa.mohorovic at gmail.com Wed Sep 28 05:55:12 2011 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Wed, 28 Sep 2011 02:55:12 -0700 (PDT) Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> Message-ID: <862e37e9-f4d2-4423-8d28-485923f1c76b@p11g2000yqe.googlegroups.com> On Sep 28, 2:17?am, Roy Smith wrote: > We rolled our own oauth2 client on top of basic urllib calls. ?It's not > terribly difficult. i'm asking about oauth2 server implementation, not client. it's easy to consume oauth2 stuff but what to do when you need to implement server side stuff? Aljosa From rosuav at gmail.com Wed Sep 28 06:04:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 20:04:43 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 7:28 PM, Xah Lee wrote: > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially Before you ask "is it faster", you need to first be sure it's correct. I would recommend doing all the replaces in a single function call to avoid risk of overlaps or other issues causing problems. ChrisA From r32813 at freescale.com Wed Sep 28 06:14:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 10:14:08 +0000 Subject: python 2.7.1 HP-UX 11 ia64 built not supporting thread References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F599D0@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I included --with-threads option into the configure script calling, which it failed to add the -D_REENTRANT into Makefile. So I manually added this into OPT of the Makefile. I ran make again and generated a new python binary. However, the new binary is still not able to start a new thread from the thread module. I reviewed the config.log file, I think this failure has caused the build with threads failed. Cthreads.h header file is missing. Should this be included in my HP UX Compiler or it comes from python source? In python source I only found pythread.h. Anyway, I am only guessing what is wrong. Hope to hear some feedback here, whether this is something missing or a bug. configure:8407: checking for --with-threads configure:8427: result: yes configure:8484: checking for _POSIX_THREADS in unistd.h configure:8503: result: yes configure:8508: checking cthreads.h usability configure:8508: cc +DD64 -I/home/r32813/local/include -c -g conftest.c >&5 "conftest.c", line 128: error #3696-D: cannot open source file "cthreads.h" #include ^ 1 error detected in the compilation of "conftest.c". | #define HAVE_LIBDLD 1 | #define _REENTRANT 1 | /* end confdefs.h. */ | #include configure:8508: result: no configure:8508: checking for cthreads.h configure:8508: result: no configure:8521: checking mach/cthreads.h usability configure:8521: cc +DD64 -I/home/r32813/local/include -c -g conftest.c >&5 "conftest.c", line 128: error #3696-D: cannot open source file "mach/cthreads.h" #include ^ 1 error detected in the compilation of "conftest.c". configure:8521: $? = 2 configure: failed program was: | /* confdefs.h */ | #define _GNU_SOURCE 1 | #define HAVE_LIBDLD 1 | #define _REENTRANT 1 | /* end confdefs.h. */ | #include configure:8521: result: no configure:8521: checking for mach/cthreads.h configure:8521: result: no configure:8533: checking for --with-pth configure:8548: result: no configure:8556: checking for pthread_create in -lpthread configure:8572: cc +DD64 -I/home/r32813/local/include -o conftest -g -L/home/r32813/local/lib -L/home/r32813/Build/2.7.1/Python-2.7.1 conftest.c -l nsl -lrt -ldld -ldl -lpthread >&5 Regards, Wah Meng Genesis Wafermap Support Ticket: To report a problem: http://dyno.freescale.net/Question/QuestionMain3.asp?location=zmy02&category=&tickettype=6820 To request a service: http://dyno.freescale.net/Question/Questionmain3.asp?location=74&category=2&tickettype=6819 Or if it is related to EWM or DSA: http://dyno.freescale.net/Question/Questionmain3.asp?location=ZMY02&tickettype=6539 -----Original Message----- From: Wong Wah Meng-R32813 Sent: Wednesday, September 28, 2011 4:37 PM To: python-list at python.org Subject: python 2.7.1 built not supporting thread? Hello there, I couldn't detect this problem until I run my application that utilizes thread module in python that I just built on HP-UX 11.31 ia64 using aCC. Could it be the build did not include enable thread option? _REENTRANT as stated in the README file? If yes, it looks like threading may not work "out of the box". >>> thread.start_new_thread(testing, ()) Traceback (most recent call last): File "", line 1, in thread.error: can't start new thread >>> Excerpts from README file for python 2.7 build HP-UX: When using threading, you may have to add -D_REENTRANT to the OPT variable in the top-level Makefile; reported by Pat Knight, this seems to make a difference (at least for HP-UX 10.20) even though pyconfig.h defines it. This seems unnecessary when using HP/UX 11 and later - threading seems to work "out of the box". From merlyn at stonehenge.com Wed Sep 28 06:57:44 2011 From: merlyn at stonehenge.com (Randal L. Schwartz) Date: Wed, 28 Sep 2011 03:57:44 -0700 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: <86bou553yv.fsf@red.stonehenge.com> >>>>> "Xah" == Xah Lee writes: Xah> curious question. Xah> suppose you have 300 different strings and they need all be replaced Xah> to say "aaa". And then suppose this isn't the *real* question, but one entirely of Fiction by Xah Lee. How helpful do you want to be? -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc. See http://methodsandmessages.posterous.com/ for Smalltalk discussion From 1248283536 at qq.com Wed Sep 28 07:50:04 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 28 Sep 2011 19:50:04 +0800 Subject: how to run in xp? Message-ID: it can run ,but there is still a problem ,nothing in my file. please run the code in xp+python32 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() print (file) what you get is: >>> b'' b'' b'' >>> how to fix it? ------------------ Original ------------------ From: "Peter Otten"<__peter__ at web.de>; Date: Wed, Sep 28, 2011 04:04 PM To: "python-list"; Subject: Re: how to run in xp? =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From devplayer at gmail.com Wed Sep 28 08:12:31 2011 From: devplayer at gmail.com (DevPlayer) Date: Wed, 28 Sep 2011 05:12:31 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: On Sep 27, 10:25?pm, alex23 wrote: > rantingrick wrote: > > Since, like the bible > > the zen is self contradicting, any argument utilizing the zen can be > > defeated utilizing the zen. > > And like the Bible, the Zen was created by humans as a joke. If you're > taking it too seriously, that's your problem. > > > If however you want to learn about the accepted rules for formatting > > code then you need to read "PEP-8"! PEP 8 is our style guide. > Contradiction is only seen by narrow perspectve. Calling the Bible a joke is used to hurt people, not enlighten them. Those words show bitter arrogance, not constructive critism as it ignores how others feel about that book. What benefit to others is gained by calling someones belief a joke? To put the "believers" minds straight? I think not. I think the unsensitive person who attackes others beliefs, even if illogical or unrealistic, is after some kind of self grandizement or to illude themself into thinking "they know the truth of the universe" and should attack others to prove they do. Although this is not the place to defend about such things it is also not the place to attack those same things (that being someone's faith). There is no real forum to defend a faith or religion, or words in a book about that, other then where such faiths are in fact attacked. However I did laugh at the ironic use of using any-kind of zen to seriously, even Python's, as that is very unzen-like. That is a contradiction by it's very own definitions! From xahlee at gmail.com Wed Sep 28 08:28:01 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 05:28:01 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> Message-ID: <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> On Sep 28, 3:57?am, mer... at stonehenge.com (Randal L. Schwartz) wrote: > >>>>> "Xah" == Xah Lee writes: > > Xah> curious question. > Xah> suppose you have 300 different strings and they need all be replaced > Xah> to say "aaa". > > And then suppose this isn't the *real* question, but one entirely of > Fiction by Xah Lee. > > How helpful do you want to be? it's a interesting question anyway. the question originally came from when i was coding elisp of a function that changes html entities to unicode char literal. The problem is slightly complicated, involving a few questions about speed in emacs. e.g. string vs buffer, and much more... i spent several hours on this but it's probably too boring to detail (but i'll do so if anyone wishes). But anyway, while digging these questions that's not clear in my mind, i thought of why not generate a regex or construct and do it in one shot, and wondered if that'd be faster. But afterwards, i realized this wouldn't be applicable to my problem because for my problem each string needs to be changed to a unique string, not all to the same string. Xah From michele.simionato at gmail.com Wed Sep 28 08:45:27 2011 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 28 Sep 2011 05:45:27 -0700 (PDT) Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <29931044.1310.1317213927830.JavaMail.geo-discussion-forums@yqnk41> plac is based on argparser and it is intended to be much easier to use. See http://plac.googlecode.com/hg/doc/plac.html Here is an example of usage. $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line plac.Interpreter.call instantiates the VCS class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments plac can also be used to write command interpreters. From michele.simionato at gmail.com Wed Sep 28 08:45:27 2011 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 28 Sep 2011 05:45:27 -0700 (PDT) Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <29931044.1310.1317213927830.JavaMail.geo-discussion-forums@yqnk41> plac is based on argparser and it is intended to be much easier to use. See http://plac.googlecode.com/hg/doc/plac.html Here is an example of usage. $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line plac.Interpreter.call instantiates the VCS class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments plac can also be used to write command interpreters. From roy at panix.com Wed Sep 28 08:53:06 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 08:53:06 -0400 Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> <862e37e9-f4d2-4423-8d28-485923f1c76b@p11g2000yqe.googlegroups.com> Message-ID: In article <862e37e9-f4d2-4423-8d28-485923f1c76b at p11g2000yqe.googlegroups.com>, Aljosa Mohorovic wrote: > On Sep 28, 2:17?am, Roy Smith wrote: > > We rolled our own oauth2 client on top of basic urllib calls. ?It's not > > terribly difficult. > > i'm asking about oauth2 server implementation, not client. > it's easy to consume oauth2 stuff but what to do when you need to > implement server side stuff? Oh, my apologies, I read your post too fast and misunderstood what you were asking. I suspect writing an oauth2 provider will be on my plate soon, so let me know what you figure out :-) From xahlee at gmail.com Wed Sep 28 09:14:33 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 06:14:33 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> here's more detail about the origin of this problem. Relevant to emacs lisp only. ------------------------------ in the definition of ?replace-regexp-in-string?, there's this comment: ;; To avoid excessive consing from multiple matches in long strings, ;; don't just call `replace-match' continually. Walk down the ;; string looking for matches of REGEXP and building up a (reversed) ;; list MATCHES. This comprises segments of STRING which weren't ;; matched interspersed with replacements for segments that were. ;; [For a `large' number of replacements it's more efficient to ;; operate in a temporary buffer; we can't tell from the function's ;; args whether to choose the buffer-based implementation, though it ;; might be reasonable to do so for long enough STRING.] note: ?For a `large' number of replacements it's more efficient to operate in a temporary buffer?. my question is, anyone got some idea, how ?large? is large? currently, i have a function replace-pairs-in-string which is implemented by repeatedly calling ?replace-pairs-in-string? like this: (while (< ii (length pairs)) (setq mystr (replace-regexp-in-string (elt tempMapPoints ii) (elt (elt pairs ii) 1) mystr t t)) (setq ii (1+ ii)) ) When there are 260 pairs of strings to be replaced on a file that's 26k in size, my function takes about 3 seconds (which i think is too slow). I'm at pain deciding whether my function should be implemented like this or whether it should create a temp buffer. The problem with temp buffer is that, if you repeatedly call it, the overhead of creating buffer is going to make it much slower. i was actually surprised that replace-regexp-in-string isn't written in C, which i thought it was. is there technical reason the replace-regexp-in-string isn't C? (i suppose only because nobody every did it and the need for speed didn't suffice?) and also, shouldn't there also be a replace-in-string (literal, not regex)? because i thought implementing replacement for string should be much simpler and faster, because buffers comes with it a whole structure such as ?point?, text properties, buffer names, buffier modifier, etc. Xah On Sep 28, 5:28?am, Xah Lee wrote: > On Sep 28, 3:57?am, mer... at stonehenge.com (Randal L. Schwartz) wrote: > > > >>>>> "Xah" == Xah Lee writes: > > > Xah> curious question. > > Xah> suppose you have 300 different strings and they need all be replaced > > Xah> to say "aaa". > > > And then suppose this isn't the *real* question, but one entirely of > > Fiction by Xah Lee. > > > How helpful do you want to be? > > it's a interesting question anyway. > > the question originally came from when i was coding elisp of a > function that changes html entities to unicode char literal. The > problem is slightly complicated, involving a few questions about speed > in emacs. e.g. string vs buffer, and much more... i spent several > hours on this but it's probably too boring to detail (but i'll do so > if anyone wishes). But anyway, while digging these questions that's > not clear in my mind, i thought of why not generate a regex or > construct and do it in one shot, and wondered if that'd be faster. But > afterwards, i realized this wouldn't be applicable to my problem > because for my problem each string needs to be changed to a unique > string, not all to the same string. > > ?Xah From rosuav at gmail.com Wed Sep 28 09:19:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:19:32 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: > each string needs to be changed to a unique > string, not all to the same string. And you'll find that this is, by and large, the most normal situation. Folding many strings down to one string is a lot less common. So, let's have some real-world use cases and then we can talk recommendations. ChrisA From neilc at norwich.edu Wed Sep 28 09:22:41 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 28 Sep 2011 13:22:41 GMT Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <9egld1F385U1@mid.individual.net> On 2011-09-28, Chris Angelico wrote: > On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: >> each string needs to be changed to a unique string, not all to >> the same string. > > And you'll find that this is, by and large, the most normal > situation. Folding many strings down to one string is a lot > less common. So, let's have some real-world use cases and then > we can talk recommendations. I'd like to know what "string replacement" is supposed to mean in the context of Python. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From rosuav at gmail.com Wed Sep 28 09:26:37 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:26:37 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 11:14 PM, Xah Lee wrote: > (while (< ii (length pairs)) > ? ? ?(setq mystr (replace-regexp-in-string > ? ? ? ? ? ? ? ? ? (elt tempMapPoints ii) > ? ? ? ? ? ? ? ? ? (elt (elt pairs ii) 1) > ? ? ? ? ? ? ? ? ? mystr t t)) > ? ? ?(setq ii (1+ ii)) > ? ? ?) from __future__ import lisp_syntax There, that makes it on-topic for the Python list... I guess. ChrisA From __peter__ at web.de Wed Sep 28 09:29:19 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Sep 2011 15:29:19 +0200 Subject: how to run in xp? References: Message-ID: =?gbk?B?ytjW6rT9zcM=?= wrote: > it can run ,but there is still a problem ,nothing in my file. > please run the code in xp+python32 > import urllib.request, urllib.parse, urllib.error > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > print (file) > what you get is: > >>>> > b'' > b'' > b'' >>>> > > how to fix it? I get the expected output, but I'm on Linux. Are you using the latest bugfix release (Python 3.2.2)? Can you download the data with your browser? From roy at panix.com Wed Sep 28 09:29:57 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 09:29:57 -0400 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <9egld1F385U1@mid.individual.net> Message-ID: In article <9egld1F385U1 at mid.individual.net>, Neil Cerutti wrote: > On 2011-09-28, Chris Angelico wrote: > > On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: > >> each string needs to be changed to a unique string, not all to > >> the same string. > > > > And you'll find that this is, by and large, the most normal > > situation. Folding many strings down to one string is a lot > > less common. So, let's have some real-world use cases and then > > we can talk recommendations. > > I'd like to know what "string replacement" is supposed to mean in > the context of Python. You just need to use "string" in the more generic computer-sciency sense, not in the python-data-type sense. s = "I am an immutable string" l = list(s) # now you can pretend strings are mutable do_stuff_to_string(l) s = ''.join(l) From rosuav at gmail.com Wed Sep 28 09:32:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:32:49 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <9egld1F385U1@mid.individual.net> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <9egld1F385U1@mid.individual.net> Message-ID: On Wed, Sep 28, 2011 at 11:22 PM, Neil Cerutti wrote: > I'd like to know what "string replacement" is supposed to mean in > the context of Python. > Substring replacement, such as: >>> "Hello, world!".replace(", "," -- ") 'Hello -- world!' The str method doesn't accept a list, though, so it won't do simultaneous replaces. (At least, I don't think it can. Tried it only in Python 3.2 on Windows.) ChrisA From python.list at tim.thechases.com Wed Sep 28 10:16:59 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Sep 2011 09:16:59 -0500 Subject: Unittest testing assert*() calls rather than methods? Message-ID: <4E832C5B.1080007@tim.thechases.com> While I asked this on the Django list as it happened to be with some Django testing code, this might be a more generic Python question so I'll ask here too. When performing unittest tests, I have a number of methods of the form def test_foo(self): data = ( (item1, result1), ... #bunch of tests for fence-post errors ) for test, result in data: self.assertEqual(process(test), result) When I run my tests, I only get a tick for running one the one test (test_foo), not the len(data) tests that were actually performed. Is there a way for unittesting to report the number of passed-assertions rather than the number of test-methods run? -tkc From ben+python at benfinney.id.au Wed Sep 28 10:17:57 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:17:57 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <87oby4zr6y.fsf@benfinney.id.au> DevPlayer writes: > Calling the Bible a joke is used to hurt people, not enlighten them. How do you know that? > Those words show bitter arrogance, not constructive critism How do you know that? > as it ignores how others feel about that book. That strikes me as a good thing; how people feel about a book should not in any way restrain our criticism of the book. > What benefit to others is gained by calling someones belief a joke? To > put the "believers" minds straight? I think not. I can't speak for the person who wrote that. But when I call a religious belief a joke, it is to point out the folly of the belief in the pursuit of convincing people not to hold beliefs I consider to be foolish. > I think the unsensitive person who attackes others beliefs, even if > illogical or unrealistic, is after some kind of self grandizement or > to illude themself into thinking "they know the truth of the universe" > and should attack others to prove they do. You are wrong to conflate ?attack others's beliefs? with ?attack others?. You are not your beliefs. If your beliefs are shown to be false ? even ridiculous ? you can distance yourself from those beliefs. It is even virtuous to do so. We must always be free to attack any belief, and encourage everyone to stop taking it as any kind of personal attack. > Although this is not the place to defend about such things it is also > not the place to attack those same things (that being someone's > faith). I will join you in deploring any attack on a person. But that's not what you're doing, and I deny your attempt to shield any idea from ridicule, in any forum. Ideas don't have feelings, and you don't get to put people in front of them as human shields against attacking those ideas. Any idea is and must be open to attack in any forum; those that can't survive ridicule deserve to go. -- \ ?Ridicule is the only weapon which can be used against | `\ unintelligible propositions.? ?Thomas Jefferson, 1816-07-30 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 10:29:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:29:18 +1000 Subject: Unittest testing assert*() calls rather than methods? References: Message-ID: <87k48szqo1.fsf@benfinney.id.au> Tim Chase writes: > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) The sets of data for running the same test we might call ?scenarios?. > When I run my tests, I only get a tick for running one the one test > (test_foo), not the len(data) tests that were actually performed. Worse, if one of the scenarios causes the test to fail, the loop will end and you won't get the results for the remaining scenarios. > Is there a way for unittesting to report the number of > passed-assertions rather than the number of test-methods run? You can use the third-party ?testscenarios? library to generate test cases at run time, one for each combination of scenarios with test cases on the class. They will all be run and reported as distinct test cases. There is even another library integrating this with Django . -- \ ?Books and opinions, no matter from whom they came, if they are | `\ in opposition to human rights, are nothing but dead letters.? | _o__) ?Ernestine Rose | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 10:53:40 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:53:40 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <87fwjgzpjf.fsf@benfinney.id.au> Ben Finney writes: > You can use the third-party ?testscenarios? library The URL got a bit mangled. The proper PyPI URL for that library is . > to generate test cases at run time, one for each combination of > scenarios with test cases on the class. They will all be run and > reported as distinct test cases. > > There is even another library integrating this with Django > . -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From drobinow at gmail.com Wed Sep 28 12:17:05 2011 From: drobinow at gmail.com (David Robinow) Date: Wed, 28 Sep 2011 12:17:05 -0400 Subject: how to run in xp? In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 9:29 AM, Peter Otten <__peter__ at web.de> wrote: > =?gbk?B?ytjW6rT9zcM=?= wrote: > >> it can run ,but there is still a problem ,nothing in my file. >> please run the code in xp+python32 >> import urllib.request, urllib.parse, urllib.error >> exchange=['NASDAQ','NYSE','AMEX'] >> for down in exchange: >> ? ? url='http://www.nasdaq.com/screening/companies-by- > industry.aspx?exchange='+down+'&render=download' >> ? ? file=urllib.request.urlopen(url).read() >> ? ? print (file) >> what you get is: >> >>>>> >> b'' >> b'' >> b'' >>>>> >> >> how to fix it? > > I get the expected output, but I'm on Linux. Are you using the latest bugfix > release (Python 3.2.2)? Can you download the data with your browser? I get the expected output, but I'm on Windows (Vista, Python 3.2.2.) From alec.taylor6 at gmail.com Wed Sep 28 12:19:32 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 29 Sep 2011 02:19:32 +1000 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> Message-ID: Fix: http://lipyrary.blogspot.com/2011/05/how-to-compile-python-on-ubuntu-1104.html On Tue, Sep 27, 2011 at 5:04 AM, Benjamin Kaplan wrote: > On Mon, Sep 26, 2011 at 2:16 PM, Jesramz wrote: >> >> I appreciate all the help, but I am still a little confused. Sorry, >> I'm a lay person. >> >> Should I download zlib1g-dev and install it to get the zlib module? >> >> and Alter the configure script to avoid future issues? >> >> Also about getting zlib I found the following: >> >> "I was able to recompile zlib >> >> $./configure --shared >> >> then recompile Python 2.5.1; I am now able to import the zlib module. >> >> cheers >> >> -sg" >> >> Does this mean that while in the zlib folder run ./configure shared >> and then install python? >> -- > > Not quite. This person was talking about configuring zlib, not Python. > Just about every Linux program out there has a ./configure file- it's > part of GNU Autotools, which many programs use as an easy way to > compile and install their software. Since the version of zlib on > Ubuntu Natty doesn't work for Python 2.5, this person just compiled > their own zlib (calling ./configure --shared; make; make install from > the zlib *source* folder that they downloaded) and then compiled their > own Python version (from the Python source folder that they > downloaded) > > >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From willem at toad.stack.nl Wed Sep 28 13:00:51 2011 From: willem at toad.stack.nl (Willem) Date: Wed, 28 Sep 2011 17:00:51 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: Xah Lee wrote: ) the question originally came from when i was coding elisp of a ) function that changes html entities to unicode char literal. The ) problem is slightly complicated, involving a few questions about speed ) in emacs. e.g. string vs buffer, and much more... i spent several ) hours on this but it's probably too boring to detail (but i'll do so ) if anyone wishes). But anyway, while digging these questions that's ) not clear in my mind, i thought of why not generate a regex or ) construct and do it in one shot, and wondered if that'd be faster. But ) afterwards, i realized this wouldn't be applicable to my problem ) because for my problem each string needs to be changed to a unique ) string, not all to the same string. In Perl, it would be applicable. You see, in Perl, you can call a function in the replacement of the regex substitution, which can then look up the html entity and return the wanted unicode literal. I think you can do that in some other languages as well. SaSW, Willem -- Disclaimer: I am in no way responsible for any of the statements made in the above text. For all I know I might be drugged or something.. No I'm not paranoid. You all think I'm paranoid, don't you ! #EOT From python at mrabarnett.plus.com Wed Sep 28 13:11:33 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 28 Sep 2011 18:11:33 +0100 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <4E835545.9010802@mrabarnett.plus.com> On 28/09/2011 18:00, Willem wrote: > Xah Lee wrote: > ) the question originally came from when i was coding elisp of a > ) function that changes html entities to unicode char literal. The > ) problem is slightly complicated, involving a few questions about speed > ) in emacs. e.g. string vs buffer, and much more... i spent several > ) hours on this but it's probably too boring to detail (but i'll do so > ) if anyone wishes). But anyway, while digging these questions that's > ) not clear in my mind, i thought of why not generate a regex or > ) construct and do it in one shot, and wondered if that'd be faster. But > ) afterwards, i realized this wouldn't be applicable to my problem > ) because for my problem each string needs to be changed to a unique > ) string, not all to the same string. > > In Perl, it would be applicable. You see, in Perl, you can call a function > in the replacement of the regex substitution, which can then look up the > html entity and return the wanted unicode literal. > > I think you can do that in some other languages as well. > Including Python... From ian.g.kelly at gmail.com Wed Sep 28 13:48:48 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 28 Sep 2011 11:48:48 -0600 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 3:28 AM, Xah Lee wrote: > curious question. > > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially (i.e. replace first > string to aaa, then do the 2nd, 3rd,...) > , or is it faster to use a regex with ?or? them all and do replace one > shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) > > let's say the sourceString this replacement to be done on is 500k > chars. > > Anyone? i suppose the answer will be similar for perl, python, ruby. > > btw, the origin of this question is about writing a emacs lisp > function that replace ~250 html named entities to unicode char. I haven't timed it at the scale you're talking about, but for Python I expect regex will be your best bet: # Python 3.2: Supposing the match strings and replacements are # in a dict stored as `repls`... import re pattern = '|'.join(map(re.escape, repls.keys())) new_str = re.sub(pattern, lambda m: repls[m.group()], old_str) The problem with doing 300 str.replace calls is the 300 intermediate strings that would be created and then collected. Cheers, Ian From * at eli.users.panix.com Wed Sep 28 15:08:21 2011 From: * at eli.users.panix.com (Eli the Bearded) Date: Wed, 28 Sep 2011 19:08:21 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: In comp.lang.perl.misc, Willem wrote: > In Perl, it would be applicable. You see, in Perl, you can call a function > in the replacement of the regex substitution, which can then look up the > html entity and return the wanted unicode literal. A function? I'd use a hash. > I think you can do that in some other languages as well. Hash / array type substitutions indexed by $1 (or language equivilent) are probably easy to implement in many languages. Elijah ------ for really fast, write code to generate a C lexer to do it From willem at toad.stack.nl Wed Sep 28 15:11:27 2011 From: willem at toad.stack.nl (Willem) Date: Wed, 28 Sep 2011 19:11:27 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: Eli the Bearded wrote: ) In comp.lang.perl.misc, Willem wrote: )> In Perl, it would be applicable. You see, in Perl, you can call a function )> in the replacement of the regex substitution, which can then look up the )> html entity and return the wanted unicode literal. ) ) A function? I'd use a hash. A function can return a sensible value for unknown substitutions. In the case where you prebuild a giant regex or-list, that is not an issue, but I would match html entities generically. SaSW, Willem -- Disclaimer: I am in no way responsible for any of the statements made in the above text. For all I know I might be drugged or something.. No I'm not paranoid. You all think I'm paranoid, don't you ! #EOT From john at castleamber.com Wed Sep 28 16:14:51 2011 From: john at castleamber.com (John Bokma) Date: Wed, 28 Sep 2011 15:14:51 -0500 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <8739fgjuf8.fsf@castleamber.com> Willem writes: > Eli the Bearded wrote: > ) In comp.lang.perl.misc, Willem wrote: > )> In Perl, it would be applicable. You see, in Perl, you can call a function > )> in the replacement of the regex substitution, which can then look up the > )> html entity and return the wanted unicode literal. > ) > ) A function? I'd use a hash. > > A function can return a sensible value for unknown substitutions. You can do that also in the RHS of the substitution and still keep it readable if you use something like s{..}{ your code goes here }ge; However, a function can be easier on the eye: s{...}{ some_good_name( ... ) }ge; -- John Bokma j3b Blog: http://johnbokma.com/ Perl Consultancy: http://castleamber.com/ Perl for books: http://johnbokma.com/perl/help-in-exchange-for-books.html From theg33k at gmail.com Wed Sep 28 17:06:23 2011 From: theg33k at gmail.com (The Geek) Date: Wed, 28 Sep 2011 17:06:23 -0400 Subject: new to python question Message-ID: I'm clearly not understanding something about scope in python... Any help is appreciated In the following script I'm attempting to create 2 Foo objects, for each Foo object I create 2 Bars and add them to Foo's bar array Something hokey is occurring with the "foo.bars.append(bar)" line such that Foo.bars is treated as a "static" (I know python doesn't have statics) I have a workaround using encapsulation for the bars array but I prefer would also like to understand the issue. TIA, Brad [SCRIPT] foos = [] class Foo: id = 0 bars = [] class Bar: id = 0 for j in range(0, 2): foo = Foo() for i in range(0, 2): bar = Bar() bar.id = i foo.bars.append(bar) foos.append(foo) for myFoo in foos: print("foo id: ", myFoo.id) for myBar in myFoo.bars: print ("\tbar id: ", myBar.id) [/SCRIPT] [OUTPUT] python test.py foo id: 0 bar id: 0 bar id: 1 bar id: 0 bar id: 1 foo id: 0 bar id: 0 bar id: 1 bar id: 0 bar id: 1 [/OUTPUT] -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Wed Sep 28 17:12:13 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 28 Sep 2011 17:12:13 -0400 Subject: new to python question In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 5:06 PM, The Geek wrote: > I'm clearly not understanding something about scope in python... ?Any help > is appreciated > In the following script I'm attempting to create 2 Foo objects, for each Foo > object I create 2 Bars and add them to Foo's bar array > Something hokey is?occurring?with the "foo.bars.append(bar)" line such that > Foo.bars is treated as a "static" (I know python doesn't have statics) > I have a workaround using encapsulation for the bars array but I prefer > would also like to understand the issue. > TIA, > Brad > [SCRIPT] > foos = [] > class Foo: > id = 0 > bars = [] > class Bar: > id = 0 > for j in range(0, 2): > foo = Foo() > for i in range(0, 2): > bar = Bar() > bar.id = i > foo.bars.append(bar) > foos.append(foo) > for myFoo in foos: > print("foo id: ", myFoo.id) > for myBar in myFoo.bars: > print ("\tbar id: ", myBar.id) > [/SCRIPT] It's a pretty common gotcha for people coming from other languages. Everything declared in the class scope becomes an attribute of the class. >>> class Foo(object) : ... a = 3 ... def b() : pass ... >>> dir(Foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_ _weakref__', 'a', 'b'] Mutating those objects mutates the attribute of the class, which is visible to all instances of the class. In order to get an instance of a class, you have to add the field to the instance of the class instead of to the class itself. class Bar(object) : def ___init__(self) : self.a = 3 From tjreedy at udel.edu Wed Sep 28 17:23:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 17:23:50 -0400 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On 9/28/2011 5:28 AM, Xah Lee wrote: > curious question. > > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially (i.e. replace first > string to aaa, then do the 2nd, 3rd,...) > , or is it faster to use a regex with ?or? them all and do replace one > shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) Here the problem is replace multiple random substrings with one random substring that could create new matches. I would start with the re 'or' solution. > btw, the origin of this question is about writing a emacs lisp > function that replace ~250 html named entities to unicode char. As you noted this is a different problem in that there is a different replacement for each. Also, the substrings being searched for are not random but have a distinct and easily recognized structure. The replacement cannot create a new match. So the multiple scan approach *could* work. Unspecified is whether the input is unicode or ascii bytes. If the latter I might copy to a bytearray (mutable), scan forward, replace entity defs with utf-8 encoding of the corresponding unicode (with a dict lookup, and which I assume are *always* fewer chars), and shift other chars to close any gaps created. If the input is unicode, I might do the same with array.array (which is where bytearray came from). Or I might use the standard idiom of constructing a list of pieces of the original, with replacements, and ''.join() at the end. -- Terry Jan Reedy From ethan at stoneleaf.us Wed Sep 28 17:26:09 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 28 Sep 2011 14:26:09 -0700 Subject: syntactic sugar for def? Message-ID: <4E8390F1.9060207@stoneleaf.us> I remember that 'class' is sugar for type(....). I don't remember if 'def' is sugar for something besides lambda. Any clues for me? Heck, I'll even be grateful for outright answers! ~Ethan~ From ian.g.kelly at gmail.com Wed Sep 28 17:36:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 28 Sep 2011 15:36:08 -0600 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. > > Any clues for me? ?Heck, I'll even be grateful for outright answers! If you mean is there a way to create functions using reflection, you can use types.FunctionType. Like type() requires a dict, FunctionType() requires a code object that must first be compiled. Cheers, Ian From arnodel at gmail.com Wed Sep 28 17:37:12 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 28 Sep 2011 22:37:12 +0100 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On 28 September 2011 22:26, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. > > Any clues for me? ?Heck, I'll even be grateful for outright answers! It's not really sugar. But I think you mean something like this: >>> class A: pass ... >>> type(A) >>> type is type(A) True So the closest you get for functions will be: >>> def f(): pass ... >>> type(f) Try help(type(f)) to see how to use it to create a function object. The problem is that you need to provide a code object, and the easiest way to create a code object is to use a def statement :) HTH -- Arnaud From tayfun92_kayhan at yahoo.com Wed Sep 28 17:49:21 2011 From: tayfun92_kayhan at yahoo.com (Tayfun Kayhan) Date: Wed, 28 Sep 2011 14:49:21 -0700 (PDT) Subject: A trivial question Message-ID: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> I accidentally wrote such a code (below) while trying to write sth else for my application but i am now just wondering much how to run the class Foo, if it is possible. Is not it weird that Python does not give any error when I run it ? Sorry for that it's pretty unimportant question according to the other questions being asked here :D def trial(): class Foo(object): def __init__(self): print("Hello, world!") trial() # not worked, as expected. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ckaynor at zindagigames.com Wed Sep 28 17:51:00 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 28 Sep 2011 14:51:00 -0700 Subject: syntactic sugar for def? In-Reply-To: References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle wrote: > On 28 September 2011 22:26, Ethan Furman wrote: >> I remember that 'class' is sugar for type(....). >> >> I don't remember if 'def' is sugar for something besides lambda. >> >> Any clues for me? ?Heck, I'll even be grateful for outright answers! > > It's not really sugar. ?But I think you mean something like this: > > >>>> class A: pass > ... >>>> type(A) > >>>> type is type(A) > True > > So the closest you get for functions will be: > >>>> def f(): pass > ... >>>> type(f) > > > Try help(type(f)) to see how to use it to create a function object. > The problem is that you need to provide a code object, and the easiest > way to create a code object is to use a def statement :) I would say compile isn't too much harder to use: >>> c = compile('a = 123', 'test', 'exec') >>> d = {} >>> f = types.FunctionType(c, d, 'test') >>> f() >>> print d {'a': 123} Although it appears you get all of the variables defined as global apparently (try "f = types.FunctionType(c, globals(), 'test')" instead). > > HTH > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From tayfun92_kayhan at yahoo.com Wed Sep 28 17:53:59 2011 From: tayfun92_kayhan at yahoo.com (Tayfun Kayhan) Date: Wed, 28 Sep 2011 14:53:59 -0700 (PDT) Subject: A Trivial Question Message-ID: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> I accidentally wrote such a code (below) while trying to write sth else for my application but i am now just wondering much how to run the class Foo, if it is possible. Is not it weird that Python does not give any error when I run it ? Sorry for that it's pretty unimportant question according to the other questions being asked here :D def trial(): class Foo(object): def __init__(self): print("Hello, world!") trial() # not worked, as expected. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Sep 28 18:03:48 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 18:03:48 -0400 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: <4E832C5B.1080007@tim.thechases.com> References: <4E832C5B.1080007@tim.thechases.com> Message-ID: On 9/28/2011 10:16 AM, Tim Chase wrote: > When performing unittest tests, I have a number of methods of the form > > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) > > When I run my tests, I only get a tick for running one the one test > (test_foo), not the len(data) tests that were actually performed. Is > there a way for unittesting to report the number of passed-assertions > rather than the number of test-methods run? In my view, unittest, based on JUnit from Java, is both overkill and inadequate for simple function testing of multiple input-output pairs. So I wrote my own short function test function that does just what I want, and which I can change if I change what I want. Ben has described the combinatorial explosion solution. But if I were using unittest, I might do something like the following: def test_foo(self): data = ( (item1, result1), ... #bunch of tests for fence-post errors ) errors = [] for input, expected in data: try: actual = process(input) if actual != expected: errors.append(input, expected, actual) except Exception as e: errors.append(input, expected, actual) self.assertEqual((0,[]), (len(errors),errors)) except that I would write a functest(func, iopairs) that returned the error pair. (This is essentially what I have done for for myself.) I am presuming that one can run unittest so that it prints the unequal items. -- Terry Jan Reedy From clp2 at rebertia.com Wed Sep 28 18:06:14 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 28 Sep 2011 15:06:14 -0700 Subject: A Trivial Question In-Reply-To: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: On Wed, Sep 28, 2011 at 2:53 PM, Tayfun Kayhan wrote: > I accidentally wrote such a code (below) while trying to write sth else for > my application but i am now just wondering much how to run the class Foo, if > it is possible. Is not it weird that Python does not give any error when I > run it ? Sorry for that it's pretty unimportant question according to the > other questions being asked here :D > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. Right now, you've merely defined a class in the local scope of a function, which is perfectly valid, although you don't take advantage of this, so there's no particular reason to put the class definition inside trial(). Foo.__init__() only gets called when you create an instance of Foo, which you aren't doing currently, hence why "Hello, world!" isn't printed. Try this: def trial(): class Foo(object): def __init__(self): print("Hello, world!") Foo() trial() Or this: class Foo(object): def __init__(self): print("Hello, world!") def trial(): Foo() trial() Cheers, Chris -- http://rebertia.com From nad at acm.org Wed Sep 28 18:21:25 2011 From: nad at acm.org (Ned Deily) Date: Wed, 28 Sep 2011 15:21:25 -0700 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e82a1a1$0$29965$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Tue, 27 Sep 2011 14:32:43 -0700, Wanderer wrote: > > I need to stay in sink with the rest of the company which is still using > > 2.6 flavors. There was some investigation into going to Python 3 but not > > enough of the libraries we use were available. I'll install 2.6.6. I > > don't think the security stuff really effects me. I think it is strange > > to release a security update but not really expect people to use it. > > > More likely the person who builds the Windows installers just hasn't made > a new release yet. > > The Python development team is relatively small and chronically busy: too > much to do and not enough time to do it. As I understand it, most of them > use Linux, so I'm afraid that Windows sometimes takes a back seat. (At > least it's not Mac OS, which is stuck riding in the boot of the car, or > the other semi-supported OSes, which are on a skateboard desperately > hanging onto the bumper trying not to be left behind.) No, it was a deliberate decision. After a release is in security-fix mode only, we don't build Windows or Mac OS X installers for them. The emphasis is on the actively maintained release branches, currently 3.2.x and 2.7.x. If third-party distributors want to support their users with binary installers, that is of course their option. "Python 2.6.7 is a security-fix only source release for Python 2.6.6, fixing several reported security issues. Python 2.6.7 was released on June 3, 2011. Python 2.6 is now in security-fix-only mode; no new features are being added, and no new bug fix releases are planned. We intend to provide source-only security fixes for the Python 2.6 series until October 2013 (five years after the 2.6 final release). For ongoing maintenance releases, please see the Python 2.7 series." http://www.python.org/getit/releases/2.6.7/ (And I think you may be just slightly mischaracterizing the status of both Mac OS X and Windows support.) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Wed Sep 28 18:30:01 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Sep 2011 19:30:01 -0300 Subject: syntactic sugar for def? References: <4E8390F1.9060207@stoneleaf.us> Message-ID: En Wed, 28 Sep 2011 18:51:00 -0300, Chris Kaynor escribi?: > On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle > wrote: >> On 28 September 2011 22:26, Ethan Furman wrote: >>> I remember that 'class' is sugar for type(....). >>> >>> I don't remember if 'def' is sugar for something besides lambda. >>> >>> Any clues for me? Heck, I'll even be grateful for outright answers! >> >> It's not really sugar. But I think you mean something like this: >> >> >>>>> class A: pass >> ... >>>>> type(A) >> >>>>> type is type(A) >> True >> >> So the closest you get for functions will be: >> >>>>> def f(): pass >> ... >>>>> type(f) >> >> >> Try help(type(f)) to see how to use it to create a function object. >> The problem is that you need to provide a code object, and the easiest >> way to create a code object is to use a def statement :) > > I would say compile isn't too much harder to use: >>>> c = compile('a = 123', 'test', 'exec') >>>> d = {} >>>> f = types.FunctionType(c, d, 'test') >>>> f() >>>> print d > {'a': 123} > > Although it appears you get all of the variables defined as global > apparently (try "f = types.FunctionType(c, globals(), 'test')" > instead). I know no way of compiling a function body alone. Suppose you have this function: def foo(x): print x y = 2*x return y py> compile(" print x\n y = 2*x\n return y", "", "exec") Traceback (most recent call last): File "", line 1, in File "", line 1 print x ^ IndentationError: unexpected indent py> compile("print x\ny = 2*x\nreturn y", "", "exec") Traceback (most recent call last): File "", line 1, in File "", line 3 SyntaxError: 'return' outside function If you include the 'def' statement in the source string, the resulting code object does not represent the function itself, but a "module" defining it: py> f = FunctionType(compile("def foo(x):\n print x\n y = 2*x\n return y\n", ... "", "exec"), globals(), "foo") py> f(3) Traceback (most recent call last): File "", line 1, in TypeError: () takes no arguments (1 given) py> dis.dis(f) 1 0 LOAD_CONST 0 (", line 1>) 3 MAKE_FUNCTION 0 6 STORE_NAME 0 (foo) 9 LOAD_CONST 1 (None) 12 RETURN_VALUE To get at the actual function code, one should use f.func_code.co_consts[0]; this would be the 'code' parameter for types.FunctionType. Very complicated, really; nothing can beat the 'def' statement for defining a function ;) -- Gabriel Genellina From ericsnowcurrently at gmail.com Wed Sep 28 18:38:26 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 28 Sep 2011 16:38:26 -0600 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. This is something I have thought about a lot since PyCon this year. I apologize in advance. Since 3.0, class statements are syntactic sugar for some extra steps beyond "meta(...)" [1]. In CPython this is facilitated through the "hidden" __build_class__() builtin[2]. We have the __import__() builtin for customizing module creation. But, as you asked, what about functions? Currently there isn't a way to customize function creation. There is no __build_function__() builtin. The best you can do is, like others have said, directly call FunctionType(...) or type(f)(...) where f is an existing function. I expect that if there were a __build_function__, it would wrap the code that is currently run for the MAKE_FUNCTION/MAKE_CLOSURE opcodes[3]. Also, both modules and classes have mechanisms built-in to allow for customization in certain parts of the creation process (PEP 302[4] and metaclasses[5], respectively). Functions lack this as well, though there hasn't been a big clamor for it. :) Nick Coghlan proposed an interesting idea for this in March[6], with some later follow-up[7]. Nothing much came of it though. Definitely an interesting topic, which has led me to learn a lot about Python and CPython. -eric [1] http://www.python.org/dev/peps/pep-3115/ http://mail.python.org/pipermail/python-3000/2007-March/006338.html [2] http://hg.python.org/cpython/file/default/Python/bltinmodule.c#l35 [3] http://hg.python.org/cpython/file/default/Python/ceval.c#l2680 [4] http://www.python.org/dev/peps/pep-0302/ http://docs.python.org/release/2.3.5/whatsnew/section-pep302.html http://docs.python.org/dev/reference/simple_stmts.html#the-import-statement [5] http://docs.python.org/dev/reference/datamodel.html#customizing-class-creation http://www.python.org/doc/essays/metaclasses/ [6] http://mail.python.org/pipermail/python-ideas/2011-March/009391.html [7] http://mail.python.org/pipermail/python-ideas/2011-March/009625.html http://mail.python.org/pipermail/python-ideas/2011-April/009765.html > > Any clues for me? ?Heck, I'll even be grateful for outright answers! > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed Sep 28 19:01:11 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 19:01:11 -0400 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On 9/28/2011 5:26 PM, Ethan Furman wrote: > I don't remember if 'def' is sugar for something besides lambda. That is a bit backwards. lambda x: expr(x) is syntactic sugar for def (x): return expr(x) del ;-) -- Terry Jan Reedy From greg.ewing at canterbury.ac.nz Wed Sep 28 19:01:27 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 29 Sep 2011 12:01:27 +1300 Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ehnaaF35hU1@mid.individual.net> Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm > > Documentation like that really makes me appreciate the sterling work done on > Python's docs. I think you have to read it in context. A couple of levels up there is a section called "The FREQ Procedure" which seems to explain more about what's going on, including examples. (I didn't look too closely at it, though, in case my eyes started to bleed...) -- Greg From tim at akwebsoft.com Wed Sep 28 19:26:51 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 28 Sep 2011 15:26:51 -0800 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <20110928232651.GT19422@johnsons-web.com> * DevPlayer [110928 04:31]: > On Sep 27, 10:25?pm, alex23 wrote: > > rantingrick wrote: > > > Since, like the bible > > > the zen is self contradicting, any argument utilizing the zen can be > > > defeated utilizing the zen. > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > taking it too seriously, that's your problem. > > > > > If however you want to learn about the accepted rules for formatting > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > Contradiction is only seen by narrow perspectve. > > Calling the Bible a joke is used to hurt people, not enlighten them. > Those words show bitter arrogance, not constructive critism as it > ignores how others feel about that book. What benefit to others is > gained by calling someones belief a joke? My wife and I are devout christians, but not fundamentalist. We would not take rantingrick too seriously. If _you_ take him seriously, you're just giving him 'street cred'. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From nobody at nowhere.com Wed Sep 28 20:10:38 2011 From: nobody at nowhere.com (Nobody) Date: Thu, 29 Sep 2011 01:10:38 +0100 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > No, it was a deliberate decision. After a release is in security-fix > mode only, we don't build Windows or Mac OS X installers for them. But you continue to offer the installers for the unfixed version. From steve+comp.lang.python at pearwood.info Wed Sep 28 20:16:30 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 10:16:30 +1000 Subject: Unittest testing assert*() calls rather than methods? References: Message-ID: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Tim Chase wrote: > While I asked this on the Django list as it happened to be with > some Django testing code, this might be a more generic Python > question so I'll ask here too. > > When performing unittest tests, I have a number of methods of the > form > > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) > > When I run my tests, I only get a tick for running one the one > test (test_foo), not the len(data) tests that were actually > performed. Is there a way for unittesting to report the number > of passed-assertions rather than the number of test-methods run? I used to ask the same question, but then I decided that if I wanted each data point to get its own tick, I should bite the bullet and write an individual test for each. If you really care, you could subclass unittest.TestCase, and then cause each assert* method to count how often it gets called. But really, how much detailed info about *passed* tests do you need? If you are writing loops inside tests, you might find this anecdote useful: http://mail.python.org/pipermail/python-list/2011-April/1270640.html -- Steven From cmpython at gmail.com Wed Sep 28 20:39:52 2011 From: cmpython at gmail.com (CM) Date: Wed, 28 Sep 2011 17:39:52 -0700 (PDT) Subject: options for plotting points on geographic map Message-ID: Recommendations sought for using Python to plot points/custom markers (and maybe other things?) on a map of an area of the U.S. of maybe 100 miles radius. (This would be a "political" map showing towns, such as from Google Maps or Mapquest, and not a "physical" map). I'll need to place markers or something based on zip codes. I see there is pymaps, a Python wrapper for Google Maps. I may try that but it seems to be barely documented and would require making a webpage with javascript to display the map, whereas I'd probably prefer a desktop app for this--though I'd consider a web page (it's probably easier than I think). I already use Matplotlib, but its Basemap seems to be only for physical geography needs. Are there other options one might recommend? (It is a little hard to Google for this given the map() function). Thanks, Che From zzzzysilence at gmail.com Wed Sep 28 20:42:09 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Wed, 28 Sep 2011 17:42:09 -0700 (PDT) Subject: red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/ Message-ID: <8edb383c-c6c7-4bc4-8b54-13c94a5c6493@18g2000yqz.googlegroups.com> Welcome to the www. currenthats.com,. The currenthats.com is a promotional shop from monster energy hats. It was authorized to provide red bull hats?snapback hats?hello kitty hats and the fashionable sports items to meet red bull hats Fans shopping needs. From zzzzysilence at gmail.com Wed Sep 28 20:46:10 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Wed, 28 Sep 2011 17:46:10 -0700 (PDT) Subject: red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/ Message-ID: Welcome to the www. currenthats.com,. The currenthats.com is a promotional shop from monster energy hats. It was authorized to provide red bull hats?snapback hats?hello kitty hats and the fashionable sports items to meet red bull hats Fans shopping needs. From roy at panix.com Wed Sep 28 20:49:24 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 20:49:24 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e83b8e0$0$29972$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > If you are writing loops inside tests, you might find this anecdote useful: > > http://mail.python.org/pipermail/python-list/2011-April/1270640.html On the other hand, the best test is one that gets written. I will often write tests that I know do not meet the usual standards of purity and wholesomeness. Here's a real-life example: for artist in artists: name = artist['name'] self.assertIsInstance(name, unicode) name = name.lower() # Due to fuzzy matching, it's not strictly guaranteed that the # following assertion is true, but it works in this case. self.assertTrue(name.startswith(term), (name, term)) Could I have written the test without the loop? Probably. Would it have been a better test? I guess, at some level, probably. And, of course, the idea of a "not strictly guaranteed" assertion is probably enough to make me lose my Unit Tester's Guild Secret Decoder Ring forever :-) But, the test was quick and easy to write, and provides value. I could have spent twice as long writing a better test, and it would have provided a little more value, but certainly not double. More importantly, had I spent the extra time writing the better test, I might have not had enough time to write all the other tests I wrote that day. Sometimes good enough is good enough. From jeanpierreda at gmail.com Wed Sep 28 20:50:03 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 28 Sep 2011 20:50:03 -0400 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: > I used to ask the same question, but then I decided that if I wanted each > data point to get its own tick, I should bite the bullet and write an > individual test for each. Nearly the entire re module test suite is a list of tuples. If it was instead a bunch of TestCase classes, there'd be a lot more boilerplate to write. (At a bare minimum, there'd be two times as many lines, and all the extra lines would be identical...) Why is writing boilerplate for a new test a good thing? It discourages the authorship of tests. Make it as easy as possible by e.g. adding a new thing to whatever you're iterating over. This is, for example, why the nose test library has a decorator for generating a test suite from a generator. Devin On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano wrote: > Tim Chase wrote: > >> While I asked this on the Django list as it happened to be with >> some Django testing code, this might be a more generic Python >> question so I'll ask here too. >> >> When performing unittest tests, I have a number of methods of the >> form >> >> ? ?def test_foo(self): >> ? ? ?data = ( >> ? ? ? ?(item1, result1), >> ? ? ? ?... #bunch of tests for fence-post errors >> ? ? ? ?) >> ? ? ?for test, result in data: >> ? ? ? ?self.assertEqual(process(test), result) >> >> When I run my tests, I only get a tick for running one the one >> test (test_foo), not the len(data) tests that were actually >> performed. ?Is there a way for unittesting to report the number >> of passed-assertions rather than the number of test-methods run? > > I used to ask the same question, but then I decided that if I wanted each > data point to get its own tick, I should bite the bullet and write an > individual test for each. > > If you really care, you could subclass unittest.TestCase, and then cause > each assert* method to count how often it gets called. But really, how much > detailed info about *passed* tests do you need? > > If you are writing loops inside tests, you might find this anecdote useful: > > http://mail.python.org/pipermail/python-list/2011-April/1270640.html > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From roy at panix.com Wed Sep 28 20:52:31 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 20:52:31 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: In article <87k48szqo1.fsf at benfinney.id.au>, Ben Finney wrote: > Worse, if one of the scenarios causes the test to fail, the loop will > end and you won't get the results for the remaining scenarios. Which, depending on what you're doing, may or may not be important. In many cases, there's only two states of interest: 1) All tests pass 2) Anything else From steve+comp.lang.python at pearwood.info Wed Sep 28 21:14:04 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 11:14:04 +1000 Subject: [OT] Benefit and belief [was Re: Suggested coding style] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> DevPlayer wrote: > On Sep 27, 10:25?pm, alex23 wrote: >> And like the Bible, the Zen was created by humans as a joke. If you're >> taking it too seriously, that's your problem. [...] > Calling the Bible a joke is used to hurt people, not enlighten them. > Those words show bitter arrogance, not constructive critism as it > ignores how others feel about that book. What benefit to others is > gained by calling someones belief a joke? It is the same benefit as the little boy who pointed out that the Emperor was not wearing any clothes. (In real life, the story was called "The Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got Arrested and Thrown in Prison Together With His Parents for Insulting The Emperor".) > To put the "believers" minds > straight? I think not. I think the unsensitive person who attackes > others beliefs, even if illogical or unrealistic, is after some kind > of self grandizement or to illude themself into thinking "they know > the truth of the universe" and should attack others to prove they do. There is a difference between attacking ideas and attacking people. "The Bible is a joke" attacks the idea. "Insensitive people after self-aggrandisement deluding themselves" attacks the person. We live in a world where religion is privileged, where governments pander to the most sick and twisted, hateful, bigoted beliefs because of religion, where organised conspiracies to support and protect child molesters and sexual predators are nevertheless looked up to as sources of morality. There are some ideas that are simply incompatible with civilization, and the idea that religious beliefs should be beyond criticism is one of them. Forget money, or even the love of money. The idea that one mustn't criticise another person's beliefs is the root of all evil. -- Steven From jeanpierreda at gmail.com Wed Sep 28 21:40:27 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 28 Sep 2011 21:40:27 -0400 Subject: [OT] Benefit and belief [was Re: Suggested coding style] In-Reply-To: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: > Forget money, or even the love of money. The idea that one mustn't > criticise another person's beliefs is the root of all evil. This was a technical discussion, and calling the bible a joke was not necessary at all. It creates a hostile atmosphere. Can't you pick somewhere else to attack Christianity? Devin On Wed, Sep 28, 2011 at 9:14 PM, Steven D'Aprano wrote: > DevPlayer wrote: > >> On Sep 27, 10:25?pm, alex23 wrote: >>> And like the Bible, the Zen was created by humans as a joke. If you're >>> taking it too seriously, that's your problem. > [...] >> Calling the Bible a joke is used to hurt people, not enlighten them. >> Those words show bitter arrogance, not constructive critism as it >> ignores how others feel about that book. What benefit to others is >> gained by calling someones belief a joke? > > It is the same benefit as the little boy who pointed out that the Emperor > was not wearing any clothes. (In real life, the story was called "The > Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got > Arrested and Thrown in Prison Together With His Parents for Insulting The > Emperor".) > > >> To put the "believers" minds >> straight? I think not. I think the unsensitive person who attackes >> others beliefs, even if illogical or unrealistic, is after some kind >> of self grandizement or to illude themself into thinking "they know >> the truth of the universe" and should attack others to prove they do. > > There is a difference between attacking ideas and attacking people. > > "The Bible is a joke" attacks the idea. > > "Insensitive people after self-aggrandisement deluding themselves" attacks > the person. > > We live in a world where religion is privileged, where governments pander to > the most sick and twisted, hateful, bigoted beliefs because of religion, > where organised conspiracies to support and protect child molesters and > sexual predators are nevertheless looked up to as sources of morality. > > There are some ideas that are simply incompatible with civilization, and the > idea that religious beliefs should be beyond criticism is one of them. > Forget money, or even the love of money. The idea that one mustn't > criticise another person's beliefs is the root of all evil. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Sep 28 21:49:25 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Sep 2011 22:49:25 -0300 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: En Wed, 28 Sep 2011 21:10:38 -0300, Nobody escribi?: > On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > >> No, it was a deliberate decision. After a release is in security-fix >> mode only, we don't build Windows or Mac OS X installers for them. > > But you continue to offer the installers for the unfixed version. As well as all the previous ones back to Python 1.x I can think of several alternatives: * Upgrade to Python 2.7, the current stable and maintained release. * Compile Python 2.6.7 yourself. For the 32 bits version, you may use Microsoft Visual C++ 2008 Express Edition (free/gratis); see PCbuild\readme.txt for details. Obtain the required dependencies using Tools\buildbot\external.bat. It compiles cleanly out of the box. * Obtain the compiled binary somewhere else. Considering that 2.6.7 is just a security patch, I'm not sure if running a precompiled binary from untrusted sources is any better than sticking with the official, previous version. I've built the binaries, in case you're interested. * Compare both source trees and look at their differences. Most of them are in Python modules that you can just drop over an existing 2.6.6 install. Only two C modules have changed, and require rebuilding python26.dll: timemodule.c r87648: Issue #8013: Fixed time.asctime segfault when OS's asctime fails unicodedata.c http://bugs.python.org/issue10254 If you think you're not affected by these, just ignore 2.6.7 (or apply only the .py changes) -- Gabriel Genellina From rantingrick at gmail.com Wed Sep 28 21:59:49 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 28 Sep 2011 18:59:49 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <42df7e77-44ab-405e-9c60-8f394e3e5628@d17g2000yqa.googlegroups.com> On Sep 27, 11:25?pm, Steven D'Aprano wrote: > The Python development team is relatively small and chronically busy: too > much to do and not enough time to do it. If that is the case then why do they snub their noses at anyone who wishes to help? What kind of people would chase off good help just to save ego? I imagine the folks at py dev sort of like a dying man in need of a heart transplant; the man informs the doctor that he would happy to get a transplant but not if the heart came from a jew, asian, african, latin, russian, or canuck. From ericsnowcurrently at gmail.com Wed Sep 28 22:01:14 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 28 Sep 2011 20:01:14 -0600 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 28, 2011 at 6:50 PM, Devin Jeanpierre wrote: >> I used to ask the same question, but then I decided that if I wanted each >> data point to get its own tick, I should bite the bullet and write an >> individual test for each. > > Nearly the entire re module test suite is a list of tuples. If it was > instead a bunch of TestCase classes, there'd be a lot more boilerplate > to write. (At a bare minimum, there'd be two times as many lines, and > all the extra lines would be identical...) > > Why is writing boilerplate for a new test a good thing? It discourages > the authorship of tests. Make it as easy as possible by e.g. adding a > new thing to whatever you're iterating over. This is, for example, why > the nose test library has a decorator for generating a test suite from > a generator. +1 > > Devin > > On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano > wrote: >> Tim Chase wrote: >> >>> While I asked this on the Django list as it happened to be with >>> some Django testing code, this might be a more generic Python >>> question so I'll ask here too. >>> >>> When performing unittest tests, I have a number of methods of the >>> form >>> >>> ? ?def test_foo(self): >>> ? ? ?data = ( >>> ? ? ? ?(item1, result1), >>> ? ? ? ?... #bunch of tests for fence-post errors >>> ? ? ? ?) >>> ? ? ?for test, result in data: >>> ? ? ? ?self.assertEqual(process(test), result) >>> >>> When I run my tests, I only get a tick for running one the one >>> test (test_foo), not the len(data) tests that were actually >>> performed. ?Is there a way for unittesting to report the number >>> of passed-assertions rather than the number of test-methods run? >> >> I used to ask the same question, but then I decided that if I wanted each >> data point to get its own tick, I should bite the bullet and write an >> individual test for each. >> >> If you really care, you could subclass unittest.TestCase, and then cause >> each assert* method to count how often it gets called. But really, how much >> detailed info about *passed* tests do you need? >> >> If you are writing loops inside tests, you might find this anecdote useful: >> >> http://mail.python.org/pipermail/python-list/2011-April/1270640.html >> >> >> >> -- >> Steven >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From rantingrick at gmail.com Wed Sep 28 22:11:08 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 28 Sep 2011 19:11:08 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: On Sep 28, 6:26?pm, Tim Johnson wrote: > * DevPlayer [110928 04:31]: > > On Sep 27, 10:25 pm, alex23 wrote: > > > rantingrick wrote: > > > > Since, like the bible > > > > the zen is self contradicting, any argument utilizing the zen can be > > > > defeated utilizing the zen. > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > > taking it too seriously, that's your problem. > > > > > If however you want to learn about the accepted rules for formatting > > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > Contradiction is only seen by narrow perspectve. > > > Calling the Bible a joke is used to hurt people, not enlighten them. > > Those words show bitter arrogance, not constructive critism as it > > ignores how others feel about that book. What benefit to others is > > gained by calling someones belief a joke? > > ?My wife and I are devout christians, but not fundamentalist. We > ?would not take rantingrick too seriously. If _you_ take him > ?seriously, you're just giving him 'street cred'. DevPlayer was not even talking about what i said, he was replying to a statement by Alex23 who said (and i quote) "And like the Bible, the Zen was created by humans as a joke". Maybe you should spend the next fifteen or so minutes catching up to the conversation...(?_?)...of course only *after* you clean that egg from your face. From devplayer at gmail.com Wed Sep 28 22:15:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Wed, 28 Sep 2011 19:15:24 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <088ba6ac-4468-4755-9336-f1ddf1ab2121@k15g2000yqd.googlegroups.com> Oh I was just testing my intellecual-enlightenment-from-ranter- conversation algorithm found in a previous post. I think my OOP model failed as I'm just too tired to finished that pattern test. He had some good points which fit the process I layed out. But the original topic is just so much better: Suggested coding style Options From ben+python at benfinney.id.au Wed Sep 28 22:25:41 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 12:25:41 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <878vp83x0a.fsf@benfinney.id.au> Steven D'Aprano writes: > I used to ask the same question, but then I decided that if I wanted > each data point to get its own tick, I should bite the bullet and > write an individual test for each. Hence my advocating the ?testscenarios? library. Have you tried that? It allows the best of both worlds: within the class, you write a collection of data scenarios, and write one test case for each separate behaviour, and that's all that appears in the code; but the test run shows every test case for every scenario. E.g. with a ParrotTestCase class having three test cases and four scenarios, the test run will run the full combination of all of them and report twelve distinct test cases and the result for each. So the ?bite the bullet? you describe isn't necessary to get what you want. > If you really care, you could subclass unittest.TestCase, and then > cause each assert* method to count how often it gets called. But > really, how much detailed info about *passed* tests do you need? The ?testscenarios? library does subclass the standard library ?unittest? module. But as explained elsewhere, it's not the counting which is the issue. The issue is to ensure (and report) that every test case is actually tested in isolation against every relevant scenario. -- \ ?Human reason is snatching everything to itself, leaving | `\ nothing for faith.? ?Bernard of Clairvaux, 1090?1153 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 22:27:27 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 12:27:27 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <874nzw3wxc.fsf@benfinney.id.au> Roy Smith writes: > In article <87k48szqo1.fsf at benfinney.id.au>, > Ben Finney wrote: > > > Worse, if one of the scenarios causes the test to fail, the loop will > > end and you won't get the results for the remaining scenarios. > > Which, depending on what you're doing, may or may not be important. In > many cases, there's only two states of interest: > > 1) All tests pass > > 2) Anything else For the purpose of debugging, it's always useful to more specifically narrow down the factors leading to failure. -- \ ?A lie can be told in a few words. Debunking that lie can take | `\ pages. That is why my book? is five hundred pages long.? ?Chris | _o__) Rodda, 2011-05-05 | Ben Finney From wuwei23 at gmail.com Wed Sep 28 22:41:51 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 28 Sep 2011 19:41:51 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <22c6d97a-a0f3-43e8-ac23-16787db5da1d@g33g2000yqc.googlegroups.com> On Sep 28, 10:12?pm, DevPlayer wrote: > Calling the Bible a joke is used to hurt people, not enlighten them. Y'know, I wouldn't even bother responding to this if Xianists were as open, forgiving and accepting as their messiah told them to be. It was a *flippant remark*. If you want to establish intent, aggression and religio-politico-philosophy from every throwaway remark made on the internet, you're not really going to have much time for Python. My belief system isn't your's. Hell, my belief system doesn't even require that I have *any respect whatsoever* for your's. If it's okay for Xianists to "suffer not a witch to live", then I'm going to assert my making light jokes about those whose world view is in direct opposition to mine isn't even comparable to that mentality. from attitude import humour (Since we're already fully derailed here, I've always preferred Borges' suggestion that it was actually Judas who carried the full weight of man's sins, given that his betrayal of Christ and inevitable condemnation to hell was a necessity. Then again, I'm able to safely view this as *allegory* and am genuinely interested in the opinions of modern minds over something first begun by nomads millenia ago...) From roy at panix.com Wed Sep 28 22:49:58 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 22:49:58 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> <874nzw3wxc.fsf@benfinney.id.au> Message-ID: In article <874nzw3wxc.fsf at benfinney.id.au>, Ben Finney wrote: > Roy Smith writes: > > > In article <87k48szqo1.fsf at benfinney.id.au>, > > Ben Finney wrote: > > > > > Worse, if one of the scenarios causes the test to fail, the loop will > > > end and you won't get the results for the remaining scenarios. > > > > Which, depending on what you're doing, may or may not be important. In > > many cases, there's only two states of interest: > > > > 1) All tests pass > > > > 2) Anything else > > For the purpose of debugging, it's always useful to more specifically > narrow down the factors leading to failure. Well, sure, but "need to debug" is just a consequence of being in state 2. If a test fails and I can't figure out why, I can always go back and add additional code to the test case to extract additional information. From ben+python at benfinney.id.au Wed Sep 28 23:05:36 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 13:05:36 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87zkho2glb.fsf@benfinney.id.au> Devin Jeanpierre writes: > > Forget money, or even the love of money. The idea that one mustn't > > criticise another person's beliefs is the root of all evil. > > This was a technical discussion, and calling the bible a joke was not > necessary at all. It creates a hostile atmosphere. I disagree. It was not an attack on any person nor group of people. If we are to be required to avoid jokes not directed at people, then *that* is an atmosphere hostile to open friendly discussion. > Can't you pick somewhere else to attack Christianity? The person who wrote the ?bible is a joke? intended it as a flippant remark. Countless other flippant remarks pass through here all the time, making jokes at the expense of some idea or other. Christianity will not be an exception to that. If you find someone attacking people, I'll join you in ostracising the attacker. But no, don't attempt to silence jokes that attack an idea. Off-topic? If we start discussing the content of the ideas being attacked, yeah, I'd say religion is pretty off-topic. But the topic of keeping this forum safe for technical discussion entails that it must be safe for *any* idea to be the butt of a joke, be it a religious text or the Zen of Python, and that is very much on-topic. -- \ ?We demand rigidly defined areas of doubt and uncertainty!? | `\ ?Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | _o__) Adams | Ben Finney From python.list at tim.thechases.com Wed Sep 28 23:13:57 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Sep 2011 22:13:57 -0500 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <4E83E275.6060209@tim.thechases.com> On 09/28/11 19:52, Roy Smith wrote: > In many cases, there's only two states of interest: > > 1) All tests pass > > 2) Anything else Whether for better or worse, at some places (such as a previous employer) the number (and accretion) of test-points is a marketing bullet-point for upgrades & new releases. -tkc From roy at panix.com Wed Sep 28 23:20:27 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 23:20:27 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: In article , Tim Chase wrote: > On 09/28/11 19:52, Roy Smith wrote: > > In many cases, there's only two states of interest: > > > > 1) All tests pass > > > > 2) Anything else > > Whether for better or worse, at some places (such as a previous > employer) the number (and accretion) of test-points is a > marketing bullet-point for upgrades & new releases. Never attribute to malice that which is adequately explained by the stupidity of the marketing department. From rosuav at gmail.com Thu Sep 29 00:27:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 29 Sep 2011 14:27:31 +1000 Subject: A Trivial Question In-Reply-To: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: On Thu, Sep 29, 2011 at 7:53 AM, Tayfun Kayhan wrote: > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. Python doesn't have "class declarations" in the way that some other languages do. The 'class' statement is an executable statement - it builds a class object and binds it to the name Foo, just like any other assignment. The 'def' command builds a function object in a similar fashion. So in your trial() function, you're defining a class and binding it to the local name Foo; and then doing nothing with it. It's perfectly legal, and as Chris Rebert suggests, you can make it useful by instantiating Foo() objects inside trial(). ChrisA From gaurav.gangalwar at gmail.com Thu Sep 29 01:17:46 2011 From: gaurav.gangalwar at gmail.com (gaurav gangalwar) Date: Thu, 29 Sep 2011 10:47:46 +0530 Subject: UnicodeDecodeError Message-ID: I am getting this error while some testing on Python2.6, File "/usr/lib64/python2.6/httplib.py", line 774, in _send_output #msg = "\r\n".join(self._buffer) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 14: ordinal not in range(128) I tried the change suggested on this link http://web.archiveorange.com/archive/v/PJbOg9pxJoUpQA9AHp3X, its working fine after that. There seems to be some problem in httplib with unicode handling. I am running it on centos5. I am still not sure why its happening and what will be ideal solution for this? Thanks, Gaurav -------------- next part -------------- An HTML attachment was scrubbed... URL: From namenobodywants at gmail.com Thu Sep 29 01:47:49 2011 From: namenobodywants at gmail.com (Sean McIlroy) Date: Wed, 28 Sep 2011 22:47:49 -0700 (PDT) Subject: change text of a Tkinter Button by clicking it Message-ID: hello (how) can you change the text of a Tkinter Button by clicking it? something like def click(index): return lambda: buttons[index].text = 'hello' buttons = [Button(root,command=click(index)) for index in range(numbuttons)] only with an attribute that Buttons actually have. sorry to have to ask such a see-spot-run question. thanks if you can help. peace stm From namenobodywants at gmail.com Thu Sep 29 02:15:20 2011 From: namenobodywants at gmail.com (Sean McIlroy) Date: Wed, 28 Sep 2011 23:15:20 -0700 (PDT) Subject: change text of a Tkinter Button by clicking it References: Message-ID: never mind. i found it. From questions.anon at gmail.com Thu Sep 29 02:16:13 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 29 Sep 2011 16:16:13 +1000 Subject: memory error In-Reply-To: References: Message-ID: Hello All, I am still having trouble with memory errors when I try to process many netcdf files. Originally I would get the memory error as mentioned in the previous post but when I added gc.collect() after each for loop I receive the error: GEOS_ERROR: bad allocation with no additional information! The error use to occur at the point when a new netcdf file was to be opened and plotted but with the things I have 'fixed' thanks to suggestions from this list it seems to happen while processing the second file. I am just trying to plot 3hourly data for each file and each file contains hourly data for a month and I am trying to do this for many months. It seems like I cannot close down the last file properly so the computer has a clean memory to start the next one. Any feedback will be greatly appreciated. My latest version of the code: ###################### from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from numpy import ma as MA from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os shapefile1="E:/DSE_BushfireClimatologyProject/griddeddatasamples/test_GIS/DSE_REGIONS" OutputFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/OutputsforValidation" def plotrawdata(variable): if variable=='TSFC': ncvariablename='T_SFC' MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/" ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] Title='Surface Temperature' cmap=plt.cm.jet elif variable=='RHSFC': ncvariablename='RH_SFC' MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/RH_SFC/" ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Title='Surface RH' cmap=plt.cm.jet_r fileforlatlon=Dataset("E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/TSFC_1974_01/IDZ00026_VIC_ADFD_T_SFC.nc", 'r+', 'NETCDF4') LAT=fileforlatlon.variables['latitude'][:] LON=fileforlatlon.variables['longitude'][:] startperiod=raw_input("Start slice (e.g. 1 ): ") endperiod=raw_input("End slice (e.g. 2): ") skipperiod=raw_input("skip slice (e.g. 1): ") if startperiod == "": startperiod = None else: startperiod = int(startperiod) if endperiod == "": endperiod = None else: endperiod = int(endperiod) if skipperiod == "": skipperiod = None else: skipperiod= int(skipperiod) for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') #global TSFC variable=ncfile.variables[ncvariablename][startperiod:endperiod:skipperiod] TIME=ncfile.variables['time'][startperiod:endperiod:skipperiod] fillvalue=ncfile.variables[ncvariablename]._FillValue ncfile.close() for variable, TIME in zip((variable[:]),(TIME[:])): #for variable, TIME in zip((variable[sliceperiod]),(TIME[sliceperiod])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title(Title+' %s UTC'%ncfiletime) CS = map.contourf(x,y,variable, ticks, cmap=cmap) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(OutputFolder, ncvariablename+date_string+'UTC.png'))) #plt.show() plt.close() ###################### On Wed, Sep 14, 2011 at 4:08 PM, questions anon wrote: > Hello All, > I keep coming across a memory error when processing many netcdf files. I > assume it has something to do with how I loop things and maybe need to close > things off properly. > In the code below I am looping through a bunch of netcdf files (each file > is hourly data for one month) and within each netcdf file I am outputting a > *png file every three hours. > This works for one netcdf file but when it begins to process the next > netcdf file I receive this memory error: > > *Traceback (most recent call last): > File > "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", > line 44, in > TSFC=ncfile.variables['T_SFC'][:] > File "netCDF4.pyx", line 2473, in netCDF4.Variable.__getitem__ > (netCDF4.c:23094) > MemoryError* > > To reduce processing requirements I have tried making the LAT and LON to > only use [0] but I also receive an error: > > *Traceback (most recent call last): > File > "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", > line 75, in > x,y=map(*N.meshgrid(LON,LAT)) > File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line > 3256, in meshgrid > numRows, numCols = len(y), len(x) # yes, reversed > TypeError: len() of unsized object* > > finally I have added gc.collect() in a couple of places but that doesn't > seem to do anything to help. > I am using :*Python 2.7.2 |EPD 7.1-2 (32-bit)| (default, Jul 3 2011, > 15:13:59) [MSC v.1500 32 bit (Intel)] on win32* > Any feedback will be greatly appreciated! > > > from netCDF4 import Dataset > import numpy > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as MA > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > import gc > > print "start processing...." > > inputpath=r'E:/GriddedData/Input/' > outputpath=r'E:/GriddedData/Validation/' > shapefile1="E:/test_GIS/DSE_REGIONS" > for (path, dirs, files) in os.walk(inputpath): > for dir in dirs: > print dir > sourcepath=os.path.join(path,dir) > relativepath=os.path.relpath(sourcepath,inputpath) > newdir=os.path.join(outputpath,relativepath) > if not os.path.exists(newdir): > os.makedirs(newdir) > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", ncfile > ncfile=os.path.join(sourcepath,ncfile) > #print ncfile > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > TSFC=ncfile.variables['T_SFC'][:,:,:] > TIME=ncfile.variables['time'][:] > LAT=ncfile.variables['latitude'][:] > LON=ncfile.variables['longitude'][:] > fillvalue=ncfile.variables['T_SFC']._FillValue > TSFC=MA.masked_values(TSFC, fillvalue) > ncfile.close() > gc.collect() > print "garbage collected" > > > for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): > print TSFC, TIME > #convert time from numbers to date and prepare it to have no > symbols for saving to filename > cdftime=utime('seconds since 1970-01-01 00:00:00') > ncfiletime=cdftime.num2date(TIME) > print ncfiletime > timestr=str(ncfiletime) > d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') > date_string = d.strftime('%Y%m%d_%H%M') > > #Set up basemap using mercator projection > http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html > map = > Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > > # compute map projection coordinates for lat/lon grid. > x,y=map(*N.meshgrid(LON,LAT)) > map.drawcoastlines(linewidth=0.5) > map.readshapefile(shapefile1, 'DSE_REGIONS') > map.drawstates() > > plt.title('Surface temperature at %s UTC'%ncfiletime) > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, b, 0.025, h], ) > cbar=plt.colorbar(CS, cax=cax, drawedges=True) > > #save map as *.png and plot netcdf file > > plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) > plt.close() > gc.collect() > print "garbage collected again" > print "end of processing" > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Thu Sep 29 02:21:21 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 28 Sep 2011 23:21:21 -0700 Subject: syntactic sugar for def? In-Reply-To: References: <4E8390F1.9060207@stoneleaf.us> Message-ID: <20110929062121.GA10216@Smoke> On Wed, Sep 28, 2011 at 07:01:11PM -0400, Terry Reedy wrote: > On 9/28/2011 5:26 PM, Ethan Furman wrote: > > >I don't remember if 'def' is sugar for something besides lambda. > > That is a bit backwards. > lambda x: expr(x) > is syntactic sugar for > def (x): return expr(x) > del > ;-) > lambda is less sugar and more of just a def as an expression. From anikom15 at gmail.com Thu Sep 29 02:24:13 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 28 Sep 2011 23:24:13 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <20110929062413.GB10216@Smoke> On Wed, Sep 28, 2011 at 07:11:08PM -0700, rantingrick wrote: > On Sep 28, 6:26?pm, Tim Johnson wrote: > > * DevPlayer [110928 04:31]: > > > On Sep 27, 10:25 pm, alex23 wrote: > > > > rantingrick wrote: > > > > > Since, like the bible > > > > > the zen is self contradicting, any argument utilizing the zen can be > > > > > defeated utilizing the zen. > > > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > > > taking it too seriously, that's your problem. > > > > > > > If however you want to learn about the accepted rules for formatting > > > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > > > Contradiction is only seen by narrow perspectve. > > > > > Calling the Bible a joke is used to hurt people, not enlighten them. > > > Those words show bitter arrogance, not constructive critism as it > > > ignores how others feel about that book. What benefit to others is > > > gained by calling someones belief a joke? > > > > ?My wife and I are devout christians, but not fundamentalist. We > > ?would not take rantingrick too seriously. If _you_ take him > > ?seriously, you're just giving him 'street cred'. > > DevPlayer was not even talking about what i said, he was replying to a > statement by Alex23 who said (and i quote) "And like the Bible, the > Zen was created by humans as a joke". Maybe you should spend the next > fifteen or so minutes catching up to the conversation...(?_?)...of > course only *after* you clean that egg from your face Perhaps you should spend a little less time on the mailing list and a little more time in church. From __peter__ at web.de Thu Sep 29 02:27:00 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Sep 2011 08:27 +0200 Subject: change text of a Tkinter Button by clicking it References: Message-ID: Sean McIlroy wrote: > hello > > (how) can you change the text of a Tkinter Button by clicking it? > something like > > def click(index): return lambda: buttons[index].text = 'hello' > buttons = [Button(root,command=click(index)) for index in > range(numbuttons)] > > only with an attribute that Buttons actually have. sorry to have to > ask such a see-spot-run question. thanks if you can help. See http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html You can set the text of a Button widget with button["text"] = ... or button.configure(text=...) From ian.g.kelly at gmail.com Thu Sep 29 02:57:21 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 00:57:21 -0600 Subject: Suggested coding style In-Reply-To: <20110929062413.GB10216@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <20110929062413.GB10216@Smoke> Message-ID: On Thu, Sep 29, 2011 at 12:24 AM, Westley Mart?nez wrote: > Perhaps you should spend a little less time on the mailing list and a > little more time in church. You must not like churchgoers very much if you want to inflict rantingrick on them... From ian.g.kelly at gmail.com Thu Sep 29 03:08:13 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 01:08:13 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <20110929062413.GB10216@Smoke> Message-ID: On Thu, Sep 29, 2011 at 12:57 AM, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 12:24 AM, Westley Mart?nez wrote: >> Perhaps you should spend a little less time on the mailing list and a >> little more time in church. > > You must not like churchgoers very much if you want to inflict > rantingrick on them... Although come to think of it, I bet he could deliver a pretty mean sermon. ;-) From jitu.icfai at gmail.com Thu Sep 29 03:41:29 2011 From: jitu.icfai at gmail.com (jitendra gupta) Date: Thu, 29 Sep 2011 13:11:29 +0530 Subject: A trivial question In-Reply-To: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> References: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> Message-ID: HI The class Foo you have defined is local NameSpace for trial functioon, for details http://docs.python.org/tutorial/classes.html def trial(): class Foo(object): def __init__(self): print("Hello, world!") lacalClass = Foo() >>>trial "Hello, world!" Thanks Jitendra On Thu, Sep 29, 2011 at 3:19 AM, Tayfun Kayhan wrote: > I accidentally wrote such a code (below) while trying to write sth else for > my application but i am now just wondering much how to run the class Foo, if > it is possible. Is not it weird that Python does not give any error when I > run it ? Sorry for that it's pretty unimportant question according to the > other questions being asked here :D > > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 29 05:21:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Sep 2011 09:21:16 GMT Subject: Python without a tty Message-ID: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> I have a Python script which I would like to test without a tty attached to the process. I could run it as a cron job, but is there an easier way? I am running Linux. -- Steven From redbullhats123 at gmail.com Thu Sep 29 05:36:29 2011 From: redbullhats123 at gmail.com (red bull hats red bull hats) Date: Thu, 29 Sep 2011 02:36:29 -0700 (PDT) Subject: red bull hats, monster energy hats, red bull t shirts, monster energy t shirts, snapback hats on www.theworldhats.com Message-ID: www.theworldhats.com are promoting the products: red bull hats:http://www.theworldhats.com/category-130-b0-Red-Bull- Hats.html snapback hats: http://www.theworldhats.com/category-230-b0-Snapback-Hats.html monster energy hats: http://www.theworldhats.com/category-128-b0-Monster-Energy-Hats.html red bull t shirts:http://www.theworldhats.com/category-227-b0-Red-Bull- T-shirts.html monster energy t shirts:http://www.theworldhats.com/category-203-b0- Monster-Energy-T-shirts.html website: www.theworldhats.com From t at jollybox.de Thu Sep 29 05:45:40 2011 From: t at jollybox.de (Thomas Jollans) Date: Thu, 29 Sep 2011 11:45:40 +0200 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E843E44.7040008@jollybox.de> On 29/09/11 11:21, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > ./program /dev/null 2>&1 From alain at dpt-info.u-strasbg.fr Thu Sep 29 05:53:12 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 29 Sep 2011 11:53:12 +0200 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Steven D'Aprano writes: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. Isn't os.setsid() what you're looking for? It makes the calling process have no controlling terminal. There's also a user command called setsid that should have the same effect. -- Alain. From passiday at gmail.com Thu Sep 29 06:37:39 2011 From: passiday at gmail.com (Passiday) Date: Thu, 29 Sep 2011 03:37:39 -0700 (PDT) Subject: Suggested coding style In-Reply-To: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> Message-ID: <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Oh, my. Who could expect this topic would iterate to some whining about religion (please don't respond on this remark of mine). Here's a summary of what I take from this longwinded thread: Read the Zen of Pthon for some fun: http://www.python.org/dev/peps/pep-0020 Read the PEP-8 for some good guidelines: http://www.python.org/dev/peps/pep-0008 My topic was "Suggested coding style" because I hoped there is some common understanding which of the ancient methods/functions are so not where they should be that the use of them should be depreciated. I can fully understand that when the language evolves, it might implement some ugly methods. Perhaps it was some quick itching need to format some numbers that drove some antique Python programmer so mad that he decided this belongs to the string class, instead of some number/date/string formatting class that attempts to build on existing well established standards. And so, the str.zfill() was born. But I'd expect that there exists some leadership who are brave enough to admit some bad decisions and lead the people by announcing that using certain methods is "bad style". No need to take them out of the implementation, that might unnecessary break some code in obscure places. However, guiding programmers for better coding practice and avoid ugly bloating of nice scripting language should be considered a holy (please don't rant on use of this word) mission. Passiday From steve+comp.lang.python at pearwood.info Thu Sep 29 06:37:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 20:37:53 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > Perhaps you should spend a little less time on the mailing list and a > little more time in church. Is that meant as punishment for Rick or for the churchgoers? -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 29 06:52:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 20:52:22 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Alain Ketterlin wrote: > Steven D'Aprano writes: > >> I have a Python script which I would like to test without a tty attached >> to the process. I could run it as a cron job, but is there an easier way? >> >> I am running Linux. > > Isn't os.setsid() what you're looking for? It makes the calling process > have no controlling terminal. There's also a user command called setsid > that should have the same effect. It doesn't appear so to me. [steve at sylar ~]$ tty /dev/pts/16 [steve at sylar ~]$ setsid tty /dev/pts/16 [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" True [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" True If I run the same Python command (without the setsid) as a cron job, I get False emailed to me. That's the effect I'm looking for. -- Steven From hansmu at xs4all.nl Thu Sep 29 07:39:25 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 29 Sep 2011 13:39:25 +0200 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8458ed$0$2486$e4fe514c@news2.news.xs4all.nl> On 29/09/11 11:21:16, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? There is module on Pypi called python-daemon; it implements PEP-3143. This module detaches the process from the tty and resets a number of process attributes that are normally inherited. You could start by reading the PEP to determine which of its features are relevant to your situation. It would provide you with a complete list of aspects you'd need to think about. If a third of what the module does is relevant to your situation and the other two thirds do not hurt, then using the module is likely to be less work than rolling your own. Hope this helps, -- HansM From alain at dpt-info.u-strasbg.fr Thu Sep 29 07:50:18 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 29 Sep 2011 13:50:18 +0200 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <877h4rwosl.fsf@dpt-info.u-strasbg.fr> Steven D'Aprano writes: > Alain Ketterlin wrote: >>> I have a Python script which I would like to test without a tty attached >>> to the process. I could run it as a cron job, but is there an easier way? >> Isn't os.setsid() what you're looking for?[...] > It doesn't appear so to me. [...] > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. If that's what you mean by "without a tty attached", simply redirecting standard channels should work, no? -- Alain. From hansmu at xs4all.nl Thu Sep 29 07:50:29 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 29 Sep 2011 13:50:29 +0200 Subject: Python without a tty In-Reply-To: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e845b85$0$2486$e4fe514c@news2.news.xs4all.nl> On 29/09/11 12:52:22, Steven D'Aprano wrote: > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. In that case, all you need to do is redirect stdout: $ python -c "import sys, os > print os.isatty(sys.stdout.fileno())" >/tmp/xxx $ cat /tmp/xxx False You'll probably want to redirect to /dev/null and maybe you want to redirect stdin and stderr as well. -- HansM From rantingrick at gmail.com Thu Sep 29 08:23:30 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 05:23:30 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 5:37?am, Passiday wrote: > Here's a summary of what I take from this longwinded thread: > Read the Zen of Pthon for some fun:http://www.python.org/dev/peps/pep-0020 > Read the PEP-8 for some good guidelines:http://www.python.org/dev/peps/pep-0008 That's the point of all this, yes. You see, around here, once the point is made there is an unwritten rule that the thread must then descend into chaos. However, it seems you "may" have brought this train wreck back to reality below... whether the trolls will allow that happen remains to be seen...? > My topic was "Suggested coding style" because I hoped > there is some common understanding which of the ancient > methods/functions are so not where they should be that the > use of them should be depreciated. I agree. Whilst zfill is useful, and probably should be a part of the stlib somewhere, the string module is no place for it. The only way zfill WOULD work as a string method is if it were changed to accept a user defined fill char. Even then i don't like it as a string method; too specific! A specific method for padding a string with ONLY zeros is ludicrous and exposes the narrow mindedness of the creator. The only thing worse than "zfill" as a string method is making zfill into built-in function! The ONLY proper place for zfill is as an option in the str.format() method. py> "{0:zf10}".format(1234) -> "00000000001234" When are they going to see that I am the best API designer this community has ever had the privilege to work with! GvR should be texting me every night in hopes that some of my API genius will rub off on him. > I can fully understand > that when the language evolves, it might implement some > ugly methods. Perhaps it was some quick itching need to > format some numbers that drove some antique Python > programmer so mad that he decided this belongs to the > string class, instead of some number/date/string > formatting class that attempts to build on existing well > established standards. And so, the str.zfill() was born. zfills foster home placement is akin to the missing Path object we still don't have. Both are a result of poor planning. Now zfill is like some red headed step child that nobody wants, but nobody has the balls to return the abortion to it's rightful place. > But I'd expect that there exists some leadership who are > brave enough to admit some bad decisions and lead the > people by announcing that using certain methods is "bad > style". Ha! I would not hold my breath waiting for "leadership" to admit wrong doings; these people think they are beyond reproach. > No need to take them out of the implementation, > that might unnecessary break some code in obscure places. What is so bad about breaking code in obscure places? We changed print to a function which broke just about every piece of code every written in this language. (BTW, print should ALWAYS have been a function!) What is so bad then about breaking some very obscure code? We could always have a lengthy deprecation period. > However, guiding programmers for better coding practice > and avoid ugly bloating of nice scripting language should > be considered a holy (please don't rant on use of this > word) mission. I agree. I think you'll agree also with me in the fact that Mr Van Rossum has created the cleanest, most simplistically elegant, and no nonsense language this world has ever seen. However. He is not immune to the wicked influence of a few high ranking people within this community who have "hidden agendas" and want to mutate Python into a clone of some other nasty languages. I believe GvR had a "mid-dev-crisis" and realized the err of his ways. He attempted to turn back the clock with Python 3000, HOWEVER he did not go far enough! Much more cleanup is in order to get this language back on track to what it should be, and COULD be! From ben+python at benfinney.id.au Thu Sep 29 08:32:37 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 22:32:37 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87vcsb34wq.fsf@benfinney.id.au> Steven D'Aprano writes: > I have a Python script which I would like to test without a tty > attached to the process. I could run it as a cron job, but is there an > easier way? > > I am running Linux. You could crib from the ?python-daemon? library implementation . Part of its job involves detaching the current program from the terminal. Or maybe you could simply invoke the library for its main purpose, if that would be sufficient to do what you need. -- \ ?Sane people have an appropriate perspective on the relative | `\ importance of foodstuffs and human beings. Crazy people can't | _o__) tell the difference.? ?Paul Z. Myers, 2010-04-18 | Ben Finney From rantingrick at gmail.com Thu Sep 29 09:21:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 06:21:36 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <1c731ba2-7104-44bb-a5d4-5798ce56bfc8@z12g2000yqz.googlegroups.com> On Sep 29, 7:23?am, rantingrick wrote: > A specific method for padding a string with ONLY zeros is ludicrous > and exposes the narrow mindedness of the creator. The only thing worse > than "zfill" as a string method is making zfill into built-in > function! The ONLY proper place for zfill is as an option in the > str.format() method. > > py> "{0:zf10}".format(1234) -> "00000000001234" If something like "zfill" where to be included as a string method, it should be more general like this: class String: def pad(self, char, count, side='left') => str py> "".pad(0, 10) '00000000001234' However the same can be accomplished with: py> '{0}1234'.format("0"*10) '00000000001234' py> "0"*10+'1234' '00000000001234' Seems like pollution either way you go. Best to just let the programmer handle it. Python IS NOT a 100% OOP language (and for good reason!) so we don't need methods to scratch every little itch -- and this itch seems to have originated in the "nether regions" instead of the "Netherlands". From roy at panix.com Thu Sep 29 09:28:35 2011 From: roy at panix.com (Roy Smith) Date: Thu, 29 Sep 2011 09:28:35 -0400 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e84388c$0$29965$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? I'm not sure what you mean by "without a tty attached to the process". If you mean no file descriptors attached to your control terminal, then some variation on foo.py < /dev/null > /dev/null (as others has suggested) might be good enough. Or, are you talking about control terminals in the process control sense? In that case, you might want to look at the "at" or "batch" commands, which do very much the same thing as cron, but without the overhead of having to edit the cron file to get things going. From python at mrabarnett.plus.com Thu Sep 29 10:02:55 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 29 Sep 2011 15:02:55 +0100 Subject: [OT] Benefit and belief In-Reply-To: <87zkho2glb.fsf@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <4E847A8F.3070401@mrabarnett.plus.com> On 29/09/2011 04:05, Ben Finney wrote: > Devin Jeanpierre writes: > >>> Forget money, or even the love of money. The idea that one mustn't >>> criticise another person's beliefs is the root of all evil. >> >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. > >> Can't you pick somewhere else to attack Christianity? > > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. > > If you find someone attacking people, I'll join you in ostracising the > attacker. But no, don't attempt to silence jokes that attack an idea. > > Off-topic? If we start discussing the content of the ideas being > attacked, yeah, I'd say religion is pretty off-topic. > > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. > Even if it offends Python worshippers? http://www.youtube.com/watch?v=asUyK6JWt9U From martin.hellwig at gmail.com Thu Sep 29 10:25:40 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 29 Sep 2011 15:25:40 +0100 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 29/09/2011 10:21, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > > > Well you could double fork and drop the parent, that would lose the tty which is the same effect what you get when you want a daemon. -- mph From brandtrade08 at 126.com Thu Sep 29 10:26:15 2011 From: brandtrade08 at 126.com (jerser-2009) Date: Thu, 29 Sep 2011 07:26:15 -0700 (PDT) Subject: Nike Air Max LeBron VIII Message-ID: <81a0b983-ea36-45ff-b482-450d07eed5ed@g23g2000vbz.googlegroups.com> Published late last year for the first time Nike Air Max LeBron VIII that caused a large response, follow-up and then released LeBron VIII P2 and LeBron 8PS versions, LeBron is so loyal fans surprises. Back to {1}{/1}Nike for the first time this exposure will open the second half of LeBron 9 flagship shoe figure. Mystery photo from the body of the shoe can be seen a lot of reference material of carbon fiber, and also impressively hidden Hyperfuse material which is easy to understand Nike LeBron on the court to strong demand torque and light weighthttp://www.cheap-nbabasketballshoes.com/ under the foot pains. Wei is currently not yet fully revealed Nike LeBron 9 picture, ladies shoes andgentlemens, friends, fans, please wait.it will come update in http://www.cheap-nbabasketballshoes.com/ From brian.curtin at gmail.com Thu Sep 29 10:27:43 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Thu, 29 Sep 2011 09:27:43 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 28, 2011 at 19:10, Nobody wrote: > On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > > > No, it was a deliberate decision. After a release is in security-fix > > mode only, we don't build Windows or Mac OS X installers for them. > > But you continue to offer the installers for the unfixed version. No one would use Python if we literally forced everyone to upgrade based on our schedule by removing any trace of previous installers. Also, "unfixed" is relative. You're only vulnerable if you're using urllib to request resources which may end up being 302 redirected. I personally don't need that fix, so 2.6.6 would be alright with me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcloete at gmail.com Thu Sep 29 10:45:53 2011 From: bcloete at gmail.com (Bradley Cloete) Date: Thu, 29 Sep 2011 16:45:53 +0200 Subject: Python without a tty In-Reply-To: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: > It doesn't appear so to me. > > [steve at sylar ~]$ tty > /dev/pts/16 > [steve at sylar ~]$ setsid tty > /dev/pts/16 > > [steve at sylar ~]$ python -c "import sys,os; print > os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print > os.isatty(sys.stdout.fileno())" > True > > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. > > Maybe nohup is what you looking for? >From the info pages... "`nohup' runs the given COMMAND with hangup signals ignored, so that the command can continue running in the background after you log out. Synopsis: nohup COMMAND [ARG]... If standard output is a terminal, it is redirected so that it is appended to the file `nohup.out'; if that cannot be written to, it is appended to the file `$HOME/nohup.out'. If that cannot be written to, the command is not run. If standard output is not a terminal, then the standard output of COMMAND will be the same as that of `nohup'. " Regards Bradley -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhagurgaon2011 at gmail.com Thu Sep 29 12:11:41 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 09:11:41 -0700 (PDT) Subject: Question on Manipulating List and on Python Message-ID: Dear Group, I have two questions one on list manipulation and other on Python. (i) I have a file of lists. Now, the first digit starts with a number or index, like, [001, "Obama", "USA", "President"] [002 "Major", "UK", "PM"] [003 "Singh", "INDIA", "PM"] Initially, I am reading the file and taking as for line in file: line_word=line.split print line_word I am getting the above result. But, my problem is if I read the array position 0, which is a number then it should give me reciprocal words like if word1=line_word[0] if word1==001: I should get line_word[1], line_word[2] reciprocating the value. Predefining it solves the problem, but I want to capture and do as it iterates. If any one can help? (ii) My second question is posted by one of my colleagues, what makes Python so fast? Regards, Subhabrata Banerjee. From gordon at panix.com Thu Sep 29 12:27:49 2011 From: gordon at panix.com (John Gordon) Date: Thu, 29 Sep 2011 16:27:49 +0000 (UTC) Subject: Question on Manipulating List and on Python References: Message-ID: In Subhabrata Banerjee writes: > (i) I have a file of lists. Now, the first digit starts with a number > or index, like, > [001, "Obama", "USA", "President"] > [002 "Major", "UK", "PM"] > [003 "Singh", "INDIA", "PM"] > Initially, I am reading the file and taking as > for line in file: > line_word=line.split > print line_word This isn't your actual code. Please show us your real code, along with a sample of your input file. > (ii) My second question is posted by one of my colleagues, what makes > Python so fast? Fast compared to what? Why does your colleague believe it should be slower? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From dwblas at gmail.com Thu Sep 29 12:34:00 2011 From: dwblas at gmail.com (David) Date: Thu, 29 Sep 2011 09:34:00 -0700 (PDT) Subject: Question on Manipulating List and on Python References: Message-ID: <12c2b6e4-5fa4-44ed-83f4-2a969ae4076b@8g2000yqm.googlegroups.com> > word1=line_word[0] > if word1==001: You are comparing a string and an integer assuming you are reading a text file. integers word1=int(line_word[0]) if word1=1: strings word1=line_word[0] if word1=="001:" From anikom15 at gmail.com Thu Sep 29 12:34:25 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 09:34:25 -0700 Subject: Suggested coding style In-Reply-To: <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110929163425.GA10980@Smoke> On Thu, Sep 29, 2011 at 08:37:53PM +1000, Steven D'Aprano wrote: > Westley Mart?nez wrote: > > > Perhaps you should spend a little less time on the mailing list and a > > little more time in church. > > Is that meant as punishment for Rick or for the churchgoers? > > Hopefully neither, probably both. From subhagurgaon2011 at gmail.com Thu Sep 29 12:36:29 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 09:36:29 -0700 (PDT) Subject: Question on Manipulating List and on Python References: Message-ID: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> On Sep 29, 9:27?pm, John Gordon wrote: > In Subhabrata Banerjee writes: > > > (i) I have a file of lists. Now, the first digit starts with a number > > or index, like, > > [001, "Obama", "USA", "President"] > > [002 ?"Major", "UK", "PM"] > > [003 ?"Singh", "INDIA", "PM"] > > Initially, I am reading the file and taking as > > for line in file: > > ? ? line_word=line.split > > ? ? print line_word > > This isn't your actual code. ?Please show us your real code, along with > a sample of your input file. > > > (ii) My second question is posted by one of my colleagues, what makes > > Python so fast? > > Fast compared to what? ?Why does your colleague believe it should be > slower? > > -- > John Gordon ? ? ? ? ? ? ? ? ? A is for Amy, who fell down the stairs > gor... at panix.com ? ? ? ? ? ? ?B is for Basil, assaulted by bears > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -- Edward Gorey, "The Gashlycrumb Tinies" Hi John, The actual code is till now is: def name_debugger(n): open_file=open("/python27/name1.txt") for line in open_file: line_word=line.split() #print line_word word1=line_word[0] print word1 And Python seems faster than C++/Java. It is indeed. I also experience it. Regards, Subhabrata Banerjee. From clp2 at rebertia.com Thu Sep 29 12:37:28 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 09:37:28 -0700 Subject: Question on Manipulating List and on Python In-Reply-To: References: Message-ID: On Thu, Sep 29, 2011 at 9:11 AM, Subhabrata Banerjee wrote: > Dear Group, > > I have two questions one on list manipulation and other on Python. > > (i) I have a file of lists. Now, the first digit starts with a number > or index, like, > > [001, "Obama", "USA", "President"] > [002 ?"Major", "UK", "PM"] > [003 ?"Singh", "INDIA", "PM"] > > Initially, I am reading the file and taking as > for line in file: > ? ?line_word=line.split > ? ?print line_word > > I am getting the above result. But, my problem is if I read the array > position 0, which is a number then it should give me reciprocal words > like > if > word1=line_word[0] > if word1==001: > ? ?I should get line_word[1], line_word[2] reciprocating the value. > > Predefining it solves the problem, but I want to capture and do as it > iterates. If any one can help? I'm not really clear what you mean by "reciprocal", so this is just a guess: Perhaps you want list slicing? >>> line_word = ["001", "Obama", "USA", "President"] >>> print(line_word[1:]) ['Obama', 'USA', 'President'] >>> Details: http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation > (ii) My second question is posted by one of my colleagues, what makes > Python so fast? CPython is actually relatively slow compared to the primary implementations of other languages since Python highly dynamic, and interpreted rather than compiled to machine code (normally). There are currently some promising efforts (like PyPy) to produce a faster implementation however. Cheers, Chris -- http://rebertia.com From moky.math at gmail.com Thu Sep 29 12:39:51 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 29 Sep 2011 18:39:51 +0200 Subject: Question on Manipulating List and on Python In-Reply-To: References: Message-ID: <4E849F57.4010101@gmail.com> Le 29/09/2011 18:27, John Gordon a ?crit : > In Subhabrata Banerjee writes: > >> (i) I have a file of lists. Now, the first digit starts with a number >> or index, like, > >> [001, "Obama", "USA", "President"] >> [002 "Major", "UK", "PM"] >> [003 "Singh", "INDIA", "PM"] What about creating a dictionary ? dic = {1:["Obama","USA","President"],2:[etc.]] >> (ii) My second question is posted by one of my colleagues, what makes >> Python so fast? If your colleague is used to program inside Word macros, I guess the answer ;) If he is used to program in C, I'm less sure. It really depends on the context of the question. Laurent From anikom15 at gmail.com Thu Sep 29 12:42:11 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 09:42:11 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <20110929164211.GA11016@Smoke> On Thu, Sep 29, 2011 at 05:23:30AM -0700, rantingrick wrote: > On Sep 29, 5:37?am, Passiday wrote: > > What is so bad about breaking code in obscure places? We changed print > to a function which broke just about every piece of code every written > in this language. (BTW, print should ALWAYS have been a function!) > What is so bad then about breaking some very obscure code? We could > always have a lengthy deprecation period. > Well, I once thought that a print function made a lot of sense. In C, printf is a function, however then I think why print is a function. In C, just about every function has side effects (the return values are more often than not either pointers or status codes). In Python functions are encouraged to not have side-effects, so the implementation of print as a statement or a method makes far more sense than as a function. But maybe I'm just batty as you all think I am. From rosuav at gmail.com Thu Sep 29 12:50:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 02:50:49 +1000 Subject: Question on Manipulating List and on Python In-Reply-To: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee wrote: > And Python seems faster than C++/Java. It is indeed. I also experience > it. > Python compared to Java? Difficult to compare. Python to C++? Impossible to compare. But performance depends MASSIVELY on algorithmic quality; if you code the exact same thing in Python and in C++, you would probably find that the C++ one is faster, but chances are you're implementing approximately the same thing in two quite different ways. Or possibly you're using a slow and inefficient library or third-party function. I've sometimes written code in one language and directly ported it to another, and then run both on the same hardware. With most such experiments, CPython generally doesn't perform all that well, and C or C++ rocks. But frequently, the C/C++ code is more verbose and more error-prone than the Python - because Python's biggest boast is not that it's fast, but that it's *fast enough*, while being easy to work with. (And every once in a while there's something where I want to use a pointer to some other variable, and that's a concept that just plain doesn't work in Python. You have references to objects, but you can't from one place change another variable, without using some kind of mutable object that they both reference.) ChrisA From miki.tebeka at gmail.com Thu Sep 29 12:52:07 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 29 Sep 2011 09:52:07 -0700 (PDT) Subject: options for plotting points on geographic map In-Reply-To: References: Message-ID: <28071425.854.1317315127547.JavaMail.geo-discussion-forums@prfb12> Probably the google maps routes will be faster (maybe using embedded webkit window). However it requires internet connection. See also http://www.scipy.org/Cookbook/Matplotlib/Maps HTH -- Miki Tebeka http://pythonwise.blogspot.com From gordon at panix.com Thu Sep 29 12:52:53 2011 From: gordon at panix.com (John Gordon) Date: Thu, 29 Sep 2011 16:52:53 +0000 (UTC) Subject: Question on Manipulating List and on Python References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: In <71c71a9d-928d-4ebe-af64-674c31bc1c09 at e9g2000vby.googlegroups.com> Subhabrata Banerjee writes: > Hi John, > The actual code is till now is: > def name_debugger(n): > open_file=3Dopen("/python27/name1.txt") > for line in open_file: > line_word=3Dline.split() > #print line_word > word1=3Dline_word[0] > print word1 Can you give us some sample lines from /python27/name1.txt ? > And Python seems faster than C++/Java. It is indeed. I also experience > it. It shouldn't be inherently faster than C++ or Java. If it is, it's because the C++ or Java code is doing more work. Do you have a sample Python program and a sample C++ or Java program to demonstrate the speed difference? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rosuav at gmail.com Thu Sep 29 13:02:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:02:29 +1000 Subject: Suggested coding style In-Reply-To: <20110929164211.GA11016@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <20110929164211.GA11016@Smoke> Message-ID: On Fri, Sep 30, 2011 at 2:42 AM, Westley Mart?nez wrote: > But maybe I'm just batty as you all think I am. Yes, I'm afraid so. Bonkers. Off your head. But let me tell you a secret... All the best people are. > Well, I once thought that a print function made a lot of sense. ?In C, > printf is a function, however then I think why print is a function. ?In > C, just about every function has side effects (the return values are > more often than not either pointers or status codes). ?In Python > functions are encouraged to not have side-effects, so the implementation > of print as a statement or a method makes far more sense than as a > function. Since functions and methods in Python are practically the same thing, I don't know that there really need be any difference in policy. But I do like any reduction in the number of "special features" of a language. If screen output can be done as an ordinary function taking ordinary arguments, that's better than having a special language construct. Also, it's just plain stupid and yet just plain cool to be able to: print = sys.stderr.write and smoothly redirect all your prints to stderr. (Unfortunately this doesn't quite work, as it means you don't get your newlines put in for you, but there's sure to be an equally stupid/cool reassignment available.) ChrisA From moky.math at gmail.com Thu Sep 29 13:08:52 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 29 Sep 2011 19:08:52 +0200 Subject: Counting the number of call of a function Message-ID: Hello Is it possible to count the number of time a function is called ? Of course, if I've access to the source code, it's easy. I tried the following : def foo(): print "foo !" class wraper(object): def __init__(self,fun): globals()[fun]=self.replacement def replacement(*args): print "I'm replaced" foo() X=wraper(foo) foo() I was hoping that globals()[foo] would be replaced by my X.replacement and thus the second call to foo() was expected to print "I'm replaced". Instead nothing is done. By the way, I tried to print globals() inside __init__() to see what happens. It turns out that the entry 'foo' is never modified. Any idea ? I fact what I have to do is to add a decorator _a posteriori_ ... Have a good night Laurent From rosuav at gmail.com Thu Sep 29 13:20:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:20:30 +1000 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens wrote: > def foo(): > ? ?print "foo !" > > > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() Are you able to change the call structure to: foo() # unchanged foo=wrapper(foo) # this changes it foo() # should now be changed perhaps? That would be a lot easier to manage. Then you could write the wrapper thus: class wrapper(object): def __init__(self,func): self.func=func def __call__(self,*args,**kwargs): print("I'm replaced!") # if you want to be noisy self.count+=1 self.func(*args,**kwargs) Tested in Python 3; should also work in Python 2, which you appear to be using. Effectively, I've written something that could actually be a decorator, and then done the same sort of thing that a decorator does by rebinding the name. ChrisA From rosuav at gmail.com Thu Sep 29 13:22:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:22:12 +1000 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens wrote: > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement and > thus the second call to foo() was expected to print "I'm replaced". Actually, I've just realized what your problem might be. Try: X = wraper("foo") You're indexing globals() with the actual function object, but you want to index it with the function _name_. I do think that the decorator technique will be a lot cleaner, though. ChrisA From python at mrabarnett.plus.com Thu Sep 29 13:26:18 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 29 Sep 2011 18:26:18 +0100 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E84AA3A.7040209@mrabarnett.plus.com> On 29/09/2011 18:08, Laurent Claessens wrote: > Hello > > > Is it possible to count the number of time a function is called ? > Of course, if I've access to the source code, it's easy. > > I tried the following : > > def foo(): > print "foo !" > > > class wraper(object): > def __init__(self,fun): > globals()[fun]=self.replacement > def replacement(*args): > print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement > and thus the second call to foo() was expected to print "I'm replaced". > > Instead nothing is done. > > By the way, I tried to print globals() inside __init__() to see what > happens. It turns out that the entry 'foo' is never modified. > > Any idea ? > I fact what I have to do is to add a decorator _a posteriori_ ... > The keys of globals() are the _names_. You're giving it the function itself. Try this: class wraper(object): def __init__(self,fun): globals()[fun.__name__]=self.replacement def replacement(*args): print("I'm replaced") A decorator would be better. From clp2 at rebertia.com Thu Sep 29 13:27:35 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 10:27:35 -0700 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Thu, Sep 29, 2011 at 10:08 AM, Laurent Claessens wrote: > ? Hello > > > ? Is it possible to count the number of time a function is called ? > Of course, if I've access to the source code, it's easy. > > I tried the following : > > def foo(): > ? ?print "foo !" > > > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement and > thus the second call to foo() was expected to print "I'm replaced". > > Instead nothing is done. That's because globals() maps names (i.e. strings) to values, whereas in this case `fun` is a function object, not a string. Trying to subscript globals() with a non-string arguably ought to be an error. By way of example (with irrelevant stuff elided): Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) Type "help", "copyright", "credits" or "license" for more information. >>> def foo(): ... pass ... >>> globals() {..., 'foo': } >>> globals()[foo] = 42 >>> globals() {..., : 42, 'foo': } >>> globals()["foo"] = 99 >>> globals() {..., 'foo': 99, : 42} Note that you can get the name of a function using its __name__ attribute. That is to say: foo.__name__ == "foo" > By the way, I tried to print globals() inside __init__() to see what > happens. It turns out that the entry 'foo' is never modified. > > Any idea ? > I fact what I have to do is to add a decorator _a posteriori_ ... Recall that the decorator syntax: @bar def qux(): pass is basically equivalent to: def qux(): pass qux = bar(qux) Therefore, you want something like: def wrapped(func): def replacement(*args, **kwargs): print "I'm replaced" return replacement foo = wrapped(foo) foo() # => I'm replaced Cheers, Chris -- http://rebertia.com From jeanpierreda at gmail.com Thu Sep 29 14:49:05 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 14:49:05 -0400 Subject: [OT] Benefit and belief In-Reply-To: <87zkho2glb.fsf@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. Well. It wasn't directly an attack on people exactly. It did mention believers directly. It could certainly be _interpreted_ as an attack (and was interpreted that way), and that's really all that's necessary for a hostile environment. I'm not saying we should censor ourselves exactly. I've always been opposed to harsh _rules_ about what's appropriate and what isn't. But I do think it's important to consider others' feelings. Just because it isn't an attack, doesn't mean it can't hurt peoples' feelings, and I think hurting peoples' feelings is something worth going out of your way to avoid. Anyway, if it was a joke before, it isn't when somebody starts calling some "group of people" "organised conspiracies to support and protect child molesters". > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. That doesn't make it right. Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. It seems, again, hurtful. Especially when the idea is totally unrelated. It's like we're having a discussion about dynamic typing and somebody blurts out "Hahaha, static typing is almost as dumb as Cartesian Dualism". The best case outcome is that nobody cares. The worse case outcomes go down to hurt feelings and flame wars from dualists. > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. It obviously isn't "safe" to joke about any topic, seeing as it caused a derailment and new thread. Devin On Wed, Sep 28, 2011 at 11:05 PM, Ben Finney wrote: > Devin Jeanpierre writes: > >> > Forget money, or even the love of money. The idea that one mustn't >> > criticise another person's beliefs is the root of all evil. >> >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. > >> Can't you pick somewhere else to attack Christianity? > > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. > > If you find someone attacking people, I'll join you in ostracising the > attacker. But no, don't attempt to silence jokes that attack an idea. > > Off-topic? If we start discussing the content of the ideas being > attacked, yeah, I'd say religion is pretty off-topic. > > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. > > -- > ?\ ? ? ? ? ?We demand rigidly defined areas of doubt and uncertainty!? | > ?`\ ? ??Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Adams | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > From petite.abeille at gmail.com Thu Sep 29 15:32:20 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 29 Sep 2011 21:32:20 +0200 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > It could certainly be _interpreted_ as an attack > (and was interpreted that way), and that's really all that's necessary > for a hostile environment. In other news: http://alt.textdrive.com/assets/public/non/nq050616.gif -- Tout le monde il est beau, tout le monde il est gentil From navkirat.py at gmail.com Thu Sep 29 15:37:34 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Fri, 30 Sep 2011 01:07:34 +0530 Subject: [OT] Benefit and belief In-Reply-To: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: Hi, I am looking for the python mailing list. . ? Have you guys seen it somewhere? I think I accidently reached the cry-me-a-river list? Regards, Nav On Sep 30, 2011 1:03 AM, "Petite Abeille" wrote: > > On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > >> It could certainly be _interpreted_ as an attack >> (and was interpreted that way), and that's really all that's necessary >> for a hostile environment. > > In other news: > > http://alt.textdrive.com/assets/public/non/nq050616.gif > > -- > Tout le monde il est beau, tout le monde il est gentil > > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Sep 29 15:39:48 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 15:39:48 -0400 Subject: options for plotting points on geographic map In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B1B@EMARC112VS01.exchad.jpmchase.net> >I see there is pymaps, a Python wrapper for Google Maps. I may try >that but it seems to be barely documented and would require making a >webpage with javascript to display the map, whereas I'd probably >prefer a desktop app for this--though I'd consider a web page (it's >probably easier than I think). You could create the webpage and then render it in your desktop app. I have seen plenty of apps like that. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Thu Sep 29 15:52:23 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 12:52:23 -0700 Subject: [OT] Benefit and belief In-Reply-To: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: <4E84CC77.7060804@stoneleaf.us> Petite Abeille wrote: > On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > >> It could certainly be _interpreted_ as an attack >> (and was interpreted that way), and that's really all that's necessary >> for a hostile environment. > > In other news: > > http://alt.textdrive.com/assets/public/non/nq050616.gif Okay, now that's funny. ~Ethan~ From ramit.prasad at jpmorgan.com Thu Sep 29 15:52:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 15:52:52 -0400 Subject: Question on Manipulating List and on Python In-Reply-To: References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B77@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Chris Angelico Sent: Thursday, September 29, 2011 11:51 AM To: python-list at python.org Subject: Re: Question on Manipulating List and on Python On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee wrote: > And Python seems faster than C++/Java. It is indeed. I also experience > it. > Python compared to Java? Difficult to compare. Python to C++? Impossible to compare. But performance depends MASSIVELY on algorithmic quality; if you code the exact same thing in Python and in C++, you would probably find that the C++ one is faster, but chances are you're implementing approximately the same thing in two quite different ways. Or possibly you're using a slow and inefficient library or third-party function. I've sometimes written code in one language and directly ported it to another, and then run both on the same hardware. With most such experiments, CPython generally doesn't perform all that well, and C or C++ rocks. But frequently, the C/C++ code is more verbose and more error-prone than the Python - because Python's biggest boast is not that it's fast, but that it's *fast enough*, while being easy to work with. (And every once in a while there's something where I want to use a pointer to some other variable, and that's a concept that just plain doesn't work in Python. You have references to objects, but you can't from one place change another variable, without using some kind of mutable object that they both reference.) ----------------------------------------------------------------------- I think Steven D'Aprano had an excellent post on this a week or so ago (on the tutor list, not this one). See: http://mail.python.org/pipermail/tutor/2011-September/085573.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 ChrisA -- http://mail.python.org/mailman/listinfo/python-list This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From petite.abeille at gmail.com Thu Sep 29 15:54:54 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 29 Sep 2011 21:54:54 +0200 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: <3D981489-D106-459B-91C1-73DE3A45B79C@gmail.com> On Sep 29, 2011, at 9:37 PM, Navkirat Singh wrote: > I am looking for the python mailing list. . ? Have you guys seen it > somewhere? I think I accidently reached the cry-me-a-river list? The portal can be reactivated by intoning Bobby Brown Goes Down in unison. From chris at simplistix.co.uk Thu Sep 29 17:00:58 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 29 Sep 2011 22:00:58 +0100 Subject: TestFixtures 2.1.0 Released! Message-ID: <4E84DC8A.4040508@simplistix.co.uk> Hi All, Another release of TestFixtures, getting things closer to where I want them to be. The only change was: - Add a "strict mode" to `compare`. When used, it ensures that the values compared are not only equal but also of the same type. This mode is not used by default, and the default mode restores the more commonly useful functionality where values of similar types but that aren't equal give useful feedback about differences. For details, read: http://packages.python.org/testfixtures/comparing.html#strict-comparison The full list of changes can be found here: http://packages.python.org/testfixtures/changes.html The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From anikom15 at gmail.com Thu Sep 29 17:20:15 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 14:20:15 -0700 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <20110929212015.GA11663@Smoke> On Thu, Sep 29, 2011 at 02:49:05PM -0400, Devin Jeanpierre wrote: > >> This was a technical discussion, and calling the bible a joke was not > >> necessary at all. It creates a hostile atmosphere. > > > > I disagree. It was not an attack on any person nor group of people. If > > we are to be required to avoid jokes not directed at people, then *that* > > is an atmosphere hostile to open friendly discussion. > > Well. It wasn't directly an attack on people exactly. It did mention > believers directly. It could certainly be _interpreted_ as an attack > (and was interpreted that way), and that's really all that's necessary > for a hostile environment. > > I'm not saying we should censor ourselves exactly. I've always been > opposed to harsh _rules_ about what's appropriate and what > isn't. But I do think it's important to consider others' feelings. > Just because it isn't an attack, doesn't mean it can't hurt peoples' > feelings, and I think hurting peoples' feelings is something worth > going out of your way to avoid. > > Anyway, if it was a joke before, it isn't when somebody starts calling > some "group of people" "organised conspiracies to support and protect > child molesters". > > > The person who wrote the ?bible is a joke? intended it as a flippant > > remark. Countless other flippant remarks pass through here all the time, > > making jokes at the expense of some idea or other. Christianity will not > > be an exception to that. > > That doesn't make it right. Is it OK to make fun of arbitrary ideas as > "jokes"? I don't think so. It seems, again, hurtful. Especially when > the idea is totally unrelated. It's like we're having a discussion > about dynamic typing and somebody blurts out "Hahaha, static typing is > almost as dumb as Cartesian Dualism". The best case outcome is that > nobody cares. The worse case outcomes go down to hurt feelings and > flame wars from dualists. > > > But the topic of keeping this forum safe for technical discussion > > entails that it must be safe for *any* idea to be the butt of a joke, be > > it a religious text or the Zen of Python, and that is very much > > on-topic. > > It obviously isn't "safe" to joke about any topic, seeing as it caused > a derailment and new thread. > Sometimes it's just not appropriate to joke. Save them for the dates. From ben+python at benfinney.id.au Thu Sep 29 17:24:15 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 07:24:15 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <87r52z2gao.fsf@benfinney.id.au> Passiday writes: > Oh, my. Who could expect this topic would iterate to some whining > about religion (please don't respond on this remark of mine). That's an unreasonable request. If you make a provocative remark (I doubt you chose to use ?whining? without knowing how dismissive it is), it's disingenuous to then ask that people please not respond. -- \ ?If nothing changes, everything will remain the same.? ?Barne's | `\ Law | _o__) | Ben Finney From ben+python at benfinney.id.au Thu Sep 29 17:32:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 07:32:42 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <87mxdn2fwl.fsf@benfinney.id.au> MRAB writes: > On 29/09/2011 04:05, Ben Finney wrote: > > But the topic of keeping this forum safe for technical discussion > > entails that it must be safe for *any* idea to be the butt of a > > joke, be it a religious text or the Zen of Python, and that is very > > much on-topic. > > Even if it offends Python worshippers? > http://www.youtube.com/watch?v=asUyK6JWt9U Even then. People who remain attached to ideas are being unreasonable if they take a joke about that idea personally. No idea, certainly not any religion, gets any special exemption. -- \ ?On the other hand, you have different fingers.? ?Steven Wright | `\ | _o__) | Ben Finney From anikom15 at gmail.com Thu Sep 29 17:33:34 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 14:33:34 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4E847A8F.3070401@mrabarnett.plus.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <20110929213334.GB11663@Smoke> I'm kind of new to the whole mailing list thing, but they seem to be a lot more lenient than internet forums about most things. I've noticed that sometimes Off-topic posts can get a little out of hand. I guess it's not really a big deal, but it bothers me, and the trolls just love to feed on it. I mean, as programmers, we should devote our time to improving computer systems. On this mailing list, we're programmers, nothing else, and so we shouldn't mingle other things into the list. Think of it as using global variables or even a goto. That's essentially what OT is. It just serves to obfuscate valuable answers to good programming questions. From rosuav at gmail.com Thu Sep 29 17:40:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 07:40:13 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <20110929213334.GB11663@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <20110929213334.GB11663@Smoke> Message-ID: On Fri, Sep 30, 2011 at 7:33 AM, Westley Mart?nez wrote: > On this mailing list, we're programmers, > nothing else, and so we shouldn't mingle other things into the list. > Think of it as using global variables or even a goto. ?That's > essentially what OT is. Not a bad analogy, that... but I accept it in perhaps not the same way as you intended it. I don't mind using a global variable once in a while. I don't object to a well-placed goto, especially when it's clear and obvious what it's doing. And the occasional off-topic post or thread on a mailing list isn't the end of the world either. ChrisA From ben+python at benfinney.id.au Thu Sep 29 18:01:32 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 08:01:32 +1000 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <20110929220132.GD2715@benfinney.id.au> On 29-Sep-2011, Devin Jeanpierre wrote: > >> This was a technical discussion, and calling the bible a joke was not > >> necessary at all. It creates a hostile atmosphere. > > > > I disagree. It was not an attack on any person nor group of people. If > > we are to be required to avoid jokes not directed at people, then *that* > > is an atmosphere hostile to open friendly discussion. > > Well. It wasn't directly an attack on people exactly. It did mention > believers directly. It did not. It mentioned only a pair of texts: the bible, and the Zen of Python. Texts are not people, and we should not go out of our way to protect them from jokes or criticism. > It could certainly be _interpreted_ as an attack (and was interpreted > that way), and that's really all that's necessary for a hostile > environment. Nonsense. *Any* joke could be interpreted as an attack; the issue is whether it's reasonable to do so. Anyone who is so confused as to take a joke about a book as an attack on people is being quite unreasonable, and we should not restrain our jokes for the sake of that. > I'm not saying we should censor ourselves exactly. I've always been > opposed to harsh _rules_ about what's appropriate and what > isn't. But I do think it's important to consider others' feelings. Agreed. But only to the extent that attacks *on those people* are concerned. Peoples feelings about ideas are not a consideration when discussing ideas, and certainly not when joking about ideas. > Just because it isn't an attack, doesn't mean it can't hurt peoples' > feelings, and I think hurting peoples' feelings is something worth > going out of your way to avoid. There we disagree. The hurt feelings of someone who attaches their identity to a text should not restrain our discourse. > Anyway, if it was a joke before, it isn't when somebody starts calling > some "group of people" "organised conspiracies to support and protect > child molesters". The group of people to whom that refers, the administrative hierarchy of the Catholic Church, have been doing exactly what the quotation says. I agree that's not a joke; it's a matter of fact, and relevant in the context where it was mentioned. > Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. Yes, a thousand times yes. Ideas are not people, have no rights, and get no exemption from criticism or dismissal or attack or ridicule. > It seems, again, hurtful. Especially when the idea is totally unrelated. That would eliminate just about every joke: a huge range of jokes *depend* for their humour on connecting seemingly-unrelated ideas. So by your logic, we don't get to make those jokes here. > It's like we're having a discussion about dynamic typing and somebody > blurts out "Hahaha, static typing is almost as dumb as Cartesian > Dualism". The best case outcome is that nobody cares. The worse case > outcomes go down to hurt feelings and flame wars from dualists. And the joke would still be okay, and it would be silly for anyone to take it as hurtful. You can call such a joke off-topic, and I'd agree. You can say it's not very funny, and I'd agree. You can say it's undeserving of a flame war, and I'd agree wholeheartedly. But whoever takes that joke and says it's deliberately hurtful is being presumptuous and censorious and unreasonable. If they then castigate the joker for supposedly hurting someone's feelings, it's at that point the atmosphere turns hostile to discussion. -- \ ?The most dangerous man to any government is the man who is | `\ able to think things out for himself, without regard to the | _o__) prevailing superstitions and taboos.? ?Henry L. Mencken | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From ian.g.kelly at gmail.com Thu Sep 29 18:12:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 16:12:51 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > A specific method for padding a string with ONLY zeros is ludicrous > and exposes the narrow mindedness of the creator. The only thing worse > than "zfill" as a string method is making zfill into built-in > function! The ONLY proper place for zfill is as an option in the > str.format() method. > > py> "{0:zf10}".format(1234) -> "00000000001234" Agree that zfill seems to be redundant with str.format, although your suggested syntax is atrocious, especially since a syntax already exists that fits better in the already-complicated format specifier syntax. "{0:=010d}".format(1234) -> "0000001234" There are a couple of warts with the existing implementation, however: 1) str.zfill() operates on strings; the .format() syntax operates on numeric types. I would suggest that the "=" fill alignment in format specifiers should be extended to do the same thing as zfill when given a string. 2) It seems to not behave as documented for floats. I expect: "{0:=010f}".format(-32.7) -> "-0000032.7" I get: "{0:=010f}".format(-32.7) -> "-32.700000" On the other hand, I can't imagine why I would ever actually want the expected result, so maybe it's not a big deal. From clp2 at rebertia.com Thu Sep 29 18:16:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 15:16:43 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <20110929213334.GB11663@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <20110929213334.GB11663@Smoke> Message-ID: On Thu, Sep 29, 2011 at 2:33 PM, Westley Mart?nez wrote: > I'm kind of new to the whole mailing list thing, but they seem to be a > lot more lenient than internet forums about most things. ?I've noticed > that sometimes Off-topic posts can get a little out of hand. ?I guess > it's not really a big deal, but it bothers me, and the trolls just love > to feed on it. ?I mean, as programmers, we should devote our time to > improving computer systems. This is why good mail clients have a "Mute" or equivalent function to ignore an entire thread and not let it waste any more of your time. You may want to plonk Xah and the ranter who goes by Rick while you're at it. :) Cheers, Chris From rantingrick at gmail.com Thu Sep 29 18:56:57 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 15:56:57 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 5:12?pm, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > > A specific method for padding a string with ONLY zeros is ludicrous > > and exposes the narrow mindedness of the creator. The only thing worse > > than "zfill" as a string method is making zfill into built-in > > function! The ONLY proper place for zfill is as an option in the > > str.format() method. > > > py> "{0:zf10}".format(1234) -> "00000000001234" > > Agree that zfill seems to be redundant with str.format, although your > suggested syntax is atrocious, especially since a syntax already > exists that fits better in the already-complicated format specifier > syntax. It's interesting that you find the format specifier "complicated". I will admit that upon first glance i lamented the new format method spec and attempted to cling to the old string interpolation crap. However, as you use the new format method you will come to appreciate it. It's an adult beverage with an acquired taste. ;-) One thing that may help format noobs is to look at the spec as two parts; the part before the colon and the part after the colon. If you break it down in this manner the meaning starts to shine through. I will agree, it is a lot of cryptic info squeezed into a small space HOWEVER you would no want a verbose format specification. But i wholeheartedly agree with you points and i would say the zfill method has no future uses in the stdlib except for historical reasons. We should deprecate it now. > "{0:=010d}".format(1234) -> "0000001234" > > There are a couple of warts with the existing implementation, however: > > 1) str.zfill() operates on strings; the .format() syntax operates on > numeric types. ?I would suggest that the "=" fill alignment in format > specifiers should be extended to do the same thing as zfill when given > a string. EXACTLY! PS: Has anyone noticed all the off topic chatter about religion and feelings? Since the main subject of this thread is about zfill i can't help but wonder if the minions where sent out to present a distraction with "scripted" pseudo arguments. Just an observation. From jeanpierreda at gmail.com Thu Sep 29 19:03:24 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 19:03:24 -0400 Subject: [OT] Benefit and belief In-Reply-To: <20110929220132.GD2715@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: > There we disagree. The hurt feelings of someone who attaches their identity > to a text should not restrain our discourse. Yes, we do. > That would eliminate just about every joke: a huge range of jokes *depend* > for their humour on connecting seemingly-unrelated ideas. So by your logic, > we don't get to make those jokes here. I didn't have much logic. I just don't think it's nice to do things that hurt other people, and if we can, we should avoid those things. Avoiding them is pretty easy here. > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. I don't really care about the "joke". I honestly I didn't understand it as a joke, which would drive most of my disagrement. I don't think it should have been made, yes. I take major issue with the anti-Christian rant that appeared afterward, but I haven't really taken much opportunity to attack it because it doesn't matter. All I'd like is for people to be a little more friendly, if you please. I also didn't reprimand anyone, except maybe Steven. But anyway, no, we don't agree on what it means to be friendly or what a hostile atmosphere is. I've noticed that people tend to be a lot harsher here than what I'm used to, so perhaps your attitude to it is more common on mailing-lists and I should just adapt. Devin On Thu, Sep 29, 2011 at 6:01 PM, Ben Finney wrote: > On 29-Sep-2011, Devin Jeanpierre wrote: >> >> This was a technical discussion, and calling the bible a joke was not >> >> necessary at all. It creates a hostile atmosphere. >> > >> > I disagree. It was not an attack on any person nor group of people. If >> > we are to be required to avoid jokes not directed at people, then *that* >> > is an atmosphere hostile to open friendly discussion. >> >> Well. It wasn't directly an attack on people exactly. It did mention >> believers directly. > > It did not. It mentioned only a pair of texts: the bible, and the Zen of > Python. Texts are not people, and we should not go out of our way to > protect them from jokes or criticism. > >> It could certainly be _interpreted_ as an attack (and was interpreted >> that way), and that's really all that's necessary for a hostile >> environment. > > Nonsense. *Any* joke could be interpreted as an attack; the issue is > whether it's reasonable to do so. Anyone who is so confused as to take a > joke about a book as an attack on people is being quite unreasonable, and > we should not restrain our jokes for the sake of that. > >> I'm not saying we should censor ourselves exactly. I've always been >> opposed to harsh _rules_ about what's appropriate and what >> isn't. But I do think it's important to consider others' feelings. > > Agreed. But only to the extent that attacks *on those people* are > concerned. Peoples feelings about ideas are not a consideration when > discussing ideas, and certainly not when joking about ideas. > >> Just because it isn't an attack, doesn't mean it can't hurt peoples' >> feelings, and I think hurting peoples' feelings is something worth >> going out of your way to avoid. > > There we disagree. The hurt feelings of someone who attaches their identity > to a text should not restrain our discourse. > >> Anyway, if it was a joke before, it isn't when somebody starts calling >> some "group of people" "organised conspiracies to support and protect >> child molesters". > > The group of people to whom that refers, the administrative hierarchy of > the Catholic Church, have been doing exactly what the quotation says. > > I agree that's not a joke; it's a matter of fact, and relevant in the > context where it was mentioned. > >> Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. > > Yes, a thousand times yes. Ideas are not people, have no rights, and get no > exemption from criticism or dismissal or attack or ridicule. > >> It seems, again, hurtful. Especially when the idea is totally unrelated. > > That would eliminate just about every joke: a huge range of jokes *depend* > for their humour on connecting seemingly-unrelated ideas. So by your logic, > we don't get to make those jokes here. > >> It's like we're having a discussion about dynamic typing and somebody >> blurts out "Hahaha, static typing is almost as dumb as Cartesian >> Dualism". The best case outcome is that nobody cares. The worse case >> outcomes go down to hurt feelings and flame wars from dualists. > > And the joke would still be okay, and it would be silly for anyone to take > it as hurtful. > > You can call such a joke off-topic, and I'd agree. You can say it's not > very funny, and I'd agree. You can say it's undeserving of a flame war, and > I'd agree wholeheartedly. > > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. > > -- > ?\ ? ? ? ? ?The most dangerous man to any government is the man who is | > ?`\ ? ? ? able to think things out for himself, without regard to the | > _o__) ? ? ? ? ?prevailing superstitions and taboos.? ?Henry L. Mencken | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > > From jeanpierreda at gmail.com Thu Sep 29 19:07:28 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 19:07:28 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) Yeah. It's a much more difficult to read thing, but once you learn how to write it it flows faster. Of course, I never managed to learn how to write it... I would suggest that rather than being "complicated" it is "dense". > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. May I suggest a email client that can group mailing list threads? Also, not accusing others of conspiracies. Devin On Thu, Sep 29, 2011 at 6:56 PM, rantingrick wrote: > On Sep 29, 5:12?pm, Ian Kelly wrote: >> On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: >> > A specific method for padding a string with ONLY zeros is ludicrous >> > and exposes the narrow mindedness of the creator. The only thing worse >> > than "zfill" as a string method is making zfill into built-in >> > function! The ONLY proper place for zfill is as an option in the >> > str.format() method. >> >> > py> "{0:zf10}".format(1234) -> "00000000001234" >> >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) > > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. > > But i wholeheartedly agree with you points and i would say the zfill > method has no future uses in the stdlib except for historical reasons. > We should deprecate it now. > > >> "{0:=010d}".format(1234) -> "0000001234" >> >> There are a couple of warts with the existing implementation, however: >> >> 1) str.zfill() operates on strings; the .format() syntax operates on >> numeric types. ?I would suggest that the "=" fill alignment in format >> specifiers should be extended to do the same thing as zfill when given >> a string. > > EXACTLY! > > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. > -- > http://mail.python.org/mailman/listinfo/python-list > From vacorama at gmail.com Thu Sep 29 19:11:02 2011 From: vacorama at gmail.com (ron) Date: Thu, 29 Sep 2011 16:11:02 -0700 (PDT) Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0acaf956-3285-4d0c-98ea-61f7ce88a3ba@x19g2000vbl.googlegroups.com> On Sep 29, 5:21?am, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > > -- > Steven Have you tried GNU Screen? It let's you run processes under virtual terminals, which can then be backgrounded, reconnected to, etc. I think it comes with most linux distros. From rosuav at gmail.com Thu Sep 29 19:12:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 09:12:50 +1000 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: On Fri, Sep 30, 2011 at 9:03 AM, Devin Jeanpierre wrote: > But anyway, no, we don't agree on what it means to be friendly or what > a hostile atmosphere is. I've noticed that people tend to be a lot > harsher here than what I'm used to, so perhaps your attitude to it is > more common on mailing-lists and I should just adapt. > I'm told that there are other mailing lists / newsgroups that are far, FAR more hostile than this. Haven't explored though, as I don't feel like torturing myself :) As to the original offensiveness, though: I'm a fundamentalist Christian (not Catholic though), and I water-off-a-duck's-backed the insult. If it's true, it's allowed to be offensive; if it's not true, I can distance myself from it. (In this case, the latter; the inner issues of the Catholic church are unconnected to the core of Christianity.) Chris Angelico From ethan at stoneleaf.us Thu Sep 29 19:21:25 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 16:21:25 -0700 Subject: [OT] Benefit and belief In-Reply-To: <20110929220132.GD2715@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <4E84FD75.5050907@stoneleaf.us> Ben Finney wrote: > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe he /wasn't/ trying to be offensive? ~Ethan~ From python at mrabarnett.plus.com Thu Sep 29 19:37:08 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 30 Sep 2011 00:37:08 +0100 Subject: [OT] Benefit and belief In-Reply-To: <4E84FD75.5050907@stoneleaf.us> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <4E850124.8070508@mrabarnett.plus.com> On 30/09/2011 00:21, Ethan Furman wrote: > Ben Finney wrote: >> But whoever takes that joke and says it's deliberately hurtful is being >> presumptuous and censorious and unreasonable. If they then castigate the >> joker for supposedly hurting someone's feelings, it's at that point the >> atmosphere turns hostile to discussion. > > Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe > he /wasn't/ trying to be offensive? > rantingrick: """Since, like the bible the zen is self contradicting, any argument utilizing the zen can be defeated utilizing the zen.""" alex23: """And like the Bible, the Zen was created by humans as a joke. If you're taking it too seriously, that's your problem.""" From ethan at stoneleaf.us Thu Sep 29 19:40:59 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 16:40:59 -0700 Subject: [OT] Benefit and belief In-Reply-To: <4E84FD75.5050907@stoneleaf.us> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <4E85020B.30207@stoneleaf.us> Ethan Furman wrote: > Ben Finney wrote: >> But whoever takes that joke and says it's deliberately hurtful is being >> presumptuous and censorious and unreasonable. If they then castigate the >> joker for supposedly hurting someone's feelings, it's at that point the >> atmosphere turns hostile to discussion. > > Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe > he /wasn't/ trying to be offensive? Okay, that's what I get for skimming -- it was alex23, not rr. My apologies, rr, for the misattribution. ~Ethan~ From rantingrick at gmail.com Thu Sep 29 19:41:34 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 16:41:34 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <30b05df7-6f16-45fd-bbe8-7f6c09d2e6e1@i28g2000yqn.googlegroups.com> On Sep 29, 6:07?pm, Devin Jeanpierre wrote: > > However, as you use the new format method you will come to appreciate > > it. It's an adult beverage with an acquired taste. ;-) > > Yeah. It's a much more difficult to read thing, but once you learn how > to write it it flows faster. > > Of course, I never managed to learn how to write it... A good way to start out is to just use the positional arguments. py> name = "Bob" py> "Hello my name is {0}".format(name) Hello my name is Bob py> "Hello my name is {name}".format(name=name) Hello my name is Bob py> "Hello my name is {0}. My named spelled backwards is: {0}".format(name) Hello my name is Bob. My named spelled backwards is: Bob py> "A small fry cost {0:0.2f}".format(1.6666666) A small fry cost 1.67 py> "A small car cost {0:,.2f}".format(11666.6666) A small car cost 11,666.67 # Python 2.7+ you can omit the index. py> "{} = {}".format("value",2) value = 2 Start with the small stuff and then diversify! You'll be glad you made the change. From rantingrick at gmail.com Thu Sep 29 19:47:40 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 16:47:40 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> On Sep 29, 5:12?pm, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > > A specific method for padding a string with ONLY zeros is ludicrous > > and exposes the narrow mindedness of the creator. The only thing worse > > than "zfill" as a string method is making zfill into built-in > > function! The ONLY proper place for zfill is as an option in the > > str.format() method. > > > py> "{0:zf10}".format(1234) -> "00000000001234" > > Agree that zfill seems to be redundant with str.format, although your > suggested syntax is atrocious, especially since a syntax already > exists that fits better in the already-complicated format specifier > syntax. > > "{0:=010d}".format(1234) -> "0000001234" > > There are a couple of warts with the existing implementation, however: > > 1) str.zfill() operates on strings; the .format() syntax operates on > numeric types. ?I would suggest that the "=" fill alignment in format > specifiers should be extended to do the same thing as zfill when given > a string. Ah ha! Found the answer! py> "{0:010d}".format(1234) 0000001234 py> "{0:0>10}".format(1234) 0000001234 py> "{0:0>10}".format("1234") 0000001234 py> "{0:@>10}".format("1234") @@@@@@1234 I would skip using the "{int}{repeat}d" syntax and just use the string padding since you won't need to worry about the input data type. I hate specificity types in string formats. With the old interpolation i ALWAYS used %s for everything. From rantingrick at gmail.com Thu Sep 29 20:04:40 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 17:04:40 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: On Sep 29, 6:40?pm, Ethan Furman wrote: > Okay, that's what I get for skimming -- it was alex23, not rr. ?My > apologies, rr, for the misattribution. Oh don't worry Ethan, this is not the first time I've been falsely accused, misquoted, and kicked in the testicles, and i'm quite sure with this fine group of folks it won't be the last either. From ben+python at benfinney.id.au Thu Sep 29 22:06:56 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 12:06:56 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <87bou23hrz.fsf@benfinney.id.au> Westley Mart?nez writes: > I'm kind of new to the whole mailing list thing, but they seem to be a > lot more lenient than internet forums about most things. Note that a mailing list *is* an internet forum: it is a forum for discussion, conducted on the internet. Mailing lists have been internet forums long before any web application came along. > I've noticed that sometimes Off-topic posts can get a little out of > hand. I guess it's not really a big deal, but it bothers me, and the > trolls just love to feed on it. Yes, these are hazards of an unmoderated discussion forum like this. The overall quality of discussion here, and the signal-to-noise ratio, makes it very worthwhile I think. > I mean, as programmers, we should devote our time to improving > computer systems. On this mailing list, we're programmers, nothing > else, and so we shouldn't mingle other things into the list. What counts as ?mingle other things in?? What sparked this latest outcry was a flippant remark at the expense of an ancient text and the Zen of Python. That outcry was, I have argued, not reasonable. I am firmly committed to allowing flippant remarks which are not at the expense of people. It's highly inappropriate to ask that such remarks not be made simply because some people might take undue offense. Are they off-topic? Maybe, but there's no compulsion to respond to them since flippant remarks, by definition, aren't meant seriously. Are they not funny? That doesn't matter. If the obligation is that people should not make unfunny jokes, we'd all be guilty. Are they poking fun at something? That *definitely* shouldn't matter; if a thing (not a person) is worth defending, then do so or not as you choose. If you like it but can't defend it adequately, that's your problem not anyone else's. If the ridicule works because it's true, then the target thing is perhaps not worth defending. We draw the line, IMO rightly so, at personal attacks on people or groups of people. I have many times spoken out against those in this forum. But books and ideas, no matter who likes them, are fair game for flippant remarks in this and any forum, and I resist efforts to quash such expression. -- \ ?What I have to do is see, at any rate, that I do not lend | `\ myself to the wrong which I condemn.? ?Henry Thoreau, _Civil | _o__) Disobedience_ | Ben Finney From ben+python at benfinney.id.au Thu Sep 29 22:10:16 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 12:10:16 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <0acaf956-3285-4d0c-98ea-61f7ce88a3ba@x19g2000vbl.googlegroups.com> Message-ID: <877h4q3hmf.fsf@benfinney.id.au> ron writes: > On Sep 29, 5:21?am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > > I have a Python script which I would like to test without a tty attached > > to the process. I could run it as a cron job, but is there an easier way? > > Have you tried GNU Screen? It let's you run processes under virtual > terminals, which can then be backgrounded, reconnected to, etc. I > think it comes with most linux distros. That would not satisfy the ?without a TTY attached? requirement. GNU Screen's main goal is to *provide* an attached TTY to multiple processes when the TTY isn't interacting with the user. I don't know whether Screen can *remove* a TTY from a process, and it would be strange to me if it did so. -- \ ?I have yet to see any problem, however complicated, which, | `\ when you looked at it in the right way, did not become still | _o__) more complicated.? ?Paul Anderson | Ben Finney From derek at simkowiak.net Thu Sep 29 22:16:52 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Thu, 29 Sep 2011 19:16:52 -0700 Subject: Motion Tracking with Python Message-ID: <4E852694.4080303@simkowiak.net> Hello, I have a neat Python project I'd like to share. It does real-time motion tracking, using the Python bindings to the OpenCV library: http://derek.simkowiak.net/motion-tracking-with-python/ There is a YouTube video showing the script in action. It's especially neat because my daughter and I worked together on this project. We used it to track her two pet gerbils, as part of her science fair project. She wrote her own (separate) Python script to read the motion tracking log files, compute distance and velocity, and then export those values in a CSV file. Like I say on the web page: "I?m convinced that Python is the best language currently available for teaching kids how to program." I also use Python professionally, and it's worked out great every time. There's no job Python can't handle. Thanks, Derek Simkowiak http://derek.simkowiak.net From steve+comp.lang.python at pearwood.info Thu Sep 29 22:38:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 12:38:01 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > On this mailing list, we're programmers, nothing else, Speak for yourself. -- Steven From rosuav at gmail.com Thu Sep 29 22:48:17 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 12:48:17 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 30, 2011 at 12:38 PM, Steven D'Aprano wrote: > Westley Mart?nez wrote: > >> On this mailing list, we're programmers, nothing else, > > Speak for yourself. > I don't think he meant that the populace here is exclusively programmers, but that *on this list* we are here because we're programmers. We may happen to have coincidental interest in (say) music, but just because some group of us (or even all of us) all enjoy music does not mean that it'd be on-topic to have a discussion of the tetrachord of Mercury. ChrisA From wuwei23 at gmail.com Thu Sep 29 22:50:27 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 19:50:27 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 10:23?pm, rantingrick wrote: > What is so bad about breaking code in obscure places? Try coding in PHP across minor release versions and see how you feel about deprecating core functions on a whim. > We changed print > to a function which broke just about every piece of code every written > in this language. In a well declared _break_ with backwards compatibility. Not on a whim between minor releases. > (BTW, print should ALWAYS have been a function!) Unfortunately, not everyone is as infallible as you. Or as intractable. Coding styles change over time: this is a concept known as "progress", although it's not as obvious in monocultures, so you may not have heard of it. > What is so bad then about breaking some very obscure code? Because while you say "some very obscure code", what you really mean is "code that isn't mine". > GvR should be texting me every night in hopes that some of my API genius will rub > off on him. Are you off your medication again? > I believe GvR had a "mid-dev-crisis"[...] You seem to believe a lot of absolute garbage. As you have no access to the inner states of _any_ of the people you regularly condemn here with your hypocritical attacks, I've no idea why you consider yourself to be an expert on their desires and opinions. From wuwei23 at gmail.com Thu Sep 29 23:05:26 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:05:26 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> On Sep 30, 9:37?am, MRAB wrote: > rantingrick: > """Since, like the bible the zen is self contradicting, any argument > utilizing > the zen can be defeated utilizing the zen.""" > > alex23: > """And like the Bible, the Zen was created by humans as a joke. If you're > taking it too seriously, that's your problem.""" Strangely, calling the bible self-contradictory wasn't seen as inflammatory... Seeing the quotes again, I'm pretty sure I was intending to be flippant _in reference to rantrantrantrick's comment_. Given that it was a response to someone else referring to the bible _and_ it made a point about the zen, I'm not entirely sure why my comment was OT. Again, if you want to disagree with my remark, knock yourself out. If you want to take it as a personal attack, then there's nothing I can do to stop you. But do realise that it is _you_ who is interpreting it as such, and then recall the provision your very own Christ stated about judging the actions of others: within your own belief system _it's not your right to do so_. That never seems to reduce the moral outrage though... From steve+comp.lang.python at pearwood.info Thu Sep 29 23:10:07 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 13:10:07 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> Devin Jeanpierre wrote: > I also didn't reprimand anyone, except maybe Steven. If you are more upset at my describing the Catholic Church as protecting child molesters than you are at the Church for actually protecting child molesters, then your priorities are completely screwed up and your reprimand means less than nothing to me. I wear it as a badge of honour. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 29 23:19:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 13:19:28 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Fri, Sep 30, 2011 at 12:38 PM, Steven D'Aprano > wrote: >> Westley Mart?nez wrote: >> >>> On this mailing list, we're programmers, nothing else, >> >> Speak for yourself. >> > > I don't think he meant that the populace here is exclusively > programmers, but that *on this list* we are here because we're > programmers. We may happen to have coincidental interest in (say) > music, but just because some group of us (or even all of us) all enjoy > music does not mean that it'd be on-topic to have a discussion of the > tetrachord of Mercury. I didn't say it would be on-topic. But we don't cease to be well-rounded human beings with concerns beyond the narrow world of Python programming just because we are writing on a programming forum. -- Steven From wuwei23 at gmail.com Thu Sep 29 23:29:51 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:29:51 -0700 (PDT) Subject: A Trivial Question References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: <65588c04-eea5-4a7a-b7ba-52dbcded227d@c1g2000yql.googlegroups.com> On Sep 29, 8:06?am, Chris Rebert wrote: > Try this: > > def trial(): > ? ? class Foo(object): > ? ? ? ? def __init__(self): > ? ? ? ? ? ? print("Hello, world!") > ? ? Foo() > trial() While this will display "Hello, world!" in the way required, with a slight adjustment you end up with something potentially a little more useful: def trial(): class Foo(object): def __init__(self): print("Hello, world!") return Foo() myfoo = trial() You'll see the same behaviour, but now myfoo refers to the Foo() object that was created inside trial. This makes trial an object factory. If you return an uninstantiated Foo instead: def trial(): class Foo(object): def __init__(self): print("Hello, world!") return Foo MyFoo = trial() foo = MyFoo() Then trial is a class factory, creating and returning a class. Factories can be handy if you're wanting to create dynamic classes based on run time information. def reader_factory(format='json'): class Reader(object): def __init__(self, file): self.file = file if format == 'json': def process(self): print 'json processing goes here' elif format == 'html': def process(self): print 'html processing goes here' return Reader >>> JSONReader = reader_factory('json') >>> j = JSONReader('file1') >>> j.process() json processing goes here This is a trivial example which would probably be better handled by subclasses, but is meant to be indicative of what's possible. From rosuav at gmail.com Thu Sep 29 23:41:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 13:41:31 +1000 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Fri, Sep 30, 2011 at 12:50 PM, alex23 wrote: >> GvR should be texting me every night in hopes that some of my API genius will rub >> off on him. > > Are you off your medication again? > He's very much like jimontrack (aka Tranzit Jim - google him if you're curious), whose username people frequently referred to with the t replaced with a c. Everyone thought he lived in April 1st. ChrisA From wuwei23 at gmail.com Thu Sep 29 23:49:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:49:56 -0700 (PDT) Subject: Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> Chris Angelico wrote: > We may happen to have coincidental interest in (say) > music, but just because some group of us (or even all of us) all enjoy > music does not mean that it'd be on-topic to have a discussion of the > tetrachord of Mercury. As general discussion it would be, sure, but I don't think there's anything that can be readily dismissed as 'not relevant' in terms of providing abstract concepts to programmers. I've tried explaining encapsulation to non-programmers using Reason's hardware rack metaphor. I'm slowly seeing more and more interest in applying hermeneutics to computer science, a discipline that arose out of the study of religious texts. We don't always know what we don't know. For that alone, I'd rather we were more inclusive of topics of discussion than exclusionary. From wuwei23 at gmail.com Thu Sep 29 23:57:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:57:56 -0700 (PDT) Subject: Benefit and belief [was Re: Suggested coding style] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ba4842c-9043-4674-a0d5-5beb915e436b@k10g2000vbn.googlegroups.com> Dennis Lee Bieber wrote: > ? ? ? ? Well... We could try for equality in offense -- the Torah or the > Koran? Maybe the Tripitaka or Sutras? I always enjoyed the possibly apocryphal claim that the design of VRML was influenced by the story of Indra's Net. Maybe some religious tomes are just better? :) From steve+comp.lang.python at pearwood.info Fri Sep 30 00:34:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 14:34:26 +1000 Subject: Hermeneutics and computer science [was off-topic, now back on] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> Message-ID: <4e8546d3$0$29984$c3e8da3$5496439d@news.astraweb.com> alex23 wrote: > I'm slowly seeing more and more interest in applying > a discipline that arose out of the > study of religious texts. Tell us more, please. -- Steven From ian.g.kelly at gmail.com Fri Sep 30 00:36:29 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 22:36:29 -0600 Subject: Benefit and belief In-Reply-To: <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> Message-ID: On Thu, Sep 29, 2011 at 9:05 PM, alex23 wrote: > Strangely, calling the bible self-contradictory wasn't seen as > inflammatory... Well, that part is factual. Whether that makes it a joke is subjective. From mickyhulse.lists at gmail.com Fri Sep 30 00:48:30 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Thu, 29 Sep 2011 21:48:30 -0700 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: That's really cool! Thanks for sharing! :) From ian.g.kelly at gmail.com Fri Sep 30 00:49:43 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 22:49:43 -0600 Subject: Suggested coding style In-Reply-To: <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> Message-ID: On Thu, Sep 29, 2011 at 5:47 PM, rantingrick wrote: > Ah ha! Found the answer! > > py> "{0:010d}".format(1234) > 0000001234 > > py> "{0:0>10}".format(1234) > 0000001234 > > py> "{0:0>10}".format("1234") > 0000001234 > > py> "{0:@>10}".format("1234") > @@@@@@1234 > > I would skip using the "{int}{repeat}d" syntax and just use the string > padding since you won't need to worry about the input data type. I > hate specificity types in string formats. With the old interpolation i > ALWAYS used %s for everything. Nope, that doesn't work. >>> "{0:0>10}".format("-1234") '00000-1234' The whole point of zfill is that it handles signs correctly. From colinphaedrus at yahoo.com Fri Sep 30 01:02:48 2011 From: colinphaedrus at yahoo.com (crazycga) Date: Fri, 30 Sep 2011 05:02:48 GMT Subject: Motion Tracking with Python References: Message-ID: On Thu, 29 Sep 2011 19:16:52 -0700, Derek Simkowiak wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion > tracking, using the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for > teaching kids how to program." > > I also use Python professionally, and it's worked out great every time. > There's no job Python can't handle. > > > Thanks, > Derek Simkowiak > http://derek.simkowiak.net That is excessively cool dude! You've given me some inspiration for my own programming as a result! Thank you! From ian.g.kelly at gmail.com Fri Sep 30 01:06:27 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 23:06:27 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Thu, Sep 29, 2011 at 4:56 PM, rantingrick wrote: >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) I find it interesting that a self-proclaimed API expert like yourself suggests that it isn't complicated. The documentation on the format specifiers is around 6 1/2 printed pages long, and that's not even including the docs for the string.Formatter API. Devin is right, though, in that a better word for it would be "dense". "Complicated" is not a bad thing here, because with that complexity comes expressiveness. It just means that care needs to be taken when adding new options to ensure that they integrate well with the existing syntax. > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. What makes you think I'm a "format noob"? The details may have evolved over the years, but the format specifiers are fundamentally still the same old printf syntax that we've all been using for decades. From ben+python at benfinney.id.au Fri Sep 30 01:14:27 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 15:14:27 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <8739fe393g.fsf@benfinney.id.au> alex23 writes: > On Sep 29, 10:23?pm, rantingrick wrote: > > GvR should be texting me every night in hopes that some of my API > > genius will rub off on him. > > Are you off your medication again? Please don't make personal attacks. If you don't feel like addressing the content of his message, don't switch to implying he has a mental illness. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but Tuesday Weld isn't a complete sentence.? ?_Pinky and | _o__) The Brain_ | Ben Finney From ben+python at benfinney.id.au Fri Sep 30 01:22:03 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 15:22:03 +1000 Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <4ba4842c-9043-4674-a0d5-5beb915e436b@k10g2000vbn.googlegroups.com> Message-ID: <87y5x61u6c.fsf@benfinney.id.au> alex23 writes: > I always enjoyed the possibly apocryphal claim that the design of VRML > was influenced by the story of Indra's Net. You see, folks? It's by ?mingling in? other aspects of life with technical discussion that we can improve the technical discussion :-) > Maybe some religious tomes are just better? :) They're all flawed, of course, as is any text. But some are wholly dreadful while others have parts worth keeping. -- \ ?Nature hath given men one tongue but two ears, that we may | `\ hear from others twice as much as we speak.? ?Epictetus, | _o__) _Fragments_ | Ben Finney From wuwei23 at gmail.com Fri Sep 30 01:24:44 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 22:24:44 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <8739fe393g.fsf@benfinney.id.au> Message-ID: <4b295504-3fbe-4d9a-b566-d12afad058c5@dd6g2000vbb.googlegroups.com> On Sep 30, 3:14?pm, Ben Finney wrote: > alex23 writes: > > On Sep 29, 10:23?pm, rantingrick wrote: > > > GvR should be texting me every night in hopes that some of my API > > > genius will rub off on him. > > > Are you off your medication again? > > Please don't make personal attacks. If you don't feel like addressing > the content of his message, don't switch to implying he has a mental > illness. Fair enough. It was intended more as a ludicrous accusation to his ridiculous claim. Lord knows there's enough in his posts to focus on without the ad hominems :) From rosuav at gmail.com Fri Sep 30 01:31:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 15:31:24 +1000 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: On Fri, Sep 30, 2011 at 12:16 PM, Derek Simkowiak wrote: > Like I say on the web page: "I?m convinced that Python is the best language > currently available for teaching kids how to program." Agreed. > There's no job Python can't handle. Ehhh... Not agreed. Not quite. Yes it's true in that Python is Turing-complete, but there are a lot of jobs that it can't handle _well_. (Unless someone's seriously considering porting the Linux kernel to Python... or writing a device driver in Python... or writing a MS Word virus in Python...) Right tool for the job! But certainly Python is excellent at many tasks, and it's easy to work with. I wholeheartedly support the sentiment behind your statement, even if I quibble slightly - your statement has accuracy, it merely wants precision :) I'll watch your vid once I'm home from work - it promises to be some pretty cool stuff! ChrisA From wuwei23 at gmail.com Fri Sep 30 01:54:43 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 22:54:43 -0700 (PDT) Subject: Hermeneutics and computer science [was off-topic, now back on] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> <4e8546d3$0$29984$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1e8a3553-75fb-45cc-ab71-998a5406fbcd@m37g2000yqc.googlegroups.com> On Sep 30, 2:34?pm, Steven D'Aprano wrote: > alex23 wrote: > > I'm slowly seeing more and more interest in applying > > a discipline that arose out of the > > study of religious texts. > > Tell us more, please. Well, it's mostly from real world discussions and may actually be an artefact of my holding degrees in both philosophy & computer science :) But googling "hermeneutics computer science" does bring up a heap of entries, although the highest ranked is from 1979, so I may have oversold the idea of it being a growing interest. Amazon also shows that there have been a number of publications dealing with this: http://www.amazon.com/s?ie=UTF8&keywords=Hermeneutics.&rh=n%3A3508%2Ck%3AHermeneutics. For me, the main aspect of hermeneutics that could apply here - to programming especially - is the concept that reading a text informs you for subsequently reinterpreting the text (the "hermeneutic circle" of Heidegger). No philosophical notion of truth is needed to explain this, I see much in common with iterative development processes. Multiplicity of perspective is similarly important in interpretation: again, computer systems are developed with many user roles and thus many 'views' of what is happening. In the interest of fair play, if anyone still smarting at my flippancy wants to take a swing at my belief system, it's mostly cobbled together from Nietzsche, Wittgenstein & Crowley. Personal email preferably, let's keep it off the list unless its particularly witty :) From thebiggestbangtheory at gmail.com Fri Sep 30 02:02:55 2011 From: thebiggestbangtheory at gmail.com (bingbang) Date: Thu, 29 Sep 2011 23:02:55 -0700 (PDT) Subject: Modifying external running process using python Message-ID: <086bd803-ddc5-4913-b1f1-5fb6cb5848bb@i28g2000yqn.googlegroups.com> Hi all, Beginner here. I am trying to figure out how to modify a running process on a linux system using Python. Example: I have a python program that takes in as an argument a PID. My goal is to use this PID and get info about the running process with that PID. (1) Find where it is located in memory (2) Where is the instruction pointer (3) Modify the program such that the next executed instruction is something else (4) Return the pointer back to the next legitimate instruction (5) Let the original process execute as it should have I am trying to develop a POC to show how a small piece of code can be injected into a running process to just print 'hello' to stdout and not disturb the rest of the process. Before you tear you hair out. The program I want to "infect" will be an infinite loop with a sleep in it and the "malware" will be a " print 'infected' " kind of program. Not looking to do anything malicious, just trying to learn. I looked up trace and some other modules but they all seem to do with following the currently executing python process. Also looked at pyhook, but its mainly to trap signals from keyboards etc.. Looked at gray hat python - tuned towards windows. Can anyone please point me to some modules that might be useful, or some code samples. I tried googling for "python inspect process PID" etc.. did not get anything very useful. I know I can run gdb -a pid from within python and such but I am looking for a non os.popen ish kind of a way. Is there a module that will be helpful. Let's assume I have sudo/root privileges and that the POC code "only needs to work in linux". Any help is very appreciated. [Also posted on StackOverflow] - no real good leads from there Thanks! From anikom15 at gmail.com Fri Sep 30 02:14:21 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 23:14:21 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <20110930061421.GA12929@Smoke> On Thu, Sep 29, 2011 at 07:07:28PM -0400, Devin Jeanpierre wrote: > > However, as you use the new format method you will come to appreciate > > it. It's an adult beverage with an acquired taste. ;-) > > Yeah. It's a much more difficult to read thing, but once you learn how > to write it it flows faster. > > Of course, I never managed to learn how to write it... > > I would suggest that rather than being "complicated" it is "dense". > I'm one of the weirdos who is absolutely hostile to the format method and continues to use % formatting. I'm pretty sure it is because of my C background (actually I learned Python before C, and thus learned % formatting in Python). However, I'm not so opposed to it that I've not learned it. It is quite "dense", almost feels like something in a scripting language like Perl. Indeed, I did try it for some time, but it was just too "heavy" and slow for me. Well someday I'll probably be forced to use it, but for anyone else who agrees with me, always know there's at least one Python programmer out there with some (or no) sense. From wuwei23 at gmail.com Fri Sep 30 02:31:50 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 23:31:50 -0700 (PDT) Subject: Motion Tracking with Python References: Message-ID: <75e59668-9002-4614-9fe8-9605e6ecf924@dm9g2000vbb.googlegroups.com> On Sep 30, 12:16?pm, Derek Simkowiak wrote: > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Thank you for sharing this. My daughter is only 20 months at the moment but I definitely hope to teach her coding as she gets older. Cheers. From rosuav at gmail.com Fri Sep 30 02:35:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 16:35:02 +1000 Subject: Suggested coding style In-Reply-To: <20110930061421.GA12929@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <20110930061421.GA12929@Smoke> Message-ID: On Fri, Sep 30, 2011 at 4:14 PM, Westley Mart?nez wrote: > I'm one of the weirdos who is absolutely hostile to the format method > and continues to use % formatting. ?I'm pretty sure it is because of my > C background (actually I learned Python before C, and thus learned % > formatting in Python). I quite like printf-style formatting. It's well known, well defined, and compact. When I write C++ programs, I often still use printf/sprintf extensively - it just "feels nicer" than iostream (and the main downside of printf, the lack of argument checking, is largely solved in recent gcc). So when I work with Python, it makes sense to use the same thing there. Dense syntax results in easy-to-read format strings, imho. ChrisA From wuwei23 at gmail.com Fri Sep 30 02:39:29 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 23:39:29 -0700 (PDT) Subject: Motion Tracking with Python References: <4E852694.4080303@simkowiak.net> Message-ID: On Sep 30, 3:31?pm, Chris Angelico wrote: > Unless someone's seriously considering porting the Linux > kernel to Python... Well, they've certainly asked: http://bytes.com/topic/python/answers/37048-reimplenting-linux-kernel-python And while not Linux kernels, there are two projects attempting to develop Python-implemented OSes: http://code.google.com/p/cleese/ http://unununium.org > or writing a device driver in Python... http://www.stealth-x.com/programming/driver-writing-with-python.php > or writing a MS Word virus in Python... Now that's just crazy talk. From subhagurgaon2011 at gmail.com Fri Sep 30 02:43:13 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 23:43:13 -0700 (PDT) Subject: Question on Manipulating List and on Python References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: On Sep 30, 12:52?am, "Prasad, Ramit" wrote: > -----Original Message----- > From: python-list-bounces+ramit.prasad=jpmorgan.... at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.... at python.org] On Behalf Of Chris Angelico > Sent: Thursday, September 29, 2011 11:51 AM > To: python-l... at python.org > Subject: Re: Question on Manipulating List and on Python > > On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee > wrote: > > And Python seems faster than C++/Java. It is indeed. I also experience > > it. > > Python compared to Java? Difficult to compare. Python to C++? > Impossible to compare. But performance depends MASSIVELY on > algorithmic quality; if you code the exact same thing in Python and in > C++, you would probably find that the C++ one is faster, but chances > are you're implementing approximately the same thing in two quite > different ways. Or possibly you're using a slow and inefficient > library or third-party function. > > I've sometimes written code in one language and directly ported it to > another, and then run both on the same hardware. With most such > experiments, CPython generally doesn't perform all that well, and C or > C++ rocks. But frequently, the C/C++ code is more verbose and more > error-prone than the Python - because Python's biggest boast is not > that it's fast, but that it's *fast enough*, while being easy to work > with. (And every once in a while there's something where I want to use > a pointer to some other variable, and that's a concept that just plain > doesn't work in Python. You have references to objects, but you can't > from one place change another variable, without using some kind of > mutable object that they both reference.) > ----------------------------------------------------------------------- > > I think Steven D'Aprano had an excellent post on this a week or so ago (on the tutor list, not this one). > > See:http://mail.python.org/pipermail/tutor/2011-September/085573.html > > Ramit > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > ChrisA > --http://mail.python.org/mailman/listinfo/python-list > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available athttp://www.jpmorgan.com/pages/disclosures/email. ? > > Dear Group, Thanks for your suggestions. I'll check if these work. Converting to dictionary I was thinking but others I have to test. Without patting my own back(I do not write algorithms that good), I can say Python is indeed damn fast. A reason many of my friends are shifting fast to Python and I was suggested by a reputed person of MIT CogLab to use Python instead of C++ and it worked just fabulous for me. To my collegue I would find out an answer. Regards, Subhabrata. From rustompmody at gmail.com Fri Sep 30 03:24:30 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 00:24:30 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> On Sep 30, 4:03?am, Devin Jeanpierre wrote: > > But anyway, no, we don't agree on what it means to be friendly or what > a hostile atmosphere is. I've noticed that people tend to be a lot > harsher here than what I'm used to, so perhaps your attitude to it is > more common on mailing-lists and I should just adapt. A Mulla Nasruddin story comes to mind: The judge in a village court had gone on vacation. Nasrudin was asked to be temporary judge for a day. Mulla sat on the Judge's chair and ordered the first case to be brought up for hearing. "You are right," said Nasrudin after carefully hearing one side. "You are right," he said after carefully hearing the other side. "But both cannot be right!" said the court clerk bewildered. After profound thought said the Mulla: "You are right" From rosuav at gmail.com Fri Sep 30 03:52:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 17:52:42 +1000 Subject: Benefit and belief In-Reply-To: <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 5:24 PM, rusi wrote: > "You are right," said Nasrudin after carefully hearing one side. > "You are right," he said after carefully hearing the other side. > "But both cannot be right!" said the court clerk bewildered. > After profound thought said the Mulla: > > ?"You are right" > And I am right, and you are right, and all is right as right can be! -- Pish-Tush, a Japanese nobleman in service of /The Mikado/ Chris Angelico From rosuav at gmail.com Fri Sep 30 03:57:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 17:57:12 +1000 Subject: Motion Tracking with Python In-Reply-To: References: <4E852694.4080303@simkowiak.net> Message-ID: On Fri, Sep 30, 2011 at 4:39 PM, alex23 wrote: >> or writing a MS Word virus in Python... > > Now that's just crazy talk. > ... and I thought all three were. You know what they say - truth is stranger than fiction, because fiction has to make sense! Although the device driver example you cite is still ring-3 code, and the Linux kernel is still in C. I like the idea of a special OS written in Python though; it wouldn't be Linux, but it could well be an excellent embedded-device OS. It'd probably end up having to reinvent all sorts of facilities like process isolation and such, though. ChrisA From ovidiudeac at gmail.com Fri Sep 30 05:10:48 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:10:48 +0300 Subject: regexp compilation error Message-ID: I have the following regexp which fails to compile. Can somebody explain why? >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat Is this a bug or a feature? Thanks, Ovidiu From moky.math at gmail.com Fri Sep 30 05:13:14 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 30 Sep 2011 11:13:14 +0200 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E85882A.6010602@gmail.com> > The keys of globals() are the _names_. You're giving it the function > itself. Ow, ok. I didn't caught it. I understand now. > A decorator would be better. Yes. I keep the solution with foo=Wraper(foo) Thanks a lot all ! Laurent From moky.math at gmail.com Fri Sep 30 05:13:14 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 30 Sep 2011 11:13:14 +0200 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E85882A.6010602@gmail.com> > The keys of globals() are the _names_. You're giving it the function > itself. Ow, ok. I didn't caught it. I understand now. > A decorator would be better. Yes. I keep the solution with foo=Wraper(foo) Thanks a lot all ! Laurent From rosuav at gmail.com Fri Sep 30 05:18:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 19:18:43 +1000 Subject: regexp compilation error In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 7:10 PM, Ovidiu Deac wrote: > I have the following regexp which fails to compile. Can somebody explain why? > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.6/re.py", line 190, in compile > ? ?return _compile(pattern, flags) > ?File "/usr/lib/python2.6/re.py", line 245, in _compile > ? ?raise error, v # invalid expression > sre_constants.error: nothing to repeat > > Is this a bug or a feature? What version of Python are you using? It looks like you're running in a Python 3 interpreter, and loading a Python 2 module (as shown by the python2.6 in the path and the Python 2 error-raise syntax). You may have a problem with your module path. Running that line of code in Python 3.2 for Windows produces this error: >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in re.compile(r"""^(?: [^y]* )*""", re.X) File "C:\Python32\lib\re.py", line 206, in compile return _compile(pattern, flags) File "C:\Python32\lib\re.py", line 256, in _compile return _compile_typed(type(pattern), pattern, flags) File "C:\Python32\lib\functools.py", line 180, in wrapper result = user_function(*args, **kwds) File "C:\Python32\lib\re.py", line 268, in _compile_typed return sre_compile.compile(pattern, flags) File "C:\Python32\lib\sre_compile.py", line 495, in compile code = _code(p, flags) File "C:\Python32\lib\sre_compile.py", line 480, in _code _compile(code, p.data, flags) File "C:\Python32\lib\sre_compile.py", line 74, in _compile elif _simple(av) and op is not REPEAT: File "C:\Python32\lib\sre_compile.py", line 359, in _simple raise error("nothing to repeat") sre_constants.error: nothing to repeat Does that help at all? ChrisA From ovidiudeac at gmail.com Fri Sep 30 05:26:52 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:26:52 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: $ python --version Python 2.6.6 On Fri, Sep 30, 2011 at 12:18 PM, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 7:10 PM, Ovidiu Deac wrote: >> I have the following regexp which fails to compile. Can somebody explain why? >> >>>>> re.compile(r"""^(?: [^y]* )*""", re.X) >> Traceback (most recent call last): >> ?File "", line 1, in >> ?File "/usr/lib/python2.6/re.py", line 190, in compile >> ? ?return _compile(pattern, flags) >> ?File "/usr/lib/python2.6/re.py", line 245, in _compile >> ? ?raise error, v # invalid expression >> sre_constants.error: nothing to repeat >> >> Is this a bug or a feature? > > What version of Python are you using? It looks like you're running in > a Python 3 interpreter, and loading a Python 2 module (as shown by the > python2.6 in the path and the Python 2 error-raise syntax). You may > have a problem with your module path. > > Running that line of code in Python 3.2 for Windows produces this error: > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ? ?re.compile(r"""^(?: [^y]* )*""", re.X) > ?File "C:\Python32\lib\re.py", line 206, in compile > ? ?return _compile(pattern, flags) > ?File "C:\Python32\lib\re.py", line 256, in _compile > ? ?return _compile_typed(type(pattern), pattern, flags) > ?File "C:\Python32\lib\functools.py", line 180, in wrapper > ? ?result = user_function(*args, **kwds) > ?File "C:\Python32\lib\re.py", line 268, in _compile_typed > ? ?return sre_compile.compile(pattern, flags) > ?File "C:\Python32\lib\sre_compile.py", line 495, in compile > ? ?code = _code(p, flags) > ?File "C:\Python32\lib\sre_compile.py", line 480, in _code > ? ?_compile(code, p.data, flags) > ?File "C:\Python32\lib\sre_compile.py", line 74, in _compile > ? ?elif _simple(av) and op is not REPEAT: > ?File "C:\Python32\lib\sre_compile.py", line 359, in _simple > ? ?raise error("nothing to repeat") > sre_constants.error: nothing to repeat > > Does that help at all? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Fri Sep 30 05:29:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 19:29:50 +1000 Subject: regexp compilation error In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: > $ python --version > Python 2.6.6 Ah, I think I was misinterpreting the traceback. You do actually have a useful message there; it's the same error that my Py3.2 produced: sre_constants.error: nothing to repeat I'm not sure what your regex is trying to do, but the problem seems to be connected with the * at the end of the pattern. ChrisA From 1248283536 at qq.com Fri Sep 30 05:35:37 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 30 Sep 2011 17:35:37 +0800 Subject: =?gbk?B?u9i4tKO6IGhvdyB0byBydW4gaW4geHA/?= Message-ID: the command : 2to3-3.2 getcode3.py -w can run in linux it can't run in window xp,can i make it in window xp? ------------------ ???? ------------------ ???: "1248283536"<1248283536 at qq.com>; ????: 2011?9?28?(???) ??7:50 ???: "Peter Otten"<__peter__ at web.de>; "python-list"; ??: Re: how to run in xp? it can run ,but there is still a problem ,nothing in my file. please run the code in xp+python32 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() print (file) what you get is: >>> b'' b'' b'' >>> how to fix it? ------------------ Original ------------------ From: "Peter Otten"<__peter__ at web.de>; Date: Wed, Sep 28, 2011 04:04 PM To: "python-list"; Subject: Re: how to run in xp? =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ovidiudeac at gmail.com Fri Sep 30 05:57:25 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:57:25 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: This is only part of a regex taken from an old perl application which we are trying to understand/port to our new Python implementation. The original regex was considerably more complex and it didn't compile in python so I removed all the parts I could in order to isolate the problem such that I can ask help here. So the problem is that this regex doesn't compile. On the other hand I'm not really sure it should. It's an anchor on which you apply *. I'm not sure if this is legal. On the other hand if I remove one of the * it compiles. >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat >>> re.compile(r"""^(?: [^y] )*""", re.X) <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>> re.compile(r"""^(?: [^y]* )""", re.X) <_sre.SRE_Pattern object at 0x7f4069cc3730> Is this a bug in python regex engine? Or maybe some incompatibility with Perl? On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >> $ python --version >> Python 2.6.6 > > Ah, I think I was misinterpreting the traceback. You do actually have > a useful message there; it's the same error that my Py3.2 produced: > > sre_constants.error: nothing to repeat > > I'm not sure what your regex is trying to do, but the problem seems to > be connected with the * at the end of the pattern. > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Fri Sep 30 08:06:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 22:06:43 +1000 Subject: regexp compilation error References: Message-ID: <4e85b0d3$0$29975$c3e8da3$5496439d@news.astraweb.com> Ovidiu Deac wrote: >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/re.py", line 190, in compile > return _compile(pattern, flags) > File "/usr/lib/python2.6/re.py", line 245, in _compile > raise error, v # invalid expression > sre_constants.error: nothing to repeat >>>> re.compile(r"""^(?: [^y] )*""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>> re.compile(r"""^(?: [^y]* )""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc3730> > > Is this a bug in python regex engine? Or maybe some incompatibility with > Perl? Before asking whether it is a bug, perhaps you should consider what (if anything) that regex is supposed to actually do. Perhaps you should post the Perl equivalent, and some examples of it in use. -- Steven From hansmu at xs4all.nl Fri Sep 30 08:12:12 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 30 Sep 2011 14:12:12 +0200 Subject: regexp compilation error In-Reply-To: References: Message-ID: <4e85b21c$0$2444$e4fe514c@news2.news.xs4all.nl> On 30/09/11 11:10:48, Ovidiu Deac wrote: > I have the following regexp which fails to compile. Can somebody explain why? > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) [...] > sre_constants.error: nothing to repeat > > Is this a bug or a feature? A feature: the message explains why this pattern is not allowed. The sub-pattern (?: [^y]* ) matches zero or more non-'y's, so it potentially matches the empty string. It you were allowed to apply '*' to such a sub-pattern, the matcher could go into an infinite loop, finding billions of matching empty strings, one after the other. I'm not sure what you are trying to match, but for zero-or-more not-'y's, you could write r"^[^y]*". This is guaranteed to always match, since there are always at least zero of them. You might as well write r"^", that is also guaranteed to always match. What are you trying to achieve? -- HansM From neilc at norwich.edu Fri Sep 30 08:15:33 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 12:15:33 GMT Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> Message-ID: <9elq75Fh5cU1@mid.individual.net> On 2011-09-30, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 5:24 PM, rusi wrote: >> "You are right," said Nasrudin after carefully hearing one side. >> "You are right," he said after carefully hearing the other side. >> "But both cannot be right!" said the court clerk bewildered. >> After profound thought said the Mulla: >> >> ?"You are right" >> > > And I am right, and you are right, and all is right as right can be! > -- Pish-Tush, a Japanese nobleman in service of /The Mikado/ Never has being right, proper and correct been so thoroughly celebrated. Except perhaps when my C++ program compiles without warnings. That's pretty good, too. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From 1248283536 at qq.com Fri Sep 30 08:36:57 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 30 Sep 2011 20:36:57 +0800 Subject: parse xml Message-ID: please click the http://www.secinfo.com/d14qfp.q9j.htm then ,click the following: 44: XML IDEA: Condensed Consolidating Statements of Income XML 5.11M (Details)--R158 there is the citigroup's annual financial report --statements of income,xml file. how can i get a table of statements of income in python ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Fri Sep 30 08:40:33 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 30 Sep 2011 08:40:33 -0400 Subject: [OT] Benefit and belief In-Reply-To: <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: > If you are more upset at my describing the Catholic Church as protecting > child molesters than you are at the Church for actually protecting child > molesters I'm not, and your rhetoric is ridiculous. Devin On Thu, Sep 29, 2011 at 11:10 PM, Steven D'Aprano wrote: > Devin Jeanpierre wrote: > >> I also didn't reprimand anyone, except maybe Steven. > > If you are more upset at my describing the Catholic Church as protecting > child molesters than you are at the Church for actually protecting child > molesters, then your priorities are completely screwed up and your > reprimand means less than nothing to me. I wear it as a badge of honour. > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From rantingrick at gmail.com Fri Sep 30 09:54:25 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 06:54:25 -0700 (PDT) Subject: Suggested coding style References: Message-ID: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Note: I am quoting "Passiday" to get this thread back on subject however my reply is for "alex23" the philosopher" On Sep 29, 9:50?pm, alex23 wrote: > On Sep 29, 10:23?pm, rantingrick wrote: > > > What is so bad about breaking code in obscure places? > > Try coding in PHP across minor release versions and see how you feel > about deprecating core functions on a whim. I never said we should remove it now, i said we should deprecate it now. > > We changed print > > to a function which broke just about every piece of code every written > > in this language. > > In a well declared _break_ with backwards compatibility. Not on a whim > between minor releases. Please Google deprecate. > > What is so bad then about breaking some very obscure code? > > Because while you say "some very obscure code", what you really mean > is "code that isn't mine". Well "alex" i can't see a mob approaching with pitchforks because we deprecate a misplaced and rarely used functionality of the stdlib. > As you have no access > to the inner states of _any_ of the people you regularly condemn here > with your hypocritical attacks, I've no idea why you consider yourself > to be an expert on their desires and opinions. Well "alex", like yourself, i hold expertise in many fields BESIDES programming. One of which being psychology. From vlastimil.brom at gmail.com Fri Sep 30 09:56:20 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 30 Sep 2011 15:56:20 +0200 Subject: regexp compilation error In-Reply-To: References: Message-ID: 2011/9/30 Ovidiu Deac : > This is only part of a regex taken from an old perl application which > we are trying to understand/port to our new Python implementation. > > The original regex was considerably more complex and it didn't compile > in python so I removed all the parts I could in order to isolate the > problem such that I can ask help here. > > So the problem is that this regex doesn't compile. On the other hand > I'm not really sure it should. It's an anchor on which you apply *. > I'm not sure if this is legal. > > On the other hand if I remove one of the * it compiles. > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.6/re.py", line 190, in compile > ? ?return _compile(pattern, flags) > ?File "/usr/lib/python2.6/re.py", line 245, in _compile > ? ?raise error, v # invalid expression > sre_constants.error: nothing to repeat >>>> re.compile(r"""^(?: [^y] )*""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>> re.compile(r"""^(?: [^y]* )""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc3730> > > Is this a bug in python regex engine? Or maybe some incompatibility with Perl? > > On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: >> On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >>> $ python --version >>> Python 2.6.6 >> >> Ah, I think I was misinterpreting the traceback. You do actually have >> a useful message there; it's the same error that my Py3.2 produced: >> >> sre_constants.error: nothing to repeat >> >> I'm not sure what your regex is trying to do, but the problem seems to >> be connected with the * at the end of the pattern. >> >> ChrisA >> -- I believe, this is a limitation of the builtin re engine concerning nested infinite quantifiers - (...*)* - in your pattern. You can try a more powerful recent regex implementation, which appears to handle it: http://pypi.python.org/pypi/regex using the VERBOSE flag - re.X all (unescaped) whitespace outside of character classes is ignored, http://docs.python.org/library/re.html#re.VERBOSE the pattern should be equivalent to: r"^(?:[^y]*)*" ie. you are not actually gaining anything with double quantifier, as there isn't anything "real" in the pattern outside [^y]* It appears, that you have oversimplified the pattern (if it had worked in the original app), however, you may simply try with import regex as re and see, if it helps. Cf: >>> >>> regex.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) ['a bcd e'] >>> re.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) Traceback (most recent call last): File "", line 1, in File "re.pyc", line 177, in findall File "re.pyc", line 244, in _compile error: nothing to repeat >>> >>> re.findall(r"^(?:[^y]*)*", "a bcd e") Traceback (most recent call last): File "", line 1, in File "re.pyc", line 177, in findall File "re.pyc", line 244, in _compile error: nothing to repeat >>> regex.findall(r"^(?:[^y]*)*", "a bcd e") ['a bcd e'] >>> regex.findall(r"^[^y]*", "a bcd e") ['a bcd e'] >>> hth, vbr From devplayer at gmail.com Fri Sep 30 09:57:17 2011 From: devplayer at gmail.com (DevPlayer) Date: Fri, 30 Sep 2011 06:57:17 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <87mxdn2fwl.fsf@benfinney.id.au> Message-ID: <60c608a5-5f56-4949-806f-f68ff2510fb0@j1g2000yqj.googlegroups.com> from attitude import humour Funny. url link to gif. Funny. Youtube video. Funny. True Pythonees do not speak in English they speak in Python. Shame, this discussion will be sent to the Pearly gates or the Flaming Iron Bars in 5 days. Well, not so much a shame. From rantingrick at gmail.com Fri Sep 30 09:58:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 06:58:36 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> Message-ID: <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> On Sep 29, 10:05?pm, alex23 wrote: > On Sep 30, 9:37?am, MRAB wrote: > > alex23: > > """And like the Bible, the Zen was created by humans as a joke. If you're > > taking it too seriously, that's your problem.""" > > Strangely, calling the bible self-contradictory wasn't seen as > inflammatory... For the same reason that telling the truth is not slander. The fact is that the Bible IS contradictory with itself. However, your opinion unlike my facts, were full of vile hatred. Nice try attempting to shift the mob against me. From rick.mansilla at gmail.com Fri Sep 30 10:06:42 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Fri, 30 Sep 2011 09:06:42 -0500 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: <201109300906.43128.rick.mansilla@gmail.com> On Thursday 29 September 2011 21:16:52 you wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion > tracking, using the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for > teaching kids how to program." > > I also use Python professionally, and it's worked out great every time. > There's no job Python can't handle. > > > Thanks, > Derek Simkowiak > http://derek.simkowiak.net Hi, this is awesome!! I'm currently working in something similar, but I am having problems with getting data from the CCD (basically i don't know how to do it :), can you give me a tip for doing this? Or explain how you did it please? I not a newbie at python but not as experienced as evidently you are. Thanks a lot in advance. -- (...)Also, since that same law states that any system able to prove its consistency to itself must be inconsistent; any mind that believes it can prove its own sanity is, therefore, insane.(...) Kurt G?del. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Fri Sep 30 10:19:20 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 07:19:20 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> Message-ID: <7d5a7284-6f73-42f7-9386-14cb5e6e69b2@z8g2000yqb.googlegroups.com> On Sep 29, 11:49?pm, Ian Kelly wrote: > Nope, that doesn't work. > > >>> "{0:0>10}".format("-1234") > > '00000-1234' > > The whole point of zfill is that it handles signs correctly. py> "{0:-010d}".format(-1234) '-000001234' My point was: Use the {char}{repeat}d format for integers and the {char}{<|>|=}{repeat} for strings. Problem solved. No more need for zfill. py> "{0:0>10}".format(-1234) '00000-1234' What result would you expect from that string argument? I think it behaves as anyone would expect. If you have a str and you want it interpreted as a negative integer then cast it. py> "{0:010d}".format(int("-1234")) '-000001234' If you would like for the spec to handle the case of integers and strings transparently then you need to lobby to have the API changed. Maybe they could add a !i like the !s and !r which would be explicit. However, i don't think implicit coercion of strings to integers is a good idea. Using the int function or !i removes and ambiguities. For me, the spec works just fine as is. From rosuav at gmail.com Fri Sep 30 10:43:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 00:43:15 +1000 Subject: Suggested coding style In-Reply-To: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 11:54 PM, rantingrick wrote: > Well "alex", like yourself, i hold expertise in many fields BESIDES > programming. One of which being psychology. > I *knew* it! We're all part of a huge experiment to see how much the human psyche can withstand. If we succeed on the Rick test, do we "level up" and get a second troll to deal with, or is this MST3K-style eternity? ChrisA From devplayer at gmail.com Fri Sep 30 10:59:27 2011 From: devplayer at gmail.com (DevPlayer) Date: Fri, 30 Sep 2011 07:59:27 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: I still assert that contradiction is caused by narrow perspective. By that I mean: just because an objects scope may not see a certain condition, doesn't mean that condition is non-existant. I also propose that just because something seems to contradict doesn't mean it is false. Take for instance: Look out your window. Is it daylight or night time? You may say it is daylight or you may say it is night time. I would disagree that only one of those conditions are true. Both conditions are true. Always. It is only day (or night) for YOU. But the opposite DOES in fact exist on the other side of the world at the same time. I call this Duality of Nature (and I believe there was some religion somewhere in some time that has the same notion, Budism I think but I could be mistaken). I see such "contradictions" in what appears to be most truths. If I am correct; not sure here; but I think that is part of the new math Choas theory. (The notion that not all variables are known and the results of well defined functions may result in completely different actual outcomes) [Missing variables in such data sets and functions, to me is basically a narrow(er) perspective of the all the revelent factors for such computations.] You could think of this in terms of classes and attributes if you want. Just because an object does not see an attribute, like "has_ connection", doesn't mean the app doesn't have a connection to the server, just that that object doesn't have access to the existance of that attribute, because it is not in scope (ie narrow perspective). I propose that if something seems to contradict itself, that that doesnt' invalidate its value outright. It -could- invalidate its value, but doesn't guarentee no value. How this matters to coding style? No connection visible. It's just a proposed notion. From breamoreboy at yahoo.co.uk Fri Sep 30 11:51:37 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 30 Sep 2011 08:51:37 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> <42df7e77-44ab-405e-9c60-8f394e3e5628@d17g2000yqa.googlegroups.com> Message-ID: <9b034444-a387-4f73-9c0c-08c159cd3017@dm9g2000vbb.googlegroups.com> On Sep 29, 2:59?am, rantingrick wrote: > On Sep 27, 11:25?pm, Steven D'Aprano > +comp.lang.pyt... at pearwood.info> wrote: > > The Python development team is relatively small and chronically busy: too > > much to do and not enough time to do it. > > If that is the case then why do they snub their noses at anyone who > wishes to help? What kind of people would chase off good help just to > save ego? I imagine the folks at py dev sort of like a dying man in > need of a heart transplant; the man informs the doctor that he would > happy to get a transplant but not if the heart came from a jew, asian, > african, latin, russian, or canuck. For the uninitiated, rr is to Python what King Herod was to baby sitting. (With apologies to Tommy Docherty) From neilc at norwich.edu Fri Sep 30 11:58:24 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 15:58:24 GMT Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <9em790Fnj9U1@mid.individual.net> On 2011-09-30, DevPlayer wrote: > I still assert that contradiction is caused by narrow perspective. > > By that I mean: just because an objects scope may not see a certain > condition, doesn't mean that condition is non-existant. > > I also propose that just because something seems to contradict doesn't > mean it is false. Take for instance: > > Look out your window. Is it daylight or night time? You may say > it is daylight or you may say it is night time. I would > disagree that only one of those conditions are true. Both > conditions are true. Always. It is only day (or night) for YOU. > But the opposite DOES in fact exist on the other side of the > world at the same time. > > I call this Duality of Nature (and I believe there was some > religion somewhere in some time that has the same notion, > Budism I think but I could be mistaken). I see such > "contradictions" in what appears to be most truths. You are not alone. Many ancient philosophers, fathers of religious and scientific thought, thought the same. They thought that contradictory qualities could exist in objects simultaneously. For example, they thought that a cat was both big and small, because it was big compared to a mouse and small compared to a house. They didn't notice that big and small were not poperties of the cat, at all but were instead statements about how a cat relates to another object. When you say, "It is night," you are making an assertion about a position on the surface of the earth and its relationship to the sun. If you are not discussing a specific a position on the Earth, then you cannot make a meaningful assertion about night or day at all. Night and Day are not qualities of the entire Earth, but only of positions on the Earth. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From ramit.prasad at jpmorgan.com Fri Sep 30 12:06:19 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 12:06:19 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> >May I suggest a[n] email client that can group mailing list threads? Please do. Bonus points if it handles threading in a Gmail-like style. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Devin Jeanpierre Sent: Thursday, September 29, 2011 6:07 PM To: rantingrick Cc: python-list at python.org Subject: Re: Suggested coding style > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) Yeah. It's a much more difficult to read thing, but once you learn how to write it it flows faster. Of course, I never managed to learn how to write it... I would suggest that rather than being "complicated" it is "dense". > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. Devin On Thu, Sep 29, 2011 at 6:56 PM, rantingrick wrote: > On Sep 29, 5:12?pm, Ian Kelly wrote: >> On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: >> > A specific method for padding a string with ONLY zeros is ludicrous >> > and exposes the narrow mindedness of the creator. The only thing worse >> > than "zfill" as a string method is making zfill into built-in >> > function! The ONLY proper place for zfill is as an option in the >> > str.format() method. >> >> > py> "{0:zf10}".format(1234) -> "00000000001234" >> >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) > > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. > > But i wholeheartedly agree with you points and i would say the zfill > method has no future uses in the stdlib except for historical reasons. > We should deprecate it now. > > >> "{0:=010d}".format(1234) -> "0000001234" >> >> There are a couple of warts with the existing implementation, however: >> >> 1) str.zfill() operates on strings; the .format() syntax operates on >> numeric types. ?I would suggest that the "=" fill alignment in format >> specifiers should be extended to do the same thing as zfill when given >> a string. > > EXACTLY! > > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rustompmody at gmail.com Fri Sep 30 12:22:59 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 09:22:59 -0700 (PDT) Subject: Benefit and belief References: <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> Message-ID: <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> On Sep 30, 8:58?pm, Neil Cerutti wrote: > On 2011-09-30, DevPlayer wrote: > > > > > I still assert that contradiction is caused by narrow perspective. > > > By that I mean: just because an objects scope may not see a certain > > condition, doesn't mean that condition is non-existant. > > > I also propose that just because something seems to contradict doesn't > > mean it is false. Take for instance: > > > Look out your window. Is it daylight or night time? You may say > > it is daylight or you may say it is night time. I would > > disagree that only one of those conditions are true. Both > > conditions are true. Always. It is only day (or night) for YOU. > > But the opposite DOES in fact exist on the other side of the > > world at the same time. > > > I call this Duality of Nature (and I believe there was some > > religion somewhere in some time that has the same notion, > > Budism I think but I could be mistaken). I see such > > "contradictions" in what appears to be most truths. > > You are not alone. Many ancient philosophers, fathers of > religious and scientific thought, thought the same. > > They thought that contradictory qualities could exist in objects > simultaneously. For example, they thought that a cat was both big > and small, because it was big compared to a mouse and small > compared to a house. They didn't notice that big and small were > not poperties of the cat, at all but were instead statements > about how a cat relates to another object. > > When you say, "It is night," you are making an assertion about a > position on the surface of the earth and its relationship to the > sun. > > If you are not discussing a specific a position on the Earth, > then you cannot make a meaningful assertion about night or day at > all. Night and Day are not qualities of the entire Earth, but > only of positions on the Earth. But just imagine that we were all pre-galiliean savages -- knowing nothing about the roundness of the earth, the earth going round and so on and somehow you and I get on the phone and we start arguing: Rusi: Its 9:30 pm Neil: No its 12 noon How many cases are there? We both may be right, I may be wrong (my watch may have stopped) or we both etc ie conflicting data may get resolved within a larger world view (which is what devplayer is probably saying). Until then it is wiser to assume that that larger world view exists (and I dont yet know it) than to assume that since I dont know it it does not exist. For me (admittedly an oriental) such agnosticism (literally "I-do-not- know-ness") is as much a foundation for true religiosity as effective science. From anikom15 at gmail.com Fri Sep 30 12:36:38 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 30 Sep 2011 09:36:38 -0700 Subject: Benefit and belief In-Reply-To: <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: <20110930163638.GA13519@Smoke> On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > On Sep 30, 8:58?pm, Neil Cerutti wrote: > > On 2011-09-30, DevPlayer wrote: > > > > > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > By that I mean: just because an objects scope may not see a certain > > > condition, doesn't mean that condition is non-existant. > > > > > I also propose that just because something seems to contradict doesn't > > > mean it is false. Take for instance: > > > > > Look out your window. Is it daylight or night time? You may say > > > it is daylight or you may say it is night time. I would > > > disagree that only one of those conditions are true. Both > > > conditions are true. Always. It is only day (or night) for YOU. > > > But the opposite DOES in fact exist on the other side of the > > > world at the same time. > > > > > I call this Duality of Nature (and I believe there was some > > > religion somewhere in some time that has the same notion, > > > Budism I think but I could be mistaken). I see such > > > "contradictions" in what appears to be most truths. > > > > You are not alone. Many ancient philosophers, fathers of > > religious and scientific thought, thought the same. > > > > They thought that contradictory qualities could exist in objects > > simultaneously. For example, they thought that a cat was both big > > and small, because it was big compared to a mouse and small > > compared to a house. They didn't notice that big and small were > > not poperties of the cat, at all but were instead statements > > about how a cat relates to another object. > > > > When you say, "It is night," you are making an assertion about a > > position on the surface of the earth and its relationship to the > > sun. > > > > If you are not discussing a specific a position on the Earth, > > then you cannot make a meaningful assertion about night or day at > > all. Night and Day are not qualities of the entire Earth, but > > only of positions on the Earth. > > But just imagine that we were all pre-galiliean savages -- knowing > nothing about the roundness of the earth, the earth going round and so > on and somehow you and I get on the phone and we start arguing: > Rusi: Its 9:30 pm > Neil: No its 12 noon > > How many cases are there? > We both may be right, I may be wrong (my watch may have stopped) or we > both etc > > ie conflicting data may get resolved within a larger world view (which > is what devplayer is probably saying). > > Until then it is wiser to assume that that larger world view exists > (and I dont yet know it) > than to assume that since I dont know it it does not exist. > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > know-ness") is as much a foundation for true religiosity as effective > science I.e. humility? From irmen.NOSPAM at xs4all.nl Fri Sep 30 12:40:32 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 30 Sep 2011 18:40:32 +0200 Subject: Motion Tracking with Python In-Reply-To: References: Message-ID: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> On 30-9-2011 4:16, Derek Simkowiak wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion tracking, using > the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this project. We used > it to track her two pet gerbils, as part of her science fair project. She wrote her own > (separate) Python script to read the motion tracking log files, compute distance and > velocity, and then export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for teaching kids how to > program." Wow. Very impressive and very enjoyable to read about it. How was her project received at school? Thanks a lot for sharing this. Irmen de Jong From ladasky at my-deja.com Fri Sep 30 12:40:46 2011 From: ladasky at my-deja.com (John Ladasky) Date: Fri, 30 Sep 2011 09:40:46 -0700 (PDT) Subject: Simplest way to resize an image-like array Message-ID: Hi folks, I have 500 x 500 arrays of floats, representing 2D "grayscale" images, that I need to resample at a lower spatial resolution, say, 120 x 120 (details to follow, if you feel they are relevant). I've got the numpy, and scipy, and matplotlib. All of these packages hint at the fact that they have the capability to resample an image- like array. But after reading the documentation for all of these packages, none of them make it straightforward, which surprises me. For example, there are several spline and interpolation methods in scipy.interpolate. They seem to return interpolator classes rather than arrays. Is there no simple method which then calls the interpolator, and builds the resampled array? Yes, I can do this myself if I must -- but over the years, I've come to learn that a lot of the code I want is already written, and that sometimes I just have to know where to look for it. Thanks! From rosuav at gmail.com Fri Sep 30 12:41:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 02:41:30 +1000 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: > ? ? ? ?And I would argue that by starting with "Look out your window..." > you have explicitly excluded the rest of the world from consideration in > answering; you have narrowed the focus to only the region visible from > "my window". > But what if I'm a great windowing magnate, owning windows all over the world? (Is anyone else amused by this thread and its ridiculosity?) ChrisA From rustompmody at gmail.com Fri Sep 30 12:49:21 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 09:49:21 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: On Sep 30, 9:41?pm, Chris Angelico wrote: > On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: > > > ? ? ? ?And I would argue that by starting with "Look out your window..." > > you have explicitly excluded the rest of the world from consideration in > > answering; you have narrowed the focus to only the region visible from > > "my window". > > But what if I'm a great windowing magnate, owning windows all over the world? > > (Is anyone else amused by this thread and its ridiculosity?) > > ChrisA Not more ridiculous than people getting religious over not just about silly (man-made) languages but even over the editors they use From ramit.prasad at jpmorgan.com Fri Sep 30 12:56:46 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 12:56:46 -0400 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677B6@EMARC112VS01.exchad.jpmchase.net> >I didn't say it would be on-topic. But we don't cease to be well-rounded >human beings with concerns beyond the narrow world of Python programming >just because we are writing on a programming forum. Everything is on topic to programmers! To (mis)quote Sheldon Cooper: "I'm a [programmer]. I have a working knowledge of the entire universe and everything it contains." Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Fri Sep 30 12:59:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 02:59:31 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Sat, Oct 1, 2011 at 2:06 AM, Prasad, Ramit wrote: >>May I suggest a[n] email client that can group mailing list threads? > > Please do. Bonus points if it handles threading in a Gmail-like style. > May I suggest Gmail? It handles threading in a very Gmail-like style. ChrisA running and ducking From ramit.prasad at jpmorgan.com Fri Sep 30 13:05:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:05:27 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> >> Please do. Bonus points if it handles threading in a Gmail-like style. >> > >May I suggest Gmail? It handles threading in a very Gmail-like style. Curses, foiled by my lack of specificity! I meant desktop client. Although...if another website does similar threading it would be good to know. Never know when I will want to start avoiding Gmail :) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Fri Sep 30 13:10:32 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 30 Sep 2011 10:10:32 -0700 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <4E85F808.9040100@stoneleaf.us> rusi wrote: > On Sep 30, 9:41 pm, Chris Angelico wrote: >> On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: >> >>> And I would argue that by starting with "Look out your window..." >>> you have explicitly excluded the rest of the world from consideration in >>> answering; you have narrowed the focus to only the region visible from >>> "my window". >> But what if I'm a great windowing magnate, owning windows all over the world? >> >> (Is anyone else amused by this thread and its ridiculosity?) >> >> ChrisA > > Not more ridiculous than people getting religious over not just about > silly (man-made) languages but even over the editors they use No kidding! Vim is *obviously* the best one out there! *ducks and runs* ~Ethan~ From paul.nospam at rudin.co.uk Fri Sep 30 13:11:36 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 30 Sep 2011 18:11:36 +0100 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> "Prasad, Ramit" writes: >>May I suggest a[n] email client that can group mailing list threads? > > Please do. Bonus points if it handles threading in a Gmail-like style. The answer to any news/mail client with feature X type question is normally "gnus" - although I don't know what "Gmail-like style" is. From rosuav at gmail.com Fri Sep 30 13:12:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 03:12:02 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Sat, Oct 1, 2011 at 3:05 AM, Prasad, Ramit wrote: > Curses, foiled by my lack of specificity! I meant desktop client. Although...if another website does similar threading it would be good to know. Never know when I will want to start avoiding Gmail :) > Ah, *desktop* client! Hm. I actually can't advise there; since I'm constantly mobile, I use webmail for everything - installed Squirrel Mail and RoundCube on my server for remote access. Neither does threading though afaik; nor does PMMail (which is a desktop client). ChrisA From neilc at norwich.edu Fri Sep 30 13:12:26 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 17:12:26 GMT Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <9embjqFb8uU1@mid.individual.net> On 2011-09-30, Paul Rudin wrote: > "Prasad, Ramit" writes: > >>>May I suggest a[n] email client that can group mailing list threads? >> >> Please do. Bonus points if it handles threading in a Gmail-like style. > > The answer to any news/mail client with feature X type question is > normally "gnus" - although I don't know what "Gmail-like style" is. slrn. Is good. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From alec.taylor6 at gmail.com Fri Sep 30 13:19:20 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 03:19:20 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> Message-ID: Maybe one Apache's Buzz? On 10/1/11, Prasad, Ramit wrote: >>> Please do. Bonus points if it handles threading in a Gmail-like style. >>> >> >>May I suggest Gmail? It handles threading in a very Gmail-like style. > > Curses, foiled by my lack of specificity! I meant desktop client. > Although...if another website does similar threading it would be good to > know. Never know when I will want to start avoiding Gmail :) > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Fri Sep 30 13:26:00 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 03:26:00 +1000 Subject: Suggested coding style In-Reply-To: <9embjqFb8uU1@mid.individual.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> Message-ID: http://incubator.apache.org/wave/ On 10/1/11, Neil Cerutti wrote: > On 2011-09-30, Paul Rudin wrote: >> "Prasad, Ramit" writes: >> >>>>May I suggest a[n] email client that can group mailing list threads? >>> >>> Please do. Bonus points if it handles threading in a Gmail-like style. >> >> The answer to any news/mail client with feature X type question is >> normally "gnus" - although I don't know what "Gmail-like style" is. > > slrn. Is good. > > -- > Neil Cerutti > "A politician is an arse upon which everyone has sat except a man." > e. e. cummings > -- > http://mail.python.org/mailman/listinfo/python-list > From ramit.prasad at jpmorgan.com Fri Sep 30 13:45:21 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:45:21 -0400 Subject: Suggested coding style In-Reply-To: <9embjqFb8uU1@mid.individual.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> >>>>May I suggest a[n] email client that can group mailing list threads? > The answer to any news/mail client with feature X type question is > normally "gnus" - although I don't know what "Gmail-like style" is. Yeah >slrn. Is good. Unless I am missing something, it does not do email. >http://incubator.apache.org/wave/ Are you suggesting I run my own webserver to aggregate emails, stick them in wave, and then write something that will convert my wave post to email? I suppose it could work, but that is *usually* not what is considered a "desktop app". > Maybe one Apache's Buzz? I think you will have to Google that one for me, as the first results I found were Apache Wicket and Apache Beehive...both which seem not related. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Sep 30 13:48:25 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:48:25 -0400 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> >> The answer to any news/mail client with feature X type question is >> normally "gnus" - although I don't know what "Gmail-like style" is. >Yeah Gah, I got distracted mid-email and forgot to finish. What I wanted to say was, "Yeah, not knowing what 'Gmail-like style' makes a big difference ;)". Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rantingrick at gmail.com Fri Sep 30 14:08:16 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 11:08:16 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: On Sep 30, 11:36?am, Westley Mart?nez wrote: > On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > > On Sep 30, 8:58???pm, Neil Cerutti wrote: > > > On 2011-09-30, DevPlayer wrote: > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > By that I mean: just because an objects scope may not see a certain > > > > condition, doesn't mean that condition is non-existant. > > > > > I also propose that just because something seems to contradict doesn't > > > > mean it is false. Take for instance: > > > > > Look out your window. Is it daylight or night time? You may say > > > > it is daylight or you may say it is night time. I would > > > > disagree that only one of those conditions are true. Both > > > > conditions are true. Always. It is only day (or night) for YOU. > > > > But the opposite DOES in fact exist on the other side of the > > > > world at the same time. > > > > > I call this Duality of Nature (and I believe there was some > > > > religion somewhere in some time that has the same notion, > > > > Budism I think but I could be mistaken). I see such > > > > "contradictions" in what appears to be most truths. > > > > You are not alone. Many ancient philosophers, fathers of > > > religious and scientific thought, thought the same. > > > > They thought that contradictory qualities could exist in objects > > > simultaneously. For example, they thought that a cat was both big > > > and small, because it was big compared to a mouse and small > > > compared to a house. They didn't notice that big and small were > > > not poperties of the cat, at all but were instead statements > > > about how a cat relates to another object. > > > > When you say, "It is night," you are making an assertion about a > > > position on the surface of the earth and its relationship to the > > > sun. > > > > If you are not discussing a specific a position on the Earth, > > > then you cannot make a meaningful assertion about night or day at > > > all. Night and Day are not qualities of the entire Earth, but > > > only of positions on the Earth. > > > But just imagine that we were all pre-galiliean savages -- knowing > > nothing about the roundness of the earth, the earth going round and so > > on and somehow you and I get on the phone and we start arguing: > > Rusi: Its 9:30 pm > > Neil: No its 12 noon > > > How many cases are there? > > We both may be right, I may be wrong (my watch may have stopped) or we > > both etc > > > ie conflicting data may get resolved within a larger world view (which > > is what devplayer is probably saying). > > > Until then it is wiser to assume that that larger world view exists > > (and I dont yet know it) > > than to assume that since I dont know it it does not exist. > > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > > know-ness") is as much a foundation for true religiosity as effective > > science > > I.e. humility? @DevPlayer, rusi, Neil, Wes, and group Yes, there are two views of reality; that of the absolute and that of the relative. Both are true. It is always daytime and nighttime simultaneously; if you look at things from a global perspective. However, the true nature of "daytime vs nighttime" is purely a relative observation. The fact that both exist does not falsify the validity of the relative view. Recognizing the paradox is important and proves you are not confined to your own selfish view points and are in fact an intelligent being. From rbotting at csusb.edu Fri Sep 30 14:34:37 2011 From: rbotting at csusb.edu (RJB) Date: Fri, 30 Sep 2011 11:34:37 -0700 (PDT) Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 29, 3:52?am, Steven D'Aprano wrote: > Alain Ketterlin wrote: > > Steven D'Aprano writes: > > >> I have a Python script which I would like to test without a tty attached > >> to the process. I could run it as a cron job, but is there an easier way? > > >> I am running Linux. > > > Isn't os.setsid() what you're looking for? It makes the calling process > > have no controlling terminal. There's also a user command called setsid > > that should have the same effect. > > It doesn't appear so to me. > > [steve at sylar ~]$ tty > /dev/pts/16 > [steve at sylar ~]$ setsid tty > /dev/pts/16 > > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. > > -- > Steven You could try the old UNIX "nohup ... &" technique for running a process in the background (the &) with no HangUP if you log out: $ nohup python -c "import sys,os; print os.isatty(sys.stdout.fileno())" & appending output to nohup.out $ cat nohup.out False But that is over kill I guess. One worrying detail.... the definition of a running process in UNIX implies is that it has standard input/output files open. You'd be wise to make sure that they are connected to things that are safe.... /dev/null. Even so /dev/tty can be opened any way... Hope this helps. From derek at simkowiak.net Fri Sep 30 14:42:57 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Fri, 30 Sep 2011 11:42:57 -0700 Subject: Motion Tracking with Python In-Reply-To: <201109300906.43128.rick.mansilla@gmail.com> References: <4E852694.4080303@simkowiak.net> <201109300906.43128.rick.mansilla@gmail.com> Message-ID: <4E860DB1.202@simkowiak.net> > /I am having problems with getting data from the CCD (basically i don't know how to do it :), can you give me a tip for doing this? Or explain how you did it please?/ I am using the OpenCV library to grab images. Here are the specific lines of code: self.capture = cv.CaptureFromCAM(0)cv.SetCaptureProperty( self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, 320 );cv.SetCaptureProperty( self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 240 );frame = cv.QueryFrame(self.capture) # ...this is done repeatedly in the main loop. These were copied from the examples that came with OpenCV. I don't know if this will work under Windows. The source code to my script is available online; I recommend downloading it and playing with it. Also, check out the OpenCV Python documentation. Thanks, Derek On 09/30/2011 07:06 AM, Ricardo Mansilla wrote: > > On Thursday 29 September 2011 21:16:52 you wrote: > > > Hello, > > > I have a neat Python project I'd like to share. It does real-time motion > > > tracking, using the Python bindings to the OpenCV library: > > > > > > http://derek.simkowiak.net/motion-tracking-with-python/ > > > > > > There is a YouTube video showing the script in action. > > > > > > It's especially neat because my daughter and I worked together on this > > > project. We used it to track her two pet gerbils, as part of her science > > > fair project. She wrote her own (separate) Python script to read the > > > motion tracking log files, compute distance and velocity, and then > > > export those values in a CSV file. Like I say on the web page: "I?m > > > convinced that Python is the best language currently available for > > > teaching kids how to program." > > > > > > I also use Python professionally, and it's worked out great every time. > > > There's no job Python can't handle. > > > > > > > > > Thanks, > > > Derek Simkowiak > > > http://derek.simkowiak.net > > Hi, this is awesome!! > > I'm currently working in something similar, but I am having problems > with getting data from the CCD (basically i don't know how to do it > :), can you give me a tip for doing this? Or explain how you did it > please? > > I not a newbie at python but not as experienced as evidently you are. > > Thanks a lot in advance. > > > -- > > (...)Also, since that same law states that any system able to prove > its consistency to itself must be inconsistent; any mind that believes > it can prove its own sanity is, therefore, insane.(...) > > Kurt G?del. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From derek at simkowiak.net Fri Sep 30 14:48:26 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Fri, 30 Sep 2011 11:48:26 -0700 Subject: Motion Tracking with Python In-Reply-To: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> References: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> Message-ID: <4E860EFA.1020807@simkowiak.net> > /How was her project received at school?/ She got an "Outstanding" blue ribbon award. The teachers were impressed. (It was only a mandatory school project; it was not part of a regional competition or anything fancy like that.) --Derek On 09/30/2011 09:40 AM, Irmen de Jong wrote: > On 30-9-2011 4:16, Derek Simkowiak wrote: >> Hello, >> I have a neat Python project I'd like to share. It does real-time motion tracking, using >> the Python bindings to the OpenCV library: >> >> http://derek.simkowiak.net/motion-tracking-with-python/ >> >> There is a YouTube video showing the script in action. >> >> It's especially neat because my daughter and I worked together on this project. We used >> it to track her two pet gerbils, as part of her science fair project. She wrote her own >> (separate) Python script to read the motion tracking log files, compute distance and >> velocity, and then export those values in a CSV file. Like I say on the web page: "I?m >> convinced that Python is the best language currently available for teaching kids how to >> program." > Wow. Very impressive and very enjoyable to read about it. How was her project received > at school? > > Thanks a lot for sharing this. > > Irmen de Jong -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Fri Sep 30 15:27:14 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 30 Sep 2011 12:27:14 -0700 Subject: Benefit and belief In-Reply-To: References: <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: <20110930192714.GA14314@Smoke> On Fri, Sep 30, 2011 at 11:08:16AM -0700, rantingrick wrote: > On Sep 30, 11:36?am, Westley Mart?nez wrote: > > On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > > > On Sep 30, 8:58???pm, Neil Cerutti wrote: > > > > On 2011-09-30, DevPlayer wrote: > > > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > > > By that I mean: just because an objects scope may not see a certain > > > > > condition, doesn't mean that condition is non-existant. > > > > > > > I also propose that just because something seems to contradict doesn't > > > > > mean it is false. Take for instance: > > > > > > > Look out your window. Is it daylight or night time? You may say > > > > > it is daylight or you may say it is night time. I would > > > > > disagree that only one of those conditions are true. Both > > > > > conditions are true. Always. It is only day (or night) for YOU. > > > > > But the opposite DOES in fact exist on the other side of the > > > > > world at the same time. > > > > > > > I call this Duality of Nature (and I believe there was some > > > > > religion somewhere in some time that has the same notion, > > > > > Budism I think but I could be mistaken). I see such > > > > > "contradictions" in what appears to be most truths. > > > > > > You are not alone. Many ancient philosophers, fathers of > > > > religious and scientific thought, thought the same. > > > > > > They thought that contradictory qualities could exist in objects > > > > simultaneously. For example, they thought that a cat was both big > > > > and small, because it was big compared to a mouse and small > > > > compared to a house. They didn't notice that big and small were > > > > not poperties of the cat, at all but were instead statements > > > > about how a cat relates to another object. > > > > > > When you say, "It is night," you are making an assertion about a > > > > position on the surface of the earth and its relationship to the > > > > sun. > > > > > > If you are not discussing a specific a position on the Earth, > > > > then you cannot make a meaningful assertion about night or day at > > > > all. Night and Day are not qualities of the entire Earth, but > > > > only of positions on the Earth. > > > > > But just imagine that we were all pre-galiliean savages -- knowing > > > nothing about the roundness of the earth, the earth going round and so > > > on and somehow you and I get on the phone and we start arguing: > > > Rusi: Its 9:30 pm > > > Neil: No its 12 noon > > > > > How many cases are there? > > > We both may be right, I may be wrong (my watch may have stopped) or we > > > both etc > > > > > ie conflicting data may get resolved within a larger world view (which > > > is what devplayer is probably saying). > > > > > Until then it is wiser to assume that that larger world view exists > > > (and I dont yet know it) > > > than to assume that since I dont know it it does not exist. > > > > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > > > know-ness") is as much a foundation for true religiosity as effective > > > science > > > > I.e. humility? > > @DevPlayer, rusi, Neil, Wes, and group > > Yes, there are two views of reality; that of the absolute and that of > the relative. Both are true. It is always daytime and nighttime > simultaneously; if you look at things from a global perspective. > > However, the true nature of "daytime vs nighttime" is purely a > relative observation. The fact that both exist does not falsify the > validity of the relative view. Recognizing the paradox is important > and proves you are not confined to your own selfish view points and > are in fact an intelligent being What paradox?. From alec.taylor6 at gmail.com Fri Sep 30 15:57:13 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 05:57:13 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> Message-ID: Meh, so run your own web-server. If wave isn't right, search on sourceforge for a while. On 10/1/11, Prasad, Ramit wrote: >>> The answer to any news/mail client with feature X type question is >>> normally "gnus" - although I don't know what "Gmail-like style" is. >>Yeah > > Gah, I got distracted mid-email and forgot to finish. What I wanted to say > was, "Yeah, not knowing what 'Gmail-like style' makes a big difference ;)". > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From nobody at nowhere.com Fri Sep 30 16:09:54 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 30 Sep 2011 21:09:54 +0100 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: >> I have a Python script which I would like to test without a tty attached >> to the process. I could run it as a cron job, but is there an easier way? >> >> I am running Linux. > > Isn't os.setsid() what you're looking for? It makes the calling process > have no controlling terminal. There's also a user command called setsid > that should have the same effect. setsid() requires that the calling process isn't a process group leader; this can be achieved by fork()ing. The setsid command does this automatically. As you say, this ensures that the process has no controlling terminal (i.e. it won't get signals from the tty driver for ^C, ^Z, hangup, etc). It won't detach stdin etc from a terminal. Also, open()ing a tty will result in it becoming the controlling terminal unless O_NOCTTY is used. I suspect that the OP just wants e.g.: script.py &>/dev/null <&- which will redirect stdout and stderr to /dev/null and close stdin. From nobody at nowhere.com Fri Sep 30 16:20:52 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 30 Sep 2011 21:20:52 +0100 Subject: Modifying external running process using python References: <086bd803-ddc5-4913-b1f1-5fb6cb5848bb@i28g2000yqn.googlegroups.com> Message-ID: On Thu, 29 Sep 2011 23:02:55 -0700, bingbang wrote: > Beginner here. I am trying to figure out how to modify a running > process on a linux system using Python. > I looked up trace and some other modules but they all seem to do with > following the currently executing python process. ptrace() is the system call which programs such as gdb, strace, ltrace, etc use to monitor or control another process. You wil probably need to use ctypes to access this function from Python. > Let's assume I have sudo/root privileges and that the POC code "only > needs to work in linux". You don't need root privilege to ptrace() a process which you own and which isn't privileged (a process which starts out setuid/setgid is still treated as privileged even if it reverts to the real user/group IDs). From joncle at googlemail.com Fri Sep 30 16:51:43 2011 From: joncle at googlemail.com (Jon Clements) Date: Fri, 30 Sep 2011 13:51:43 -0700 (PDT) Subject: Simplest way to resize an image-like array References: Message-ID: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> On Sep 30, 5:40?pm, John Ladasky wrote: > Hi folks, > > I have 500 x 500 arrays of floats, representing 2D "grayscale" images, > that I need to resample at a lower spatial resolution, say, 120 x 120 > (details to follow, if you feel they are relevant). > > I've got the numpy, and scipy, and matplotlib. All of these packages > hint at the fact that they have the capability to resample an image- > like array. ?But after reading the documentation for all of these > packages, none of them make it straightforward, which surprises me. > For example, there are several spline and interpolation methods in > scipy.interpolate. ?They seem to return interpolator classes rather > than arrays. ?Is there no simple method which then calls the > interpolator, and builds the resampled array? > > Yes, I can do this myself if I must -- but over the years, I've come > to learn that a lot of the code I want is already written, and that > sometimes I just have to know where to look for it. > > Thanks! Is something like http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html#scipy.misc.imresize any use? From hansmu at xs4all.nl Fri Sep 30 17:09:02 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 30 Sep 2011 23:09:02 +0200 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e862fee$0$2438$e4fe514c@news2.news.xs4all.nl> On 30/09/11 20:34:37, RJB wrote: > You could try the old UNIX "nohup ...&" technique for running a > process in the background (the&) with no HangUP if you log out: > > $ nohup python -c "import sys,os; print > os.isatty(sys.stdout.fileno())"& > appending output to nohup.out > $ cat nohup.out > False > > But that is over kill I guess. > > One worrying detail.... the definition of a running process in > UNIX implies is that it has standard input/output files open. > You'd be wise to make sure that they are connected to things > that are safe.... /dev/null. > > Even so /dev/tty can be opened any way... Not if you really detach from your tty: after you've detached, there is no tty for /dev/tty to connect to and any attempt to open it will raise IOError. -- HansM From navkirat.py at gmail.com Fri Sep 30 23:25:54 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Sat, 1 Oct 2011 08:55:54 +0530 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List Message-ID: Lol you all sound like google's angry birds with their feathers ruffled by a comment. You guys should open up another mailing list to extinguish your virtually bruised egos. . . . On Sep 30, 2011 10:27 PM, "Prasad, Ramit" wrote: -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Thu Sep 1 00:22:23 2011 From: nagle at animats.com (John Nagle) Date: Wed, 31 Aug 2011 21:22:23 -0700 Subject: try... except with unknown error types In-Reply-To: <4e51a32d$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e4ec405$0$29994$c3e8da3$5496439d@news.astraweb.com> <7xipprsxha.fsf@ruckus.brouhaha.com> <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> <4e51a32d$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e5f089b$0$2148$742ec2ed@news.sonic.net> On 8/21/2011 5:30 PM, Steven D'Aprano wrote: > Chris Angelico wrote: > > >> A new and surprising mode of network failure would be indicated by a >> new subclass of IOError or EnvironmentError. > > /s/would/should/ > > I don't see why you expect this, when *existing* network-related failures > aren't: > >>>> import socket >>>> issubclass(socket.error, EnvironmentError) > False > > (Fortunately that specific example is fixed in Python 3.) I think I reported that some years ago. There were some other errors in the URL and SSL area that weren't subclasses of EnvironmentError. It's also possible to get UnicodeError from URL operations. John Nagle From sahil at FreeBSD.org Thu Sep 1 00:56:50 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 1 Sep 2011 00:56:50 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } Message-ID: <20110901045650.GA3466@magic.hamla.org> I've been tasked with converting some programs from Perl -> Python, and am (as will soon be obvious) new to the language. A few archive/google searches were inconclusive on a consensus approach, which is OK, but I just wonder if there is a more Python-esque way to do the following in Python 2.7.1: %% # unbuffer STDOUT sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # process input, line-by-line, and print responses after parsing input while 1: rval = parse(raw_input()) if rval == None: print('foo') else: print('bar') %% This works, but while reading the documentation, I thought of using 'for line in fileinput.input()' in lieu of 'while 1:' construct. This does not work when debugging the program on the command line -- the script appears to just hang no matter what is typed into STDIN. I believe this is because of some internal buffering when using fileinput. Is there a recommended way to disable such buffering? Am I taking a totally wrong approach? Feel free to just link me to previous discussions on the topic(s) if I have missed them. Please be gentle with your cluebats. :-) Thanks, -- Sahil Tandon From kushal.kumaran+python at gmail.com Thu Sep 1 01:21:36 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 1 Sep 2011 10:51:36 +0530 Subject: How to daemonize a HTTPServer In-Reply-To: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On 1 Sep 2011 08:54, "babbu Pehlwan" wrote: > > I have written a http server using BaseHTTPServer module. Now I want > to instantiate it through another python script. The issue here is > after instantiate the control doesn't come back till the server is > running. Please suggest. What did a web search for "python daemon" lead to? I believe there's a python-daemon package available on pypi. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 1 02:02:54 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 01 Sep 2011 16:02:54 +1000 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: Message-ID: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. A few archive/google > searches were inconclusive on a consensus approach, which is OK, but I > just wonder if there is a more Python-esque way to do the following in > Python 2.7.1: > > %% > # unbuffer STDOUT > sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) I've never bothered with unbuffered stdout, but that looks fine to me. I'm not sure if it is necessary though, because print seems to automatically flush the buffer after each line in my testing. Unless you're printing repeatedly to the same line, I'm not sure unbuffered stdout is helpful. > # process input, line-by-line, and print responses after parsing input > while 1: > rval = parse(raw_input()) > if rval == None: > print('foo') > else: > print('bar') > %% "while True" is considered slightly more idiomatic (readable), but otherwise, that seems fine. > This works, but while reading the documentation, I thought of using 'for > line in fileinput.input()' in lieu of 'while 1:' construct. This does > not work when debugging the program on the command line -- the script > appears to just hang no matter what is typed into STDIN. I believe this > is because of some internal buffering when using fileinput. Is there a > recommended way to disable such buffering? Am I taking a totally wrong > approach? I'm not sure anything about fileinput is exactly *recommended*, it's kinda discouraged on account of being a bit slow. See help(fileinput) at the interactive prompt. For what it's worth, the default buffersize for fileinput.input is 0, so if that doesn't do what you want, I don't think fileinput is the right solution. -- Steven From __peter__ at web.de Thu Sep 1 02:31:32 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 08:31:32 +0200 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <20110901045650.GA3466@magic.hamla.org> Message-ID: Sahil Tandon wrote: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. A few archive/google > searches were inconclusive on a consensus approach, which is OK, but I > just wonder if there is a more Python-esque way to do the following in > Python 2.7.1: > > %% > # unbuffer STDOUT > sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) > > # process input, line-by-line, and print responses after parsing input > while 1: > rval = parse(raw_input()) > if rval == None: > print('foo') > else: > print('bar') > %% > > This works, but while reading the documentation, I thought of using 'for > line in fileinput.input()' in lieu of 'while 1:' construct. This does > not work when debugging the program on the command line -- the script > appears to just hang no matter what is typed into STDIN. I believe this > is because of some internal buffering when using fileinput. Is there a > recommended way to disable such buffering? Am I taking a totally wrong > approach? > > Feel free to just link me to previous discussions on the topic(s) if I > have missed them. Please be gentle with your cluebats. :-) A quick look into fileinput.py reveals that it uses readlines() and slurps in the complete "file". I'm not sure that was a clever design decision... Here's a partial reimplementation that should work for your use-case: import sys from itertools import chain def _open_many(files): for file in files: if file == "-": yield sys.stdin else: with open(file) as f: yield f def input(files=None, buffered=False): if files is None: files = sys.argv[1:] if not files: files = ["-"] files = _open_many(files) if not buffered: files = (iter(file.readline, "") for file in files) return chain.from_iterable(files) for line in input(): print line.strip().upper() From __peter__ at web.de Thu Sep 1 03:43:04 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 09:43:04 +0200 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <20110901045650.GA3466@magic.hamla.org> Message-ID: Peter Otten wrote: > A quick look into fileinput.py reveals that it uses readlines() and slurps > in the complete "file". I'm not sure that was a clever design decision... Correction: >>> with open("tmp.txt") as f: lines = f.readlines(0) ... >>> len(lines) 1000000 >>> with open("tmp.txt") as f: lines = f.readlines(1) ... >>> len(lines) 301 >>> len("".join(lines)) 8208 So on my system file.readlines(size) stops after about 2**13 bytes which is not a problem memorywise. Sorry for the confusion. From msamogh at gmail.com Thu Sep 1 03:48:52 2011 From: msamogh at gmail.com (Amogh M S) Date: Thu, 1 Sep 2011 13:18:52 +0530 Subject: Constructors...BIIIIG PROBLEM! Message-ID: Hey guys... I think we have a problem with my _init_ method and the constructor When I create a class and its _init_ method and try to create an object of it outside the class, Say, something like class S: def _init_(self, name=None): self.name = name s = S("MyName") It says that the constructor takes no arguments!! I have to explicitly call the _init_ method which, I think is not the right way of doing things... Could you tell me if that is what is supposed to happen or is something wrong with my code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 1 03:56:11 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 09:56:11 +0200 Subject: Constructors...BIIIIG PROBLEM! References: Message-ID: Amogh M S wrote: > Hey guys... > I think we have a problem with my _init_ method and the constructor > When I create a class and its _init_ method and try to create an object of > it outside the class, > Say, something like > > class S: > def _init_(self, name=None): Your __init__() method needs two leading and two trailing underscores. > self.name = name > s = S("MyName") > > It says that the constructor takes no arguments!! I have to explicitly > call the _init_ method which, I think is not the right way of doing > things... Could you tell me if that is what is supposed to happen or is > something wrong with my code? From motoom at xs4all.nl Thu Sep 1 04:00:27 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 10:00:27 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: References: Message-ID: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> On Sep 1, 2011, at 09:48, Amogh M S wrote: > Hey guys... > I think we have a problem with my _init_ method and the constructor > When I create a class and its _init_ method and try to create an object of it outside the class, > Say, something like > > class S: > def _init_(self, name=None): > self.name = name > s = S("MyName") Two things: Derive your class from object, and the constructor function should be '__init__', that is, with *two* underscores before and after it. Are you reading a book or tutorial which does use a badly chosen font which doesn't distinguish two consecutive underscores well? class S(object): def __init__(self, name=None): self.name = name s = S("MyName") print s.name Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand From airween at gmail.com Thu Sep 1 04:24:29 2011 From: airween at gmail.com (=?utf-8?Q?Heged=C3=BCs?= Ervin) Date: Thu, 1 Sep 2011 10:24:29 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> Message-ID: <20110901082427.GA18046@arxnet.hu> hello, On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: > On Sep 1, 2011, at 09:48, Amogh M S wrote: [...] > > class S: > > def _init_(self, name=None): > > self.name = name > > s = S("MyName") > > Two things: Derive your class from object, why's that better than just create a simple class, without derive? thanks: a. From motoom at xs4all.nl Thu Sep 1 05:04:18 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 11:04:18 +0200 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <20110901082427.GA18046@arxnet.hu> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> <20110901082427.GA18046@arxnet.hu> Message-ID: <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> On Sep 1, 2011, at 10:24, Heged?s Ervin wrote: > On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >> Derive your class from object, > > why's that better than just create a simple class, without > derive? Amongst other things, fixes to the type system and the method resolution order. http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html http://www.python.org/download/releases/2.2.3/descrintro/ Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand From dotancohen at gmail.com Thu Sep 1 05:42:04 2011 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 1 Sep 2011 12:42:04 +0300 Subject: Regex to match all trailing whitespace _and_ newlines. Message-ID: In the terrific Anki [1] application I am trying to remove trailing whitespace from form fields. This is my regex: [\n+\s+]$ Actually, even simplifying it to [\n] or [\r\n] is not matching any newlines! What might be the cause of this? Note that I am not entering the regex in Python code, I am entering it in a regex-supporting Find/Replace dialogue in Anki. Anki is written in Python. Thanks. [1] ankisrs.net -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From __peter__ at web.de Thu Sep 1 06:30:15 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 12:30:15 +0200 Subject: Regex to match all trailing whitespace _and_ newlines. References: Message-ID: Dotan Cohen wrote: > In the terrific Anki [1] application I am trying to remove trailing > whitespace from form fields. This is my regex: > [\n+\s+]$ My attempt: >>> sub = re.compile(r"\s*?(\n|$)").sub >>> sub("", "alpha \nbeta \r\n\ngamma\n") 'alphabetagamma' >>> sub("", "alpha \nbeta \r\n\ngamma") 'alphabetagamma' >>> sub("", "alpha \nbeta \r\n\ngamma\t") 'alphabetagamma' From fnautaNO at SPAMsolfon.nl Thu Sep 1 06:30:40 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 1 Sep 2011 12:30:40 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net> Message-ID: <9c9578F5eaU1@mid.individual.net> "Paul K?lle" wrote in message news:mailman.620.1314810894.27778.python-list at python.org... > Hi, answers below... > > Am 31.08.2011 14:18, schrieb Fokke Nauta: >> "Paul K?lle" wrote in message >> news:mailman.595.1314780791.27778.python-list at python.org... >>> Hi, >>> >>> Am 30.08.2011 22:00, schrieb Fokke Nauta: >>>> Hi all, >>>> >>>> I am completely new to Python, but I'm confronted with a problem I >>>> can't >>>> solve. >>> Welcome to python. >>> >>>> This is my question: >>> [snip] >>> >>>> I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. >>>> Now >>>> I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 >>>> and >>>> PyXML-0.8.4. In the PyWebDAV README it says: >>>> >>>> Installation and setup of server can be as easy as follows: >>>> >>>> $ easy_install PyWebDAV >>>> $ davserver -D /tmp -n -J >>>> >>>> But of course it doesn't work like that. When I start up Python GUI I >>>> see >>>> the ">>>" prompt instead of the "$" prompt. But where do I place the >>>> two >>>> directories? And there is no easy_install script in the PyXML-0.8.4 >>>> directory, only a setup.py and ez_setup.py script. I guess the latter >>>> is >>>> the >>>> one to use. But how? >>> You dont install from "Python GUI", use normal cmd, navigate to the >>> folder >>> you downloaded PyXML and PyWebDAV and run "python setup.py install" >>> (python.exe has to be in your PATH). Then you have to find the >>> startup-script "davserver". Find your python installation directory and >>> look into/Tools/Scripts, in my computer this is >>> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the >>> site-packages folder i.e. E:\python27\Lib/site-packages. You might have >>> to >>> look for "davserver" there... >>> >> >> Thanks, Paul. >> >> I ran "python setup.py install" in both the PyXML and PyWebDAV >> directories. >> A lot of things happened and are added into those directories and I guess >> it >> will be OK. >> Next step, the startup-script "davserver". There is no script as such, >> also >> not in \python27\tools\scripts. >> I found 2 similar scripts: >> 1. server.py in D:\Python27\WebDAV\PyWebDAV\DAVServer >> 2. WebDAVServer.py in D:\Python27\WebDAV\PyWebDAV\DAV >> >> Which one is the one to use? > Your install locations look odd, but it might work nevertheless. The > server is in DAVServer\server.py, you can look at the file and you will > see: > > if __name__ == '__main__': > run() > > at the bottom. This is the "entry point" of a python script if called from > the command line. Yes, it was server.py. > My install looks a bit different but I can start the server as follows: > python.exe > E:\Python27\Lib\site-packages\pywebdav-0.9.4.1-py2.7.egg\DAVServer\server.py > -D c:\home -n > WARNING:pywebdav:Authentication disabled! > Listening on localhost (8008) I used server.py e:/wwwroot -m -c config.ini >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer > I would use a config file outside the program directory and use the -c > or --config switch, run server.py without arguments to see possible > startup options. > >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? > Don't know if that's documented somewhere but you can just look at the > code in mysqlauth.py in the same directory as server.py. Seems it needs > three columns, (User,Pass,can_write<0|1>) but I haven't > tried. > I have understood that the database will be configured with the first run, but in my case it didn't. In my congig.ini there was # Create User Database Table and Insert system user # Disable after the Table is created; for performance reasons firstrun=1 Fokke From fnautaNO at SPAMsolfon.nl Thu Sep 1 06:30:43 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 1 Sep 2011 12:30:43 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net> Message-ID: <9c9578F5eaU2@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.643.1314851358.27778.python-list at python.org... > On Wed, 31 Aug 2011 14:18:00 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? >> > After looking at the config file. > > I presume you have specified the MySQL username/password Sure > (personally, and out of paranoia, I'd create a webDAV user/password that > only has access rights to the specified webDAV database). > > Next, if you'd read further and didn't take the comment as the > instruction. set > firstrun=1 I did > to tell the server this is the first time it is being run - IT WILL > create the database table (after the first start, reset the flag to 0 to > speed up later runs). It didn't create the table. The database kept empty. > Later in the config file set > mysql_auth=1 > to enable the use of MySQL, and set the admin user/password to what you > plan to have it use. I did > You probably want to set > daemonize=1 > (maybe after first run) I left this to 0. > Oh, and don't forget to set the main data directory and any > port/host changes. I left host and port as they were. The main directory is e:\wwwroot > Start the server - it should connect to MySQL, create the table, and > add the admin user to the table. I started the server with server.py (in D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini The seems to work as I get a login screen in the browser. Later on I changed the ini file: # disable auth noauth = 1 # Enable mysql auth mysql_auth=0 No login screen anymore but I got an error message "fshandler:get_data: e:\wwwroot not found" Fokke From martin.hellwig at gmail.com Thu Sep 1 06:32:35 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 01 Sep 2011 11:32:35 +0100 Subject: How to daemonize a HTTPServer In-Reply-To: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On 01/09/2011 04:16, babbu Pehlwan wrote: > I have written a http server using BaseHTTPServer module. Now I want > to instantiate it through another python script. The issue here is > after instantiate the control doesn't come back till the server is > running. Please suggest. Sounds like something you could use the multiprocessing module for, but then again my crystal ball is a bit fuzzy today. -- mph From andrei.lisnic at gmail.com Thu Sep 1 06:40:25 2011 From: andrei.lisnic at gmail.com (UncleLaz) Date: Thu, 1 Sep 2011 03:40:25 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> On Aug 31, 5:35?pm, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. > > For example, consider Python?s indent-sensitive syntax. ?Although > other languages didn?t use indentation to specify scope, programmers > always used indentation anyways. ?Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? ?It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. ?It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. It's required to make distinction between objects inside the calss and outside of it. Seems pretty logical to me. From yasar11732 at gmail.com Thu Sep 1 06:51:43 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 1 Sep 2011 13:51:43 +0300 Subject: Invoking profile from command line prevent my sys.path modification Message-ID: Hi, I am new to profile module, so I am sorry if this is an absolute beginner question. In order to my code to run, I need to add a directory to sys.path. When I invole python -m profile myfile.py, my code won't work, saying that the thing that is supposed to be in path, isn't. Code works fine without profiling. Profiling works if I write it into the file, but I don't prefer doing that, if that is possible. -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Thu Sep 1 07:23:54 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 1 Sep 2011 13:23:54 +0200 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <058cb764-2ba2-4b63-be4d-33307a9a81cc@g31g2000yqh.googlegroups.com> Message-ID: <2B38B9D1-4DD5-4E88-B4DB-324A677C6BD1@xs4all.nl> > On Aug 31, 5:35 pm, "T. Goodchild" wrote: >> So why is 'self' necessary on class methods? >> >> Just curious about the rationale behind this part of the language. When instance variables are accessed with the 'self.varname' syntax, it is clear to the programmer that an instance variable is accessed, and not some global. Other languages have weird syntax conventions like that you have to prepend all instance attributes with an '@', and in languages like C++ where there is not necessarily such a syntactic requirement, many programmers use ad-hoc constructs like '_varname' or 'm_varname' to make the distinction clear. >> It seems to me that the >> most common practice is that class methods *almost always* operate on >> the instance that called them. It would make more sense to me if this >> was assumed by default, and for "static" methods (methods that are >> part of a class, but never associated with a specific instance) to be >> labelled instead. Yes, you have a point there. My personal preference would be to optimize for the most common case, while exceptions to the norm are still possible, but perhaps a bit more verbose. Greetings -- "Learn to value yourself, which means: fight for your happiness." - Ayn Rand From johnroth1 at gmail.com Thu Sep 1 08:45:36 2011 From: johnroth1 at gmail.com (John Roth) Date: Thu, 1 Sep 2011 05:45:36 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> On Aug 31, 8:35?am, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. > > For example, consider Python?s indent-sensitive syntax. ?Although > other languages didn?t use indentation to specify scope, programmers > always used indentation anyways. ?Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? ?It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. ?It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. I personally consider this to be a wart. Some time ago I did an implementation analysis. The gist is that, if self and cls were made special variables that returned the current instance and class respectively, then the compiler could determine whether a function was an instance or class method. If it then marked the code object appropriately you could get rid of all of the wrappers and the attendant run-time overhead. I've never published the analysis because that train has already left the shed. The earliest it could be considered would be 4.0, which isn't even on the horizon. John Roth From lanyjie at yahoo.com Thu Sep 1 09:43:54 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 06:43:54 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> Message-ID: <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Hi Matt, ======================================================= From: Matt Joiner The "trailing \" workaround is nonobvious. Wrapping in () is noisy and already heavily used by other syntactical structures.? ======================================================= How about only require indentation to freely break lines? Here is an example: x = firstpart * secondpart #line breaks here + anotherpart #continue by indentation + stillanother #continue on. #until here, another line starts by dedentation? y = some_expression?- another_one All this would be completely compatible with former code, while having almost free line breaking! Plus, indentation makes it pretty. Really hope Python can have freedom in breaking lines. Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Sep 1 09:57:00 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 07:57:00 -0600 Subject: Constructors...BIIIIG PROBLEM! In-Reply-To: <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> References: <8D536E41-941B-45A8-BD27-0896ACD8CCD5@xs4all.nl> <20110901082427.GA18046@arxnet.hu> <85112CB3-E5C1-42F5-9F2C-EFDFB3086EB0@xs4all.nl> Message-ID: On Thu, Sep 1, 2011 at 3:04 AM, Michiel Overtoom wrote: > > On Sep 1, 2011, at 10:24, Heged?s Ervin wrote: > >> On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >>> Derive your class from object, >> >> why's that better than just create a simple class, without >> derive? > > Amongst other things, fixes to the type system and the method resolution order. > > http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes > http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ > http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html > http://www.python.org/download/releases/2.2.3/descrintro/ That is for Python 2. For Python 3, old-style classes are gone, all classes derive from object by default, and writing it explicitly is merely good style for compatibility. From dalist0 at gmail.com Thu Sep 1 10:05:20 2011 From: dalist0 at gmail.com (Daniel) Date: Thu, 1 Sep 2011 07:05:20 -0700 (PDT) Subject: fun with nested loops References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steve, Thanks for your comments, I appreciate any input. > Do you think the software in the Apple iPod is "simple"? Or Microsoft No, that's much more complicated that what I am doing. But the iPod probably (?) doesn't get new algorithms based on a specification discussed with non-programmers once a month. I didn't explain enough of what I am doing. This is a fairly complex application that has been running for a few years now, I am just trying to improve it. The code runs a big test machine, that runs >100000 individual tests in one run on something like semiconductor chips. The specification of these tests is already very complex, it has the form of the nested loops, for all these configurations try these steps, if they fail try them again n times, if it still doesn't work give up this configuration, if it works continue on to the next steps etc. That's the form the specification is in, and it makes sense and is very readable. In pseudocode it looks like this, I am using @ to give loops a name: @loop1 for c in configurations: @loop2 while not_done: @loop3 while step1_did_not_work: @loop4 for substeps in step1 # loop 4a if hopeless(): continue loop1 # run next configuration if substepsFailed(): restart loop4 # try again if substepsWorked(): break loop3 # go on to next steps, like loop4 That format is fine, everyone involved can understand it, even the people in charge. I'd like to make this executable without changing too much of the form. It would be possible to do this as a FSM, but then you'd loose the line to line correspondence with the specification, and of course some errors always creep in. > non-CS people to be hacking the source code, they only interact with the This is a research setting, so the person running the machine will have to change the source from time to time if he gets a new specification. The specifications are far to complex to be entered into a user interface because of all the loops. > the code by splitting it into functions appropriately, instead of the > spaghetti code you have (apparently) written with jumps all over the place. I wouldn't call the example above spaghetti code in the sense of old Fortran or Basic full of gotos. In a language that can break out of nested loops this is highly structured code. I am not jumping forward to labels, not jumping into functions, not using jumps to replace loops etc. It is like the Fortran example (just to show the syntax, has an infinite loop), everyone can understand that right away, even non Fortran people: 10 loop1: do I=1,3 loop2: do J=1,4 print *,I,J goto 10 ! redo loop1 cycle loop1 exit loop1 enddo loop2 enddo loop1 There is no wild jumping her. The only problem is that Fortran does not allow to restart a loop, so instead of restart loop1 you have to do a goto 10. Otherwise you could do entirely without gotos (like in Ruby with the redo, which is of course much much better) > To take the most obvious, simple example: any time you have a loop that you > might want to redo, the right solution is to put the loop inside a > function, and then "redo the loop" becomes "call the function again". Doesn't work, because it can only redo one level, to break out of the next loop, I'd need exceptions anyway. And having all of these exceptions as gotos doesn't make it more readable. Replacing loop4 by a function makes it possible to replace the restart loop4 by a return, but then I still need an exception to continue loop1 and one to break out of loop4 to indicate that we can go on to the next step. > I suppose that, just possibly, your application really would benefit from > named labels to jump to. But if so, you've stumbled across something rarer > than iridium. Don't think so. I am doing that all of the time in other languages, and I am convinced the named loops (not raw labels+gotos, which are just a necessary evil) are beautiful and clean things. They have a lot of symmetry, break is always break, not sometimes break, sometimes return and sometimes raise breakSomeLoopExcept(). Rewriting the simple Fortran example above in Python would be much, much uglier and more difficult to comprehend. You always call break and continue with a label, searching for that label will tell you right away which loop the break breaks. I am always doing that, even if there is only one loop. break and continue (without label) are IMO (please no flame war about that) worse than goto, at least the goto tells you where it goes, with break/ continue you always have to scan the surroundings to find the right loop. I know I am not the only one who is trying to solve that problem, I was hoping someone has come up with a hack to solve it, like this goto Chis has come up with. I have to play with that a bit. Dan From ian.g.kelly at gmail.com Thu Sep 1 10:26:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 08:26:53 -0600 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> Message-ID: On Thu, Sep 1, 2011 at 6:45 AM, John Roth wrote: > I personally consider this to be a wart. Some time ago I did an > implementation analysis. The gist is that, if self and cls were made > special variables that returned the current instance and class > respectively, then the compiler could determine whether a function was > an instance or class method. If it then marked the code object > appropriately you could get rid of all of the wrappers and the > attendant run-time overhead. I don't see how you could get rid of the wrappers. Methods would still need to be bound, somehow, so that code like this will work: methods = {} for obj in objs: if obj.is_flagged: methods[obj.user_id] = obj.do_work else: methods[obj.user_id] = obj.do_other_work # ... methods[some_user_id]() Without method wrappers, how does the interpreter figure out which instance is bound to the method being called? Cheers, Ian From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 1 10:57:39 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 01 Sep 2011 16:57:39 +0200 Subject: fun with nested loops In-Reply-To: References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 01.09.2011 16:05 schrieb Daniel: > In pseudocode it looks like this, I am using @ to give loops a name: > > @loop1 > for c in configurations: > @loop2 > while not_done: > @loop3 > while step1_did_not_work: > @loop4 > for substeps in step1 # loop 4a > if hopeless(): continue loop1 # run next configuration > if substepsFailed(): restart loop4 # try again > if substepsWorked(): break loop3 # go on to next > steps, like loop4 let me have a try: def loop(f): def wrapper(*a, **k): while True: try: ret = f(*a, **k): return ret except wrapper.restart: continue # next try except wrapper.stop: return None return ret wrapper.restart = type('restart', (Exception,), {}) wrapper.stop = type('stop', (Exception,), {}) return wrapper @loop def level1(): for c in configurations: level2(c) @loop def level2(): while not_done: level3() @loop def level3(): while step1_did_not_work: level4() @loop def level4a(): for substeps in step1 if hopeless: raise level2.stop if substepsFailed: raise level4a.restart if substepsWorked: return ok I don't know if I have the levels right, but that should be a way which works, without too many indentations. Another approach could be a decorator which immediately runs the given functions, after adding the needed exception classes. Thomas From as at sci.fi Thu Sep 1 11:25:30 2011 From: as at sci.fi (Anssi Saari) Date: Thu, 01 Sep 2011 18:25:30 +0300 Subject: idiomatic analogue of Perl's: while (<>) { ... } References: Message-ID: Sahil Tandon writes: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. If it's any help, I have usually done handling of standard input line by line with this kind of thing: for inputline in sys.stdin: From mukeshtiwari.iiitm at gmail.com Thu Sep 1 11:46:50 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Thu, 1 Sep 2011 08:46:50 -0700 (PDT) Subject: Listing HAL devices Message-ID: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Hello all I am trying to write a python script which detects usb pen drive and copy all the data into my home directory. After bit of searching , i found these two links 1] http://en.wikibooks.org/wiki/Python_Programming/Dbus and 2] http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-device-inserted-events-in-linux-in-python . I just copied the wiki program but after running it , i got error import dbus class BusListener: def __init__( self ): self.bus = dbus.SystemBus() self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/ Manager' ) print self.proxy if __name__ == "__main__": obj = BusListener() Traceback (most recent call last): File "Mount.py", line 13, in obj = BusListener() File "Mount.py", line 7, in __init__ self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/ freedesktop/Hal/Manager' ) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in get_object follow_name_owner_changes=follow_name_owner_changes) File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in __init__ self._named_service = conn.activate_name_owner(bus_name) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in activate_name_owner self.start_service_by_name(bus_name) File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in start_service_by_name 'su', (bus_name, flags))) File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Hal was not provided by any .service files Kindly some one please tell me why i am getting this error . Thank you From patentsvnc at gmail.com Thu Sep 1 11:52:49 2011 From: patentsvnc at gmail.com (Den) Date: Thu, 1 Sep 2011 08:52:49 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows Message-ID: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Obviously, this is a windows-based question. I know that Ctrl-Alt-Del is handled deep inside the OS, and I'm not trying to interrupt that. But is there some way to detect that a C-A-D has been pressed? Also, is there a corresponding key-sequence in Mac and Linux? And how might one detect those too? Den From mukeshtiwari.iiitm at gmail.com Thu Sep 1 12:04:29 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Thu, 1 Sep 2011 09:04:29 -0700 (PDT) Subject: Listing HAL devices References: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Message-ID: On Sep 1, 8:46?pm, mukesh tiwari wrote: > Hello all > I am trying to write a python script which detects usb pen drive and > copy all the data into my home directory. After bit of searching , i > found these two links 1]http://en.wikibooks.org/wiki/Python_Programming/Dbus > and 2]http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-de... > . I just copied the wiki program but after running it , i got error > > import dbus > > class BusListener: > ? ? ? ? def __init__( self ): > ? ? ? ? ? ? ? ? self.bus = dbus.SystemBus() > ? ? ? ? ? ? ? ? self.hal_obj = > self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/ > Manager' ) > ? ? ? ? ? ? ? ? print self.proxy > > if __name__ == "__main__": > ? ? ? ? obj = BusListener() > > Traceback (most recent call last): > ? File "Mount.py", line 13, in > ? ? obj = BusListener() > ? File "Mount.py", line 7, in __init__ > ? ? self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/ > freedesktop/Hal/Manager' ) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in > get_object > ? ? follow_name_owner_changes=follow_name_owner_changes) > ? File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in > __init__ > ? ? self._named_service = conn.activate_name_owner(bus_name) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in > activate_name_owner > ? ? self.start_service_by_name(bus_name) > ? File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in > start_service_by_name > ? ? 'su', (bus_name, flags))) > ? File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in > call_blocking > ? ? message, timeout) > dbus.exceptions.DBusException: > org.freedesktop.DBus.Error.ServiceUnknown: The name > org.freedesktop.Hal was not provided by any .service files > > Kindly some one please tell me why i am getting this error . > Thank you I am using Ubuntu 11.04 . From ansuman.python at gmail.com Thu Sep 1 12:46:52 2011 From: ansuman.python at gmail.com (Ansuman Bebarta) Date: Thu, 1 Sep 2011 09:46:52 -0700 (PDT) Subject: Microphone Input Message-ID: <3a8e8ad0-5ff8-4236-88b6-73be500e1ad3@p25g2000pri.googlegroups.com> I want to have a microphone input in a python program on cross platform. I don't want to use any third party module rather I want to have a module of my own. Please guide me in this direction. From ian.g.kelly at gmail.com Thu Sep 1 13:19:33 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 11:19:33 -0600 Subject: Listing HAL devices In-Reply-To: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> References: <781677b3-722d-4c9d-80d6-ca00b0de4abc@r40g2000prf.googlegroups.com> Message-ID: On Thu, Sep 1, 2011 at 9:46 AM, mukesh tiwari wrote: > dbus.exceptions.DBusException: > org.freedesktop.DBus.Error.ServiceUnknown: The name > org.freedesktop.Hal was not provided by any .service files > > Kindly some one please tell me why i am getting this error . > Thank you It looks like you don't have HAL installed. In any case, this is a Ubuntu / DBus issue, not really a Python issue, so you might find better support at those fora. By the way, HAL is deprecated. I believe current best practice is to interface with udev directly, but I don't know exactly what that entails. From james.thornton at gmail.com Thu Sep 1 13:58:54 2011 From: james.thornton at gmail.com (JT) Date: Thu, 1 Sep 2011 10:58:54 -0700 (PDT) Subject: Help parsing a text file In-Reply-To: References: Message-ID: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: > > I have a text file with XML like records that I need to parse. By XML > like I mean records have proper opening and closing tags. but fields > don't have closing tags (they rely on line ends). Not all fields appear > in all records, but they do adhere to a defined sequence. lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). - James -- Bulbflow: A Python framework for graph databases (http://bulbflow.com) From nospam at domain.invalid Thu Sep 1 14:38:09 2011 From: nospam at domain.invalid (William Gill) Date: Thu, 01 Sep 2011 14:38:09 -0400 Subject: Help parsing a text file In-Reply-To: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> References: <015c1b3a-947f-4e11-8b1b-6f4ae52c31fd@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/1/2011 1:58 PM, JT wrote: > On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: >> >> I have a text file with XML like records that I need to parse. By XML >> like I mean records have proper opening and closing tags. but fields >> don't have closing tags (they rely on line ends). Not all fields appear >> in all records, but they do adhere to a defined sequence. > > lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). > > - James > Thanks to everyone. Though I didn't get what I expected, it made me think more about the reason I need to parse these files to begin with. So I'm going to do some more homework on the overall business application and work backward from there. Once I know how the data fits in the scheme of things, I will create an appropriate abstraction layer, either from scratch, or using one of the existing parsers mentioned, but I won't really know that until I have finished modeling. From tjreedy at udel.edu Thu Sep 1 14:40:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 14:40:28 -0400 Subject: fun with nested loops In-Reply-To: References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/1/2011 10:05 AM, Daniel wrote: You seems to be requesting one of the options in http://python.org/dev/peps/pep-3136/ Labeled break and continue (The 'Other languages' section omits Fortran.) The rejection post is at http://mail.python.org/pipermail/python-3000/2007-July/008663.html I basically agree with it. Your use case seems to be valid, extreme, and rare. You would probably use the proposed feature responsibly. But you are not everyone. I am not sure what Python-solution I would recommend. I might just stick with whatever you are doing that works for your group. However, I can also understand the desire to improve. -- Terry Jan Reedy From pavlovevidence at gmail.com Thu Sep 1 15:02:45 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 Sep 2011 12:02:45 -0700 (PDT) Subject: fun with nested loops In-Reply-To: References: Message-ID: <7f43d4ad-fbd7-45f0-bcf5-719e19813429@glegroupsg2000goo.googlegroups.com> On Wednesday, August 31, 2011 8:51:45 AM UTC-7, Daniel wrote: > Dear All, > > I have some complicated loops of the following form > > for c in configurations: # loop 1 > while nothing_bad_happened: # loop 2 > while step1_did_not_work: # loop 3 > for substeps in step1 # loop 4a > # at this point, we may have to > -leave loop 1 > -restart loop 4 > -skip a step in loop 4 > -continue on to loop 4b > > while step2_did_not_work: # loop 4b > for substeps in step2: > # at this point, we may have to > -leave loop 1 > -restart loop 2 > -restart loop 4b > ... > ...many more loops... > > > I don't see any way to reduce these nested loops logically, they > describe pretty well what the software has to do. > This is a data acquisition application, so on ever line there is > a lot of IO that might fail or make subsequent steps useless or > require a > retry. > > Now every step could need to break out of any of the enclosing loops. I feel your pain. Every language, even Python, has cases where the trade-offs made in the language design make some legitimate task very difficult. In such cases I typically throw out the guidebook and make use of whatever shameless Perlesque thing it takes to keep things manageable. In your example you seem like you're trying to maintain some semblance of structure and good habit; I'd it's probably no longer worth it. Just store the level to break to in a variable, and after every loop check the variable and break if you need to break further. Something like this, for example: break_level = 99 while loop1: while loop2: while loop3: if some_condition: break_level = (1, 2, or 3) break if break_level < 3: break break_level = 99 if break_level < 2: break break_level = 99 Carl Banks From woooee at gmail.com Thu Sep 1 15:17:37 2011 From: woooee at gmail.com (woooee) Date: Thu, 1 Sep 2011 12:17:37 -0700 (PDT) Subject: Text file with mixed end-of-line terminations References: <4e5e8d71$0$2554$e4fe514c@news2.news.xs4all.nl> Message-ID: <93d72f06-2e4d-4857-9d9a-f21473ef3267@x11g2000prb.googlegroups.com> You can use f.read() to read the entire file's contents into a string, providing the file isn't huge. Then, split on "\r" and replace "\n" when found. A simple test: input_data = "abc\rdef\rghi\r\njkl\r\nmno\r\n" first_split = input_data.split("\r") for rec in first_split: rec = rec.replace("\n", "") print rec From aaron.hildebrandt at gmail.com Thu Sep 1 15:54:02 2011 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 1 Sep 2011 12:54:02 -0700 (PDT) Subject: OSX application built with py2app can't see bundled PySide module? Message-ID: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> I'm trying to deploy a Python app on OSX that was built with PySide. py2app packages it without issue, copying and linking a lot of PySide and Qt files in the process. But then, when I try to run the built app, I get this error: Traceback (most recent call last): File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 31, in _run('dailies_v02.py') File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/dailies_v02.py", line 9, in from PySide.QtCore import * File "PySide/__init__.pyc", line 2, in File "PySide/private.pyc", line 2, in File "PySide/QtCore.pyc", line 18, in File "PySide/QtCore.pyc", line 15, in __load ImportError: '/usr/lib/python2.6/lib-dynload/PySide/QtCore.so' not found The weird thing is, QtCore.so IS included in the application bundle: py2app copied it to the build under Contents/Resources/lib/python2.6/lib-dynload/PySide/. Is there a reason the application isn't seeing this? From false at pp.jaring.my Thu Sep 1 17:12:44 2011 From: false at pp.jaring.my (Fulvio) Date: Fri, 02 Sep 2011 05:12:44 +0800 Subject: Optparse buggy? Message-ID: Hello, I'm on python3.2, trying some experiment with OptionParser but no success >>> from optparse import OptionParser as parser >>> parser.add_option('-n','--new', dest='new') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.2/optparse.py", line 1001, in add_option option = self.option_class(*args, **kwargs) AttributeError: 'str' object has no attribute 'option_class' >>> Any futher item in the option won't make any better. -- Archlinux on $(uname -a) :P From mydevgroup at gmail.com Thu Sep 1 17:14:23 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 22:14:23 +0100 Subject: Python thread Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George From ian.g.kelly at gmail.com Thu Sep 1 17:24:33 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 1 Sep 2011 15:24:33 -0600 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 3:12 PM, Fulvio wrote: > Hello, > > I'm on python3.2, trying some experiment with OptionParser but no success > >>>> from optparse import OptionParser as parser >>>> parser.add_option('-n','--new', dest='new') > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python3.2/optparse.py", line 1001, in add_option > ? ?option = self.option_class(*args, **kwargs) > AttributeError: 'str' object has no attribute 'option_class' >>>> > > Any futher item in the option won't make any better. You're trying to call the method from the OptionParser class -- you need to instantiate it first. from optparse import OptionParser parser = OptionParser() parser.add_option('-n', '--new', dest='new') ... Cheers, Ian From jason.swails at gmail.com Thu Sep 1 17:27:25 2011 From: jason.swails at gmail.com (Jason Swails) Date: Thu, 1 Sep 2011 17:27:25 -0400 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 5:12 PM, Fulvio wrote: > Hello, > > I'm on python3.2, trying some experiment with OptionParser but no success > > >>> from optparse import OptionParser as parser > >>> parser.add_option('-n','--new', dest='new') > Here you've imported parser as an alias to the OptionParser class. You can only use add_option() on an instance of that class. Try this: from optparse import OptionParser parser = OptionParser() parser.add_option('-n','--new',dest='new') However, I think argparse has replaced optparse since Python 2.7 and higher... HTH, Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From mydevgroup at gmail.com Thu Sep 1 17:41:13 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 22:41:13 +0100 Subject: PythonThreading Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George From mydevgroup at gmail.com Thu Sep 1 17:45:11 2011 From: mydevgroup at gmail.com (George Kovoor) Date: Thu, 1 Sep 2011 22:45:11 +0100 Subject: Threads in Python Message-ID: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Sep 1 17:51:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 17:51:32 -0400 Subject: Optparse buggy? In-Reply-To: References: Message-ID: On 9/1/2011 5:12 PM, Fulvio wrote: > I'm on python3.2, trying some experiment with OptionParser but no success Do note "The optparse module is deprecated and will not be developed further; development will continue with the argparse module." -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 1 17:54:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 17:54:37 -0400 Subject: Python thread In-Reply-To: References: Message-ID: On 9/1/2011 5:14 PM, George wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. Perhaps because threads are not subprocesses? > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. > > Does it mean that python threads are not mapped to the core in the system. They all run on the same core. > On using multiprocessing module, separate processes are created with unique > PID. That is why multiprocessing was added. -- Terry Jan Reedy From mydevgroup at gmail.com Thu Sep 1 18:08:01 2011 From: mydevgroup at gmail.com (George) Date: Thu, 01 Sep 2011 23:08:01 +0100 Subject: Python thread In-Reply-To: Message-ID: So what exactly does threading module do, if it doesn't create a subprocess. Does each thread have its own stack and PC. What advantage would a threading module provide over sequential execution. On 01/09/2011 22:54, "Terry Reedy" wrote: > On 9/1/2011 5:14 PM, George wrote: >> Hi, >> Why doesn't python threads show an associated PID? On spawning python >> threads using the threading module I can only see the main thread's pid on >> using top or ps unix command, no subprocesses are displayed. In otherwords >> top or ps in not aware of any subprocesses created using threading module in >> python. > > Perhaps because threads are not subprocesses? > >> Whereas in Java , creating threads will result in separate pid , these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. >> >> Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > >> On using multiprocessing module, separate processes are created with unique >> PID. > > That is why multiprocessing was added. > From ramit.prasad at jpmorgan.com Thu Sep 1 18:21:37 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 1 Sep 2011 18:21:37 -0400 Subject: Python thread In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> >So what exactly does threading module do, if it doesn't create a subprocess. >Does each thread have its own stack and PC. >What advantage would a threading module provide over sequential execution. I believe it merely simulates multiple processes through scheduling (like the CPU). From http://docs.python.org/library/threading.html: CPython implementation detail: Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From me+list/python at ixokai.io Thu Sep 1 18:27:32 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Thu, 01 Sep 2011 15:27:32 -0700 Subject: Threads in Python In-Reply-To: References: Message-ID: <4E6006D4.9080106@ixokai.io> On 9/1/11 2:45 PM, George Kovoor wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. I think you're confused about what threads and subprocesses are. They are completely different mechanisms for concurrent code. Threads never show up on top or ps, in any language ... or the language isn't offering threads. I don't know Java, so I can't really comment on it much, but it may be misusing the 'thread' word, but I somehow doubt it. I suspect you're just mistaken about what Java is offering. Threads are separate operating ..er, chains-of-instructions within a single process... Notably with threads, they share the same address space so you can easily share objects amongst threads, without any copying and with no overhead ... Also notably with threads, this can be dangerous, so you often end up wrapping lots of locks around those shared objects and have to take extreme care to make sure nothing goes haywire. Subprocesses are different; they are a whole, separate process with its own address space and no shared memory (unless you go out of your way to do it manually). Heck, each subprocess can have any number of threads. Anything you want to share between them you have to take special care to set up and do -- multiprocessing exists to make this easier and make subprocesses easier to use, like threads are. They're very distinct. Threads are a lot more lightweight and start up a lot faster, but doing multithreaded programming right with any sort of shared objects is really, really, really hard to get right. Some say you can't. But, in Python, only one thread actually ever executes actual Python code at any given time. This does not actually make threading useless as some people claim; if you're making a lot of calls into C-code, for instance, the lock gets released while said C-code runs and other Python code can continue along. Its just not useful if your program is CPU-bound and wants to take advantage of multiple cores. But there's lots of other reasons to go concurrent. But if you do need lots of CPU power, multiprocessing lets you chew up multiple cores and does so /fairly/ easily. Communication between the processes can be expensive depending on the types of objects you need to pass back and forth, but it depends on how you're designing your app. They're just different ways of achieving concurrency, and the two primary ways Python provides. (Greenlets is another, available as a third-party module; Twisted's asynch dispatching isn't really exactly concurrency, but it does a better job then concurrency does for some operations; someone's always working on coroutines in some fashion or another, which is another kind of concurrency.) Lots of different ways to go concurrent, depending on your needs. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From cs at zip.com.au Thu Sep 1 18:43:01 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 2 Sep 2011 08:43:01 +1000 Subject: Threads in Python In-Reply-To: <4E6006D4.9080106@ixokai.io> References: <4E6006D4.9080106@ixokai.io> Message-ID: <20110901224301.GA8878@cskk.homeip.net> On 01Sep2011 15:27, Stephen Hansen wrote: | On 9/1/11 2:45 PM, George Kovoor wrote: | > Why doesn't python threads show an associated PID? On spawning python | > threads using the threading module I can only see the main thread's pid on | > using top or ps unix command, no subprocesses are displayed. In otherwords | > top or ps in not aware of any subprocesses created using threading module in | > python. | > | > Whereas in Java , creating threads will result in separate pid , these | > subprocesses can be listed using top or ps. Java threads get mapped to the | > cores in the system. | | I think you're confused about what threads and subprocesses are. They | are completely different mechanisms for concurrent code. Threads never | show up on top or ps, in any language ... or the language isn't offering | threads. I don't know Java, so I can't really comment on it much, but it | may be misusing the 'thread' word, but I somehow doubt it. I suspect | you're just mistaken about what Java is offering. No, you're mistaken about the threading models on offer. Some systems offer a threading model where threads can have distinct process ids; the only real criterion is that they share the same address space. The advantages of separate process ids for threads include letting the OS arrange their scheduling, delivery of signals (on UNIX systems) to a particular thread, ability to use multiple cores. On the flipside, threads with distinct process ids tend to be more expensive to set up and may be more expensive in thread switching. Java has long shipped with multiple threading implementations; IIRC "green threads" is an "all in one process id" model that can be used on any platform. Some use a mix of heavyweight (threads with distinct pids) and lightweight threads. | But, in Python, only one thread actually ever executes actual Python | code at any given time. In CPython this is true. Other implementations like Jython can use other threading models; I'd expect Jython to take a lot of advantage of Java's native threads. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Seeing my great fault Through darkening blue windows I begin again - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From benjamin.kaplan at case.edu Thu Sep 1 18:46:32 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 1 Sep 2011 18:46:32 -0400 Subject: Python thread In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Sep 1, 2011 at 6:21 PM, Prasad, Ramit wrote: >>So what exactly does threading module do, if it doesn't create a subprocess. >>Does each thread have its own stack and PC. >>What advantage would a threading module provide over sequential execution. > > I believe it merely simulates multiple processes through scheduling (like the CPU). > > >From http://docs.python.org/library/threading.html: CPython implementation detail: Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocessing. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously. > > Ramit Threading is an OS-level construct to allow concurrency within a single process (and address space). Threads are never supposed to be separate processes (they aren't at the C-level, so I don't know what Java is doing here). CPython code has a global interpreter lock which prevents two threads from running Python code at the same time, but they're still useful for asynchronous operations. For example, one thread can be waiting for user input while another thread continues to process data. Other Python implementations such as Jython and IronPython don't have a global interpreter lock so threads can run concurrently (and on different cores in a multi-core machine). > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Thu Sep 1 19:02:17 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 19:02:17 -0400 Subject: Python thread In-Reply-To: References: Message-ID: On 9/1/2011 6:08 PM, George wrote: > So what exactly does threading module do, if it doesn't create a subprocess. > Does each thread have its own stack and PC. > What advantage would a threading module provide over sequential execution. https://secure.wikimedia.org/wikipedia/en/wiki/Thread_%28computer_science%29 -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 1 19:06:16 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 01 Sep 2011 19:06:16 -0400 Subject: PythonThreading In-Reply-To: References: Message-ID: Please do not repeatedly post the same thing. Doing so, with different titles, will only annoy people. It takes awhile for a post to show up with whatever news or mail reader you are using. -- Terry Jan Reedy From lists at cheimes.de Thu Sep 1 19:09:51 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 Sep 2011 01:09:51 +0200 Subject: Python thread In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F165DD74C@EMARC112VS01.exchad.jpmchase.net> Message-ID: Am 02.09.2011 00:46, schrieb Benjamin Kaplan: > Threading is an OS-level construct to allow concurrency within a > single process (and address space). Threads are never supposed to be > separate processes (they aren't at the C-level, so I don't know what > Java is doing here). CPython code has a global interpreter lock which > prevents two threads from running Python code at the same time, but > they're still useful for asynchronous operations. For example, one > thread can be waiting for user input while another thread continues to > process data. Other Python implementations such as Jython and > IronPython don't have a global interpreter lock so threads can run > concurrently (and on different cores in a multi-core machine). On Linux threading is implemented with multiple processes. A Linux pthread is a clone of the process created with the clone(2) syscall. [1] Each thread has a PID and an entry in the kernel's process table. Tools like htop can show user land threads as different processes. This may explain the confusion of the OP. He may have seen multiple Java threads as different processes. psutil can list all threads with PIDs. The getpid(2) syscall returns always the PID of the main process, gettid (only available through syscall(SYS_gettid)) returns the PID of the current thread. Christian [1] http://linux.die.net/man/2/clone From nobody at nowhere.com Thu Sep 1 20:10:14 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 02 Sep 2011 01:10:14 +0100 Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? Not reliably. You might infer that Ctrl-Alt-Del has been used by the way that certain operations behave, but that's fairly error-prone. > Also, is there a corresponding key-sequence in Mac and Linux? And how > might one detect those too? I don't know about Mac. Linux has some support for Ctrl-Alt-Del on the console, and the optional "Magic SysRq" feature. But there's no easy way to detect these (if the sequence is recognised by the kernel, it's not reported by the usual mechanisms). From dalist0 at gmail.com Thu Sep 1 20:21:33 2011 From: dalist0 at gmail.com (Daniel) Date: Thu, 1 Sep 2011 17:21:33 -0700 (PDT) Subject: fun with nested loops References: <7f43d4ad-fbd7-45f0-bcf5-719e19813429@glegroupsg2000goo.googlegroups.com> Message-ID: I thought a bit about Carl's and Thomas' proposals, and it gave me an idea how this problem could be approached: Break is relatively easy to implement with a context manager that returns an iterable that throws an exception specific to that context manager: with named_loop(i for i in range(10)) as loop1: for i in loop1: with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._break() # this is easy loop1._continue() # this is difficult # if we _continue here, we need to do a continue right after the with loop2a: if loop1.cont: continue # context manager does not create new scope with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() this throws an exception that propagates through all the context managers till it hits the one that made loop1 at that point the exception is caught. Now using the idea of break_levels, something like loop1._continue() should work. It is more difficult, because it should be caught in the last loop before the one that is targeted, loop1._continue throws an exception that is caught in loop2. Then loop1 just continues with the next value. I don't know how loop2 can learn that it is enclosed in loop1. Maybe loop1 could add itself to a global stack on enter and delete itself on exit, or maybe inspect could help? The big problem is that loop1._continue breaks out of loop2a, but then starts to execute loop2b, which we don't want. If loop1 is _continued inside of loop2a, a continue needs to directly follow the loop2a with block. An alternative would be to wrap each sequence of statements in another with statement, I think this is better: for i in loop1: with sequenced_stuff(): with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._continue() # this is caught in sequenced_stuff() with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() Loops can even be restarted with a small modification: In a loop like "for i in loop1:" the __iter__ method of loop1 is called. If __iter__ returns a smart iterator that keeps a reference to loop1, then it can be restarted, advanced etc. loop1.restart() would throw an exception that __exits__ all the inner loops and gets caught in the loop just before loop1. Then it resets the iterable that the iterator returned by __iter__ links to, i.e. loop1 restarts. Nice side benefit: loops can have a method peek(n) to look ahead. Thanks for all your input, Dan From bkasterm at gmail.com Thu Sep 1 20:35:10 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Thu, 01 Sep 2011 18:35:10 -0600 Subject: List comprehension timing difference. Message-ID: <87zkinkcht.fsf@gmail.com> In the following code I create the graph with vertices sgb-words.txt (the file of 5 letter words from the stanford graphbase), and an edge if two words differ by one letter. The two methods I wrote seem to me to likely perform the same computations, the list comprehension is faster though (281 seconds VS 305 seconds on my dell mini). Is the right interpretation of this timing difference that the comprehension is performed in the lower level C code? As this time I have no other conjecture about the cause. --------------------------------------------------------- import time import copy data = map (lambda x: x.strip(), open('sgb-words.txt').readlines()) def d (w1, w2): count = 0 for idx in range(0,5): if w1[idx] != w2[idx]: count += 1 return count print "creating graph" t0 = time.clock () graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a < b] t1 = time.clock () print "took " + str (t1 - t0) + " seconds." t0 = time.clock () graph2 = [] for i in range (0, len(data)): for j in range(0,len(data)): if d(data[i],data[j]) == 1 and i < j: graph2.append ([i,j]) t1 = time.clock () print "took " + str (t1 - t0) + " seconds." From steve+comp.lang.python at pearwood.info Thu Sep 1 21:04:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 11:04:01 +1000 Subject: fun with nested loops References: <9dc99e77-af2e-4d28-b563-e1a66236318e@er4g2000vbb.googlegroups.com> <4e5ecdcf$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e5ed6ef$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e602b81$0$29985$c3e8da3$5496439d@news.astraweb.com> Daniel wrote: > That's the form the specification is in, and it makes sense and is > very readable. > In pseudocode it looks like this, I am using @ to give loops a name: > > @loop1 > for c in configurations: > @loop2 > while not_done: > @loop3 > while step1_did_not_work: > @loop4 > for substeps in step1 # loop 4a > if hopeless(): continue loop1 # run next configuration > if substepsFailed(): restart loop4 # try again > if substepsWorked(): break loop3 # go on to next > steps, like loop4 > > That format is fine, everyone involved can understand it, even the > people in charge. Well good for them, because I sure as hell don't understand it. To me, that's exactly the sort of thing that Guido was worried about when he rejected the idea of named labels. I'd need to sit down and trace a few loops by hand to grasp it. I wonder how new people coming into the project find it? Personally, I consider two nested loops right on the boundary of my "magic number seven, plus or minus two" short term memory[1]. I prefer to chunk code into functions so that I can ignore details of the inner loops while reasoning about the outer loops, and vice versa. If you feel different, then I'm not being sarcastic when I say "good for you". If you require a 1:1 correspondence between your code and your pseudo-code specification, then maybe Python isn't the right language for this task. Ruby is very Python-like, and has labelled loops. Perl and PHP less so, but can also be quite readable with some discipline. You could also check out Cobra -- their website is down just at the moment, so I can't check whether it has labelled loops. http://cobra-language.com/ [1] Not really magic, and probably more like 4?2. -- Steven From python at mrabarnett.plus.com Thu Sep 1 21:12:47 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 02 Sep 2011 02:12:47 +0100 Subject: List comprehension timing difference. In-Reply-To: <87zkinkcht.fsf@gmail.com> References: <87zkinkcht.fsf@gmail.com> Message-ID: <4E602D8F.4090408@mrabarnett.plus.com> On 02/09/2011 01:35, Bart Kastermans wrote: > > In the following code I create the graph with vertices > sgb-words.txt (the file of 5 letter words from the > stanford graphbase), and an edge if two words differ > by one letter. The two methods I wrote seem to me to > likely perform the same computations, the list comprehension > is faster though (281 seconds VS 305 seconds on my dell mini). > > Is the right interpretation of this timing difference > that the comprehension is performed in the lower level > C code? > > As this time I have no other conjecture about the cause. > > --------------------------------------------------------- > import time > import copy > > data = map (lambda x: x.strip(), open('sgb-words.txt').readlines()) > > def d (w1, w2): > count = 0 > for idx in range(0,5): > if w1[idx] != w2[idx]: > count += 1 > return count > > print "creating graph" > t0 = time.clock () > graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a< b] > t1 = time.clock () > print "took " + str (t1 - t0) + " seconds." > > t0 = time.clock () > graph2 = [] > for i in range (0, len(data)): > for j in range(0,len(data)): > if d(data[i],data[j]) == 1 and i< j: > graph2.append ([i,j]) > t1 = time.clock () > print "took " + str (t1 - t0) + " seconds." Are they actually equivalent? Does graph == graph2? The first version (list comprehension) creates a list of pairs of values: [a, b] whereas the second version (for loops) creates a list of pairs of indexes: [i, j] The second version has subscripting ("data[i]" and "data[j]"), which will slow it down. From rtomek at ceti.com.pl Thu Sep 1 21:53:07 2011 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Fri, 2 Sep 2011 03:53:07 +0200 (CEST) Subject: slightly OT -- LaTeX In-Reply-To: <4E60379F.4000702@stoneleaf.us> References: <4E60379F.4000702@stoneleaf.us> Message-ID: On Thu, 1 Sep 2011, Ethan Furman wrote: > I asked a question a couple weeks ago about scripting WordPerfect with Python, > and a couple respondents suggested LaTeX was very good. Where would I start > if I wanted to learn about it? > > ~Ethan~ 1. Leslie Lamport, "LaTeX: A Document Preparation System" - I have used it, learning LaTeX in front of a computer, as I wrote my first document in it. I guess this is a very good book on the subject but I have never tried anything else. 2. http://www.latex-project.org/ http://www.latex-project.org/guides/ http://www.ctan.org/ Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From ethan at stoneleaf.us Thu Sep 1 21:55:43 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 01 Sep 2011 18:55:43 -0700 Subject: slightly OT -- LaTeX Message-ID: <4E60379F.4000702@stoneleaf.us> I asked a question a couple weeks ago about scripting WordPerfect with Python, and a couple respondents suggested LaTeX was very good. Where would I start if I wanted to learn about it? ~Ethan~ From sahil at FreeBSD.org Thu Sep 1 22:02:54 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 01 Sep 2011 22:02:54 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E60394E.2080708@FreeBSD.org> [Thanks to everyone who responded] Steven D'Aprano wrote: > On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: >> %% >> # unbuffer STDOUT >> sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) > > I've never bothered with unbuffered stdout, but that looks fine to me. > > I'm not sure if it is necessary though, because print seems to automatically > flush the buffer after each line in my testing. Unless you're printing > repeatedly to the same line, I'm not sure unbuffered stdout is helpful. I found it necessary because without reopening sys.stdout with buffering explicitly turned off, I would have to manually flush the buffer after each print. This is because the program must reply (via writing to STDOUT) after parsing each line read via STDIN. If I neither disable buffering nor manually flush after each print, the program just hangs instead of printing right away. >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: >> print('foo') >> else: >> print('bar') >> %% > > "while True" is considered slightly more idiomatic (readable), but > otherwise, that seems fine. Ah, thanks -- I've changed '1' to 'True'. >> This works, but while reading the documentation, I thought of using 'for >> line in fileinput.input()' in lieu of 'while 1:' construct. This does >> not work when debugging the program on the command line -- the script >> appears to just hang no matter what is typed into STDIN. I believe this >> is because of some internal buffering when using fileinput. Is there a >> recommended way to disable such buffering? Am I taking a totally wrong >> approach? > > I'm not sure anything about fileinput is exactly *recommended*, it's kinda > discouraged on account of being a bit slow. See help(fileinput) at the > interactive prompt. > > For what it's worth, the default buffersize for fileinput.input is 0, so if > that doesn't do what you want, I don't think fileinput is the right > solution. Got it. Based on your and others' response, I will stick with my existing approach. -- Sahil Tandon From ben+python at benfinney.id.au Thu Sep 1 22:11:23 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 02 Sep 2011 12:11:23 +1000 Subject: slightly OT -- LaTeX References: Message-ID: <8762lbsng4.fsf@benfinney.id.au> Ethan Furman writes: > I asked a question a couple weeks ago about scripting WordPerfect with > Python, and a couple respondents suggested LaTeX was very good. Someone (you, or the respondents, or some combination of those) has omitted a few steps there, and what you've said here has become a non sequitur: I can't see the path you've taken from ?scripting WordPerfect with Python? to ?LaTeX?. How does this relate to Python? (If it relates only to WordPerfect or LaTeX, you're in the wrong forum, so I assume there must be some particular relevance to Python.) > Where would I start if I wanted to learn about it? About LaTeX? seems the obvious answer. If you want something more specific, please be more specific with the question. -- \ ?Now Maggie, I?ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.? ?Homer, _The Simpsons_ | _o__) | Ben Finney From false at pp.jaring.my Thu Sep 1 22:11:55 2011 From: false at pp.jaring.my (Fulvio) Date: Fri, 02 Sep 2011 10:11:55 +0800 Subject: Optparse buggy? References: Message-ID: Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." Then,do you propose me to opt to argparse? -- Archlinux on $(uname -a) :P F From roy at panix.com Thu Sep 1 22:16:13 2011 From: roy at panix.com (Roy Smith) Date: Thu, 01 Sep 2011 22:16:13 -0400 Subject: Optparse buggy? References: Message-ID: In article , Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." One of the unfortunate things about optparse and argparse is the names. I can never remember which is the new one and which is the old one. It would have been a lot simpler if the new one had been named optparse2 (in the style of unittest2 and urllib2). From ben+python at benfinney.id.au Thu Sep 1 22:18:19 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 02 Sep 2011 12:18:19 +1000 Subject: Optparse buggy? References: Message-ID: <871uvzsn4k.fsf@benfinney.id.au> Fulvio writes: > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > Then,do you propose me to opt to argparse? Without argument, yes; though for now it is opt-in. -- \ ?We are no more free to believe whatever we want about God than | `\ we are free to adopt unjustified beliefs about science or | _o__) history [?].? ?Sam Harris, _The End of Faith_, 2004 | Ben Finney From askutt at gmail.com Thu Sep 1 22:25:22 2011 From: askutt at gmail.com (Adam Skutt) Date: Thu, 1 Sep 2011 19:25:22 -0700 (PDT) Subject: Python thread References: Message-ID: On Sep 1, 5:14?pm, George wrote: > Hi, > Why doesn't python threads show an associated PID? ?On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no ?subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. You probably need to run 'ps axm' or something similar to see to threads associated with a processes on your system. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. No. It depends on your runtime, but if Java uses native threads, it will have the same behavior as Python here. It also doesn't mean they get mapped to cores in the system. All it means is the operating system is responsible for scheduling the threads and managing their lifecycle. Adam From gagsl-py2 at yahoo.com.ar Thu Sep 1 22:26:54 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Sep 2011 23:26:54 -0300 Subject: Calling Script from Command line not working References: Message-ID: En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S escribi?: > We created a DLL using cygwin and have written a class based python > module > for the same. We have created a sample script for the class based python > module, that creates an object of the class and calls various methods in > the > class. This Test script works fine while I run it from IDLE. However > when I > run it from command prompt it either hangs or just returns without > executing > the functions. When it returns I do not get a error trace. > > When I tried to findout where exactly the issue is happening. the issue > occurs when I try to call the *cygwin_dll_init* method of the > cygwin1.dll . > This cygwin1.dll is actualy a dependency to the DLL we have built. So we > have to load this DLL and call this *cygwin_dll_init* method before > loading > my DLL. > > > cyg = cdll.LoadLibrary("cygwin1.dll") > cyg.cygwin_dll_init() #hangs or returns here > mydll=cdll.LoadLibrary("my.dll") >mydll.func1() >I'm trying to understand what exactly is the difference, when we call it > IDLE and when we call it from command prompt using the python command. I > will have to get the script working from command prompt as well. A few comments: * why do you initialize cygwin1.dll in Python? If it's a dependency of my.dll, it might be better to load and initialize it there. * for this function prototype: void cygwin_dll_init(void); you should declare it using: cyg = cdll.LoadLibrary("cygwin1.dll") cyg.restype = None cyg.cygwin_dll_init() #hangs or returns here ... Anyway, I don't see why a console application would fail but not inside IDLE. -- Gabriel Genellina From askutt at gmail.com Thu Sep 1 22:28:58 2011 From: askutt at gmail.com (Adam Skutt) Date: Thu, 1 Sep 2011 19:28:58 -0700 (PDT) Subject: Python thread References: Message-ID: On Sep 1, 5:54?pm, Terry Reedy wrote: > > Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > No, CPython is a native thread implementation, so they'll be scheduled however the kernel sees fit. Only allowing one thread to run at a time doesn't mean they'll always run on the same core. Adam From dan at tombstonezero.net Thu Sep 1 22:32:17 2011 From: dan at tombstonezero.net (Dan Sommers) Date: Fri, 2 Sep 2011 02:32:17 +0000 (UTC) Subject: idiomatic analogue of Perl's: while (<>) { ... } References: <4e5f2010$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 01 Sep 2011 16:02:54 +1000, Steven D'Aprano wrote: > On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: >> print('foo') >> else: >> print('bar') >> %% > "while True" is considered slightly more idiomatic (readable), but > otherwise, that seems fine. Arguably more readable, but arguably less idomatic, is to describe the actual condition that controls the loop in a string (non-empty strings are equivalent to True in this context): while "there is more input": rval = parse(raw_input()) if real is None: print('foo') else: print('bar') (Although now that I've said that, this looks like an infinite loop unless parse, raw_input, or print raises an exception.) Dan From miki.tebeka at gmail.com Fri Sep 2 00:01:56 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 1 Sep 2011 21:01:56 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <0d3e6227-9435-4103-b810-ae3b6e58c04f@glegroupsg2000goo.googlegroups.com> I found http://tobi.oetiker.ch/lshort/lshort.pdf very useful. From miki.tebeka at gmail.com Fri Sep 2 00:01:56 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 1 Sep 2011 21:01:56 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <0d3e6227-9435-4103-b810-ae3b6e58c04f@glegroupsg2000goo.googlegroups.com> I found http://tobi.oetiker.ch/lshort/lshort.pdf very useful. From invalid at invalid.invalid Fri Sep 2 00:32:48 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 2 Sep 2011 04:32:48 +0000 (UTC) Subject: Threads in Python References: Message-ID: On 2011-09-01, Stephen Hansen wrote: > On 9/1/11 2:45 PM, George Kovoor wrote: >> Why doesn't python threads show an associated PID? On spawning >> python threads using the threading module I can only see the main >> thread's pid on using top or ps unix command, no subprocesses are >> displayed. In otherwords top or ps in not aware of any subprocesses >> created using threading module in python. That's because threads are displayed by top/ps in most Linux systems. >> Whereas in Java , creating threads will result in separate pid, these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. If that's on the same system, then those aren't threads. > I think you're confused about what threads and subprocesses are. They > are completely different mechanisms for concurrent code. Threads never > show up on top or ps, in any language... That depends on your threading model. Some versions of Linux using LinuxThreads rather than NPTL will show each thread in top or ps. > or the language isn't offering threads. The difference between threads and processes isn't whether they show up in top or ps. For many years threads showed up in top and ps. They were still threads. But, you're right that on most modern, non-embedded, Linux systems threads don't show up in top or ps. > I don't know Java, so I can't really comment on it much, but it may > be misusing the 'thread' word, but I somehow doubt it. I suspect > you're just mistaken about what Java is offering. Sure sounds like it. -- Grant From cs at zip.com.au Fri Sep 2 01:01:59 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 2 Sep 2011 15:01:59 +1000 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: <4E60394E.2080708@FreeBSD.org> References: <4E60394E.2080708@FreeBSD.org> Message-ID: <20110902050158.GA20589@cskk.homeip.net> On 01Sep2011 22:02, Sahil Tandon wrote: | [Thanks to everyone who responded] | | Steven D'Aprano wrote: | >On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: | >>%% | >># unbuffer STDOUT | >>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) | > | >I've never bothered with unbuffered stdout, but that looks fine to me. | > | >I'm not sure if it is necessary though, because print seems to automatically | >flush the buffer after each line in my testing. Unless you're printing | >repeatedly to the same line, I'm not sure unbuffered stdout is helpful. | | I found it necessary because without reopening sys.stdout with | buffering explicitly turned off, I would have to manually flush the | buffer after each print. This is because the program must reply | (via writing to STDOUT) after parsing each line read via STDIN. If | I neither disable buffering nor manually flush after each print, the | program just hangs instead of printing right away. Yes. Steven was probably testing on a terminal. UNIX stdio buffering is line buffered on a terminal and block buffered otherwise (except for stderr, which is normally unbuffered regardless). So Steven saw stuff flushed on newlines and you would see stuff flushed when you explicitly flush or when the buffer fills (probably doesn't happen for your use because you need a response, and never write enough to fill the buffer). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Gentle suggestions being those which are written on rocks of less than 5lbs. - Tracy Nelson in comp.lang.c From anacrolix at gmail.com Fri Sep 2 01:33:01 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Fri, 2 Sep 2011 15:33:01 +1000 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > ======================================================= > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > ======================================================= > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression?- another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie From pavlovevidence at gmail.com Fri Sep 2 01:42:08 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 Sep 2011 22:42:08 -0700 (PDT) Subject: Optparse buggy? In-Reply-To: References: Message-ID: <058eeca4-6892-4075-abab-3ddcf6773692@glegroupsg2000goo.googlegroups.com> On Thursday, September 1, 2011 7:16:13 PM UTC-7, Roy Smith wrote: > In article , > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > One of the unfortunate things about optparse and argparse is the names. > I can never remember which is the new one and which is the old one. It > would have been a lot simpler if the new one had been named optparse2 > (in the style of unittest2 and urllib2). It's easy: "opt"parse parses only "opt"ions (-d and the like), whereas "arg"parse parses all "arg"uments. argparse is the more recent version since it does more. optparse2 would have been a bad name for something that parses more than options. (In fact, although I have some minor philosophical disagreements with optparse's design decisions, the main reason I always recommended using argparse instead was that optparse didn't handle positional arguments. optparse has all these spiffy features with type checking and defaults, but it never occurred to the optparse developers that this stuff would be useful for positional arugments, too. They just dropped the ball there.) Carl Banks From gahtune at gmail.com Fri Sep 2 02:14:12 2011 From: gahtune at gmail.com (Gabriel AHTUNE) Date: Fri, 2 Sep 2011 14:14:12 +0800 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: So can be done with this syntax: > x = firstpart * secondpart + #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE 2011/9/2 Matt Joiner > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. > > On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > > Hi Matt, > > ======================================================= > > From: Matt Joiner > > > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > > already heavily used by other syntactical structures. > > ======================================================= > > How about only require indentation > > to freely break lines? Here is an example: > > x = firstpart * secondpart #line breaks here > > + anotherpart #continue by indentation > > + stillanother #continue on. > > #until here, another line starts by dedentation > > y = some_expression - another_one > > All this would be completely compatible with former code, while > > having almost free line breaking! Plus, indentation makes it pretty. > > Really hope Python can have freedom in breaking lines. > > Yingjie > _______________________________________________ > Python-ideas mailing list > Python-ideas at python.org > http://mail.python.org/mailman/listinfo/python-ideas > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sathish at solitontech.com Fri Sep 2 02:17:18 2011 From: sathish at solitontech.com (Sathish S) Date: Fri, 2 Sep 2011 11:47:18 +0530 Subject: Calling Script from Command line not working In-Reply-To: References: Message-ID: Hey Gabriel, Thanks a lot for replying. I was able to run this python script from console/command prompt using cygwin python. I'm not sure whats the difference between these two versions of python. But it seems to be working. Searching theough the web i found that having cygwin1.dll could be causing this issue. So I'm trying to build my DLL using MinGW which will not create an dependecy DLL's. But I'm stuck up with few more issue in porting few functions to MinGW. I'm using Python2.7 and Cygwin Python 2.6.5 *Reply to your comments:* ** why do you initialize cygwin1.dll in Python? If it's a dependency of my.dll, it might be better to load and initialize it there.* Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it and initializing it ** for this function prototype: void cygwin_dll_init(void);* *you should declare it using:* I'm doing this as you said. But didn't mention it in my mail hCyg = cdll.LoadLibrary(CygWinDLL_Name) hCyg = CDLL(CygWinDLL_Name) Prototype_Cyg = CFUNCTYPE(c_void_p) Init = Prototype_Cyg (("cygwin_dll_init", hCyg)) Init.restype = c_void_p Init() Thanks, Sathish On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina wrote: > En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S > escribi?: > > > We created a DLL using cygwin and have written a class based python module >> for the same. We have created a sample script for the class based python >> module, that creates an object of the class and calls various methods in >> the >> class. This Test script works fine while I run it from IDLE. However when >> I >> run it from command prompt it either hangs or just returns without >> executing >> the functions. When it returns I do not get a error trace. >> >> When I tried to findout where exactly the issue is happening. the issue >> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll >> . >> This cygwin1.dll is actualy a dependency to the DLL we have built. So we >> have to load this DLL and call this *cygwin_dll_init* method before >> loading >> my DLL. >> >> >> cyg = cdll.LoadLibrary("cygwin1.dll"**) >> cyg.cygwin_dll_init() #hangs or returns here >> mydll=cdll.LoadLibrary("my.**dll") >> mydll.func1() >> I'm trying to understand what exactly is the difference, when we call it >> IDLE and when we call it from command prompt using the python command. I >> will have to get the script working from command prompt as well. >> > > A few comments: > > * why do you initialize cygwin1.dll in Python? If it's a dependency of > my.dll, it might be better to load and initialize it there. > > * for this function prototype: void cygwin_dll_init(void); > you should declare it using: > > > cyg = cdll.LoadLibrary("cygwin1.dll"**) > cyg.restype = None > > cyg.cygwin_dll_init() #hangs or returns here > ... > > Anyway, I don't see why a console application would fail but not inside > IDLE. > > -- > Gabriel Genellina > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Fri Sep 2 02:19:58 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 02 Sep 2011 18:19:58 +1200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <9cbashF8buU1@mid.individual.net> > On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: > >>Also, is there a corresponding key-sequence in Mac and Linux? The nearest equivalent in MacOSX is Command-Option-Escape, which brings up the force-quit dialog. I don't know how deep down in the system it's implemented. It's possible to use SetSystemUIMode to put an app into a "kiosk mode" where force-quitting is disabled, but I don't know whether the app can intercept Command-Option-Escape in that situation and do something else with it. -- Greg From sathish at solitontech.com Fri Sep 2 02:21:52 2011 From: sathish at solitontech.com (Sathish S) Date: Fri, 2 Sep 2011 11:51:52 +0530 Subject: Calling Script from Command line not working In-Reply-To: References: Message-ID: One more thing I observed is, while running the script from IDLE it launches a seperate process of pythonw.exe and I could see this console window poping up. However while running it from command prompt this does not happens. I was wondering if the command prompt way of calling the script is not able to launch this new process, that why it could be hanging. BTW I'm still trying to get the script running using Python 2.7 from the command prompt. Thanks, Sathish On Fri, Sep 2, 2011 at 11:47 AM, Sathish S wrote: > Hey Gabriel, > Thanks a lot for replying. I was able to run this python script from > console/command prompt using cygwin python. I'm not sure whats the > difference between these two versions of python. But it seems to be working. > Searching theough the web i found that having cygwin1.dll could be causing > this issue. So I'm trying to build my DLL using MinGW which will not create > an dependecy DLL's. But I'm stuck up with few more issue in porting few > functions to MinGW. > > I'm using Python2.7 and Cygwin Python 2.6.5 > > *Reply to your comments:* > > > ** why do you initialize cygwin1.dll in Python? If it's a dependency of > my.dll, it might be better to load and initialize it there.* > Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it > and initializing it > > ** for this function prototype: void cygwin_dll_init(void);* > *you should declare it using:* > I'm doing this as you said. But didn't mention it in my mail > > hCyg = cdll.LoadLibrary(CygWinDLL_Name) > hCyg = CDLL(CygWinDLL_Name) > Prototype_Cyg = CFUNCTYPE(c_void_p) > Init = Prototype_Cyg (("cygwin_dll_init", hCyg)) > Init.restype = c_void_p > Init() > > Thanks, > Sathish > > > > On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina wrote: > >> En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S >> escribi?: >> >> >> We created a DLL using cygwin and have written a class based python >>> module >>> for the same. We have created a sample script for the class based python >>> module, that creates an object of the class and calls various methods in >>> the >>> class. This Test script works fine while I run it from IDLE. However when >>> I >>> run it from command prompt it either hangs or just returns without >>> executing >>> the functions. When it returns I do not get a error trace. >>> >>> When I tried to findout where exactly the issue is happening. the issue >>> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll >>> . >>> This cygwin1.dll is actualy a dependency to the DLL we have built. So we >>> have to load this DLL and call this *cygwin_dll_init* method before >>> loading >>> my DLL. >>> >>> >>> cyg = cdll.LoadLibrary("cygwin1.dll"**) >>> cyg.cygwin_dll_init() #hangs or returns here >>> mydll=cdll.LoadLibrary("my.**dll") >>> mydll.func1() >>> I'm trying to understand what exactly is the difference, when we call it >>> IDLE and when we call it from command prompt using the python command. I >>> will have to get the script working from command prompt as well. >>> >> >> A few comments: >> >> * why do you initialize cygwin1.dll in Python? If it's a dependency of >> my.dll, it might be better to load and initialize it there. >> >> * for this function prototype: void cygwin_dll_init(void); >> you should declare it using: >> >> >> cyg = cdll.LoadLibrary("cygwin1.dll"**) >> cyg.restype = None >> >> cyg.cygwin_dll_init() #hangs or returns here >> ... >> >> Anyway, I don't see why a console application would fail but not inside >> IDLE. >> >> -- >> Gabriel Genellina >> >> -- >> http://mail.python.org/**mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Fri Sep 2 02:38:01 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 23:38:01 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <1314945481.74495.YahooMailNeo@web121517.mail.ne1.yahoo.com> Hi Gabriel, ================================================== From: Gabriel AHTUNE Subject: Re: [Python-ideas] allow line break at operators So can be done with this syntax: > x = firstpart * secondpart? +? #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE ================================================== That's good to me too, which I proposed early in this thread. Then somebody would like to have the operator in the beginning of the next line so that it would stand out.Then still another one said that indentation is good here. So I finally proposed line continuation with indentation. Since this is Python, we will live with indentation. Currently indentation in Python starts a new block, but if you view it from the perspective of line breaking, it also function as if the line is continued. The line if condition: do_a(); do_b() can be ?written as: if condition: #line breaks do_a(); # ';' is optional here? do_b() # continue Sounds a pretty natural way to allow free line breaking. Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Fri Sep 2 02:45:07 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 1 Sep 2011 23:45:07 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <1314945907.94847.YahooMailNeo@web121513.mail.ne1.yahoo.com> Yeah, that might be a challenge for the Python?interpreter, for it has to check if the next line is indented or not. But it might be worthwhile to take this trouble, so that the coder has more freedom, and the code is hopefully better to read. ________________________________ From: Matt Joiner To: Yingjie Lan Cc: "python-list at python.org" ; python-ideas Sent: Friday, September 2, 2011 1:33 PM Subject: Re: [Python-ideas] allow line break at operators I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > ======================================================= > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > ======================================================= > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression?- another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From me+list/python at ixokai.io Fri Sep 2 03:06:12 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Fri, 02 Sep 2011 00:06:12 -0700 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4E608064.9030005@ixokai.io> On 9/1/11 8:52 AM, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? IIUC, by definition, Ctrl-Alt-Delete can't be responded to in any way. Its the entire point of the sequence: when you type it you can be entirely, totally, 100% certain that what happens next is the true OS and not any app faking things. That's why you have to hit CAD to get to the login form in some versions of Windows. The whole point of that secure sequence is that the OS and only the OS responds. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From tavares at fe.up.pt Fri Sep 2 03:08:14 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Fri, 2 Sep 2011 00:08:14 -0700 (PDT) Subject: CompIMAGE 2012: Call for Thematic Sessions and Papers Message-ID: Dear Colleague, We would like to call your attention to the International Symposium CompIMAGE 2012 ? Computational Modeling of Objects Presented in Images: Fundamentals, Methods and Applications (www.dis.uniroma1.it/ compimage2012), that will be held in Rome, Italy, in September 5-7, 2012. MAIN TOPICS - image processing and analysis - image segmentation - 2D and 3D reconstruction - data interpolation - registration and acquisition - objects tracking - scientific data visualization - satellite data - shape modeling - simulation - biometric person identification - medical imaging - motion and deformation analysis - material science - large set data visualization - vision in robotics and automation INVITED LECTURERS - Lorenzo Bruzzone, University of Trento, Italy - Jorge Marques, Instituto Superior T?cnico, Lisboa, Portugal - Fiorella Sgallari, University of Bologna, Italy - Bertrand Thirion, INRIA, France - Luminita Vese, UCLA, USA THEMATIC SESSIONS Proposals to organize Thematic Session within CompIMAGE2012 are welcome and should be submitted by email to: compimage2012 at dis.uniroma1.it. PUBLICATIONS - The proceedings book will be published by Taylor & Francis Group and indexed by Thomson Reuters Conference Proceedings Citation Index, IET Inspect and Elsevier Scopus. - A book with 20 invited works from the best ones presented in CompIMAGE 2012 (extended versions) will be published by Springer. - The organizers will encourage the submission of extended versions of the accepted papers to related International Journals; in particular, for special issues dedicated to CompIMAGE 2012. IMPORTANT DATES - Deadline for Thematic Sessions proposals: November 1, 2011 - Deadline for Full Paper Submission: December 31, 2011 - Authors Notification: March 16, 2012 - Final camera-ready papers: April 20, 2012 - Early Symposium registration (mandatory for Authors): April 20, 2012 - Symposium dates: September 5-7, 2012 AWARDS "Best paper award" and "Best student paper award" are going to be given to the author(s) of two papers presented at CompIMAGE 2012, selected by the Organizing Committee based on the best combined marks from the Scientific Committee and Session Chairs. Kind regards, Paolo Di Giamberardino Daniela Iacoviello Renato M. Natal Jorge Jo?o Manuel R. S. Tavares PS. For further details, please, visit CompIMAGE 2012 website at: www.dis.uniroma1.it/compimage2012. From nemjain at gmail.com Fri Sep 2 03:12:18 2011 From: nemjain at gmail.com (nemi) Date: Fri, 2 Sep 2011 00:12:18 -0700 (PDT) Subject: How to daemonize a HTTPServer References: <594e0376-3a1d-4430-bf47-d1e0f856c4dd@f31g2000prj.googlegroups.com> Message-ID: On Sep 1, 6:32?am, "Martin P. Hellwig" wrote: > On 01/09/2011 04:16, babbu Pehlwan wrote: > > > I have written a http server using BaseHTTPServer module. Now I want > > to instantiate it through another python script. The issue here is > > after instantiate the control doesn't come back till the server is > > running. Please suggest. > > Sounds like something you could use the multiprocessing module for, but > then again my crystal ball is a bit fuzzy today. > > -- > mph Thanks dear, the issue get solved now. You are absolutely right, actually I was daemonising the same thread. Now I have created a seperate thread for the server. From stephen at xemacs.org Fri Sep 2 03:28:16 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Fri, 02 Sep 2011 16:28:16 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Gabriel AHTUNE writes: > So can be done with this syntax: > > > x = firstpart * secondpart + #line breaks here > > anotherpart + #continue > > stillanother #continue on. > > after a "+" operator the line is clearly not finished yet. Sure, but IIRC one design principle of Python is that the keyword that denotes the syntax should be the first thing on the line, making it easy to scan down the left side of the code to see the syntactic structure. The required indentation of the controlled suite also helps emphasize that keyword. Analogously, if operators are going to denote continuation, they should come first on the line. I just don't think this idea is going anywhere. Explicit continuation with backslash or implicit continuation of parenthesized expressions is just not that heavy a price to pay. Perhaps historically some of these ideas could have been implemented, but now they're just going to confuse a host of editors and code analysis tools. From rosuav at gmail.com Fri Sep 2 03:55:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 2 Sep 2011 17:55:41 +1000 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <4E608064.9030005@ixokai.io> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: On Fri, Sep 2, 2011 at 5:06 PM, Stephen Hansen wrote: > That's why you have to hit CAD to get to the login form in some versions > of Windows. The whole point of that secure sequence is that the OS and > only the OS responds. > Although I heard somewhere that that's more gimmick than guarantee, and that it IS possible for an app to hook CAD - just that it's a lot harder than building a simple window that looks like the login... but it's pretty easy to fool a lot of people. Just look at the emails in your spam box one day, find the ones spoofing a bank, and see what a poor job they do. And yet they work. ChrisA From vinay_sajip at yahoo.co.uk Fri Sep 2 05:56:29 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 02:56:29 -0700 (PDT) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From vinay_sajip at yahoo.co.uk Fri Sep 2 05:58:29 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 09:58:29 +0000 (UTC) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From vinay_sajip at yahoo.co.uk Fri Sep 2 06:00:30 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 03:00:30 -0700 (PDT) Subject: Help me understand this logging config References: Message-ID: On Aug 30, 1:39 pm, Roy Smith wrote: > Oh, my, it turns out that django includes: > > # This is a copy of the Pythonlogging.config.dictconfig module, > # reproduced with permission. It is provided here for backwards > # compatibility for Python versions prior to 2.7. > > Comparing the django copy to lib/logging/config.py from Python 2.7.2, > they're not identical. It's likely they grabbed something earlier in > the 2.7 series. I'll check 2.7.0 and 2.7.1 to see. They're not identical, but should be functionally equivalent. I'm not able to reproduce your results: I copied the "loggers" part of your config into a Django 1.3 project, and from a manage.py shell session: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> import logging >>> logger = logging.getLogger('djfront.auth.facebook') >>> logger.debug('Debug') >>> logger.info('Info') 2011-09-02 10:51:13,445 INFO djfront.auth.facebook Info >>> ... as expected. Since it's Python 2.6, it should be using the dictconfig which ships with Django 1.3. Regards, Vinay Sajip From t at jollybox.de Fri Sep 2 06:01:34 2011 From: t at jollybox.de (Thomas Jollans) Date: Fri, 02 Sep 2011 12:01:34 +0200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4E60A97E.2080506@jollybox.de> On 01/09/11 17:52, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? > > Also, is there a corresponding key-sequence in Mac and Linux? And how > might one detect those too? On Linux Ctrl+Alt+Delete is typically configured to reboot the machine when in console mode. In X11 (graphical), as far as I know, it's no different than other keys. To catch it globally, you'd probably have to go through the individual window manager. As m'colleague Nobody mentions, there's also the SysRq feature, but that always goes straight to the kernel and is, like Ctrl+Alt+Delete on Windows, impossible to handle in userspace code. Thomas From fnautaNO at SPAMsolfon.nl Fri Sep 2 08:04:55 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 14:04:55 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><6545843.yvFAXZvWTv@PointedEars.de><9c528rFi5aU1@mid.individual.net><4761603.ypaU67uLZW@PointedEars.de><9c6d4cFa54U1@mid.individual.net> Message-ID: <9cbvupFjr3U2@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.622.1314812583.27778.python-list at python.org... > On Wed, 31 Aug 2011 11:27:36 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> >> Ofcourse I realized it was Unix/Linux. I already could tell that as the >> packages I downloaded were tar.gz files. >> So I unpacked them and expected to run a Python installer script from the >> Python command line. >> Hence my question "How do I do that", but perhaps I did not make myself >> clear enough. >> > NO Python package installer runs "from the Python command line" (ie; > from a Python interactive session prompt). > > Typically you run them from the OS command interpreter. If the > installer is a .py file and the associations are correct, the Python > interpreter will be started to process the installer script. If the > associations aren't set, you may have to enter > > python installer.py > > at the system prompt instead of > > installer.py > >> Tried to run the Python installer script from the DOS command line but >> that >> resulted in an error. >> > Okay -- so what was the error? > -- Sorry - I didn't come back on your question. In the mean time I forgot what the error message was. But I installed it the way Paul K?lle mentioned: "You dont install from "Python GUI", use normal cmd, navigate to the folder you downloaded PyXML and PyWebDAV and run "python setup.py install" (python.exe has to be in your PATH)." Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 08:19:32 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 14:19:32 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> Message-ID: <9cbvupFjr3U3@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.687.1314941410.27778.python-list at python.org... > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> "Dennis Lee Bieber" wrote in message >> news:mailman.643.1314851358.27778.python-list at python.org... > >> > Next, if you'd read further and didn't take the comment as the >> > instruction. set >> > firstrun=1 >> >> I did >> >> > to tell the server this is the first time it is being run - IT WILL >> > create the database table (after the first start, reset the flag to 0 >> > to >> > speed up later runs). >> >> It didn't create the table. The database kept empty. > > Odd -- but then, I'm not running it myself, and wasn't up to reading > all the code to see what path it takes. It's only for experimenting with calendar software, so authorization is not a point. So I forget about MySQL. >> >> > Later in the config file set >> > mysql_auth=1 >> > to enable the use of MySQL, and set the admin user/password to what you >> > plan to have it use. >> >> I did >> >> > You probably want to set >> > daemonize=1 >> > (maybe after first run) >> >> I left this to 0. >> >> > Oh, and don't forget to set the main data directory and any >> > port/host changes. >> >> I left host and port as they were. The main directory is e:\wwwroot >> >> > Start the server - it should connect to MySQL, create the table, and >> > add the admin user to the table. >> >> I started the server with server.py (in >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini >> > If the main directory is already in the config file, you probably > don't need to specify it on the command line... OK > And... could there be > something in the code where overriding the directory by command line > changes where it looks for the config file? (Just guessing at this > point). > Possibly. I tried this: server.py -n -c config.ini Once again, the server is up and running and when I am logging in with my browser (10.0.0.140:8081) I can see information showing up at the command prompt, showing somebody is logging is, but the same error: "fshandler:get_data: \Webdav not found". During starting up the server mentioned: "pywebdav:Serving data from \Webdav". In the config file it says: "# main directory directory = \Webdav" Perhaps my Python configuration is at fault. Fokke From msamogh at gmail.com Fri Sep 2 08:25:28 2011 From: msamogh at gmail.com (Amogh M S) Date: Fri, 2 Sep 2011 17:55:28 +0530 Subject: Python-list Digest, Vol 96, Issue 4 In-Reply-To: References: Message-ID: Thank you very much And no, no, I have not been reading a book with bad font =D haha!! The problem was that I did not inherit from Object... Since I am from a JAVA background, I assumed that Python would inherit implicitly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmsoft at gmail.com Fri Sep 2 08:27:50 2011 From: sjmsoft at gmail.com (sjm) Date: Fri, 2 Sep 2011 05:27:50 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sep 1, 12:52?pm, Den wrote: > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? If you manage to write a program that can detect CTRL-ALT-DEL, please report it as a bug in Windows! CTRL-ALT-DEL is Windows' "secure attention sequence" which must only be handled by the OS. -- Steve From msamogh at gmail.com Fri Sep 2 08:29:17 2011 From: msamogh at gmail.com (Amogh M S) Date: Fri, 2 Sep 2011 17:59:17 +0530 Subject: Python-list Digest, Vol 96, Issue 4 In-Reply-To: References: Message-ID: Two underscores??!!! OH!!! I thank thee! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Sep 2 08:45:39 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 02 Sep 2011 13:45:39 +0100 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: <4e60ce59$0$18107$426a74cc@news.free.fr> References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4e60ce59$0$18107$426a74cc@news.free.fr> Message-ID: <4E60CFF3.6080006@timgolden.me.uk> >> Obviously, this is a windows-based question. I know that Ctrl-Alt-Del >> is handled deep inside the OS, and I'm not trying to interrupt that. >> But is there some way to detect that a C-A-D has been pressed? Others have pointed out that this shouldn't really be possible for reasons of security. (And I agree). However, if what you're really after is to detect a session switch or a logon then this might be of some use: http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html TJG From bex.lewis at gmail.com Fri Sep 2 09:09:06 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Fri, 2 Sep 2011 06:09:06 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> Message-ID: <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> On Sep 2, 1:19?pm, "Fokke Nauta" wrote: > "Dennis Lee Bieber" wrote in messagenews:mailman.687.1314941410.27778.python-list at python.org... > > > > > > > > > > > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > > declaimed the following in > > gmane.comp.python.general: > > >> "Dennis Lee Bieber" wrote in message > >>news:mailman.643.1314851358.27778.python-list at python.org... > > >> > Next, if you'd read further and didn't take the comment as the > >> > instruction. set > >> > firstrun=1 > > >> I did > > >> > to tell the server this is the first time it is being run - IT WILL > >> > create the database table (after the first start, reset the flag to 0 > >> > to > >> > speed up later runs). > > >> It didn't create the table. The database kept empty. > > > Odd -- but then, I'm not running it myself, and wasn't up to reading > > all the code to see what path it takes. > > It's only for experimenting with calendar software, so authorization is not > a point. > So I forget about MySQL. > > > > > > > > > > > > >> > Later in the config file set > >> > mysql_auth=1 > >> > to enable the use of MySQL, and set the admin user/password to what you > >> > plan to have it use. > > >> I did > > >> > You probably want to set > >> > daemonize=1 > >> > (maybe after first run) > > >> I left this to 0. > > >> > Oh, and don't forget to set the main data directory and any > >> > port/host changes. > > >> I left host and port as they were. The main directory is e:\wwwroot > > >> > Start the server - it should connect to MySQL, create the table, and > >> > add the admin user to the table. > > >> I started the server with server.py (in > >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini > > > If the main directory is already in the config file, you probably > > don't need to specify it on the command line... > > OK > > > And... could there be > > something in the code where overriding the directory by command line > > changes where it looks for the config file? (Just guessing at this > > point). > > Possibly. > I tried this: > server.py -n -c config.ini > Once again, the server is up and running and when I am logging in with my > browser (10.0.0.140:8081) I can see information showing up at the command > prompt, showing somebody is logging is, but the same error: > "fshandler:get_data: \Webdav not found". During starting up the server > mentioned: "pywebdav:Serving data from \Webdav". > > In the config file it says: > "# main directory > directory = \Webdav" > > Perhaps my Python configuration is at fault. > > Fokke Is the path supposed to be absolute? In which case you'd need to have: directory=C:\path\to\Webdav instead of just directory=\Webdav Becky Lewis From python at bdurham.com Fri Sep 2 09:11:13 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 02 Sep 2011 09:11:13 -0400 Subject: Installing WebDAV server In-Reply-To: <9cbvupFjr3U3@mid.individual.net> References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> Message-ID: <1314969073.6889.140258136595213@webmail.messagingengine.com> Hi Fokke, Disclaimer: I have no experience with the Python WebDAV package you're using. But a thought: > In the config file it says: > "# main directory > directory = \Webdav" Perhaps you should qualify your directory path with a drive letter? I would try this 2 ways: directory = E:\Webdav And if that doesn't work: directory = E:/Webdav My thinking about the 2nd example is that perhaps the \W is getting interpreted as a control character vs. "backslash" "W". Malcolm From alan.isaac at gmail.com Fri Sep 2 09:12:37 2011 From: alan.isaac at gmail.com (Alan) Date: Fri, 2 Sep 2011 06:12:37 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> http://www.pytex.org/ hth, Alan Isaac From alan.isaac at gmail.com Fri Sep 2 09:12:37 2011 From: alan.isaac at gmail.com (Alan) Date: Fri, 2 Sep 2011 06:12:37 -0700 (PDT) Subject: slightly OT -- LaTeX In-Reply-To: References: Message-ID: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> http://www.pytex.org/ hth, Alan Isaac From kw at codebykevin.com Fri Sep 2 09:21:43 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 02 Sep 2011 09:21:43 -0400 Subject: OSX application built with py2app can't see bundled PySide module? In-Reply-To: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> References: <2e0b44ea-0d71-4c30-8efe-6582cf6923bd@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/1/11 3:54 PM, Aaron Scott wrote: > I'm trying to deploy a Python app on OSX that was built with PySide. py2app packages it without issue, copying and linking a lot of PySide and Qt files in the process. But then, when I try to run the built app, I get this error: > > Traceback (most recent call last): > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 31, in > _run('dailies_v02.py') > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py", line 28, in _run > execfile(path, globals(), globals()) > File "/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/dailies_v02.py", line 9, in > from PySide.QtCore import * > File "PySide/__init__.pyc", line 2, in > File "PySide/private.pyc", line 2, in > File "PySide/QtCore.pyc", line 18, in > File "PySide/QtCore.pyc", line 15, in __load > ImportError: '/usr/lib/python2.6/lib-dynload/PySide/QtCore.so' not found > > The weird thing is, QtCore.so IS included in the application bundle: py2app copied it to the build under Contents/Resources/lib/python2.6/lib-dynload/PySide/. Is there a reason the application isn't seeing this? You might want to post this question to the MacPython list--that's where the py2app experts are found. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From python at bdurham.com Fri Sep 2 09:49:30 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 02 Sep 2011 09:49:30 -0400 Subject: slightly OT -- LaTeX In-Reply-To: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> References: <5f676110-1623-47a9-8cc3-47a6f0ac9831@glegroupsg2000goo.googlegroups.com> Message-ID: <1314971370.18457.140258136609677@webmail.messagingengine.com> Hi Alan, Thanks for sharing that link - very interesting! http://www.pytex.org/ Malcolm (former LaTeX/TeX user from early 90's) From bkasterm at gmail.com Fri Sep 2 09:54:50 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 02 Sep 2011 07:54:50 -0600 Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> Message-ID: <87sjofjbh1.fsf@gmail.com> MRAB writes: > On 02/09/2011 01:35, Bart Kastermans wrote: >> graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a< b] >> graph2 = [] >> for i in range (0, len(data)): >> for j in range(0,len(data)): >> if d(data[i],data[j]) == 1 and i< j: >> graph2.append ([i,j]) > > Are they actually equivalent? Does graph == graph2? > > The first version (list comprehension) creates a list of pairs of > values: > > [a, b] > > whereas the second version (for loops) creates a list of pairs of > indexes: > > [i, j] > > The second version has subscripting ("data[i]" and "data[j]"), which > will slow it down. You are absolutely right. I had changed the code from the equivalent: graph2 = [] for i in range (0, len(data)): for j in range(0,len(data)): if d(data[i],data[j]) == 1 and i < j: graph2.append ([data[i],data[j]]) But then also tried the equivalent for a in data: for b in data: if d(a,b) == 1 and a < b: graph2.append([a,b]) Which does away with the indexing, and is just about exactly as fast as the list comprehension. That'll teach me; I almost didn't ask the question thinking it might be silly. And it was, but I thought it for the wrong reason. I tell my students there are no stupid questions, I should listen to myself more when I do. Thanks! From ting at thsu.org Fri Sep 2 10:50:24 2011 From: ting at thsu.org (ting at thsu.org) Date: Fri, 2 Sep 2011 07:50:24 -0700 (PDT) Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> <87sjofjbh1.fsf@gmail.com> Message-ID: <07906043-d732-43ca-8313-bee4746eca75@fi7g2000vbb.googlegroups.com> On Sep 2, 9:54?am, Bart Kastermans wrote: > if d(a,b) == 1 and a < b: It will probably be faster if you reverse the evaluation order of that expression. if a I have a function I want to run in a thread and return a value. It seems like the most obvious way to do this is to have my target function return the value, the Thread object stash that someplace, and return it as the return value for join(). Yes, I know there's other ways for a thread to return values (pass the target a queue, for example), but making the return value of the target function available would have been the most convenient. I'm curious why threading wasn't implemented this way. From d_vineet at yahoo.com Fri Sep 2 11:34:25 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Fri, 2 Sep 2011 08:34:25 -0700 (PDT) Subject: convert python List to javascript array Message-ID: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Hi ! Within a web framework, I want want to pass a python sequence (list or tuple) to client-side javascript function as an array (javascript compatible) e.g., I have this list: L = ['spam', 'ham', 'eggs', 12, (13.63)] What is the correct way to convert L to?javascript array format? 1) jsonify the list and pass it to javascript (whether json format & javascript array are similar?) OR 2) >> import array >> y = array.array(i, L) ?then return y to javascript function But the problem with this method is, it will give an array of basic values only. OR 3) Any other alternative? Thanks, Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 2 11:45:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 03 Sep 2011 01:45:22 +1000 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> Message-ID: <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: > I have a function I want to run in a thread and return a value. It > seems like the most obvious way to do this is to have my target > function return the value, the Thread object stash that someplace, and > return it as the return value for join(). > > Yes, I know there's other ways for a thread to return values (pass the > target a queue, for example), but making the return value of the > target function available would have been the most convenient. I'm > curious why threading wasn't implemented this way. Because then the code launching the thread would have to block, waiting until the thread is completed, so it will have a result to return. -- Steven From benjamin.kaplan at case.edu Fri Sep 2 11:50:12 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 2 Sep 2011 11:50:12 -0400 Subject: convert python List to javascript array In-Reply-To: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 11:34 AM, Vineet Deodhar wrote: > Hi ! > Within a web framework, I want want to pass a python sequence (list or > tuple) to client-side javascript function as an array (javascript > compatible) > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to?javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) > > OR > 2) >>> import array >>> y = array.array(i, L) > ?then return y to javascript function > But the problem with this method is, it will give an array of basic values > only. > > OR > 3) Any other alternative? > > Thanks, > Vineet > -- The JavaScript Object Notation (JSON) is meant exactly for this purpose. From patentsvnc at gmail.com Fri Sep 2 12:19:35 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:19:35 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <4310f6ad-8aab-481b-9e68-3931f67b49b6@m4g2000pri.googlegroups.com> On Sep 2, 5:27?am, sjm wrote: > On Sep 1, 12:52?pm, Den wrote: > > > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > > is handled deep inside the OS, and I'm not trying to interrupt that. > > But is there some way to detect that a C-A-D has been pressed? > > If you manage to write a program that can detect CTRL-ALT-DEL, please > report it as a bug in Windows! ?CTRL-ALT-DEL is Windows' "secure > attention sequence" which must only be handled by the OS. > > -- Steve I have already done that, in AutoHotKey ... or at least it used to work. AHK can detect when a window opened. And when CAD was pressed the ... well, I've forgotten what it was called ... but a window opened asking if you wanted to open the task manager, or quit or log off or what. Then you would know that CAD was pressed. There was nothing you could do to stop it, but you could at least detect that it had been pressed. That's why I was wondering if there was a similar technique which could be used in Python. Den From patentsvnc at gmail.com Fri Sep 2 12:20:23 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:20:23 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: <2ab915f4-a0cb-42ed-8d4b-5bd16a9ee9ca@x21g2000prd.googlegroups.com> On Sep 2, 5:27?am, sjm wrote: > On Sep 1, 12:52?pm, Den wrote: > > > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > > is handled deep inside the OS, and I'm not trying to interrupt that. > > But is there some way to detect that a C-A-D has been pressed? > > If you manage to write a program that can detect CTRL-ALT-DEL, please > report it as a bug in Windows! ?CTRL-ALT-DEL is Windows' "secure > attention sequence" which must only be handled by the OS. > > -- Steve I'm not trying to hook it or stop it, just detect it. Den From patentsvnc at gmail.com Fri Sep 2 12:26:12 2011 From: patentsvnc at gmail.com (Den) Date: Fri, 2 Sep 2011 09:26:12 -0700 (PDT) Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sep 1, 8:52?am, Den wrote: > Obviously, this is a windows-based question. ?I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? > > Also, is there a corresponding key-sequence in Mac and Linux? ?And how > might one detect those too? > > Den I've been doing some more thinking on what I want. This may be a better explanation. Is there a way of detecting if my program has lost "focus" (I'm not sure the correct term)? For example, if someone is typing in my program, but some other program takes control (or CAD has been pressed) I would like simply to log that. I have no interest in trying to hijack or interfere with anything, simply log it. Den From gagsl-py2 at yahoo.com.ar Fri Sep 2 12:36:17 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 13:36:17 -0300 Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> Message-ID: En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks escribi?: > On Aug 31, 7:37 pm, Gregory Ewing wrote: >> Ian Kelly wrote: >> > if sys.version_info < (3,): >> > getDictValues = dict.itervalues >> > else: >> > getDictValues = dict.values >> >> > (which is basically what the OP was doing in the first place). >> > My problem was that I didn't understand the scoping rules. It is still > strange to me that the getValues variable is still in scope outside > the if/else branches. Those if/else are at global scope. An 'if' statement does not introduce a new scope; so getDictValues, despite being "indented", is defined at global scope, and may be used anywhere in the module. -- Gabriel Genellina From usenet-nospam at seebs.net Fri Sep 2 12:42:34 2011 From: usenet-nospam at seebs.net (Seebs) Date: 02 Sep 2011 16:42:34 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-09-02, Steven D'Aprano wrote: > Roy Smith wrote: >> I have a function I want to run in a thread and return a value. It >> seems like the most obvious way to do this is to have my target >> function return the value, the Thread object stash that someplace, and >> return it as the return value for join(). >> Yes, I know there's other ways for a thread to return values (pass the >> target a queue, for example), but making the return value of the >> target function available would have been the most convenient. I'm >> curious why threading wasn't implemented this way. > Because then the code launching the thread would have to block, waiting > until the thread is completed, so it will have a result to return. Isn't "waiting until the thread is completed" sort of the point of join()? -s -- Copyright 2011, all wrongs reversed. Peter Seebach / usenet-nospam at seebs.net http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated! I am not speaking for my employer, although they do rent some of my opinions. From jehugaleahsa at gmail.com Fri Sep 2 12:53:37 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 09:53:37 -0700 (PDT) Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> Message-ID: <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> On Sep 2, 12:36?pm, "Gabriel Genellina" wrote: > En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks ? > escribi : > > > On Aug 31, 7:37 pm, Gregory Ewing wrote: > >> Ian Kelly wrote: > >> > if sys.version_info < (3,): > >> > ? ? getDictValues = dict.itervalues > >> > else: > >> > ? ? getDictValues = dict.values > > >> > (which is basically what the OP was doing in the first place). > > > My problem was that I didn't understand the scoping rules. It is still > > strange to me that the getValues variable is still in scope outside > > the if/else branches. > > Those if/else are at global scope. An 'if' statement does not introduce a ? > new scope; so getDictValues, despite being "indented", is defined at ? > global scope, and may be used anywhere in the module. > > -- > Gabriel Genellina > > Does that mean the rules would be different inside a function? From jehugaleahsa at gmail.com Fri Sep 2 12:59:03 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 09:59:03 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers Message-ID: Hello: I am working on an algorithms library. It provides LINQ like functionality to Python iterators. Eventually, I plan on having feaures that work against sequences and mappings. I have the code up at http://code.google.com/p/py-compass. This is my first project in Python, so I'd like some feedback. I want to know if I am following conventions (overall style and quality of code). Thanks, Travis Parks From clp2 at rebertia.com Fri Sep 2 13:26:15 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 10:26:15 -0700 Subject: convert python List to javascript array In-Reply-To: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 8:34 AM, Vineet Deodhar wrote: > Hi ! > Within a web framework, I want want to pass a python sequence (list or > tuple) to client-side javascript function as an array (javascript > compatible) > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to?javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) JSON is in fact a subset of JavaScript, and modern browsers now include a specific API for parsing and generating it (https://developer.mozilla.org/En/Using_native_JSON ). Python likewise has a JSON module in the std lib: http://docs.python.org/library/json.html > OR > 2) >>> import array >>> y = array.array(i, L) > ?then return y to javascript function > But the problem with this method is, it will give an array of basic values > only. The word "array" gets tossed around a lot by programmers. The `array` module is not at all what you want in this case. Cheers, Chris -- http://rebertia.com From norrisd at bellsouth.net Fri Sep 2 13:41:32 2011 From: norrisd at bellsouth.net (aMereCat) Date: Fri, 2 Sep 2011 10:41:32 -0700 (PDT) Subject: Tenjin and External CSS Message-ID: I'm new at Python, Cherrypy and Tenjin and I can't get tenjin to recognize external css file. Does anyone have an example showing how it's done? Thanks. From johnroth1 at gmail.com Fri Sep 2 13:51:14 2011 From: johnroth1 at gmail.com (John Roth) Date: Fri, 2 Sep 2011 10:51:14 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> Message-ID: <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> On Sep 1, 8:26?am, Ian Kelly wrote: > On Thu, Sep 1, 2011 at 6:45 AM, John Roth wrote: > > I personally consider this to be a wart. Some time ago I did an > > implementation analysis. The gist is that, if self and cls were made > > special variables that returned the current instance and class > > respectively, then the compiler could determine whether a function was > > an instance or class method. If it then marked the code object > > appropriately you could get rid of all of the wrappers and the > > attendant run-time overhead. > > I don't see how you could get rid of the wrappers. ?Methods would > still need to be bound, somehow, so that code like this will work: > > methods = {} > for obj in objs: > ? ? if obj.is_flagged: > ? ? ? ? methods[obj.user_id] = obj.do_work > ? ? else: > ? ? ? ? methods[obj.user_id] = obj.do_other_work > # ... > methods[some_user_id]() > > Without method wrappers, how does the interpreter figure out which > instance is bound to the method being called? > > Cheers, > Ian Good question. Currently the instance wrapper is created during method instantiation, so the instance is obviously available at that point. There are two rather obvious ways of remembering it. One is to use the invocation stack, which has the instance. Another would be for the compiler to create a local variable for the instance and possibly the class and fill them in at instantiation time. Both of these require fixing the names "self" and "cls" so the compiler knows what to do with them. The first would require giving these two names their own bytecodes, the second makes them simple local variables the same as the ones in the method headers. The latter also allows them to be changed by the method, which is probably not the world's best programming practice although it's possible now. John Roth From askutt at gmail.com Fri Sep 2 14:01:17 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 11:01:17 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> Message-ID: <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> On Sep 2, 10:53?am, Roy Smith wrote: > I have a function I want to run in a thread and return a value. ?It > seems like the most obvious way to do this is to have my target > function return the value, the Thread object stash that someplace, and > return it as the return value for join(). > > Yes, I know there's other ways for a thread to return values (pass the > target a queue, for example), but making the return value of the > target function available would have been the most convenient. ?I'm > curious why threading wasn't implemented this way. I assume it is because the underlying operating system APIs do not support it. Windows and POSIX threads only support returning an integer when a thread exits, similar to the exit code of a process. More importantly, there's no way to tell whether the exit code of a thread was set by user code or by the system. Even worse, some of those integer values are reserved by some operating systems. If your thread died via an exception, it still has an error code set by the operating system. How would you going to distinguish those codes from your own? Adam From alain at dpt-info.u-strasbg.fr Fri Sep 2 14:23:28 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Fri, 02 Sep 2011 20:23:28 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Adam Skutt writes: > On Sep 2, 10:53?am, Roy Smith wrote: >> I have a function I want to run in a thread and return a value. ?It >> seems like the most obvious way to do this is to have my target >> function return the value, the Thread object stash that someplace, and >> return it as the return value for join(). >> > Yes, I know there's other ways for a thread to return values (pass the >> target a queue, for example), but making the return value of the >> target function available would have been the most convenient. ?I'm >> curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Windows and POSIX threads only support returning an > integer when a thread exits, similar to the exit code of a process. Sorry, you're wrong, at least for POSIX threads: void pthread_exit(void *value_ptr); int pthread_join(pthread_t thread, void **value_ptr); pthread_exit can pass anything, and that value will be retrieved with pthread_join. Threads of a process share their address space, there is no reason to restrict their return value to an int. > More importantly, there's no way to tell whether the exit code of a > thread was set by user code or by the system. Even worse, some of > those integer values are reserved by some operating systems. I'm not sure what you are talking about here. Maybe you confuse threads with processes? Re. the original question: since you can define your own Thread subclass, with wathever attribute you want, I guess there was no need to use join() to communicate the result. The Thread's run() can store its result in an attribute, and the "client" can get it from the same attribute after a successful call to join(). -- Alain. From Tim.Arnold at sas.com Fri Sep 2 14:43:53 2011 From: Tim.Arnold at sas.com (Tim Arnold) Date: Fri, 02 Sep 2011 14:43:53 -0400 Subject: sqlite3 with context manager Message-ID: Hi, I'm using the 'with' context manager for a sqlite3 connection: with sqlite3.connect(my.database,timeout=10) as conn: conn.execute('update config_build set datetime=?,result=? where id=?', (datetime.datetime.now(), success, self.b['id'])) my question is what happens if the update fails? Shouldn't it throw an exception? I ask because apparently something went wrong yesterday and the code never updated but I never got any warning. I rebooted the machine and everything is okay now, but I'd like to understand what happened. thanks, --Tim From vinay_sajip at yahoo.co.uk Fri Sep 2 14:47:33 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 11:47:33 -0700 (PDT) Subject: ANN: A new version (0.2.8) of the Python module which wraps GnuPG has been released. Message-ID: A new version of the Python module which wraps GnuPG has been released. What Changed? ============= This is a minor enhancement and bug-fix release. See the project website ( http://code.google.com/p/python-gnupg/ ) for more information. Summary: Better support for status messages from GnuPG. The fixing of some Unicode encoding problems. Quoted some command-line arguments to gpg for increased safety. The current version passes all tests on Windows (CPython 2.4, 2.5, 2.6, 3.1, 2.7 and Jython 2.5.1) and Ubuntu (CPython 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2). On Windows, GnuPG 1.4.11 has been used for the tests. What Does It Do? ================ The gnupg module allows Python programs to make use of the functionality provided by the Gnu Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP. This module is expected to be used with Python versions >= 2.4, as it makes use of the subprocess module which appeared in that version of Python. This module is a newer version derived from earlier work by Andrew Kuchling, Richard Jones and Steve Traugott. A test suite using unittest is included with the source distribution. Simple usage: >>> import gnupg >>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') >>> gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) ']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) ']}] >>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A']) >>> str(encrypted) '-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -----END PGP MESSAGE-----\n' >>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret') >>> str(decrypted) 'Hello, world!' >>> signed = gpg.sign("Goodbye, world!", passphrase='secret') >>> verified = gpg.verify(str(signed)) >>> print "Verified" if verified else "Not verified" 'Verified' For more information, visit http://code.google.com/p/python-gnupg/ - as always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. From askutt at gmail.com Fri Sep 2 14:53:43 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 11:53:43 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: On Sep 2, 2:23?pm, Alain Ketterlin wrote: > Sorry, you're wrong, at least for POSIX threads: > > void pthread_exit(void *value_ptr); > int pthread_join(pthread_t thread, void **value_ptr); > > pthread_exit can pass anything, and that value will be retrieved with > pthread_join. No, it can only pass a void*, which isn't much better than passing an int. Passing a void* is not equivalent to passing anything, not even in C. Moreover, specific values are still reserved, like PTHREAD_CANCELLED. Yes, it was strictly inappropriate for me to say both return solely integers, but my error doesn't meaningful alter my description of the situation. The interface provided by the underlying APIs is not especially usable for arbitrary data transfer. Doubly so when we're discussing something like Python's threading module. > I'm not sure what you are talking about here. Maybe you confuse threads > with processes? Windows threads have exit codes, just like processes. At least one code is reserved and cannot be used by the programmer. Adam From gagsl-py2 at yahoo.com.ar Fri Sep 2 15:10:41 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 16:10:41 -0300 Subject: Help required accessing dictionary References: <54e7c93d35c11cdf72cee56a8a1c5abc@edss.co.in> Message-ID: En Wed, 31 Aug 2011 22:46:54 -0300, escribi?: > I need to access the dictionary of the script that I am running through > my vc++ application by embedding python. > I am linking to python dynamically. I want to obtain the dictionary of > the script and access the variables declared in the script. > However, with the PyObject * that I get from the dictionary, I am not > able to find the type of the object. The reason being that > GetProcAddress to PyInt_Check returns a NULL. The same thing with > PyFloat_Check and so on. I think this is because they are macros and > not > exported functions. > > What can be done to be able to perform these checks without statically > linking to the pyhon lib ? Just include python.h PyInt_Check is completely implemented as a macro, it doesn't call any function. /* from intobject.h */ #define PyInt_Check(op) \ PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_INT_SUBCLASS) /* from object.h */ #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) -- Gabriel Genellina From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:12:36 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:12:36 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net> Message-ID: <9cco6uFvh4U1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.711.1314983727.27778.python-list at python.org... > On Fri, 2 Sep 2011 14:19:32 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > > >> >> In the config file it says: >> "# main directory >> directory = \Webdav" >> > I think that's the line that should have your e:/wwwroot > specification > -- Sorry! It used to have. But as it did not work, with the same error message, it could not find E:\wwwroot, I changed it into \Webdav. Ofcourse, in the command line as well. Later on I left the D specification out in the command line. Perhaps another drive letter might cause the problem, so in this case I kept it on the same partition. But I still got the same error. Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:21:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:21:03 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> Message-ID: <9ccoqkF5efU1@mid.individual.net> "becky_lewis" wrote in message news:86b084e0-09a8-4997-9e0c-4526d7851e1d at s2g2000vby.googlegroups.com... On Sep 2, 1:19 pm, "Fokke Nauta" wrote: > "Dennis Lee Bieber" wrote in > messagenews:mailman.687.1314941410.27778.python-list at python.org... > > > On Thu, 1 Sep 2011 12:30:43 +0200, "Fokke Nauta" > > declaimed the following in > > gmane.comp.python.general: > > >> "Dennis Lee Bieber" wrote in message > >>news:mailman.643.1314851358.27778.python-list at python.org... > > >> > Next, if you'd read further and didn't take the comment as the > >> > instruction. set > >> > firstrun=1 > > >> I did > > >> > to tell the server this is the first time it is being run - IT WILL > >> > create the database table (after the first start, reset the flag to 0 > >> > to > >> > speed up later runs). > > >> It didn't create the table. The database kept empty. > > > Odd -- but then, I'm not running it myself, and wasn't up to reading > > all the code to see what path it takes. > > It's only for experimenting with calendar software, so authorization is > not > a point. > So I forget about MySQL. > >> > Later in the config file set > >> > mysql_auth=1 > >> > to enable the use of MySQL, and set the admin user/password to what > >> > you > >> > plan to have it use. > > >> I did > > >> > You probably want to set > >> > daemonize=1 > >> > (maybe after first run) > > >> I left this to 0. > > >> > Oh, and don't forget to set the main data directory and any > >> > port/host changes. > > >> I left host and port as they were. The main directory is e:\wwwroot > > >> > Start the server - it should connect to MySQL, create the table, and > >> > add the admin user to the table. > > >> I started the server with server.py (in > >> D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini > > > If the main directory is already in the config file, you probably > > don't need to specify it on the command line... > > OK > > > And... could there be > > something in the code where overriding the directory by command line > > changes where it looks for the config file? (Just guessing at this > > point). > > Possibly. > I tried this: > server.py -n -c config.ini > Once again, the server is up and running and when I am logging in with my > browser (10.0.0.140:8081) I can see information showing up at the command > prompt, showing somebody is logging is, but the same error: > "fshandler:get_data: \Webdav not found". During starting up the server > mentioned: "pywebdav:Serving data from \Webdav". > > In the config file it says: > "# main directory > directory = \Webdav" > > Perhaps my Python configuration is at fault. > > Fokke Is the path supposed to be absolute? In which case you'd need to have: directory=C:\path\to\Webdav instead of just directory=\Webdav I tried: directory=D:\Webdav directory=D:/Webdav To no avail. It didn.t make any difference. I surely believe my WebDAV installation is at fault. Fokke From fnautaNO at SPAMsolfon.nl Fri Sep 2 15:24:02 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Fri, 2 Sep 2011 21:24:02 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net> Message-ID: <9ccoqkF5efU2@mid.individual.net> wrote in message news:mailman.703.1314969082.27778.python-list at python.org... > Hi Fokke, > > Disclaimer: I have no experience with the Python WebDAV package you're > using. > > But a thought: > >> In the config file it says: >> "# main directory >> directory = \Webdav" > > Perhaps you should qualify your directory path with a drive letter? > > I would try this 2 ways: > > directory = E:\Webdav > > And if that doesn't work: > > directory = E:/Webdav > > My thinking about the 2nd example is that perhaps the \W is getting > interpreted as a control character vs. "backslash" "W". > I tried: directory=D:\Webdav directory=D:/Webdav To no avail. It didn't make any difference. I surely believe my WebDAV installation is at fault. And D: is the same partition as where Python is, D:\Python27 Fokke From guido at python.org Fri Sep 2 15:30:34 2011 From: guido at python.org (Guido van Rossum) Date: Fri, 2 Sep 2011 12:30:34 -0700 Subject: [Python-ideas] allow line break at operators In-Reply-To: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > Gabriel AHTUNE writes: > ?> So can be done with this syntax: > ?> > ?> > x = firstpart * secondpart ?+ ?#line breaks here > ?> > anotherpart + #continue > ?> > stillanother #continue on. > ?> > ?> after a "+" operator the line is clearly not finished yet. > > Sure, but IIRC one design principle of Python is that the keyword that > denotes the syntax should be the first thing on the line, making it > easy to scan down the left side of the code to see the syntactic > structure. ?The required indentation of the controlled suite also > helps emphasize that keyword. That's true for *statements* (except assignments and calls). > Analogously, if operators are going to denote continuation, they > should come first on the line. That doesn't follow. My preferred style is actually to put the binary operator at the end of the line. This also matches the prevailing style for breaking lines after commas (a comma can be seen as a kind of binary operator). > I just don't think this idea is going anywhere. ?Explicit continuation > with backslash or implicit continuation of parenthesized expressions > is just not that heavy a price to pay. ?Perhaps historically some of > these ideas could have been implemented, but now they're just going to > confuse a host of editors and code analysis tools. Totally agreed that this isn't going to happen. -- --Guido van Rossum (python.org/~guido) From sahil at FreeBSD.org Fri Sep 2 15:56:46 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Fri, 02 Sep 2011 15:56:46 -0400 Subject: idiomatic analogue of Perl's: while (<>) { ... } In-Reply-To: References: <20110901045650.GA3466@magic.hamla.org> Message-ID: <4E6134FE.9060309@FreeBSD.org> Dennis Lee Bieber wrote: > On Thu, 1 Sep 2011 00:56:50 -0400, Sahil Tandon >> # process input, line-by-line, and print responses after parsing input >> while 1: >> rval = parse(raw_input()) >> if rval == None: > > There is only ONE "None" object so the preferred method is > > if rval is None: Understood; thanks for that enlightenment. > Note: I don't see any exit handler/condition... Indeed. I excluded such things in the interest of brevity, to focus the discussion on my question. :) -- Sahil Tandon From gagsl-py2 at yahoo.com.ar Fri Sep 2 16:06:57 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 17:06:57 -0300 Subject: Invoking profile from command line prevent my sys.path modification References: Message-ID: En Thu, 01 Sep 2011 07:51:43 -0300, Ya?ar Arabac? escribi?: > I am new to profile module, so I am sorry if this is an absolute beginner > question. In order to my code to run, I need to add a directory to > sys.path. > When I invole python -m profile myfile.py, my code won't work, saying > that > the thing that is supposed to be in path, isn't. Code works fine without > profiling. Profiling works if I write it into the file, but I don't > prefer > doing that, if that is possible. You may set the PYTHONPATH environment variable, just for the profiling session. http://docs.python.org/install/index.html#modifying-python-s-search-path -- Gabriel Genellina From ian.g.kelly at gmail.com Fri Sep 2 16:09:26 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 14:09:26 -0600 Subject: Algorithms Library - Asking for Pointers In-Reply-To: References: Message-ID: On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > Hello: > > I am working on an algorithms library. It provides LINQ like > functionality to Python iterators. Eventually, I plan on having > feaures that work against sequences and mappings. > > I have the code up at http://code.google.com/p/py-compass. > > This is my first project in Python, so I'd like some feedback. I want > to know if I am following conventions (overall style and quality of > code). Sure, here are my comments. In the "forever" and "__forever" functions, your use of the term "generator" is confusing. "__forever" is a generator function, because it has a yield statement. Its argument, called "generator", appears to be a callable, not a generator or even necessarily a generator function. Also, note that __forever(lambda: value) is functionally equivalent to the more efficient itertools.repeat(value). The staticmethod __next(iterator) accesses the class it is defined in, which suggests that it might be better written as a classmethod __next(cls, iterator). Each of the LINQ-style methods is divided into two parts: the public method that contains the docstring and some argument checks, and a private staticmethod that contains the implementation. I'm not certain what the purpose of that is. If it's to facilitate overriding the implementation in subclasses, then you need to change the names of the private methods to start with only one _ character so that they won't be mangled by the compiler. The comments before each method that only contain the name of the immediately following method are redundant. aggregate: the default aggregator is unintuitive to me. I would make it a required field and add a separate method called sum that calls aggregate with the operator.add aggregator. Also, the implementation doesn't look correct. Instead of passing in each item to the aggregator, you're passing in the number of items seen so far? The LINQ Aggregate method is basically reduce, so rather than reinvent the wheel I would suggest this: # MISSING is a unique object solely defined to represent missing arguments. # Unlike None we can safely assume it will never be passed as actual data. MISSING = object() def aggregate(self, aggregator, seed=MISSING): if seed is self.MISSING: return reduce(aggregator, self._iterable) else: return reduce(aggregator, self._iterable, seed) Note for compatibility that in Python 3 the reduce function has been demoted from a builtin to a member of the functools module. any: the name of this method could cause some confusion with the "any" builtin that does something a bit different. compare: the loop would more DRY as a for loop: def __compare(first, second, comparison): for firstval, secondval in itertools.izip_longest(first, second, fillvalue=self.MISSING): if firstval is self.MISSING: return -1 elif secondval is self.MISSING: return 1 else: result = comparison(firstval, secondval) if result != 0: return result return 0 concatenate: again, no need to reinvent the wheel. This should be more efficient: def concatenate(self, other): return extend(itertools.chain(self.__iterable, other)) equals: could be just "return self.compare(other, comparison) == 0" __last: the loop could be a for loop: # assume we're looking at the last item and try moving to the next item = result.Value for item in iterator: pass return item lastOrDefault: there's a lot of repeated logic here. This could just be: def lastOrDefault(self, default=None): try: return self.last() except ValueError: return default map / forEach: .NET has to separate these into separate methods due to static typing. It seems a bit silly to have both of them in Python. Also, map would be more efficient as "return itertools.imap(mapper, self.__iterable)" max / min: it would be more efficient to use the builtin: def max(self, key): return max(self.__iterable, key=key) If somebody really needs to pass a comparison function instead of a key function, they can use functools.cmp_to_key. randomSamples: a more canonical way to pass the RNG would be to pass an instance of random.Random rather than an arbitrary function. Then to get a random integer you can just call generator.randrange(total). Note that for the default you can just use the random module itself, which provides default implementations of all the Random methods. Also, for loops: def __randomSamples(iterable, sampleCount, generator): samples = [] iterator = iter(iterable) # fill up the samples with the items from the beginning of the iterable for i, value in zip(xrange(sampleCount), iterator): samples.append(value) # replace items if the generated number is less than the total total = len(samples) for value in iterator: total += 1 index = generator.randrange(total) if index < len(samples): samples[index] = result return samples __reverse: you could just "return reversed(list(iterable))" __rotateLeft: def __rotateLeft(iterable, shift): iterator = iter(iterable) front = list(itertools.islice(iterator, shift)) return itertools.chain(iterator, front) skipWhile: suggest using itertools.dropwhile take: suggest using itertools.islice takeWhile: suggest using itertools.takewhile __toList: "return list(iterable)" __toSet: "return set(iterable)" __toTuple: "return tuple(iterable)". Note that as currently written this actually returns a generator, not a tuple. __where: suggest using itertools.ifilter __zip: suggest using a for loop over itertools.izip(first, second) Lookup: is inconsistent. The overridden __iter__ method returns an iterator over the values of the groups, but all the inherited methods are going to iterate over the keys. Probably you want to pass groups.values() to the superclass __init__ method. Cheers, Ian From nospam at torek.net Fri Sep 2 16:14:56 2011 From: nospam at torek.net (Chris Torek) Date: 2 Sep 2011 20:14:56 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: >On Sep 2, 2:23?pm, Alain Ketterlin >wrote: >> Sorry, you're wrong, at least for POSIX threads: >> >> void pthread_exit(void *value_ptr); >> int pthread_join(pthread_t thread, void **value_ptr); >> >> pthread_exit can pass anything, and that value will be retrieved with >> pthread_join. In article Adam Skutt wrote: >No, it can only pass a void*, which isn't much better than passing an >int. It is far better than passing an int, although it leaves you with an annoying storage-management issue, and sidesteps any reasonable attempts at type-checking (both of which are of course "par for the course" in C). For instance: struct some_big_value { ... lots of stuff ... }; struct some_big_value storage_management_problem[SIZE]; ... void *func(void *initial_args) { ... #ifdef ONE_WAY_TO_DO_IT pthread_exit(&storage_management_problem[index]); /* NOTREACHED */ #else /* the other way */ return &storage_management_problem[index]; #endif } ... int error; pthread_t threadinfo; pthread_attr_t attr; ... pthread_attr_init(&attr); /* set attributes if desired */ error = pthread_create(&threadinfo, &attr, func, &args_to_func); if (error) { ... handle error ... } else { ... void *rv; result = pthread_join(&threadinfo, &rv); if (rv == PTHREAD_CANCELED) { ... the thread was canceled ... } else { struct some_big_value *ret = rv; ... work with ret->field ... } } (Or, do dynamic allocation, and have a struct with a distinguishing ID followed by a union of multiple possible values, or a flexible array member, or whatever. This means you can pass any arbitrary data structure back, provided you can manage the storage somehow.) >Passing a void* is not equivalent to passing anything, not even >in C. Moreover, specific values are still reserved, like >PTHREAD_CANCELLED. Some manual pages are clearer about this than others. Here is one that I think is not bad: The symbolic constant PTHREAD_CANCELED expands to a constant expression of type (void *), whose value matches no pointer to an object in memory nor the value NULL. So, provided you use pthread_exit() "correctly" (always pass either NULL or the address of some actual object in memory), the special reserved value is different from all of "your" values. (POSIX threads are certainly klunky, but not all *that* badly designed given the constraints.) >>Re. the original question: since you can define your own Thread >>subclass, with wathever attribute you want, I guess there was no need to >>use join() to communicate the result. The Thread's run() can store its >>result in an attribute, and the "client" can get it from the same >>attribute after a successful call to join(). For that matter, you can use the following to get what the OP asked for. (Change all the instance variables to __-prefixed versions if you want them to be Mostly Private.) import threading class ValThread(threading.Thread): "like threading.Thread, but the target function's return val is captured" def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(ValThread, self).__init__(group, None, name, None, None, verbose) self.value = None self.target = target self.args = args self.kwargs = {} if kwargs is None else kwargs def run(self): "run the thread" if self.target: self.value = self.target(*self.args, **self.kwargs) def join(self, timeout = None): "join, then return value set by target function" super(ValThread, self).join(timeout) return self.value -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From tjreedy at udel.edu Fri Sep 2 16:22:35 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 02 Sep 2011 16:22:35 -0400 Subject: Handling 2.7 and 3.0 Versions of Dict In-Reply-To: <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> Message-ID: On 9/2/2011 12:53 PM, Travis Parks wrote: > On Sep 2, 12:36 pm, "Gabriel Genellina" >> Those if/else are at global scope. An 'if' statement does not introduce a >> new scope; so getDictValues, despite being "indented", is defined at >> global scope, and may be used anywhere in the module. > Does that mean the rules would be different inside a function? Yes. Inside a function, you would have to add global getDictValues before the if statement in order for the assignments to have global effect. -- Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Fri Sep 2 16:29:59 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Sep 2011 17:29:59 -0300 Subject: Handling 2.7 and 3.0 Versions of Dict References: <50924476-9ada-487e-bd4b-5b77bce11d5b@gz5g2000vbb.googlegroups.com> <4E5E051B.8060002@v.loewis.de> <9c7utuF8q8U1@mid.individual.net> <93c5378e-03f8-4764-96e8-2c3e8568baec@z8g2000yqe.googlegroups.com> <42b6b7cb-d659-4921-bec9-6a43671848e2@s20g2000yql.googlegroups.com> Message-ID: En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks escribi?: > On Sep 2, 12:36 pm, "Gabriel Genellina" > wrote: >> En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks >> escribi : >> >> > On Aug 31, 7:37 pm, Gregory Ewing wrote: >> >> Ian Kelly wrote: >> >> > if sys.version_info < (3,): >> >> > getDictValues = dict.itervalues >> >> > else: >> >> > getDictValues = dict.values >> >> >> > (which is basically what the OP was doing in the first place). >> >> > My problem was that I didn't understand the scoping rules. It is still >> > strange to me that the getValues variable is still in scope outside >> > the if/else branches. >> >> Those if/else are at global scope. An 'if' statement does not introduce >> a new scope; so getDictValues, despite being "indented", is defined at >> global scope, and may be used anywhere in the module. > > Does that mean the rules would be different inside a function? Yes: a function body *does* create a new scope, as well as the class statement. See http://docs.python.org/reference/executionmodel.html -- Gabriel Genellina From ian.g.kelly at gmail.com Fri Sep 2 16:30:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 14:30:14 -0600 Subject: Why do class methods always need 'self' as the first parameter? In-Reply-To: <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> Message-ID: On Fri, Sep 2, 2011 at 11:51 AM, John Roth wrote: >> I don't see how you could get rid of the wrappers. ?Methods would >> still need to be bound, somehow, so that code like this will work: >> >> methods = {} >> for obj in objs: >> ? ? if obj.is_flagged: >> ? ? ? ? methods[obj.user_id] = obj.do_work >> ? ? else: >> ? ? ? ? methods[obj.user_id] = obj.do_other_work >> # ... >> methods[some_user_id]() >> >> Without method wrappers, how does the interpreter figure out which >> instance is bound to the method being called? >> >> Cheers, >> Ian > > Good question. > > Currently the instance wrapper is created during method instantiation, > so the instance is obviously available at that point. There are two > rather obvious ways of remembering it. One is to use the invocation > stack, which has the instance. Another would be for the compiler to > create a local variable for the instance and possibly the class and > fill them in at instantiation time. Both of these require fixing the > names "self" and "cls" so the compiler knows what to do with them. The > first would require giving these two names their own bytecodes, the > second makes them simple local variables the same as the ones in the > method headers. The latter also allows them to be changed by the > method, which is probably not the world's best programming practice > although it's possible now. That's not what I asked. Both of those options are storing the instance within a stack frame, once it's been called. I'm asking how you would remember the instance during the interval from the time when the method is accessed until when it has been called. In the code above, the method is accessed just before it is stored in the dictionary. That is when the method wrapper is currently created, and the instance is available. It is not called until much later, possibly not even within the same function. How would you remember the instance over that period without wrapping the function? Cheers, Ian From steve+comp.lang.python at pearwood.info Fri Sep 2 16:49:17 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 03 Sep 2011 06:49:17 +1000 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <4e60fa12$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e61414e$0$29994$c3e8da3$5496439d@news.astraweb.com> Seebs wrote: > On 2011-09-02, Steven D'Aprano > wrote: [...] >> Because then the code launching the thread would have to block, waiting >> until the thread is completed, so it will have a result to return. > > Isn't "waiting until the thread is completed" sort of the point of join()? Doh! I mean, well done, you have passed my little test! -- Steven From rosuav at gmail.com Fri Sep 2 17:47:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 3 Sep 2011 07:47:54 +1000 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> Message-ID: On Sat, Sep 3, 2011 at 2:26 AM, Den wrote: > I've been doing some more thinking on what I want. ?This may be a > better explanation. ?Is there a way of detecting if my program has > lost "focus" (I'm not sure the correct term)? ?For example, if someone > is typing in my program, but some other program takes control (or CAD > has been pressed) I would like simply to log that. ?I have no interest > in trying to hijack or interfere with anything, simply log it. Ah, then yes most definitely! If you're writing a GUI program, a LostFocus event is a normal thing to be able to catch. Now, if you're writing a console program, that mightn't be so easy. But certainly you can detect loss of focus to any window that you control. ChrisA From askutt at gmail.com Fri Sep 2 18:02:08 2011 From: askutt at gmail.com (Adam Skutt) Date: Fri, 2 Sep 2011 15:02:08 -0700 (PDT) Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <2c0123f1-f776-45af-b39e-a802f2009e7d@y21g2000yqy.googlegroups.com> On Sep 2, 4:14?pm, Chris Torek wrote: > In article > Adam Skutt ? wrote: > > >No, it can only pass a void*, which isn't much better than passing an > >int. > > It is far better than passing an int, although it leaves you with > an annoying storage-management issue, and sidesteps any reasonable > attempts at type-checking (both of which are of course "par for > the course" in C). And when written out, makes it sound distinctly worse than passing an int :p. And let's not kid ourselves, unless you're a C programmer, it is distinctly worse than passing an int. Heck, your example (snipped) goes out of your way to unnecessarily leverage the functionality provided by pthreads. > Some manual pages are clearer about this than others. ?Here is one > that I think is not bad: > > ? ? The symbolic constant PTHREAD_CANCELED expands to a constant > ? ? expression of type (void *), whose value matches no pointer to > ? ? an object in memory nor the value NULL. > > So, provided you use pthread_exit() "correctly" (always pass either > NULL or the address of some actual object in memory), the special > reserved value is different from all of "your" values. Unfortunately, I'm not sure all implementations behave that way. Not that cancellation is really worth bothering with anyway, but it's a pretty nasty corner case. Adam From johnroth1 at gmail.com Fri Sep 2 18:30:35 2011 From: johnroth1 at gmail.com (John Roth) Date: Fri, 2 Sep 2011 15:30:35 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <42e335a7-b872-4229-ae02-13d61b7fab35@w22g2000prj.googlegroups.com> <975cd42a-00b0-4d2e-9f22-95b4021a7fbb@g32g2000pri.googlegroups.com> Message-ID: On Sep 2, 2:30?pm, Ian Kelly wrote: > On Fri, Sep 2, 2011 at 11:51 AM, John Roth wrote: > >> I don't see how you could get rid of the wrappers. ?Methods would > >> still need to be bound, somehow, so that code like this will work: > > >> methods = {} > >> for obj in objs: > >> ? ? if obj.is_flagged: > >> ? ? ? ? methods[obj.user_id] = obj.do_work > >> ? ? else: > >> ? ? ? ? methods[obj.user_id] = obj.do_other_work > >> # ... > >> methods[some_user_id]() > > >> Without method wrappers, how does the interpreter figure out which > >> instance is bound to the method being called? > > >> Cheers, > >> Ian > > > Good question. > > > Currently the instance wrapper is created during method instantiation, > > so the instance is obviously available at that point. There are two > > rather obvious ways of remembering it. One is to use the invocation > > stack, which has the instance. Another would be for the compiler to > > create a local variable for the instance and possibly the class and > > fill them in at instantiation time. Both of these require fixing the > > names "self" and "cls" so the compiler knows what to do with them. The > > first would require giving these two names their own bytecodes, the > > second makes them simple local variables the same as the ones in the > > method headers. The latter also allows them to be changed by the > > method, which is probably not the world's best programming practice > > although it's possible now. > > That's not what I asked. ?Both of those options are storing the > instance within a stack frame, once it's been called. ?I'm asking how > you would remember the instance during the interval from the time when > the method > is accessed until when it has been called. > > In the code above, the method is accessed just before it is stored in > the dictionary. ?That is when the method wrapper is currently created, > and the instance is available. ?It is not called until much later, > possibly not even within the same function. ?How would you remember > the instance over that period without wrapping the function? > > Cheers, > Ian I see what you're saying now - I didn't get your example the first time. So the optimization of eliminating the instance wrapper is only possible if it's retrieved via the instance and then called immediately. That would seem to be a useful optimization if it was possible - I wonder if PyPy is doing it since they've got that fancy JIT, and it would seem that an immediate call after retrieving the method is overwhelmingly more frequent than saving it for later. I think it's still true that calling the underlying function object through the instance wrapper requires remaking the parameter list, which seems to be another piece of unnecessary overhead, unless there's a fast path through the call machinery that treats the instance specially. It does, however, decouple the two issues so I can't claim the optimization as a benefit. Drat. John Roth From jehugaleahsa at gmail.com Fri Sep 2 18:49:03 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 15:49:03 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: Message-ID: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> On Sep 2, 4:09?pm, Ian Kelly wrote: > On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > > Hello: > > > I am working on an algorithms library. It provides LINQ like > > functionality to Python iterators. Eventually, I plan on having > > feaures that work against sequences and mappings. > > > I have the code up athttp://code.google.com/p/py-compass. > > > This is my first project in Python, so I'd like some feedback. I want > > to know if I am following conventions (overall style and quality of > > code). > > Sure, here are my comments. > > In the "forever" and "__forever" functions, your use of the term > "generator" is confusing. ?"__forever" is a generator function, > because it has a yield statement. ?Its argument, called "generator", > appears to be a callable, not a generator or even necessarily a > generator function. ?Also, note that __forever(lambda: value) is > functionally equivalent to the more efficient itertools.repeat(value). > > The staticmethod __next(iterator) accesses the class it is defined in, > which suggests that it might be better written as a classmethod > __next(cls, iterator). > > Each of the LINQ-style methods is divided into two parts: the public > method that contains the docstring and some argument checks, and a > private staticmethod that contains the implementation. ?I'm not > certain what the purpose of that is. ?If it's to facilitate overriding > the implementation in subclasses, then you need to change the names of > the private methods to start with only one _ character so that they > won't be mangled by the compiler. > > The comments before each method that only contain the name of the > immediately following method are redundant. > > aggregate: the default aggregator is unintuitive to me. ?I would make > it a required field and add a separate method called sum that calls > aggregate with the operator.add aggregator. > Also, the implementation doesn't look correct. ?Instead of passing in > each item to the aggregator, you're passing in the number of items > seen so far? ?The LINQ Aggregate method is basically reduce, so rather > than reinvent the wheel I would suggest this: > > # MISSING is a unique object solely defined to represent missing arguments. > # Unlike None we can safely assume it will never be passed as actual data. > MISSING = object() > > def aggregate(self, aggregator, seed=MISSING): > ? ? if seed is self.MISSING: > ? ? ? ? return reduce(aggregator, self._iterable) > ? ? else: > ? ? ? ? return reduce(aggregator, self._iterable, seed) > > Note for compatibility that in Python 3 the reduce function has been > demoted from a builtin to a member of the functools module. > > any: the name of this method could cause some confusion with the "any" > builtin that does something a bit different. > > compare: the loop would more DRY as a for loop: > > def __compare(first, second, comparison): > ? ? for firstval, secondval in itertools.izip_longest(first, second, > fillvalue=self.MISSING): > ? ? ? ? if firstval is self.MISSING: > ? ? ? ? ? ? return -1 > ? ? ? ? elif secondval is self.MISSING: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? result = comparison(firstval, secondval) > ? ? ? ? ? ? if result != 0: > ? ? ? ? ? ? ? ? return result > ? ? return 0 > > concatenate: again, no need to reinvent the wheel. ?This should be > more efficient: > > def concatenate(self, other): > ? ? return extend(itertools.chain(self.__iterable, other)) > > equals: could be just "return self.compare(other, comparison) == 0" > > __last: the loop could be a for loop: > > ? ? ? ? # assume we're looking at the last item and try moving to the next > ? ? ? ? item = result.Value > ? ? ? ? for item in iterator: pass > ? ? ? ? return item > > lastOrDefault: there's a lot of repeated logic here. ?This could just be: > > def lastOrDefault(self, default=None): > ? ? try: > ? ? ? ? return self.last() > ? ? except ValueError: > ? ? ? ? return default > > map / forEach: .NET has to separate these into separate methods due to > static typing. ?It seems a bit silly to have both of them in Python. > Also, map would be more efficient as "return itertools.imap(mapper, > self.__iterable)" > > max / min: it would be more efficient to use the builtin: > def max(self, key): > ? ? return max(self.__iterable, key=key) > If somebody really needs to pass a comparison function instead of a > key function, they can use functools.cmp_to_key. > > randomSamples: a more canonical way to pass the RNG would be to pass > an instance of random.Random rather than an arbitrary function. Then > to get a random integer you can just call generator.randrange(total). > Note that for the default you can just use the random module itself, > which provides default implementations of all the Random methods. > Also, for loops: > > ? ? def __randomSamples(iterable, sampleCount, generator): > ? ? ? ? samples = [] > ? ? ? ? iterator = iter(iterable) > ? ? ? ? # fill up the samples with the items from the beginning of the iterable > ? ? ? ? for i, value in zip(xrange(sampleCount), iterator): > ? ? ? ? ? ? samples.append(value) > ? ? ? ? # replace items if the generated number is less than the total > ? ? ? ? total = len(samples) > ? ? ? ? for value in iterator: > ? ? ? ? ? ? total += 1 > ? ? ? ? ? ? index = generator.randrange(total) > ? ? ? ? ? ? if index < len(samples): > ? ? ? ? ? ? ? ? samples[index] = result > ? ? ? ? return samples > > __reverse: you could just "return reversed(list(iterable))" > > __rotateLeft: > def __rotateLeft(iterable, shift): > ? ? iterator = iter(iterable) > ? ? front = list(itertools.islice(iterator, shift)) > ? ? return itertools.chain(iterator, front) > > skipWhile: suggest using itertools.dropwhile > take: suggest using itertools.islice > takeWhile: suggest using itertools.takewhile > __toList: "return list(iterable)" > __toSet: "return set(iterable)" > __toTuple: "return tuple(iterable)". ?Note that as currently written > this actually returns a generator, not a tuple. > __where: suggest using itertools.ifilter > __zip: suggest using a for loop over itertools.izip(first, second) > > Lookup: is inconsistent. ?The overridden __iter__ method returns an > iterator over the values of the groups, but all the inherited methods > are going to iterate over the keys. ?Probably you want to pass > groups.values() to the superclass __init__ method. > > Cheers, > Ian Awesome tips. I appreciate the time you spent commenting on just about every function. I really like your suggestions about using itertools more, and for loops. I was feeling like some things were becoming way too complicated. I also noted the bugs you discovered. I will incorporate your suggestions. Thanks again! From vinay_sajip at yahoo.co.uk Fri Sep 2 18:59:31 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 2 Sep 2011 15:59:31 -0700 (PDT) Subject: Making `logging.basicConfig` log to *both* `sys.stderr` and `sys.stdout`? References: <7f46ab8f-710c-4463-a072-fa80c49f90de@ea4g2000vbb.googlegroups.com> Message-ID: <34939e5a-19ba-4cc5-b10b-36f8b2e42830@h9g2000vbr.googlegroups.com> On Aug 30, 9:53?am, Michel Albert wrote: > Unfortunately this setup makes `logging.basicConfig` pretty useless. > However, I believe that this is something that more people could > benefit from. I also believe, that it just "makes sense" to send > warnings (and above) to `stderr`, the rest to `stdout`. > > So I was thinking: "Why does `logging.basicConfig` not behave that > way". Because what seems entirely natural and obvious to you might not seem so for someone else. The API in the stdlib tries to provide baseline functionality which others can build on. For example, if you always have a particular pattern which you use, you can always write a utility function to set things up exactly how you like, and others who want to set things up differently (for whatever reason) can do the same thing, without having to come into conflict (if that's not too strong a word) with views different from their own. > Naturally, I was thinking of writing a patch against the python > codebase and submit it as a suggestion. But before doing so, I would > like to hear your thoughts on this. Does it make sense to you too or > am I on the wrong track? Are there any downsides I am missing? Python 2.x is closed to feature changes, and Python 2.7 and Python 3.2 already support flexible configuration using dictConfig() - see http://docs.python.org/library/logging.config.html#logging.config.dictConfig Also, Python 3.3 will support passing a list of handlers to basicConfig(): see http://plumberjack.blogspot.com/2011/04/added-functionality-for-basicconfig-in.html which will allow you to do what you want quite easily. Regards, Vinay Sajip From roy at panix.com Fri Sep 2 19:16:29 2011 From: roy at panix.com (Roy Smith) Date: Fri, 02 Sep 2011 19:16:29 -0400 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: In article <5da6bf87-9412-46c4-ad32-f8337d56b2c3 at o15g2000vbe.googlegroups.com>, Adam Skutt wrote: > On Sep 2, 10:53?am, Roy Smith wrote: > > I have a function I want to run in a thread and return a value. ?It > > seems like the most obvious way to do this is to have my target > > function return the value, the Thread object stash that someplace, and > > return it as the return value for join(). > > > Yes, I know there's other ways for a thread to return values (pass the > > target a queue, for example), but making the return value of the > > target function available would have been the most convenient. ?I'm > > curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Windows and POSIX threads only support returning an > integer when a thread exits, similar to the exit code of a process. But the whole point of higher level languages is to hide the warts of the lower-level APIs they are built on top of. Just because a POSIX thread can only return an int (actually, a void *) doesn't mean that level of detail needed to be exposed at the Python threading library level. > More importantly, there's no way to tell whether the exit code of a > thread was set by user code or by the system. Even worse, some of > those integer values are reserved by some operating systems. If your > thread died via an exception, it still has an error code set by the > operating system. How would you going to distinguish those codes from > your own? I think you're talking about processes, not threads, but in any case, it's a non-sequitur. Thread.join() currently returns None, so there's no chance for confusion. From greg.ewing at canterbury.ac.nz Fri Sep 2 20:51:11 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 03 Sep 2011 12:51:11 +1200 Subject: Detecting Ctrl-Alt-Del in Windows In-Reply-To: References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: <9cdc00Fnq3U1@mid.individual.net> Chris Angelico wrote: > Although I heard somewhere that that's more gimmick than guarantee, > and that it IS possible for an app to hook CAD - just that it's a lot > harder than building a simple window that looks like the login... And of course it's possible that someone has snuck in during the night and installed Linux on the machine, with a program that fakes a Windows login screen, with Ctrl-Alt-Delete and everything... -- Greg From nospam at torek.net Fri Sep 2 21:04:16 2011 From: nospam at torek.net (Chris Torek) Date: 3 Sep 2011 01:04:16 GMT Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: In article Roy Smith wrote: >Thread.join() currently returns None, so there's >no chance for [return value] confusion. Well, still some actually. If you use my example code (posted elsethread), you need to know: - that there was a target function (my default return value if there is none is None); and - that the joined thread really did finish (if you pass a timeout value, rather than None, and the join times out, the return value is again None). Of course, if your target function always exists and never returns None, *then* there's no chance for confusion. :-) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From jehugaleahsa at gmail.com Fri Sep 2 21:39:21 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Fri, 2 Sep 2011 18:39:21 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> Message-ID: <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> On Sep 2, 6:49?pm, Travis Parks wrote: > On Sep 2, 4:09?pm, Ian Kelly wrote: > > > > > > > On Fri, Sep 2, 2011 at 10:59 AM, Travis Parks wrote: > > > Hello: > > > > I am working on an algorithms library. It provides LINQ like > > > functionality to Python iterators. Eventually, I plan on having > > > feaures that work against sequences and mappings. > > > > I have the code up athttp://code.google.com/p/py-compass. > > > > This is my first project in Python, so I'd like some feedback. I want > > > to know if I am following conventions (overall style and quality of > > > code). > > > Sure, here are my comments. > > > In the "forever" and "__forever" functions, your use of the term > > "generator" is confusing. ?"__forever" is a generator function, > > because it has a yield statement. ?Its argument, called "generator", > > appears to be a callable, not a generator or even necessarily a > > generator function. ?Also, note that __forever(lambda: value) is > > functionally equivalent to the more efficient itertools.repeat(value). > > > The staticmethod __next(iterator) accesses the class it is defined in, > > which suggests that it might be better written as a classmethod > > __next(cls, iterator). > > > Each of the LINQ-style methods is divided into two parts: the public > > method that contains the docstring and some argument checks, and a > > private staticmethod that contains the implementation. ?I'm not > > certain what the purpose of that is. ?If it's to facilitate overriding > > the implementation in subclasses, then you need to change the names of > > the private methods to start with only one _ character so that they > > won't be mangled by the compiler. > > > The comments before each method that only contain the name of the > > immediately following method are redundant. > > > aggregate: the default aggregator is unintuitive to me. ?I would make > > it a required field and add a separate method called sum that calls > > aggregate with the operator.add aggregator. > > Also, the implementation doesn't look correct. ?Instead of passing in > > each item to the aggregator, you're passing in the number of items > > seen so far? ?The LINQ Aggregate method is basically reduce, so rather > > than reinvent the wheel I would suggest this: > > > # MISSING is a unique object solely defined to represent missing arguments. > > # Unlike None we can safely assume it will never be passed as actual data. > > MISSING = object() > > > def aggregate(self, aggregator, seed=MISSING): > > ? ? if seed is self.MISSING: > > ? ? ? ? return reduce(aggregator, self._iterable) > > ? ? else: > > ? ? ? ? return reduce(aggregator, self._iterable, seed) > > > Note for compatibility that in Python 3 the reduce function has been > > demoted from a builtin to a member of the functools module. > > > any: the name of this method could cause some confusion with the "any" > > builtin that does something a bit different. > > > compare: the loop would more DRY as a for loop: > > > def __compare(first, second, comparison): > > ? ? for firstval, secondval in itertools.izip_longest(first, second, > > fillvalue=self.MISSING): > > ? ? ? ? if firstval is self.MISSING: > > ? ? ? ? ? ? return -1 > > ? ? ? ? elif secondval is self.MISSING: > > ? ? ? ? ? ? return 1 > > ? ? ? ? else: > > ? ? ? ? ? ? result = comparison(firstval, secondval) > > ? ? ? ? ? ? if result != 0: > > ? ? ? ? ? ? ? ? return result > > ? ? return 0 > > > concatenate: again, no need to reinvent the wheel. ?This should be > > more efficient: > > > def concatenate(self, other): > > ? ? return extend(itertools.chain(self.__iterable, other)) > > > equals: could be just "return self.compare(other, comparison) == 0" > > > __last: the loop could be a for loop: > > > ? ? ? ? # assume we're looking at the last item and try moving to the next > > ? ? ? ? item = result.Value > > ? ? ? ? for item in iterator: pass > > ? ? ? ? return item > > > lastOrDefault: there's a lot of repeated logic here. ?This could just be: > > > def lastOrDefault(self, default=None): > > ? ? try: > > ? ? ? ? return self.last() > > ? ? except ValueError: > > ? ? ? ? return default > > > map / forEach: .NET has to separate these into separate methods due to > > static typing. ?It seems a bit silly to have both of them in Python. > > Also, map would be more efficient as "return itertools.imap(mapper, > > self.__iterable)" > > > max / min: it would be more efficient to use the builtin: > > def max(self, key): > > ? ? return max(self.__iterable, key=key) > > If somebody really needs to pass a comparison function instead of a > > key function, they can use functools.cmp_to_key. > > > randomSamples: a more canonical way to pass the RNG would be to pass > > an instance of random.Random rather than an arbitrary function. Then > > to get a random integer you can just call generator.randrange(total). > > Note that for the default you can just use the random module itself, > > which provides default implementations of all the Random methods. > > Also, for loops: > > > ? ? def __randomSamples(iterable, sampleCount, generator): > > ? ? ? ? samples = [] > > ? ? ? ? iterator = iter(iterable) > > ? ? ? ? # fill up the samples with the items from the beginning of the iterable > > ? ? ? ? for i, value in zip(xrange(sampleCount), iterator): > > ? ? ? ? ? ? samples.append(value) > > ? ? ? ? # replace items if the generated number is less than the total > > ? ? ? ? total = len(samples) > > ? ? ? ? for value in iterator: > > ? ? ? ? ? ? total += 1 > > ? ? ? ? ? ? index = generator.randrange(total) > > ? ? ? ? ? ? if index < len(samples): > > ? ? ? ? ? ? ? ? samples[index] = result > > ? ? ? ? return samples > > > __reverse: you could just "return reversed(list(iterable))" > > > __rotateLeft: > > def __rotateLeft(iterable, shift): > > ? ? iterator = iter(iterable) > > ? ? front = list(itertools.islice(iterator, shift)) > > ? ? return itertools.chain(iterator, front) > > > skipWhile: suggest using itertools.dropwhile > > take: suggest using itertools.islice > > takeWhile: suggest using itertools.takewhile > > __toList: "return list(iterable)" > > __toSet: "return set(iterable)" > > __toTuple: "return tuple(iterable)". ?Note that as currently written > > this actually returns a generator, not a tuple. > > __where: suggest using itertools.ifilter > > __zip: suggest using a for loop over itertools.izip(first, second) > > > Lookup: is inconsistent. ?The overridden __iter__ method returns an > > iterator over the values of the groups, but all the inherited methods > > are going to iterate over the keys. ?Probably you want to pass > > groups.values() to the superclass __init__ method. > > > Cheers, > > Ian > > Awesome tips. I appreciate the time you spent commenting on just about > every function. I really like your suggestions about using itertools > more, and for loops. I was feeling like some things were becoming way >too complicated. > > I also noted the bugs you discovered. I will incorporate your > suggestions. > > Thanks again!- Hide quoted text - > > - Show quoted text - You commented that the itertools algorithms will perform faster than the hand-written ones. Are these algorithms optimized internally? From bkasterm at gmail.com Fri Sep 2 22:15:11 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Fri, 02 Sep 2011 20:15:11 -0600 Subject: List comprehension timing difference. References: <87zkinkcht.fsf@gmail.com> <87sjofjbh1.fsf@gmail.com> <07906043-d732-43ca-8313-bee4746eca75@fi7g2000vbb.googlegroups.com> Message-ID: <87bov29xsg.fsf@gmail.com> ting at thsu.org writes: > On Sep 2, 9:54?am, Bart Kastermans wrote: >> if d(a,b) == 1 and a < b: > > It will probably be faster if you reverse the evaluation order of that > expression. > > if a > That way the d() function is called less than half the time. Of course > this assumes that a that's true for your example. > -- > // T.Hsu Indeed makes quite a difference, goes from 275 seconds down to 153 seconds. From clp2 at rebertia.com Fri Sep 2 22:23:11 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 19:23:11 -0700 Subject: Algorithms Library - Asking for Pointers In-Reply-To: <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: On Fri, Sep 2, 2011 at 6:39 PM, Travis Parks wrote: > You commented that the itertools algorithms will perform faster than > the hand-written ones. Are these algorithms optimized internally? For one thing, they are written in C. Cheers, Chris From lanyjie at yahoo.com Sat Sep 3 00:18:21 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 2 Sep 2011 21:18:21 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> Have you considered line continuation by indentation? It seems to meet the design principle. I think it is the most natural way to allow free line breaking in Python. (Sorry, the yahoo web email interface is so weird that I don't know how to format comments between the quoted message below.) >________________________________ >From: Stephen J. Turnbull >To: Gabriel AHTUNE >Cc: Matt Joiner ; "python-list at python.org" ; python-ideas ; Yingjie Lan >Sent: Friday, September 2, 2011 3:28 PM >Subject: Re: [Python-ideas] allow line break at operators > >Gabriel AHTUNE writes: >> So can be done with this syntax: >> >> > x = firstpart * secondpart? +? #line breaks here >> > anotherpart + #continue >> > stillanother #continue on. >> >> after a "+" operator the line is clearly not finished yet. > >Sure, but IIRC one design principle of Python is that the keyword that >denotes the syntax should be the first thing on the line, making it >easy to scan down the left side of the code to see the syntactic >structure.? The required indentation of the controlled suite also >helps emphasize that keyword. > >Analogously, if operators are going to denote continuation, they >should come first on the line. > > > >I just don't think this idea is going anywhere.? Explicit continuation >with backslash or implicit continuation of parenthesized expressions >is just not that heavy a price to pay.? Perhaps historically some of >these ideas could have been implemented, but now they're just going to >confuse a host of editors and code analysis tools. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at torek.net Sat Sep 3 00:35:05 2011 From: nospam at torek.net (Chris Torek) Date: 3 Sep 2011 04:35:05 GMT Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: In article <18fe4afd-569b-4580-a629-50f6c74829e8 at c29g2000yqd.googlegroups.com> Travis Parks wrote: >[Someone] commented that the itertools algorithms will perform >faster than the hand-written ones. Are these algorithms optimized >internally? They are written in C, so avoid a lot of CPython interpreter overhead. Mileage in Jython, etc., may vary... -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From stephen at xemacs.org Sat Sep 3 00:38:15 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Sat, 03 Sep 2011 13:38:15 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Guido van Rossum writes: > On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > > Sure, but IIRC one design principle of Python is that the keyword that > > denotes the syntax should be the first thing on the line, [...] > That's true for *statements* (except assignments and calls). > > > Analogously, if operators are going to denote continuation, they > > should come first on the line. > That doesn't follow. Agreed, it's not a logical implication. The analogy is only an analogy, but my eyes do work that way. My conclusion is that we shouldn't try to encourage either style, because people "see" continuation differently. Legislating a style isn't going to change that, I think. From ian.g.kelly at gmail.com Sat Sep 3 00:38:22 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 2 Sep 2011 22:38:22 -0600 Subject: sqlite3 with context manager In-Reply-To: References: Message-ID: On Fri, Sep 2, 2011 at 12:43 PM, Tim Arnold wrote: > Hi, > I'm using the 'with' context manager for a sqlite3 connection: > > with sqlite3.connect(my.database,timeout=10) as conn: > ? ? ? ? ? ?conn.execute('update config_build set datetime=?,result=? > where id=?', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?(datetime.datetime.now(), success, > self.b['id'])) > > my question is what happens if the update fails? Shouldn't it throw an > exception? That depends on why it fails. If you pass in an id that doesn't exist in the database, it "successfully" updates 0 rows. I would guess that's what happened here. You should check cursor.rowcount after running the update query to make sure it actually did something. Cheers, Ian From d_vineet at yahoo.com Sat Sep 3 01:36:56 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Fri, 2 Sep 2011 22:36:56 -0700 (PDT) Subject: json in python 2.5 References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> Message-ID: <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> > e.g., I have this list: > L = ['spam', 'ham', 'eggs', 12, (13.63)] > What is the correct way to convert L to javascript array format? > 1) jsonify the list and pass it to javascript > (whether json format & javascript array are similar?) JSON is in fact a subset of JavaScript, and modern browsers now include a specific API for parsing and generating it (https://developer.mozilla.org/En/Using_native_JSON ). ============= @Chris, thanks for the pointer on parsing json. ============= Python likewise has a JSON module in the std lib: http://docs.python.org/library/json.html ======== I tried with json in std lib. But it is included in python 2.6 onwards. For my current proj, I need to use python 2.5. Hence can't use json from the std lib. Any idea on converting list to json in python 2.5? ========= Thanks, Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Sep 3 01:50:36 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 2 Sep 2011 22:50:36 -0700 Subject: json in python 2.5 In-Reply-To: <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> Message-ID: On Fri, Sep 2, 2011 at 10:36 PM, Vineet Deodhar wrote: >> e.g., I have this list: >> L = ['spam', 'ham', 'eggs', 12, (13.63)] >> What is the correct way to convert L to javascript array format? > Python likewise has a JSON module in the std lib: > http://docs.python.org/library/json.html > ======== > I tried with json in std lib. > But it is included in python 2.6 onwards. > For my current proj, I need to use python 2.5. > Hence can't use json from the std lib. > Any idea on converting list to json in python 2.5? http://pypi.python.org/pypi/simplejson/ Cheers, Chris From stephen at xemacs.org Sat Sep 3 02:10:26 2011 From: stephen at xemacs.org (Stephen J. Turnbull) Date: Sat, 03 Sep 2011 15:10:26 +0900 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> Message-ID: <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> Yingjie Lan writes: > Have you considered line continuation by indentation? It seems to > meet the design principle. I think it is the most natural way to > allow free line breaking in Python. Briefly, yes, and I think it would need a lot of tuning and probably complex rules. Unlike statements, where everybody (except the judges of the Obfuscated C Contest) agrees on a simple rule: "In a control structure, the controlled suite should be uniformly indented one level", line breaking and indentation of long expressions is an art, and people have different opinions on "readability" and "beauty." Achieving a compromise that is workable even for a few major styles is likely to be annoying and bug-prone. Pretty much every program I write seems to have a continued list of data or a multi-line dictionary display as data. It's not unusual for me to comment the formal arguments in a function definition, or the parent classes of a class definition. The exception for parenthesized objects is something I depend on for what I consider good style. Of course I could use explicit continuation, but in a long table that's ugly and error-prone. Long expressions that need to be broken across lines, on the other hand, often indication that I haven't thought carefully enough about that component of the program, and an extra pair of parentheses or a terminal backslash just isn't that "heavy" or ugly in the context of such long expressions. For me, they're also pretty rare; many programs I write have no explicit continuations in them at all. YMMV, of course, but I find the compromise that Python arrived at to be very useful, and I must suppose that it was substantially easier to implement than "fully free" line breaking (whatever that means to you). From pavlovevidence at gmail.com Sat Sep 3 03:03:22 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 00:03:22 -0700 (PDT) Subject: sqlite3 with context manager In-Reply-To: References: Message-ID: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote: > Hi, > I'm using the 'with' context manager for a sqlite3 connection: > > with sqlite3.connect(my.database,timeout=10) as conn: > conn.execute('update config_build set datetime=?,result=? > where id=?', > (datetime.datetime.now(), success, > self.b['id'])) > > my question is what happens if the update fails? Shouldn't it throw an > exception? If you look at the sqlite3 syntax documentation, you'll see it has a SQL extension that allows you to specify error semantics. It looks something like this: UPDATE OR IGNORE UPDATE OR FAIL UPDATE OR ROLLBACK I'm not sure exactly how this interacts with pysqlite3, but using one of these might help it throw exceptions when you want it to. Carl Banks From nobody at nowhere.com Sat Sep 3 03:49:49 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 03 Sep 2011 08:49:49 +0100 Subject: Detecting Ctrl-Alt-Del in Windows References: <6e602a19-8cca-4924-bd95-df08615662d2@c8g2000prn.googlegroups.com> <4E608064.9030005@ixokai.io> Message-ID: On Fri, 02 Sep 2011 17:55:41 +1000, Chris Angelico wrote: >> That's why you have to hit CAD to get to the login form in some versions >> of Windows. The whole point of that secure sequence is that the OS and >> only the OS responds. > > Although I heard somewhere that that's more gimmick than guarantee, > and that it IS possible for an app to hook CAD It's possible to configure how CAD is handled, but this requires Administrator privilege, so it's not exploitable (i.e. it doesn't gain you anything you can't obtain by other means). From lanyjie at yahoo.com Sat Sep 3 03:51:11 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 00:51:11 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> I agree that long lines of code are not very common in many projects, though it might be the case with some heavily involved in math. For some reason, when the feature of free line breaking came about in computer languages, it is welcomed and generally well accepted. Python uses indentation for blocks, and by the same mechanism, line breaking can be?accommodated without requiring parenthesis or ending backslashes. For the tuning, yes, people would disagree on how to split expressions/code. The continue-by-indentation would allow people to break a line in whatever way that pleases their aesthetic taste, as long as there is an indentation. Most people seems to like an indentation on the continuing lines, probably for a visual indication of a continuation line. Some general guidelines may be provided, but there is no need for other hard rules on breaking lines, except that an identifier should never be split apart. For the implementation, I don't have much clue. At least on the parser, it needs to look beyond the linefeed to determine if a line is completed. If the indentation is defined as a single symbol, then it would only require a one-step look-ahead, and that should not be hard. Again, my?apology?for top posting. >________________________________ >From: Stephen J. Turnbull >To: Yingjie Lan >Cc: Gabriel AHTUNE ; Matt Joiner ; "python-list at python.org" ; python-ideas >Sent: Saturday, September 3, 2011 2:10 PM >Subject: Re: [Python-ideas] allow line break at operators > >Yingjie Lan writes: > >> Have you considered line continuation by indentation? It seems to >> meet the design principle. I think it is the most natural way to >> allow free line breaking in Python. > >Briefly, yes, and I think it would need a lot of tuning and probably >complex rules.? Unlike statements, where everybody (except the judges >of the Obfuscated C Contest) agrees on a simple rule: "In a control >structure, the controlled suite should be uniformly indented one >level", line breaking and indentation of long expressions is an art, >and people have different opinions on "readability" and "beauty." >Achieving a compromise that is workable even for a few major styles is >likely to be annoying and bug-prone. > >Pretty much every program I write seems to have a continued list of >data or a multi-line dictionary display as data.? It's not unusual for >me to comment the formal arguments in a function definition, or the >parent classes of a class definition.? The exception for parenthesized >objects is something I depend on for what I consider good style.? Of >course I could use explicit continuation, but in a long table that's >ugly and error-prone. > >Long expressions that need to be broken across lines, on the other >hand, often indication that I haven't thought carefully enough about >that component of the program, and an extra pair of parentheses or a >terminal backslash just isn't that "heavy" or ugly in the context of >such long expressions.? For me, they're also pretty rare; many >programs I write have no explicit continuations in them at all. > >YMMV, of course, but I find the compromise that Python arrived at to >be very useful, and I must suppose that it was substantially easier to >implement than "fully free" line breaking (whatever that means to you). > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kissgoodbye5204 at yahoo.com.cn Sat Sep 3 04:28:12 2011 From: kissgoodbye5204 at yahoo.com.cn (www.brandtrade10.com) Date: Sat, 3 Sep 2011 01:28:12 -0700 (PDT) Subject: Nike Air Max LeBron VIII Message-ID: <89bd2be6-2cea-4c1a-8491-769fca930562@w22g2000prj.googlegroups.com> Published late last year for the first time Nike Air Max LeBron VIII that caused a large response, follow-up and then released LeBron VIII P2 and LeBron 8PS versions, LeBron is so loyal fans surprises. Back to {1}{/1}Nike for the first time this exposure will open the second half of LeBron 9 flagship shoe figure. Mystery photo from the body of the shoe can be seen a lot of reference material of carbon fiber, and also impressively hidden Hyperfuse material which is easy to understand Nike LeBron on the court to strong demand torque and light weighthttp://www.cheap-nbabasketballshoes.com/ under the foot pains. Wei is currently not yet fully revealed Nike LeBron 9 picture, ladies shoes andgentlemens, friends, fans, please wait.it will come update in http://www.cheap-nbabasketballshoes.com/ From alain at dpt-info.u-strasbg.fr Sat Sep 3 04:33:10 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 03 Sep 2011 10:33:10 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <878vq62fg9.fsf@dpt-info.u-strasbg.fr> Adam Skutt writes: > On Sep 2, 2:23?pm, Alain Ketterlin > wrote: >> Sorry, you're wrong, at least for POSIX threads: >> >> void pthread_exit(void *value_ptr); >> int pthread_join(pthread_t thread, void **value_ptr); >> >> pthread_exit can pass anything, and that value will be retrieved with >> pthread_join. > > No, it can only pass a void*, which isn't much better than passing an > int. We'll have to disagree. A void* simply can point to anything you want. Since thread stacks disappear at end of thread, only dynamically allocated memory can be used to store the result. That's why you get a pointer. There is no restriction on that pointer provided it doesn't point to memory that has been deallocated. > Passing a void* is not equivalent to passing anything, not even in C. > Moreover, specific values are still reserved, like PTHREAD_CANCELLED. Thread cancellation is program logic (pthread_cancel), it doesn't mean you thread crashed, it means your program decided to cancel the thread. If you still care about the return value after having called pthread_cancel(), > Yes, it was strictly inappropriate for me to say both return solely > integers, but my error doesn't meaningful alter my description of the > situation. The interface provided by the underlying APIs is not > especially usable for arbitrary data transfer. Again, I may misunderstand your wording, but there is no "data transfer" at all, since memory is shared between threads. > Doubly so when we're discussing something like Python's threading > module. The OP was clearly discussing the case where a thread has a result, and how to get it back. POSIX threads let you do that. There are of course tons of other ways to do the same thing. Win32 will force you to use some other way. >> I'm not sure what you are talking about here. Maybe you confuse threads >> with processes? > > Windows threads have exit codes, just like processes. At least one > code is reserved and cannot be used by the programmer. Is that STILL_ACTIVE that we are talking about? That's an artefact of the design of GetExitCodeThread, which will return either the thread exit code or its own error code. The python lib could easily hide this, and use run()'s return value to store the (python) result somewhere. -- Alain. From d_vineet at yahoo.com Sat Sep 3 04:58:44 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 01:58:44 -0700 (PDT) Subject: json: python 2.5: error in browser In-Reply-To: References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> Message-ID: <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> > Any idea on converting list to json in python 2.5? http://pypi.python.org/pypi/simplejson/ Cheers, Chris ============= Now I built json from simplejson. While trying to render the same in browser, nothing is displayed. Opera Dragonfly shows this error:-- ? Uncaught exception: SyntaxError: JSON.parse: Unable to parse value: A,B,C Error thrown at line 3, column 0 in http://127.0.0.1:8000/mywheels/test/cat: ??? var ctg = JSON.parse(["A", "B", "C"]); ~~~~~~~~~~~~~~~~ I validated this json --? ["A", "B", "C"]?? in jsonlint.com It is valid json. ? Why the?method "JSON.parse" is unable to parse JSON? ? --Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From alain at dpt-info.u-strasbg.fr Sat Sep 3 05:00:22 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 03 Sep 2011 11:00:22 +0200 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> <878vq62fg9.fsf@dpt-info.u-strasbg.fr> Message-ID: <874o0u2e6x.fsf@dpt-info.u-strasbg.fr> Alain Ketterlin writes: >> Passing a void* is not equivalent to passing anything, not even in C. >> Moreover, specific values are still reserved, like PTHREAD_CANCELLED. > > Thread cancellation is program logic (pthread_cancel), it doesn't mean > you thread crashed, it means your program decided to cancel the thread. > If you still care about the return value after having called > pthread_cancel(), Sotry, forgot to end this sentence... What I mean is: If you still care about the return value after having called pthread_cancel(), your program logic is unnecessarily complex, and you should find some other way to handle this case. -- Alain. From clp2 at rebertia.com Sat Sep 3 05:21:44 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 3 Sep 2011 02:21:44 -0700 Subject: json: python 2.5: error in browser In-Reply-To: <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> References: <1314977665.30984.YahooMailNeo@web160510.mail.bf1.yahoo.com> <1315028216.36570.YahooMailNeo@web160520.mail.bf1.yahoo.com> <1315040324.53959.YahooMailNeo@web160509.mail.bf1.yahoo.com> Message-ID: On Sat, Sep 3, 2011 at 1:58 AM, Vineet Deodhar wrote: > Opera Dragonfly shows this error:-- > > Uncaught exception: SyntaxError: JSON.parse: Unable to parse value: A,B,C > Error thrown at line 3, column 0 in http://127.0.0.1:8000/mywheels/test/cat: > ??? var ctg = JSON.parse(["A", "B", "C"]); > ~~~~~~~~~~~~~~~~ > I validated this json --? ["A", "B", "C"]?? in jsonlint.com > It is valid json. > > Why the?method "JSON.parse" is unable to parse JSON? It takes a *string* containing JSON. You want: var ctg = JSON.parse('["A", "B", "C"]');// note outer quotes! Think about it: If you already had ["A", "B", "C"] in the first place, then you could just do: var ctg = ["A", "B", "C"]; And JSON would never enter into the discussion. Your issue is akin to confusing the following two outputs: Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 'foo' # expression resulting in the string 'foo' >>> print 'foo' # contents of the string foo Regards, Chris From lanyjie at yahoo.com Sat Sep 3 06:33:48 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 03:33:48 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Ambiguity: yes, when the last line of a suite is a continued line, it would require double dedentations to end the line and the suite. I noticed a similar case in current Python language as well: ================================== #BEGIN CODE 1 if condition: for i in range(5): triangulate(i) else: #double dedentations for body in space: triangulate(body) #double dedentations again log('triangulation done') #END CODE 1 ================================== If lines can be continued by indentation, similar situation would rise: ================================== #BEGIN CODE 2 if condition: result = [sin(i) for i in range(5)] + [cos(i) for i in range(5)] else: result = [cos(i) for i in range(5)] + [sin(i) for i in range(5)] log('triangulation done') #END CODE 2 ================================== Generating text example: right, this is a case that can't be handled by standard indentation, unless we only consider full dedentation (dedentation to the exact level of the initial indentation) as the signal of ending the line. Whether to?accommodate?for such a case might be an issue of debate, but at least we can have such 'freedom' :) >________________________________ >From: Stephen J. Turnbull >To: Yingjie Lan >Cc: Gabriel AHTUNE ; Matt Joiner ; python-ideas >Sent: Saturday, September 3, 2011 5:29 PM >Subject: Re: [Python-ideas] allow line break at operators > >Yingjie Lan writes: > >> Python uses indentation for blocks, and by the same mechanism, line >> breaking can be?accommodated without requiring parenthesis or >> ending backslashes. > >Possibly, but now you have a problem that a dedent has ambiguous >meaning.? It might mean that you're ending a suite, or it might mean >you're ending a continued expression.? This probably can be >disambiguated, but I don't know how easy that will be to do perfectly, >including in reporting ill-formed programs. > >> Most people seems to like an indentation on the continuing lines, > >Most of the time, yes, but sometimes not.? For example, in generating >text, it's often useful to dedent substantially so you can have a >nearly normal length line in the literal strings being concatenated. >Or you might have a pattern like this: > >? ? x = long_named_variable_a >? ? ? ? ? ? - long_named_variable_a_base >? ? ? ? + long_named_variable_b >? ? ? ? ? ? - long_named_variable_b_base > >which your parser would raise an error on, I presume.? That's not >freedom! > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Sat Sep 3 06:50:30 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 03:50:30 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <1315047030.94472.YahooMailNeo@web121507.mail.ne1.yahoo.com> Oops, the generating text part of my reply is referring to your last code example. For literal texts, it is is not governed by this proposal, nor are expressions within brackets and backslash continued lines. In a word, this proposal is fully backward compatible. >________________________________ >From: Yingjie Lan >To: Stephen J. Turnbull >Cc: python list ; Gabriel AHTUNE ; python-ideas ; Matt Joiner >Sent: Saturday, September 3, 2011 6:33 PM >Subject: Re: [Python-ideas] allow line break at operators > > >Ambiguity: yes, when the last line of a suite is a continued line, it would require double dedentations to end the line and the suite. I noticed a similar case in current Python language as well: > > >================================== >#BEGIN CODE 1 >if condition: >for i in range(5): >triangulate(i) >else: #double dedentations >for body in space: >triangulate(body) >#double dedentations again >log('triangulation done') >#END CODE 1 >================================== > > > >If lines can be continued by indentation, similar situation would rise: > > >================================== >#BEGIN CODE 2 >if condition: >result = [sin(i) for i in range(5)] >+ [cos(i) for i in range(5)] >else: > >result = [cos(i) for i in range(5)] >+ [sin(i) for i in range(5)] > > >log('triangulation done') >#END CODE 2 >================================== > > > >Generating text example: right, this is a case that can't be handled by standard indentation, unless we only consider full dedentation (dedentation to the exact level of the initial indentation) as the signal of ending the line. Whether to?accommodate?for such a case might be an issue of debate, but at least we can have such 'freedom' :) > > > > > >>________________________________ >>From: Stephen J. Turnbull >>To: Yingjie Lan >>Cc: Gabriel AHTUNE ; Matt Joiner ; python-ideas >>Sent: Saturday, September 3, 2011 5:29 PM >>Subject: Re: [Python-ideas] allow line break at operators >> >>Yingjie Lan writes: >> >>> Python uses indentation for blocks, and by the same mechanism, line >>> breaking can be?accommodated without requiring parenthesis or >>> ending backslashes. >> >>Possibly, but now you have a problem that a dedent has ambiguous >>meaning.? It might mean that you're ending a suite, or it might mean >>you're ending a continued expression.? This probably can be >>disambiguated, but I don't know how easy that will be to do perfectly, >>including in reporting ill-formed programs. >> >>> Most people seems to like an indentation on the continuing lines, >> >>Most of the time, yes, but sometimes not.? For example, in generating >>text, it's often useful to dedent substantially so you can have a >>nearly normal length line in the literal strings being concatenated. >>Or you might have a pattern like this: >> >>? ? x = long_named_variable_a >>? ? ? ? ? ? - long_named_variable_a_base >>? ? ? ? + long_named_variable_b >>? ? ? ? ? ? - long_named_variable_b_base >> >>which your parser would raise an error on, I presume.? That's not >>freedom! >> >> >> >> >-- >http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Sep 3 08:04:42 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 05:04:42 -0700 (PDT) Subject: Why doesn't threading.join() return a value? In-Reply-To: <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> Message-ID: <6a30f0e6-cd0b-4ae2-9a0a-067411bc184f@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:01:17 AM UTC-7, Adam Skutt wrote: > On Sep 2, 10:53?am, Roy Smith wrote: > > I have a function I want to run in a thread and return a value. ?It > > seems like the most obvious way to do this is to have my target > > function return the value, the Thread object stash that someplace, and > > return it as the return value for join(). > > > Yes, I know there's other ways for a thread to return values (pass the > > target a queue, for example), but making the return value of the > > target function available would have been the most convenient. ?I'm > > curious why threading wasn't implemented this way. > > I assume it is because the underlying operating system APIs do not > support it. Nope. This could easily be implemented by storing the return value in the Thread object. It's not done that way probably because no one thought of doing it. Carl Bannks From pavlovevidence at gmail.com Sat Sep 3 08:27:51 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 3 Sep 2011 05:27:51 -0700 (PDT) Subject: Why doesn't threading.join() return a value? In-Reply-To: References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: <7ea98c63-e045-45f2-9602-0c3b4495d141@glegroupsg2000goo.googlegroups.com> On Friday, September 2, 2011 11:53:43 AM UTC-7, Adam Skutt wrote: > On Sep 2, 2:23?pm, Alain Ketterlin > wrote: > > Sorry, you're wrong, at least for POSIX threads: > > > > void pthread_exit(void *value_ptr); > > int pthread_join(pthread_t thread, void **value_ptr); > > > > pthread_exit can pass anything, and that value will be retrieved with > > pthread_join. > > No, it can only pass a void*, which isn't much better than passing an > int. Passing a void* is not equivalent to passing anything, not even > in C. Moreover, specific values are still reserved, like > PTHREAD_CANCELLED. Yes, it was strictly inappropriate for me to say > both return solely integers, but my error doesn't meaningful alter my > description of the situation. The interface provided by the > underlying APIs is not especially usable for arbitrary data transfer. I'm sorry, but your claim is flat out wrong. It's very common in C programming to use a void* to give a programmer ability to pass arbitrary data through some third-party code. The Python API itself uses void* in this way in several different places. For instance, ake a look at the Capsule API (http://docs.python.org/c-api/capsule.html). You'll notice it uses a void* to let a user pass in opaque data. Another case is when declaring properties in C: it's common to define a single get or set function, and only vary some piece of data for the different properties. The API provides a void* so that the extension writer can pass arbitrary data to the get and set functions. Carl Banks From benjamin at schollnick.net Sat Sep 3 10:11:17 2011 From: benjamin at schollnick.net (Benjamin Schollnick) Date: Sat, 3 Sep 2011 10:11:17 -0400 Subject: Need advice on Web / Database framework... Message-ID: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Folks, I need some advice on a python web & database framework to use...? I have handcrafted a sqllite3 python script, that is a basic web application, interfacing with a sqlite3 database... But I am concerned at the thought of handcrafting a administration interface, and so forth. Are there any recommendations on a python toolkit / framework that could help deal with the realities of this? The main issue is hand crafting all the forms and html web pages... I have done a little cheetah templating... So that might be a partial solution, but I'm concerned with someone trying to craft a malicious payload in the fields, and so forth... I have thought about an out of the box solution, for example, using a wordpress install for the front-end, but I haven't been able to think of a good way to bridge this gap. Would Zope be a good solution possibly? Any suggestions would be appreciated... - Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From mukeshtiwari.iiitm at gmail.com Sat Sep 3 10:40:03 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Sat, 3 Sep 2011 07:40:03 -0700 (PDT) Subject: Reading pen drive data Message-ID: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> Hello all I am trying to write a python script which can mount a pen drive and read the data from pen drive. I am using pyudev [ http://packages.python.org/pyudev/api/index.html ] and wrote a small python code import pyudev, sys if __name__ =="__main__": context = pyudev.Context() devices = context.list_devices(subsystem ="usb") for device in devices : print device which prints Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') My problem is, how to know out of these usb which one to read . The other solution I got is whenever I insert the pen drive , my system mounts it in /media directory so I can read the /media directory to check if its empty or not but this does not seems promising to me because it may be possible that my system is not able to mount the pen drive so I have to manually do it . Kindly some one please tell me how to solve this problem. From noreply at domain.invalid Sat Sep 3 12:15:12 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 12:15:12 -0400 Subject: Functions vs OOP Message-ID: During some recent research, and re-familiarization with Python, I came across documentation that suggests that programming using functions, and programming using objects were somehow opposing techniques. It seems to me that they are complimentary. It makes sense to create objects and have some functions that take those objects as arguments. Are they suggesting that any function that takes an object as an argument should always be a method of that object? Conversely I can see creating functions that take raw input (e.g. strings) and return it in a format compatible with an object's constructor, rather than have objects accept any conceivable format for its constructor. Am I missing something, or am I taking things too literally? From mukeshtiwari.iiitm at gmail.com Sat Sep 3 12:21:57 2011 From: mukeshtiwari.iiitm at gmail.com (mukesh tiwari) Date: Sat, 3 Sep 2011 09:21:57 -0700 (PDT) Subject: Reading pen drive data References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> Message-ID: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> On Sep 3, 7:40?pm, mukesh tiwari wrote: > Hello all > I am trying to write a python script which can mount a pen drive and > read the data from pen drive. I am using pyudev [http://packages.python.org/pyudev/api/index.html] and wrote a small > python code > > import pyudev, sys > if __name__ =="__main__": > ? ? ? ? context = pyudev.Context() > ? ? ? ? devices = context.list_devices(subsystem ? ? ? ?="usb") > ? ? ? ? for device in devices : > ? ? ? ? ? ? ? ? print device > > which prints > > Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') > Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') > Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') > Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') > Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') > Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') > Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') > Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') > Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') > Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') > > My problem is, ?how to know ?out of these usb which one to read . The > other solution I got is whenever I insert the pen drive , my system > mounts ?it in /media ?directory so I can read the /media directory ?to > check if its empty or not but this does not seems promising to me > because it may be possible that my system is not able to mount the pen > drive so I have to manually do it . ?Kindly some one please tell me > how to solve this problem. I got this link and its working fine [ http://packages.python.org/pyudev/api/monitor.html ] >>> context = pyudev.Context() >>> monitor = pyudev.Monitor.from_netlink(context) >>> monitor.filter_by(subsystem='input') >>> for action, device in monitor: ... print('{0}: {1}'.format(action, device)) but when I am trying to execute code [ http://packages.python.org/pyudev/api/toolkit.html ] import pyudev, sys context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') observer = QUDevMonitorObserver(monitor) def device_connected(device): print('{0!r} added'.format(device)) observer.deviceAdded.connect(device_connected) monitor.start() I am getting Traceback (most recent call last): File "Mount.py", line 7, in observer = QUDevMonitorObserver(monitor) NameError: name 'QUDevMonitorObserver' is not defined Could any one please tell me how to avoid this error . Thank you From steve+comp.lang.python at pearwood.info Sat Sep 3 12:25:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 04 Sep 2011 02:25:43 +1000 Subject: Functions vs OOP References: Message-ID: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. > > It seems to me that they are complimentary. It makes sense to create > objects and have some functions that take those objects as arguments. Python is a mixed paradigm language, with object, functional and imperative paradigms. > Are they suggesting that any function that takes an object as an > argument should always be a method of that object? Yes. http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html [...] > Am I missing something, or am I taking things too literally? No, it is the OO purists who are missing something. -- Steven From python at mrabarnett.plus.com Sat Sep 3 12:29:11 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Sep 2011 17:29:11 +0100 Subject: Functions vs OOP In-Reply-To: References: Message-ID: <4E6255D7.2070005@mrabarnett.plus.com> On 03/09/2011 17:15, William Gill wrote: > During some recent research, and re-familiarization with Python, I > came across documentation that suggests that programming using > functions, and programming using objects were somehow opposing > techniques. > > It seems to me that they are complimentary. I think you mean "complementary". :-) > It makes sense to create objects and have some functions that take > those objects as arguments. Are they suggesting that any function > that takes an object as an argument should always be a method of that > object? Conversely I can see creating functions that take raw input > (e.g. strings) and return it in a format compatible with an object's > constructor, rather than have objects accept any conceivable format > for its constructor. > > Am I missing something, or am I taking things too literally? I think that it's all about "state". In functional programming, there's no state; a function's result depends solely on its arguments, so it will always return the same result for the same given arguments. In OOP, on the other hand, an object often has a state; a method may return a different result each time it's called, even for the same given arguments. From me+list/python at ixokai.io Sat Sep 3 12:50:25 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Sat, 03 Sep 2011 09:50:25 -0700 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <4E625AD1.6060103@ixokai.io> On 9/3/11 3:33 AM, Yingjie Lan wrote: > but at least we can have such 'freedom' :) Freedom is not and never has been, IMHO, a virtue or goal or even desire in Python. Where it occurs, it is at best a happy coincidence, and even if that happy coincidence happens often, it is not a design feature, IMHO. Simplicity and readability are virtues in Python. Freedom is even declared a vice to be avoided by the Zen, that holy document which defines all things Pythonic in clear and unambiguously absolute terms*. Looking over this whole thread at the various examples -- they add complication (a vice!). Complication to the parser, complication to the language itself and worse, understanding of code (as your head has to parse things too), all for what? So you don't have to use parens, which quite explicitly (another virtue!) do the job, to wrap around a long expression? Escaping newlines is arguably a bit on the ugly side (a vice!), so maybe the proposal has a little weight there, but since you can just avoid that by using parens, that's pretty much nullified. (Since it is also a virtue to offer only the Dutch way of doing things -- at least without hiding the alternatives in modules with a little bit of shame -- and this is clearly a case of the Dutch liking limited use of grouping parens). There just isn't even vaguely enough justification based on Python-virtues (readability, simplicity, explicitness, things like that) to even kind of make it worth the complication. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ * Obvious exaggeration :P -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From roy at panix.com Sat Sep 3 12:51:03 2011 From: roy at panix.com (Roy Smith) Date: Sat, 03 Sep 2011 12:51:03 -0400 Subject: Why doesn't threading.join() return a value? References: <61044fa5-2850-4f05-a55a-d61521c74313@d7g2000vbv.googlegroups.com> <5da6bf87-9412-46c4-ad32-f8337d56b2c3@o15g2000vbe.googlegroups.com> <87hb4u3isf.fsf@dpt-info.u-strasbg.fr> Message-ID: In article , Chris Torek wrote: > For that matter, you can use the following to get what the OP asked > for. (Change all the instance variables to __-prefixed versions > if you want them to be Mostly Private.) > > import threading > > class ValThread(threading.Thread): > "like threading.Thread, but the target function's return val is captured" > def __init__(self, group=None, target=None, name=None, > args=(), kwargs=None, verbose=None): > super(ValThread, self).__init__(group, None, name, None, None, > verbose) > self.value = None > self.target = target > self.args = args > self.kwargs = {} if kwargs is None else kwargs > > def run(self): > "run the thread" > if self.target: > self.value = self.target(*self.args, **self.kwargs) > > def join(self, timeout = None): > "join, then return value set by target function" > super(ValThread, self).join(timeout) > return self.value Yeah, that's pretty much what I had in mind. I'm inclined to write up a PEP proposing that this become the standard behavior of threading.Thread. It seems useful, and I can't see any way it would break any existing code. From roy at panix.com Sat Sep 3 12:59:59 2011 From: roy at panix.com (Roy Smith) Date: Sat, 03 Sep 2011 12:59:59 -0400 Subject: [Python-ideas] allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> Message-ID: In article , Matt Joiner wrote: > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. I wrote a weird bug the other day. I had a function that returned a 4-tuple and wanted to unpack it, so I wrote: var1, var2, var3, var4 = my_function() which isn't a syntax error, but also isn't what I meant. Depending on whether var[123] have pre-existing values, this doesn't even produce a run-time error. Emacs encouraged me in this crime by merrily auto-indenting the code the way I expected :-) From malaclypse2 at gmail.com Sat Sep 3 13:08:26 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sat, 3 Sep 2011 13:08:26 -0400 Subject: Reading pen drive data In-Reply-To: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> Message-ID: On Sat, Sep 3, 2011 at 12:21 PM, mukesh tiwari wrote: > I am getting > Traceback (most recent call last): > File "Mount.py", line 7, in > observer = QUDevMonitorObserver(monitor) > NameError: name 'QUDevMonitorObserver' is not defined > > Could any one please tell me how to avoid this error . > It looks to me like that should be pyudev.QUDevMonitorObserver, shouldn't it? -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Sep 3 13:16:01 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 03 Sep 2011 18:16:01 +0100 Subject: Reading pen drive data In-Reply-To: <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> References: <3c05935f-3e0b-4b1b-afca-889c63e5b650@r8g2000prd.googlegroups.com> <4ee9b05c-b1cf-4542-a3af-6a42b669c37f@a10g2000prn.googlegroups.com> Message-ID: <4E6260D1.4010905@mrabarnett.plus.com> On 03/09/2011 17:21, mukesh tiwari wrote: > On Sep 3, 7:40 pm, mukesh tiwari wrote: >> Hello all >> I am trying to write a python script which can mount a pen drive and >> read the data from pen drive. I am using pyudev [http://packages.python.org/pyudev/api/index.html] and wrote a small >> python code >> >> import pyudev, sys >> if __name__ =="__main__": >> context = pyudev.Context() >> devices = context.list_devices(subsystem ="usb") >> for device in devices : >> print device >> >> which prints >> >> Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.1/usb4/4-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.2/usb5/5-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1') >> Device(u'/sys/devices/pci0000:00/0000:00:1a.7/usb1/1-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb6/6-2/6-2:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.1/usb7/7-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.2/usb8/8-0:1.0') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2') >> Device(u'/sys/devices/pci0000:00/0000:00:1d.7/usb2/2-0:1.0') >> >> My problem is, how to know out of these usb which one to read . The >> other solution I got is whenever I insert the pen drive , my system >> mounts it in /media directory so I can read the /media directory to >> check if its empty or not but this does not seems promising to me >> because it may be possible that my system is not able to mount the pen >> drive so I have to manually do it . Kindly some one please tell me >> how to solve this problem. > > I got this link and its working fine [ http://packages.python.org/pyudev/api/monitor.html > ] >>>> context = pyudev.Context() >>>> monitor = pyudev.Monitor.from_netlink(context) >>>> monitor.filter_by(subsystem='input') >>>> for action, device in monitor: > ... print('{0}: {1}'.format(action, device)) > > but when I am trying to execute code [ http://packages.python.org/pyudev/api/toolkit.html > ] > > import pyudev, sys > > context = pyudev.Context() > monitor = pyudev.Monitor.from_netlink(context) > monitor.filter_by(subsystem='usb') > observer = QUDevMonitorObserver(monitor) > def device_connected(device): > print('{0!r} added'.format(device)) > observer.deviceAdded.connect(device_connected) > monitor.start() > > I am getting > Traceback (most recent call last): > File "Mount.py", line 7, in > observer = QUDevMonitorObserver(monitor) > NameError: name 'QUDevMonitorObserver' is not defined > > Could any one please tell me how to avoid this error . > Thank you I think you need to import it from pyudev.pyqt4. From d_vineet at yahoo.com Sat Sep 3 13:23:17 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 10:23:17 -0700 (PDT) Subject: framework suggestions for Ben Message-ID: <1315070597.66606.YahooMailNeo@web160520.mail.bf1.yahoo.com> >Folks, >I need some advice on a python web & database framework to use...? >I have handcrafted a sqllite3 python script, that is a basic web application, interfacing with a >sqlite3 database... It depends on whether you want to develop?desktop apps or browser-based apps. I will suggest 2 frameworks with their urls. I will not enumerate the features?here,?because their?websites?contain loads of advocacy about them. ? ========= For desktop apps, my STRONG advise to you is DABO. http://dabodev.com/ It is developed by the experts in data-centric business apps. It contains the features which I haven't seen in any other framework except MS VFP & cursor adapter?(if at all you are familiar with them). ======== For browser based apps, I found web2py very simple yet powerful. http://web2py.com/ ? It requires no installation (not even python). Everything works out of the box. No dependencies. ========= ? Hope this helps. :) Vineet ...... >- Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From mithrandi at mithrandi.net Sat Sep 3 13:26:22 2011 From: mithrandi at mithrandi.net (Tristan Seligmann) Date: Sat, 3 Sep 2011 19:26:22 +0200 Subject: [ANN] Pyflakes 0.5.0 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 It is my unexpected pleasure to announce the release of Pyflakes 0.5.0, the first release in several years, and available now from PyPI[1]. Highlights of this release include the use of the built-in AST instead of the compiler module, and support for various new syntax constructs in Python 2.7. Note that development of Pyflakes (as well as the other divmod.org projects) has moved to Launchpad[2] since the last release. [1] http://pypi.python.org/packages/source/p/pyflakes/pyflakes-0.5.0.tar.gz#md5=568dab27c42e5822787aa8a603898672 [2] https://launchpad.net/pyflakes -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.18 (GNU/Linux) iQIcBAEBCgAGBQJOYmL+AAoJEFjA+xzeO3YAme4P/AxLuy0WJN2zG97my1oEwky9 VT79BwnxOqR4NB7I1dRKE3PG4Llgl6frAa0SouM12Dr0QZj9Ug3qHAmmf+TZFrF6 OIQcBUGkZW7EanBhCbjmfqo+0atJ8toAcj9uyF7Db/0A7gCDw160JIMnmTmxu8z6 3r5xRLNSnxs4jj6OSViv9oHNs2r2lpU/RObkGXy6EHxMgezYqw84FbA61fxquK4p +J1n++vzfiasqgcQFFU3R67T0P2gWUe0C6pv/D+CurSCOdgQJv4LeRtNeYgKhw/W rN0/3cERXGyRMa4JYDbFyP2G8lrpOuWo2F+jFtEGAxgziK8EqCK58ZSeqMBsodJ9 slAZobSQkrUj6GfpNKdW5mjYRqymBmUhPFc+sUI2poGb3zvMnWmUa2tiSfwl9uxO 9Di82XXAztKba8++cGJQCbuONiLRPgW5kArz5dRz3jFVdAZYL7xUvah4uznwfazc CA8Q0tiXXoL7X1sT6heNu4VRtnJfEh5LojFdizA4nJEpNssZrPFkSZMv+eSR4Sow 8u2n4f07od6EBzHMhEyqFN7goaniW05VL+EvMdC5px+brnyKOIoLSAGWptBL5EYL aaAb2zRrebyr/u5vGa+sKEXcoW2TEsc9qO8p/nNSetcoIcNfDwnd3cdyJPU+lYbn Wctc68Y+xNWChiuTYa3e =kKgi -----END PGP SIGNATURE----- From milleja46 at gmail.com Sat Sep 3 13:54:15 2011 From: milleja46 at gmail.com (Joshua Miller) Date: Sat, 3 Sep 2011 13:54:15 -0400 Subject: IDLE from python 3.2 constantly crashes Message-ID: Ok i've been using IDLE on my home computer and everytime i try and open a file that i saved to my hdd instead of my flashdrive(because it's a school project) by accident, it opens for a second and i try to do something else like open another file and it crashes. Is there anyway to remedy this error? By the way i'm running python 3.2 on windows 7 if it makes a difference From nagle at animats.com Sat Sep 3 14:10:06 2011 From: nagle at animats.com (John Nagle) Date: Sat, 03 Sep 2011 11:10:06 -0700 Subject: SSL module needs issuer information Message-ID: <4e626d97$0$1665$742ec2ed@news.sonic.net> The SSL module still doesn't return much information from the certificate. SSLSocket.getpeercert only returns a few basic items about the certificate subject. You can't retrieve issuer information, and you can't get the extensions needed to check if a cert is an EV cert. With the latest flaps about phony cert issuers, it's worth having issuer info available. It was available in the old M2Crypto module, but not in the current Python SSL module. John Nagle From ian.g.kelly at gmail.com Sat Sep 3 14:50:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 3 Sep 2011 12:50:14 -0600 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On Sat, Sep 3, 2011 at 10:15 AM, William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. > > It seems to me that they are complimentary. ?It makes sense to create > objects and have some functions that take those objects as arguments. Are > they suggesting that any function that takes an object as an argument should > always be a method of that object? ?Conversely I can see creating functions > that take raw input (e.g. strings) and return it in a format compatible with > an object's constructor, rather than have objects accept any conceivable > format for its constructor. > > Am I missing something, or am I taking things too literally? I think you may be confusing "functional programming" and "programming using functions". These are not the same thing. Functional programming is about using functions in the *mathematical* sense. A mathematical function maps one value (or tuple of values) to another value. The mapped value never varies; if it did, it would be a different function. So functional programming eschews the use of functions where the results depend on any internal or external state beyond the values of the passed-in arguments, such as the variable state of the object the method is being called on. Functional programming and OOP are not entirely opposed -- for example, string methods in Python such as str.upper are perfectly functional, since strings are immutable. Many functional languages such as Common LISP also have powerful OOP facilities. Still, functional programming does not fit well with the traditional OOP model of objects passing messages to other objects, which generally implies statefulness. Cheers, Ian From paul at subsignal.org Sat Sep 3 14:59:27 2011 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Sat, 03 Sep 2011 20:59:27 +0200 Subject: Need advice on Web / Database framework... In-Reply-To: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: Hi, Am 03.09.2011 16:11, schrieb Benjamin Schollnick: > Folks, > > I need some advice on a python web& database framework to use...? Hardest question ever ;) > > I have handcrafted a sqllite3 python script, that is a basic web > application, interfacing with a sqlite3 database... > > But I am concerned at the thought of handcrafting a administration > interface, and so forth. If you are not familiar with the various pitfalls of web security I'd recomment a framework which has all the layers already integrated. Take a look at http://www.web2py.com, I think it's quite powerful and has good documentation. If you want to get your hands dirty you can compose your own "framework" cherrypy+sqlalchemy+cheetah might be a good combination. hth Paul From tjreedy at udel.edu Sat Sep 3 15:01:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:01:31 -0400 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: On 9/3/2011 3:51 AM, Yingjie Lan wrote: > I agree that long lines of code are not very common in many projects, > though it might be the case with some heavily involved in math. For some > reason, when the feature of free line breaking came about in computer > languages, it is welcomed and generally well accepted. Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance. > Python uses indentation for blocks, and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. > and by the same mechanism, line breaking can be > accommodated without requiring parenthesis or ending backslashes. You need proof for your claim that indentation can be used for both jobs in the form of a grammar that works with Python's parser. I am dubious that you can do that with an indents *after* the newline. Even if you could, it would be confusing for human readers. There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:15:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:15:28 -0400 Subject: Functions vs OOP In-Reply-To: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 12:25 PM, Steven D'Aprano wrote: > William Gill wrote: > >> During some recent research, and re-familiarization with Python, I came >> across documentation Ours, or someone else's? >> that suggests that programming using functions, and >> programming using objects were somehow opposing techniques. >> >> It seems to me that they are complimentary. It makes sense to create >> objects and have some functions that take those objects as arguments. > > Python is a mixed paradigm language, with object, functional and imperative > paradigms. > >> Are they suggesting that any function that takes an object as an >> argument should always be a method of that object? Or of the class of the object. > Yes. > http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html Since in Python, everything is an object, that would mean that every function has to be a method, which would mean creating classes just to have a class to attach functions to. How awful. (Oh, right, I believe I just described Java.) >> Am I missing something, or am I taking things too literally? > > No, it is the OO purists who are missing something. Yes, Python. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:20:52 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:20:52 -0400 Subject: IDLE from python 3.2 constantly crashes In-Reply-To: References: Message-ID: On 9/3/2011 1:54 PM, Joshua Miller wrote: > Ok i've been using IDLE on my home computer and everytime i try and > open a file that i saved to my hdd instead of my flashdrive(because > it's a school project) by accident, it opens for a second and i try to > do something else like open another file and it crashes. Is there > anyway to remedy this error? > > By the way i'm running python 3.2 on windows 7 if it makes a difference Since I and others am using the same (3.2 on Win 7) quite successfully, it is hard to know what the problem is with your setup. Start with more details of exactly what you do and what 'it crashes' means. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 3 15:23:13 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 15:23:13 -0400 Subject: SSL module needs issuer information In-Reply-To: <4e626d97$0$1665$742ec2ed@news.sonic.net> References: <4e626d97$0$1665$742ec2ed@news.sonic.net> Message-ID: On 9/3/2011 2:10 PM, John Nagle wrote: > The SSL module still doesn't return much information from the > certificate. SSLSocket.getpeercert only returns a few basic items > about the certificate subject. You can't retrieve issuer information, > and you can't get the extensions needed to check if a cert is an EV cert. > > With the latest flaps about phony cert issuers, it's worth > having issuer info available. It was available in the old M2Crypto > module, but not in the current Python SSL module. Check the tracker to see if there is an issue about this already. If not, open one with a specific feature request. -- Terry Jan Reedy From noreply at domain.invalid Sat Sep 3 17:09:03 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:09:03 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/3/2011 12:29 PM, MRAB wrote: > I think you mean "complementary". :-) How polite of you to point out my spelling deficiency. I guess shouldn't be watching football while typing (I'm sure the beer didn't help either). > I think that it's all about "state". > > In functional programming, there's no state; a function's result > depends solely on its arguments, so it will always return the same > result for the same given arguments. > > In OOP, on the other hand, an object often has a state; a method may > return a different result each time it's called, even for the same > given arguments. I think you mean "it [sic, a function] will "return the same result for the same given values..." x=1 y= myFn(x) will return the same result as y= myFn(1) A method may use an attribute as an implicit argument, and that attribute's value change, just like the value of x (above) may change. It may or may not return anything (it may just modify an attribute). The question wasn't about encapsulation, it was about programming paradigms, and if they conflict. As was pointed out elsewhere, I may have just confused "functional programming" with "programming using functions". From noreply at domain.invalid Sat Sep 3 17:13:06 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:13:06 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/3/2011 2:50 PM, Ian Kelly wrote: > I think you may be confusing "functional programming" and "programming > using functions". These are not the same thing. > I think you may be right, Ian. It didn't make much sense From noreply at domain.invalid Sat Sep 3 17:34:05 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:34:05 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 3:15 PM, Terry Reedy wrote: >> William Gill wrote: >> >>> During some recent research, and re-familiarization with Python, I came >>> across documentation > > Ours, or someone else's? Python. > > Since in Python, everything is an object, that would mean that every > function has to be a method, which would mean creating classes just to > have a class to attach functions to. How awful. Exactly why I asked, but I realize the the mistake was mine. I think they were talking about "functional programming" not "using functions in an OO program." From ben+python at benfinney.id.au Sat Sep 3 17:39:30 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 04 Sep 2011 07:39:30 +1000 Subject: Functions vs OOP References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87bov1qp9p.fsf@benfinney.id.au> William Gill writes: > On 9/3/2011 3:15 PM, Terry Reedy wrote: > >> William Gill wrote: > >> > >>> During some recent research, and re-familiarization with Python, I > >>> came across documentation > > > > Ours, or someone else's? > > Python. Can you show exactly where in the Python documentation you found the passage which confused you? -- \ ?If you're a cowboy and you're dragging a guy behind your | `\ horse, I bet it would really make you mad if you looked back | _o__) and the guy was reading a magazine.? ?Jack Handey | Ben Finney From nospam at domain.invalid Sat Sep 3 17:58:01 2011 From: nospam at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 17:58:01 -0400 Subject: Functions vs OOP In-Reply-To: <87bov1qp9p.fsf@benfinney.id.au> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> <87bov1qp9p.fsf@benfinney.id.au> Message-ID: On 9/3/2011 5:39 PM, Ben Finney wrote: > William Gill writes: > >> On 9/3/2011 3:15 PM, Terry Reedy wrote: >>>> William Gill wrote: >>>> >>>>> During some recent research, and re-familiarization with Python, I >>>>> came across documentation >>> >>> Ours, or someone else's? >> >> Python. > > Can you show exactly where in the Python documentation you found the > passage which confused you? > Sorry, no. I tried to locate the exact reference again, and couldn't remember where I read it (short term memory problems). From bkasterm at gmail.com Sat Sep 3 18:15:18 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Sat, 03 Sep 2011 16:15:18 -0600 Subject: Tkinter label height to fit content Message-ID: <87mxelgtmx.fsf@gmail.com> I have a label into which I am going to put content of different sizes. I would like to know how high I need to make the label so that I can size the window so it can stay the same for the different content sizes. I have a strategy, but it seems more complicated then it should be. I want to set a label to a given width and wraplength: l = Label(root) l['width'] = 30 l['wraplength'] = 244 l['text'] = "testing this" Now I want to query the label to find how many lines are used. l['height'] stays at 0, so the best I have been able to come up with is to use l.winfo_height() and convert the height given in pixels to the number of lines used. Nothing in dir(l) seems to give me the information directly, but this strategy is fragile to font changes and other changes. Any suggestions? From PointedEars at web.de Sat Sep 3 18:58:15 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 04 Sep 2011 00:58:15 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> Message-ID: <109595831.VCN276Cjj6@PointedEars.de> Fokke Nauta wrote: > "Thomas 'PointedEars' Lahn" [?]: >> Fokke Nauta wrote: >>> "Thomas 'PointedEars' Lahn" [?] wrote: >>>> The Python shell executes Python code. The above obviously is not >>>> Python >>>> code, but *system* shell commands. So let the *system* command shell >>>> execute them (as indicated by the `$' prompt, which is customary for a >>>> sh-based UNIX/Linux shell prompt). >>> I know. I worked with SCO Unix and various sorts of Linux. >>> But never with Python, so I hadn't got a clue about the prompt. >> Come on, with that experience you see a `$' and those commands and don't >> realize it is (ba)sh? > > Ofcourse I realized it was Unix/Linux. I already could tell that as the > packages I downloaded were tar.gz files. For *Windows*? > So I unpacked them and expected to run a Python installer script from the > Python command line. Again, given all that experience you claim to have, how come it did not occur to you that the `$' was meant to be a *command* *shell* prompt? Other OSes have command shells, too, you know; they are just named and run differently. > Tried to run the Python installer script from the DOS command line but > that resulted in an error. "There was an error" is no error report at all. >>>> However, you appear to have found the *UNIX/Linux* README (and the >>>> corresponding version?) of that server: the second command is usually >>>> how you would run a program as daemon on Unices (run through an init >>>> script), while on Windows NT (like XP) you would have a setup program >>>> install a service for you (maybe to execute that command when the >>>> service is started). Look for the Windows version. >>> There is no other Windows version except the packages I mentioned, >>> PyWebDAV and PyXML. The only Windows thing I got was the Python >>> interpreter itself. >> Has it not occurred to you to STFW for "easy_install" first? > > What do you mean by STFW? Search The F****ing Web. > I wasn't aware that easy_install was a utility. Downloaded and installed > the Windows version and run easy_install pywebdav. > It downloaded something, installed something and finished something. > But, once again, don't know how to proceed. RTFM. >>>>> And there is no easy_install script in the PyXML-0.8.4 >>>>> directory, only a setup.py and ez_setup.py script. I guess the latter >>>>> is >>>>> the one to use. But how? >>>> RTFM. >>> Which fucking manual? >> That of the server, on Windows-related information. Or that of >> easy_install. Or Python. Whichever comes first. > > It's my own server and I didn't write a manual for it. No, the people providing it for you obviously did, but you do not seem to care to read it. > In the manual of Easy_install it says how to install packaged etc and I > did sucessfully. > There is no furter information as how to proceed. Either you are lying, or you are really forgetful, or you are simply not smart enough for this. You yourself told me/us before what the next step is: >>>>> How do I proceed next? >>>> Look for the Windows version. If there is none, get easy_install and >>>> use >>>> it as described. > > I did and it worked. What's next? Start the now-installed server, for goodness' sake! Observing this, be reminded that playing stupid does not work with me: And please get rid of that attribution novel and trim your quotes to the relevant minimum. I am asking you the last time here. If you cannot find it within you to think about your readers when you post, you are not worth my attention or (free) time. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From lanyjie at yahoo.com Sat Sep 3 19:22:57 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sat, 3 Sep 2011 16:22:57 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> >?Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance.? >?and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. Agreed.?Currently indentation in Python starts a new block,?but if you view it from the perspective of line breaking,?it also functions as if the line is continued. The line of code below if condition: do_a(); do_b() can be ?written as: if condition: #line breaks do_a(); # ';' is optional here? do_b() # continue That indentation can be also employed for line breaking is quite evident to me. During the open email correspondence with Stephen, it seems to be a tenable point.? >?There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. I believe the other two ways are not as good as this new way. As the proposal is fully backward compatible, people may choose whatever way they prefer.? >________________________________ >From: Terry Reedy >To: python-list at python.org >Cc: python-ideas at python.org >Sent: Sunday, September 4, 2011 3:01 AM >Subject: Re: [Python-ideas] allow line break at operators > >On 9/3/2011 3:51 AM, Yingjie Lan wrote: >> I agree that long lines of code are not very common in many projects, >> though it might be the case with some heavily involved in math. For some >> reason, when the feature of free line breaking came about in computer >> languages, it is welcomed and generally well accepted. > >Every language with blocks needs some mechanism to indicate the beginning and ending of blocks and of statements within blocks. If visible fences ('begin/end' or '{}') and statement terminators (';') are used, then '\n' can be treated as merely a space, as it is in C, for instance. > >> Python uses indentation for blocks, > >and it uses unescaped '\n' (with two escapement options) to terminate statements. This is fundamental to Python's design and goes along with significant indents. > >> and by the same mechanism, line breaking can be >> accommodated without requiring parenthesis or ending backslashes. > >You need proof for your claim that indentation can be used for both jobs in the form of a grammar that works with Python's parser. I am dubious that you can do that with an indents *after* the newline. > >Even if you could, it would be confusing for human readers. There would then be three ways to escape newline, with one doing double duty. And for what? Merely to avoid using either of the two methods already available. > >-- Terry Jan Reedy > >-- http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gelonida at gmail.com Sat Sep 3 20:15:32 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 04 Sep 2011 02:15:32 +0200 Subject: SSL module needs issuer information In-Reply-To: <4e626d97$0$1665$742ec2ed@news.sonic.net> References: <4e626d97$0$1665$742ec2ed@news.sonic.net> Message-ID: Hi John, On 09/03/2011 08:10 PM, John Nagle wrote: > The SSL module still doesn't return much information from the > certificate. SSLSocket.getpeercert only returns a few basic items > about the certificate subject. You can't retrieve issuer information, > and you can't get the extensions needed to check if a cert is an EV cert. > > With the latest flaps about phony cert issuers, it's worth > having issuer info available. It was available in the old M2Crypto > module, but not in the current Python SSL module. Your phrasing 'old M2Crypto' disturbs me slightly. I am using Python 2.6. Is M2Crypto also obsolete for python 2.6? Is there any serious alternative if I want to verify the server certificate in a safe way (and if I want to send a client certificate)?? I am in search for a set of libraries, which allows me to: - verify the server certificate (ideally via a custom call back, which can inspect the certificate data and then decide whether the certificate shall be accepted or not) - send a client certificate - use https with a cookie jar (ideally even persistent, but session cookies are enough) - do XMLRPC calls (but send cookies in the headers) Would m2crypto be the right choice? From gelonida at gmail.com Sat Sep 3 20:18:34 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 04 Sep 2011 02:18:34 +0200 Subject: Need advice on Web / Database framework... In-Reply-To: References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: Hi Paul, On 09/03/2011 08:59 PM, Paul K?lle wrote: > Am 03.09.2011 16:11, schrieb Benjamin Schollnick: >> Folks, >> >> I need some advice on a python web& database framework to use...? > Hardest question ever ;) . . . >> But I am concerned at the thought of handcrafting a administration >> interface, and so forth. > If you are not familiar with the various pitfalls of web security I'd > recomment a framework which has all the layers already integrated. Take > a look at http://www.web2py.com, I think it's quite powerful and has > good documentation. > If you want to get your hands dirty you can compose your own "framework" > cherrypy+sqlalchemy+cheetah might be a good combination. > How does web2py compare to django? I just started playing with django, but don't know web2py From rantingrick at gmail.com Sat Sep 3 21:15:52 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 3 Sep 2011 18:15:52 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> Message-ID: <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> On Sep 3, 5:15?pm, Bart Kastermans wrote: > Any suggestions? Yeah, have you considered using the "linespace()" method of tk.Font objects to calculate the height? Although i must say it "feels" as if your doing something you should not need to do, however i cannot be sure without knowing more about this GUI. Sounds a lot like trying to put socks on a rooster. http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#fonts From tjreedy at udel.edu Sat Sep 3 21:51:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 03 Sep 2011 21:51:37 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 5:34 PM, William Gill wrote: > On 9/3/2011 3:15 PM, Terry Reedy wrote: >>> William Gill wrote: >>> >>>> During some recent research, and re-familiarization with Python, I came >>>> across documentation >> >> Ours, or someone else's? > > Python. > >> >> Since in Python, everything is an object, that would mean that every >> function has to be a method, which would mean creating classes just to >> have a class to attach functions to. How awful. > > Exactly why I asked, but I realize the the mistake was mine. I think > they were talking about "functional programming" not "using functions in > an OO program." It is possible that our doc was less than crystal clear. We are constantly improving it where we can see fixable faults. If you run across whatever it was and it still seems a bit muddy, post something again. -- Terry Jan Reedy From python at mrabarnett.plus.com Sat Sep 3 22:04:54 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 04 Sep 2011 03:04:54 +0100 Subject: [Python-ideas] allow line break at operators In-Reply-To: <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> Message-ID: <4E62DCC6.8000906@mrabarnett.plus.com> On 04/09/2011 00:22, Yingjie Lan wrote: >> Every language with blocks needs some mechanism to indicate the > beginning and ending of blocks and of statements within blocks. If > visible fences ('begin/end' or '{}') and statement terminators (';') are > used, then '\n' can be treated as merely a space, as it is in C, for > instance. >> and it uses unescaped '\n' (with two escapement options) to terminate > statements. This is fundamental to Python's design and goes along with > significant indents. > > Agreed. Currently indentation in Python starts a new block, but if you > view it from the perspective of line breaking, it also functions as if > the line is continued. The line of code below > > if condition: do_a(); do_b() > > can be written as: > > if condition: #line breaks > do_a(); # ';' is optional here > do_b() # continue > > That indentation can be also employed for line breaking is quite evident > to me. During the open email correspondence with Stephen, it seems to be > a tenable point. > > > There would then be three ways to escape newline, with one doing > double duty. And for what? Merely to avoid using either of the two > methods already available. > > I believe the other two ways are not as good as this new way. As the > proposal is fully backward compatible, people may choose whatever way > they prefer. > I think that the rules would be: If a line ends with a colon and the next line is indented, then it's the start of a block, and the following lines which belong to that block have the same indent. If a line doesn't end with a colon but the next line is indented, then it's the start of a continuation, and the following lines which belong to that continuation have the same indent. In both cases there could be blocks nested in blocks and possibly continuations nested in continuations, as well as blocks nested in continuations and continuations nested in blocks. I'm not sure what the effect would be if you had mis-indented lines. For example, if a line was accidentally indented after a comment, then it would be treated as part of the comment. It's in cases like those that syntax colouring would be helpful. It would be a good idea to use an editor which could indicate in some way when a line is a continuation. > ------------------------------------------------------------------------ > *From:* Terry Reedy > *To:* python-list at python.org > *Cc:* python-ideas at python.org > *Sent:* Sunday, September 4, 2011 3:01 AM > *Subject:* Re: [Python-ideas] allow line break at operators > > On 9/3/2011 3:51 AM, Yingjie Lan wrote: > > I agree that long lines of code are not very common in many projects, > > though it might be the case with some heavily involved in math. > For some > > reason, when the feature of free line breaking came about in computer > > languages, it is welcomed and generally well accepted. > > Every language with blocks needs some mechanism to indicate the > beginning and ending of blocks and of statements within blocks. If > visible fences ('begin/end' or '{}') and statement terminators (';') > are used, then '\n' can be treated as merely a space, as it is in C, > for instance. > > > Python uses indentation for blocks, > > and it uses unescaped '\n' (with two escapement options) to > terminate statements. This is fundamental to Python's design and > goes along with significant indents. > > > and by the same mechanism, line breaking can be > > accommodated without requiring parenthesis or ending backslashes. > > You need proof for your claim that indentation can be used for both > jobs in the form of a grammar that works with Python's parser. I am > dubious that you can do that with an indents *after* the newline. > > Even if you could, it would be confusing for human readers. There > would then be three ways to escape newline, with one doing double > duty. And for what? Merely to avoid using either of the two methods > already available. > From noreply at domain.invalid Sat Sep 3 22:18:19 2011 From: noreply at domain.invalid (William Gill) Date: Sat, 03 Sep 2011 22:18:19 -0400 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 9:51 PM, Terry Reedy wrote: > > It is possible that our doc was less than crystal clear. We are > constantly improving it where we can see fixable faults. If you run > across whatever it was and it still seems a bit muddy, post something > again. > Will do. Thanks. From shilparani9030 at gmail.com Sat Sep 3 23:14:29 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Sat, 3 Sep 2011 20:14:29 -0700 (PDT) Subject: KATRINA KAIF RARE PHOTOS Message-ID: <66624c9c-94ca-44a1-a6f1-fc67871b334b@r40g2000prf.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html KAJAL AGARWAL LATEST HOT http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From jehugaleahsa at gmail.com Sat Sep 3 23:35:24 2011 From: jehugaleahsa at gmail.com (Travis Parks) Date: Sat, 3 Sep 2011 20:35:24 -0700 (PDT) Subject: Algorithms Library - Asking for Pointers References: <8f893753-abbc-47df-9d90-77263e96be1b@p10g2000yqi.googlegroups.com> <18fe4afd-569b-4580-a629-50f6c74829e8@c29g2000yqd.googlegroups.com> Message-ID: <112f5d1d-fbf7-44da-a0dd-cbbeb3a59c6d@dq7g2000vbb.googlegroups.com> On Sep 3, 12:35?am, Chris Torek wrote: > In article <18fe4afd-569b-4580-a629-50f6c7482... at c29g2000yqd.googlegroups.com> > Travis Parks ? wrote: > > >[Someone] commented that the itertools algorithms will perform > >faster than the hand-written ones. Are these algorithms optimized > >internally? > > They are written in C, so avoid a lot of CPython interpreter > overhead. ?Mileage in Jython, etc., may vary... > -- > In-Real-Life: Chris Torek, Wind River Systems > Intel require I note that my opinions are not those of WRS or Intel > Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) ?+1 801 277 2603 > email: gmail (figure it out) ? ? ?http://web.torek.net/torek/index.html I thought I would point out that many of the itertools functions change between 2.x and 3.x versions. Since 2.7 is supposed to be the last 2.x language, I suppose I will wait until 3.2 becomes the norm before I incorporate some of these changes. In the mean time, I will starting working on algorithms that work against Sequences. I think a really important lesson is that Python really doesn't need an algorithms library, like many others do. A lot of the common algorithms are supported by the syntax itself. All my library did was allow for easier function composition. From d_vineet at yahoo.com Sun Sep 4 01:03:08 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Sat, 3 Sep 2011 22:03:08 -0700 (PDT) Subject: my suggestions for framework Message-ID: <1315112588.16268.YahooMailNeo@web160517.mail.bf1.yahoo.com> > recomment a framework which has all the layers already integrated. Take > a look at http://www.web2py.com, I think it's quite powerful and has > good documentation. > If you want to get your hands dirty you can compose your own "framework" > cherrypy+sqlalchemy+cheetah might be a good combination. > How does web2py compare to django? I just started playing with django, but don't know web2py ---- IMHO, django is suitable for CMS kind of apps. AFAIK, originally it was written for a newspaper website, subsequently it has grown over the time. I have tried turbogears(TG), django & web2py. TG is like picking all good eggs from different open source projects. It integrates sqlalchemy, genshi, cheetah, pylons, for sql abstraction layer, templating system, web server respectively. One can choose other options also, if desired. -1 for TG is its complexity and not-so-good docs, too many dependencies. ? django has very good docs & active community. It is better in terms of simplicity & dependency?as compared to TG. ? web2py is vastly flexible, no dependencies, no installation required, just plug & play, very good community & docs. Honestly, I did not find any -1 for web2py. ? Of course, one has to form his/her own opinion. On stackoverflow.com, there are plenty of threads which compare the python frameworks. ? :-) ---Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From tinnews at isbd.co.uk Sun Sep 4 04:13:49 2011 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: Sun, 4 Sep 2011 09:13:49 +0100 Subject: Functions vs OOP References: Message-ID: Ian Kelly wrote: > On Sat, Sep 3, 2011 at 10:15 AM, William Gill wrote: > > During some recent research, and re-familiarization with Python, I came > > across documentation that suggests that programming using functions, and > > programming using objects were somehow opposing techniques. > > > > It seems to me that they are complimentary. ?It makes sense to create > > objects and have some functions that take those objects as arguments. Are > > they suggesting that any function that takes an object as an argument should > > always be a method of that object? ?Conversely I can see creating functions > > that take raw input (e.g. strings) and return it in a format compatible with > > an object's constructor, rather than have objects accept any conceivable > > format for its constructor. > > > > Am I missing something, or am I taking things too literally? > > I think you may be confusing "functional programming" and "programming > using functions". These are not the same thing. > > Functional programming is about using functions in the *mathematical* > sense. A mathematical function maps one value (or tuple of values) to > another value. The mapped value never varies; if it did, it would be > a different function. So functional programming eschews the use of > functions where the results depend on any internal or external state > beyond the values of the passed-in arguments, such as the variable > state of the object the method is being called on. > I think there may be another issue here. If someone says "functional programming" to me then I would generally assume that they *do* mean "programming using functions". While your distinction of the two may be strictly correct I don't think it's the generally accepted meaning. -- Chris Green From fnautaNO at SPAMsolfon.nl Sun Sep 4 04:59:41 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Sun, 4 Sep 2011 10:59:41 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> <109595831.VCN276Cjj6@PointedEars.de> Message-ID: <9cgsvvFdhuU1@mid.individual.net> "Thomas 'PointedEars' Lahn" wrote in message news:109595831.VCN276Cjj6 at PointedEars.de... If you don't have anything better to contribute, please stop answering. Es gen?gt schon. Fokke From adam.jorgensen.za at gmail.com Sun Sep 4 05:05:32 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Sun, 4 Sep 2011 11:05:32 +0200 Subject: Functions vs OOP In-Reply-To: References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: Progranming with functions vs Progranming with objects sounds like C vs. C++ more than functional programming vs. OO programming On 4 September 2011 04:18, William Gill wrote: > On 9/3/2011 9:51 PM, Terry Reedy wrote: > >> >> It is possible that our doc was less than crystal clear. We are >> constantly improving it where we can see fixable faults. If you run >> across whatever it was and it still seems a bit muddy, post something >> again. >> >> Will do. > > Thanks. > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lanyjie at yahoo.com Sun Sep 4 05:58:08 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Sun, 4 Sep 2011 02:58:08 -0700 (PDT) Subject: [Python-ideas] allow line break at operators In-Reply-To: <4E62DCC6.8000906@mrabarnett.plus.com> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <1315092177.54288.YahooMailNeo@web121504.mail.ne1.yahoo.com> <4E62DCC6.8000906@mrabarnett.plus.com> Message-ID: <1315130288.86666.YahooMailNeo@web121515.mail.ne1.yahoo.com> > Thanks, I think that's the rule described in its full glory. Currently I am not ?quite sure of the use case for continuation nested in continuation -- it seems to be still a single continuation, but it allows for some additional freedom in formatting the continued line. Do you have other use cases for that? For the case of mis-indentation, as demonstrated in your scenario,?I think it is better that the rule is not applied to a comment?continued onto the next line. The effect of a '#' only carries to the end of a line, if one would like the next line to be a comment, just use another '#'. It remains to consider a mis-indentation that only involves code lines. However, that is not a new problem, so we should not worry (it is like a sunken cost).? Sorry for top posting. It seems yahoo web email is not designed with such a use case in mind. >________________________________ >From: MRAB >To: python-list at python.org >Sent: Sunday, September 4, 2011 10:04 AM >Subject: Re: [Python-ideas] allow line break at operators > >On 04/09/2011 00:22, Yingjie Lan wrote: >>>? Every language with blocks needs some mechanism to indicate the >> beginning and ending of blocks and of statements within blocks. If >> visible fences ('begin/end' or '{}') and statement terminators (';') are >> used, then '\n' can be treated as merely a space, as it is in C, for >> instance. >>>? and it uses unescaped '\n' (with two escapement options) to terminate >> statements. This is fundamental to Python's design and goes along with >> significant indents. >> >> Agreed. Currently indentation in Python starts a new block, but if you >> view it from the perspective of line breaking, it also functions as if >> the line is continued. The line of code below >> >> if condition: do_a(); do_b() >> >> can be written as: >> >> if condition: #line breaks >> do_a(); # ';' is optional here >> do_b() # continue >> >> That indentation can be also employed for line breaking is quite evident >> to me. During the open email correspondence with Stephen, it seems to be >> a tenable point. >> >>? > There would then be three ways to escape newline, with one doing >> double duty. And for what? Merely to avoid using either of the two >> methods already available. >> >> I believe the other two ways are not as good as this new way. As the >> proposal is fully backward compatible, people may choose whatever way >> they prefer. >> >I think that the rules would be: > >If a line ends with a colon and the next line is indented, then it's >the start of a block, and the following lines which belong to that >block have the same indent. > >If a line doesn't end with a colon but the next line is indented, then >it's the start of a continuation, and the following lines which belong >to that continuation have the same indent. > >In both cases there could be blocks nested in blocks and possibly >continuations nested in continuations, as well as blocks nested in >continuations and continuations nested in blocks. > >I'm not sure what the effect would be if you had mis-indented lines. >For example, if a line was accidentally indented after a comment, then >it would be treated as part of the comment. It's in cases like those >that syntax colouring would be helpful. It would be a good idea to use >an editor which could indicate in some way when a line is a >continuation. > >>? ? ------------------------------------------------------------------------ >>? ? *From:* Terry Reedy >>? ? *To:* python-list at python.org >>? ? *Cc:* python-ideas at python.org >>? ? *Sent:* Sunday, September 4, 2011 3:01 AM >>? ? *Subject:* Re: [Python-ideas] allow line break at operators >> >>? ? On 9/3/2011 3:51 AM, Yingjie Lan wrote: >>? ? ? > I agree that long lines of code are not very common in many projects, >>? ? ? > though it might be the case with some heavily involved in math. >>? ? For some >>? ? ? > reason, when the feature of free line breaking came about in computer >>? ? ? > languages, it is welcomed and generally well accepted. >> >>? ? Every language with blocks needs some mechanism to indicate the >>? ? beginning and ending of blocks and of statements within blocks. If >>? ? visible fences ('begin/end' or '{}') and statement terminators (';') >>? ? are used, then '\n' can be treated as merely a space, as it is in C, >>? ? for instance. >> >>? ? ? > Python uses indentation for blocks, >> >>? ? and it uses unescaped '\n' (with two escapement options) to >>? ? terminate statements. This is fundamental to Python's design and >>? ? goes along with significant indents. >> >>? ? ? > and by the same mechanism, line breaking can be >>? ? ? > accommodated without requiring parenthesis or ending backslashes. >> >>? ? You need proof for your claim that indentation can be used for both >>? ? jobs in the form of a grammar that works with Python's parser. I am >>? ? dubious that you can do that with an indents *after* the newline. >> >>? ? Even if you could, it would be confusing for human readers. There >>? ? would then be three ways to escape newline, with one doing double >>? ? duty. And for what? Merely to avoid using either of the two methods >>? ? already available. >> > >-- >http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandru at bastilla.coruscant.org.invalid Sun Sep 4 06:07:26 2011 From: alexandru at bastilla.coruscant.org.invalid (Alexandru Lazar) Date: Sun, 4 Sep 2011 10:07:26 +0000 (UTC) Subject: Need advice on Web / Database framework... References: <21960A6D-CD06-4F0C-AC35-8D176E964B38@schollnick.net> Message-ID: > How does web2py compare to django? I just started playing with django, > but don't know web2py I haven't used Django, but I did use web2py for a project that fell on my head just before leaving my old workplace. I just wanted it to end quickly so I took web2py as a shortcut. It's a great framework -- there seems to be an abstraction layer for anything, so you can write a fairly pythonic web app with it. The app I had to write was fairly trivial to be sure, and I barely had to write any code at all. What I didn't quite like about it was the documentation, that felt rather sketchy. There's the Official Web2py Book, but that has more of a tutorial structure. The API reference feels a tad sketchy and I sometimes had to guess my way around. But there's a good chance that this is just my bad impression, as I am not a web developer. Alex From steve+comp.lang.python at pearwood.info Sun Sep 4 07:18:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 04 Sep 2011 21:18:53 +1000 Subject: Functions vs OOP References: Message-ID: <4e635e9e$0$29984$c3e8da3$5496439d@news.astraweb.com> tinnews at isbd.co.uk wrote: > I think there may be another issue here. If someone says "functional > programming" to me then I would generally assume that they *do* mean > "programming using functions". Strictly speaking you are correct, "functional programming" does mean "programming using functions", the usual name for which is "procedural programming". But it means more than that: functions in the sense of mathematical functions, not merely sub-routines. http://en.wikipedia.org/wiki/Functional_programming Merely using functions is not the same as functional programming. > While your distinction of the two may > be strictly correct I don't think it's the generally accepted meaning. On the contrary, "functional programming" specifically refers to languages derived from, based on, or at least inspired by, the ideas of Alonzo Church's lambda calculus. It should be understood as somewhat in opposition to the idea of imperative programming, where the programmer gives instructions for changing program state. http://en.wikipedia.org/wiki/Programming_paradigm In practice, there are degrees of purity: strictly speaking, a purely functional language would be impractical, because it would have no I/O and therefore not be very useful. But generally, functional programming implies: - all coding is done using functions - functions are first-class data values - higher-order functions are used (functions which take functions as arguments) - no global variables - all data is immutable (cannot be modified) - functions should always return the same result each time they are called with the same arguments (so-called "referential transparency") - computations should be performed lazily as needed - no side-effects other than those caused by hardware limitations (e.g. there is only a finite amount of memory available), usually with an exemption made for I/O - use of recursion instead of imperative features such as iteration (for loops, while loops, etc.) Pure functional programming languages enforce those conventions as design features, rather than just leaving it up to the coder to apply them as a convention. Impure functional languages, such as Python, don't enforce all (or even any) of those conditions, although they may provide certain functional features. -- Steven From rustompmody at gmail.com Sun Sep 4 09:13:58 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 4 Sep 2011 06:13:58 -0700 (PDT) Subject: Functions vs OOP References: Message-ID: On Sep 3, 9:15?pm, William Gill wrote: > During some recent research, and re-familiarization with Python, I came > across documentation that suggests that programming using functions, and > programming using objects were somehow opposing techniques. Staying with (for the moment) the suggestion that OO-P and F-P are complementary, I believe it is worthwhile to distinguish syntactic OO- P vs F-P from semantic OO-P vs F-P. Syntactically: f(x) is functional x.f() is object oriented. Semantically if f's return value depends only on x ie does not depend on state it is functional (in the math sense) -- the jargon is that f is referentially transparent. Referential opaqueness is usually such a source of problems that it turns out good to contain the problem somewhat -- hence the wish for encapsulation. One can find in the python library itself all 4 combinations: syntactically and semantically OO : sort syntactically and semantically FP: sorted syntactically OO semantically FP: join From erik.williamson at gmail.com Sun Sep 4 10:22:07 2011 From: erik.williamson at gmail.com (Erik) Date: Sun, 4 Sep 2011 07:22:07 -0700 (PDT) Subject: Can't use subprocess.Popen() after os.chroot() - why? Message-ID: Hi All, I'm trying to do the following: import os from subprocess import Popen, PIPE os.chroot("/tmp/my_chroot") p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout_val, stderr_val = p.communicate() print stdout_val but the Popen call is dying with the following exception: Traceback (most recent call last): File "./test.py", line 7, in p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads File "/home/erik/lib/python2.7/pickle.py", line 858, in load File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string LookupError: unknown encoding: string-escape Am I missing something here? does the chroot environment need to be populated with more than just the date executable in this case? I can't seem to find any examples of this & would appreciate any insight. Thanks, Erik. From ron3200 at gmail.com Sun Sep 4 11:22:32 2011 From: ron3200 at gmail.com (ron3200) Date: Sun, 04 Sep 2011 10:22:32 -0500 Subject: [Python-ideas] allow line break at operators In-Reply-To: <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4e424208$0$29965$c3e8da3$5496439d@news.astraweb.com> <1312981104.89312.YahooMailNeo@web121520.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <1315149752.24283.18.camel@Gutsy> On Sat, 2011-09-03 at 13:38 +0900, Stephen J. Turnbull wrote: > Guido van Rossum writes: > > On Fri, Sep 2, 2011 at 12:28 AM, Stephen J. Turnbull wrote: > > > > Sure, but IIRC one design principle of Python is that the keyword that > > > denotes the syntax should be the first thing on the line, > [...] > > That's true for *statements* (except assignments and calls). > > > > > Analogously, if operators are going to denote continuation, they > > > should come first on the line. > > > That doesn't follow. > > Agreed, it's not a logical implication. The analogy is only an > analogy, but my eyes do work that way. > > My conclusion is that we shouldn't try to encourage either style, > because people "see" continuation differently. Legislating a style > isn't going to change that, I think. I like to start continued lines with an operator as well. I also think it helps me keep it in my head a bit easier when I do that. I think this is one of those areas where computers and people differ, but it may also depend on the persons native language as to what works better for them. Ron From alain at dpt-info.u-strasbg.fr Sun Sep 4 11:25:48 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sun, 04 Sep 2011 17:25:48 +0200 Subject: Can't use subprocess.Popen() after os.chroot() - why? References: Message-ID: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> Erik writes: > import os > from subprocess import Popen, PIPE > > os.chroot("/tmp/my_chroot") > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > stdout_val, stderr_val = p.communicate() > print stdout_val > > but the Popen call is dying with the following exception: > > Traceback (most recent call last): > File "./test.py", line 7, in > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ > File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child > File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads > File "/home/erik/lib/python2.7/pickle.py", line 858, in load > File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string > LookupError: unknown encoding: string-escape > > Am I missing something here? does the chroot environment need to be > populated with more than just the date executable in this case? Yes, because /bin/date is probably dynamically linked: you need the libs as well. (Try first with a statically linked executable, e.g., /bin/busybox, and everything should be ok). I agree the message is strange. For some reason, subprocess is calling pickle.loads, which calls rep.decode("string-escape"), which probably needs to access some file and fails because of the chroot(). I woud advise to use the chroot command instead of chrooting your python process, if that's possible for you. -- Alain. From rantingrick at gmail.com Sun Sep 4 12:37:00 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 09:37:00 -0700 (PDT) Subject: allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <1315023501.31777.YahooMailNeo@web121514.mail.ne1.yahoo.com> <87aaamjgvh.fsf@uwakimon.sk.tsukuba.ac.jp> <1315036271.77996.YahooMailNeo@web121504.mail.ne1.yahoo.com> <878vq6j7og.fsf@uwakimon.sk.tsukuba.ac.jp> <1315046028.59053.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On Sep 3, 11:50?am, Stephen Hansen wrote: > Freedom is not and never has been, IMHO, a virtue or goal or even desire > in Python. Exactly! > Where it occurs, it is at best a happy coincidence, Exactly! > and even > if that happy coincidence happens often, it is not a design feature, IMHO. Exactly! Actually i believe Python allows TOO many freedoms and indulges TOO many excesses to the detriment of our code bases. Take the fact that both tabs AND spaces are legal in Python source. We should have choose one over the other! From hansmu at xs4all.nl Sun Sep 4 13:36:28 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 04 Sep 2011 19:36:28 +0200 Subject: Can't use subprocess.Popen() after os.chroot() - why? In-Reply-To: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> References: <87zkikz5vn.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e63b71c$0$2421$e4fe514c@news2.news.xs4all.nl> On 4/09/11 17:25:48, Alain Ketterlin wrote: > Erik writes: > >> import os >> from subprocess import Popen, PIPE >> >> os.chroot("/tmp/my_chroot") >> p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) >> stdout_val, stderr_val = p.communicate() >> print stdout_val >> >> but the Popen call is dying with the following exception: >> >> Traceback (most recent call last): >> File "./test.py", line 7, in >> p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) >> File "/home/erik/lib/python2.7/subprocess.py", line 679, in __init__ >> File "/home/erik/lib/python2.7/subprocess.py", line 1224, in _execute_child >> File "/home/erik/lib/python2.7/pickle.py", line 1382, in loads >> File "/home/erik/lib/python2.7/pickle.py", line 858, in load >> File "/home/erik/lib/python2.7/pickle.py", line 971, in load_string >> LookupError: unknown encoding: string-escape >> >> Am I missing something here? does the chroot environment need to be >> populated with more than just the date executable in this case? > > Yes, because /bin/date is probably dynamically linked: you need the libs > as well. (Try first with a statically linked executable, e.g., > /bin/busybox, and everything should be ok). /bin/date also needs timezone information from either /etc/localtime or /usr/share/zoneinfo/ (depends on whether the environment variable TZ is set). It may need other data files as well (e.g. for localization). > I agree the message is strange. For some reason, subprocess is calling > pickle.loads, which calls rep.decode("string-escape"), which probably > needs to access some file and fails because of the chroot(). The child process tries to exec /bin/date and fails. The child process then pickles the resulting exception and sends it to the parent via a pipe that the parent has created for this purpose. The parent then tries to unpickle the exception and fails to find the string-escape decoder in its usual place, due to the chroot. If you fix that, then the parent process will be able to re-raise the exception from the child process (which may or may not confuse you). > I woud advise to use the chroot command instead of chrooting your python > process, if that's possible for you. You'll find you need to copy a lot of dynamic libraries and several data files to your chroot box, before the normal commands in /bin work. Keep in mind that the more features you copy to the chroot jail, the easier it becomes to escape from it. Hope this helps, -- HansM From rantingrick at gmail.com Sun Sep 4 14:08:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 11:08:36 -0700 (PDT) Subject: allow line break at operators References: <1312951356.77394.YahooMailNeo@web121518.mail.ne1.yahoo.com> <1312982377.95657.YahooMailNeo@web121508.mail.ne1.yahoo.com> <1313031175.38817.YahooMailNeo@web121515.mail.ne1.yahoo.com> <4E43D2F2.1090004@mrabarnett.plus.com> <1314884634.78252.YahooMailNeo@web121507.mail.ne1.yahoo.com> <877h5rjtdb.fsf@uwakimon.sk.tsukuba.ac.jp> <87bov2jl54.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: On Sep 4, 10:22?am, ron3200 wrote: > I think this is one of those areas where computers and people differ, > but it may also depend on the persons native language as to what works > better for them. Yes but what works better for "them" is not always a better way of doing things! People do foolish things all the time just from pure habit. A foolish consistency is a foolish consistency my friend. I mean, look at the folks who popped their cherry writing Basic code; talk about dysfunctional! From tjreedy at udel.edu Sun Sep 4 14:32:07 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 04 Sep 2011 14:32:07 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 4:13 AM, tinnews at isbd.co.uk wrote: > Ian Kelly wrote: >> Functional programming is about using functions in the *mathematical* >> sense. A mathematical function maps one value (or tuple of values) to >> another value. The mapped value never varies; if it did, it would be >> a different function. So functional programming eschews the use of >> functions where the results depend on any internal or external state >> beyond the values of the passed-in arguments, such as the variable >> state of the object the method is being called on. >> > I think there may be another issue here. If someone says "functional > programming" to me then I would generally assume that they *do* mean > "programming using functions". While your distinction of the two may > be strictly correct I don't think it's the generally accepted meaning. The distintion drawn by Ian *is* generally accepted in computer science. See https://secure.wikimedia.org/wikipedia/en/wiki/Functional_programming For instance, programming is C is imperative programming with functions but it generally is not 'functional programming' in the sense referred to by Ian and the Wikipedia article. Given that our docs are written by people who do understand the technical distinction, you are probably wrong to assume otherwise. However, as I said to William, it is possible that our docs could be improved so as to not depend on all readers having prior knowledge of the intended meaning of 'functional programming'. As the use of Python has expanded, so has the variety of backgrounds of Python programmers. -- Terry Jan Reedy From PointedEars at web.de Sun Sep 4 14:35:02 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Sun, 04 Sep 2011 20:35:02 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> <6545843.yvFAXZvWTv@PointedEars.de> <9c528rFi5aU1@mid.individual.net> <4761603.ypaU67uLZW@PointedEars.de> <9c6d4cFa54U1@mid.individual.net> <109595831.VCN276Cjj6@PointedEars.de> <9cgsvvFdhuU1@mid.individual.net> Message-ID: <1536106.qVoOGUtdWV@PointedEars.de> Fokke Nauta wrote: > "Thomas 'PointedEars' Lahn" wrote in message > news:109595831.VCN276Cjj6 at PointedEars.de... > > > > If you don't have anything better to contribute, please stop answering. > > Es gen?gt schon. I should have expected as much from an address munger. *plonk* -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From bkasterm at gmail.com Sun Sep 4 15:39:49 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Sun, 04 Sep 2011 13:39:49 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> Message-ID: <87obz0w0ze.fsf@gmail.com> rantingrick writes: > On Sep 3, 5:15?pm, Bart Kastermans wrote: > >> Any suggestions? > > Yeah, have you considered using the "linespace()" method of tk.Font > objects to calculate the height? Although i must say it "feels" as if > your doing something you should not need to do, however i cannot be > sure without knowing more about this GUI. Sounds a lot like trying to > put socks on a rooster. > > http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#fonts Thx. That function should allow for a bit of robustness. I get bits of information over RSS, these are of varying length. I want to show 10 at a time, and scroll through them. Now when I scroll the window grows and shrinks depending on their size, I want to right from the start make it high enough to contain even the biggest that will have to be shown. So the question is determining the height parameter for the labels ahead of time. My strategy has been to put all in labels and then try to get the information from the label of how high it needs to be made at a certain width. From nospam at domain.invalid Sun Sep 4 15:43:31 2011 From: nospam at domain.invalid (William Gill) Date: Sun, 04 Sep 2011 15:43:31 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 2:32 PM, Terry Reedy wrote: > On 9/4/2011 4:13 AM, tinnews at isbd.co.uk wrote: >> Ian Kelly wrote: > >>> Functional programming is about using functions in the *mathematical* >>> sense. A mathematical function maps one value (or tuple of values) to >>> another value. The mapped value never varies; if it did, it would be >>> a different function. So functional programming eschews the use of >>> functions where the results depend on any internal or external state >>> beyond the values of the passed-in arguments, such as the variable >>> state of the object the method is being called on. >>> >> I think there may be another issue here. If someone says "functional >> programming" to me then I would generally assume that they *do* mean >> "programming using functions". While your distinction of the two may >> be strictly correct I don't think it's the generally accepted meaning. > > The distintion drawn by Ian *is* generally accepted in computer science. > See > https://secure.wikimedia.org/wikipedia/en/wiki/Functional_programming > For instance, programming is C is imperative programming with functions > but it generally is not 'functional programming' in the sense referred > to by Ian and the Wikipedia article. Given that our docs are written by > people who do understand the technical distinction, you are probably > wrong to assume otherwise. > > However, as I said to William, it is possible that our docs could be > improved so as to not depend on all readers having prior knowledge of > the intended meaning of 'functional programming'. As the use of Python > has expanded, so has the variety of backgrounds of Python programmers. > Since I am the one who opened this can of worms, and since I believe I have relocated the document that I misinterpreted, I feel compelled to jump in here. The source of my error is "Functional Programming HOWTO (/python-3.1.3-docs-html/howto/functional.html)" Having arrived at this page indirectly (searching for and skimming other information regarding functions and methods) I was only half paying attention. As a result I made the same mistake Chris did. As a point of reference, I would not call myself a programmer, and any formal exposure was many, many years ago. I am familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional. At least not in this context. Having done a little more digging I now understand the difference. "Functional programming" is the proper terminology, and had I come across it from another direction, or with a more deliberate focus I probably wouldn't have made the initial mistake. If you read the material with even a nominal understanding of the functional paradigm (functional relationships in a mathematical sense, not functions in the procedural sense), it is clear. If you read it without consciously recognizing this difference, the material does nothing to alert you to the initial error. From georg at python.org Sun Sep 4 16:21:50 2011 From: georg at python.org (Georg Brandl) Date: Sun, 04 Sep 2011 22:21:50 +0200 Subject: [RELEASED] Python 3.2.2 Message-ID: <4E63DDDE.2040108@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the Python 3.2.2 maintenance release. Python 3.2.2 mainly fixes `a regression `_ in the ``urllib.request`` module that prevented opening many HTTP resources correctly with Python 3.2.1. Python 3.2 is a continuation of the efforts to improve and stabilize the Python 3.x line. Since the final release of Python 2.7, the 2.x line will only receive bugfixes, and new features are developed for 3.x only. Since PEP 3003, the Moratorium on Language Changes, is in effect, there are no changes in Python's syntax and built-in types in Python 3.2. Development efforts concentrated on the standard library and support for porting code to Python 3. Highlights are: * numerous improvements to the unittest module * PEP 3147, support for .pyc repository directories * PEP 3149, support for version tagged dynamic libraries * PEP 3148, a new futures library for concurrent programming * PEP 384, a stable ABI for extension modules * PEP 391, dictionary-based logging configuration * an overhauled GIL implementation that reduces contention * an extended email package that handles bytes messages * a much improved ssl module with support for SSL contexts and certificate hostname matching * a sysconfig module to access configuration information * additions to the shutil module, among them archive file support * many enhancements to configparser, among them mapping protocol support * improvements to pdb, the Python debugger * countless fixes regarding bytes/string issues; among them full support for a bytes environment (filenames, environment variables) * many consistency and behavior fixes for numeric operations For a more extensive list of changes in 3.2, see http://docs.python.org/3.2/whatsnew/3.2.html To download Python 3.2 visit: http://www.python.org/download/releases/3.2/ Please consider trying Python 3.2 with your code and reporting any bugs you may notice to: http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and 3.2's contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.18 (GNU/Linux) iEYEARECAAYFAk5j3d4ACgkQN9GcIYhpnLA2BACeLZ8nSdVOoxlJw4DnbM42neeA fwAAoKTHetXsVxrEfvCWSorUhoJ083kZ =5Wm1 -----END PGP SIGNATURE----- From rantingrick at gmail.com Sun Sep 4 17:10:59 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 14:10:59 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> Message-ID: <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> On Sep 4, 2:39?pm, Bart Kastermans wrote: > I get bits of information over RSS, these are of varying length. ?I > want to show 10 at a time, and scroll through them. ?Now when I > scroll the window grows and shrinks depending on their size, I want > to right from the start make it high enough to contain even the > biggest that will have to be shown. ?So the question is determining > the height parameter for the labels ahead of time. ?My strategy has > been to put all in labels and then try to get the information from > the label of how high it needs to be made at a certain width. I see. However i might opt instead for a text widget with columns of wrapped text. You could use the textwrap.py module to help (although you'll have to work around it's shortcomings for paragraphs and such). In any event it's difficult to offer good advice without seeing the code directly. From rantingrick at gmail.com Sun Sep 4 17:15:07 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 4 Sep 2011 14:15:07 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> Message-ID: On Sep 4, 2:39?pm, Bart Kastermans wrote: > Thx. ?That function should allow for a bit of robustness. Correction. The function is actually "tkFont.metrics(arg)" which takes "linespace" as an optional argument. From exarkun at twistedmatrix.com Sun Sep 4 17:26:01 2011 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sun, 04 Sep 2011 21:26:01 -0000 Subject: pyOpenSSL 0.13 release Message-ID: <20110904212601.1808.1179874796.divmod.xquotient.244@localhost.localdomain> Hello all, I'm happy to announce the release of pyOpenSSL 0.13. With this release, pyOpenSSL now supports OpenSSL 1.0. Additionally, pyOpenSSL now works with PyPy. Apart from those two major developments, the following interesting changes have been made since the last release: * (S)erver (N)ame (I)ndication is now supported. * There are now APIs with which the underlying OpenSSL version can be queried. * The peer's certificate chain for a connection can now be inspected. * New methods have been added to PKey and X509 objects exposing more OpenSSL functionality. Release files are available on PyPI. The latest development version and the issue tracker can be found on Launchpad. Jean-Paul From steve+comp.lang.python at pearwood.info Sun Sep 4 19:41:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 05 Sep 2011 09:41:42 +1000 Subject: Functions vs OOP References: Message-ID: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> William Gill wrote: > The source of my error is "Functional Programming HOWTO > (/python-3.1.3-docs-html/howto/functional.html)" For those who don't have access to William's local file system, I expect he's looking at this: http://docs.python.org/release/3.1.3/howto/functional.html or the most recent version: http://docs.python.org/dev/howto/functional.html [...] > If you read the material with even a nominal understanding of the > functional paradigm (functional relationships in a mathematical sense, > not functions in the procedural sense), it is clear. If you read it > without consciously recognizing this difference, the material does > nothing to alert you to the initial error. What about the entire "Introduction" section, which starts with this statement? "This section explains the basic concept of functional programming" If you would like to suggest improvements, please do so. -- Steven From nospam at domain.invalid Sun Sep 4 20:46:19 2011 From: nospam at domain.invalid (William Gill) Date: Sun, 04 Sep 2011 20:46:19 -0400 Subject: Functions vs OOP In-Reply-To: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> References: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/4/2011 7:41 PM, Steven D'Aprano wrote: > William Gill wrote: > >> The source of my error is "Functional Programming HOWTO >> (/python-3.1.3-docs-html/howto/functional.html)" > > For those who don't have access to William's local file system, I expect > he's looking at this: > > http://docs.python.org/release/3.1.3/howto/functional.html > > or the most recent version: > > http://docs.python.org/dev/howto/functional.html I didn't expect anyone to access my file system so I trimmed the path, but left enough for an industrious soul like yourself to figure it out. You did, so it seems I was correct, or do you think "functional.html" would have been sufficient? ;-) > > [...] >> If you read the material with even a nominal understanding of the >> functional paradigm (functional relationships in a mathematical sense, >> not functions in the procedural sense), it is clear. If you read it >> without consciously recognizing this difference, the material does >> nothing to alert you to the initial error. > > What about the entire "Introduction" section, which starts with this > statement? > > "This section explains the basic concept of functional programming" Which clears up the misunderstanding, how? Unless the target audience is people who already understands "the basic concept of functional programming." That seems like a circular reference. The article is introducing a concept. To assume any familiarity with that concept as a basis, is not an introduction. As previously stated; I was already familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional programming. Nothing I read (I'll be honest; scanned) did anything to contradict my incorrect point of reference. > If you would like to suggest improvements, please do so. How about a caveat stating something like "NOTE: functional as in mathematical functions, not to be confused with functions/procedures." From rosuav at gmail.com Sun Sep 4 20:59:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 5 Sep 2011 10:59:59 +1000 Subject: Functions vs OOP In-Reply-To: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> References: <4e640cb7$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Sep 5, 2011 at 9:41 AM, Steven D'Aprano wrote: > http://docs.python.org/dev/howto/functional.html > > What about the entire "Introduction" section, which starts with this > statement? > > "This section explains the basic concept of functional programming" > > If you would like to suggest improvements, please do so. Well, it does invite you to skip that whole section :) Since you asked, though, the copyeditor in me does want to suggest one small tweak: Second paragraph after the bullet list ends "Avoiding side effects means not using data structures that get updated as a program runs; every function?s output must only depend on its input." - I'd word it as "must depend only on". Pretty immaterial, but the formal style prefers correctness. Somewhat more significant: Under "Modularity", may be of value to add a paragraph about parallelism. With functional code, it's easy for an interpreter to ascertain which functions depend on each other (because one's return value is another's input). Independent functions can be run in parallel without affecting the result; the interpreter can therefore divide a complex task across multiple CPUs without any work from the programmer. Like I said, it's just "since you asked". :) The above paragraph is hereby given out as public domain, use it (edit it, whatever) under whatever license the Python docs require. ChrisA From simoncropper at fossworkflowguides.com Mon Sep 5 01:18:30 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 15:18:30 +1000 Subject: Hello, and request for help with 'dynamic grids' Message-ID: <4E645BA6.4070500@fossworkflowguides.com> Hi, I am a applications developer - originally from Windows using primarily Visual Foxpro, although I am familiar with a variety of other xbase derivatives. I now use Linux / Ubuntu, and have been actively teaching myself Python with the view to migrate most of my applications to sqlite-based database. I am looking for the ability to create dynamic grids in a window but can't for the life of me find how to do this. Here is the functionality that I desire... 1. Have a dialog appear that allows me to select a database, e.g. sqlite3 database. 2. Select table in the database and have all the records appear in a grid. Fields represented as column, width and order adjustable, rows representing records. Each cell can be edited directly. 3. I would like to create filters on this grid based on attributes in the table. So if the table is a list of names, filter and show only those people with a particular first name. For people familiar with xbase languages it equivalent to browsing a table and applying a filter. 4. Once the record is identified I would like to select the record or hit enter to have the data sent to the keyboard buffer or put into the clipboard. I have found most of these elements available. I can create dialogs, I can connect to a database, I can extract data from the tables using SQL but I can't find how to easily get these lists into a grid -- it appears to me you need to allocate list record 1 to grid row 1, list record 2 to grid row 2, etc and manage how many rows are displayed and 'page' through the table. Am I missing something? I presume that you could just supply a list or array selected using SQL from a table and just pass this data to a grid and have it manage all the basics like if the window is resized the number of rows and columns are adjusted accordingly, buffering records, etc. My investigations have generally found that windows/forms/data entry screen can be created for a specific table or view, but these are hard-wired during development. Is there anyway of rapidly defining the grid during runtime so any table can be viewed? -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From krille012 at gmail.com Mon Sep 5 02:47:42 2011 From: krille012 at gmail.com (=?ISO-8859-1?Q?Kristofer_Tengstr=F6m?=) Date: Sun, 4 Sep 2011 23:47:42 -0700 (PDT) Subject: Need help with simple OOP Python question Message-ID: Hi, I'm having trouble creating objects that in turn can have custom objects as variables. The code looks like this: --------------------------------------------- class A: sub = dict() def sub_add(self, cls): obj = cls() self.sub[obj.id] = obj class B(A): id = 'inst' base = A() base.sub_add(B) base.sub['inst'].sub_add(B) print # prints a blank line print base.sub['inst'] print base.sub['inst'].sub['inst'] ---------------------------------------------- Now, what I get from this is the following: <__main__.B instance at 0x01FC20A8> <__main__.B instance at 0x01FC20A8> Why is this? What I want is for them to be two separate objects, but it seems like they are the same one. I've tried very hard to get this to work, but as I've been unsuccessful I would really appreciate some comments on this. I'm sure it's something really easy that I just haven't thought of. Python version is 2.6.5 (I'm using Panda3D to create a 2?D game). From me+list/python at ixokai.io Mon Sep 5 03:07:45 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Mon, 05 Sep 2011 00:07:45 -0700 Subject: Need help with simple OOP Python question In-Reply-To: References: Message-ID: <4E647541.7080304@ixokai.io> On 9/4/11 11:47 PM, Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() You are sharing this single "sub" dictionary with all instances of your A class. If you want to define instance-specific attributes, define them in the __init__ method, like so: class A: def __init__(self): self.sub = dict() def sub_add(self, cls): obj = cls() self.sub[obj.id] = obj -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Mon Sep 5 03:10:14 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 09:10:14 +0200 Subject: Need help with simple OOP Python question References: Message-ID: Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() Putting it into the class like this means sub is shared by all instances. > def sub_add(self, cls): > obj = cls() > self.sub[obj.id] = obj > > class B(A): > id = 'inst' > > base = A() > base.sub_add(B) > base.sub['inst'].sub_add(B) > > print # prints a blank line > print base.sub['inst'] > print base.sub['inst'].sub['inst'] > > ---------------------------------------------- > > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? What I want is for them to be two separate objects, but > it seems like they are the same one. I've tried very hard to get this > to work, but as I've been unsuccessful I would really appreciate some > comments on this. I'm sure it's something really easy that I just > haven't thought of. Your class A needs an initialiser: class A: def __init__(self): self.sub = {} # one dict per instance # ... From steve+comp.lang.python at pearwood.info Mon Sep 5 03:19:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 05 Sep 2011 17:19:12 +1000 Subject: Hello, and request for help with 'dynamic grids' References: Message-ID: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote: > I am looking for the ability to create dynamic grids in a window but > can't for the life of me find how to do this. What GUI toolkit are you using? -- Steven From ben+python at benfinney.id.au Mon Sep 5 03:26:51 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 05 Sep 2011 17:26:51 +1000 Subject: Need help with simple OOP Python question References: Message-ID: <87sjobo3es.fsf@benfinney.id.au> Kristofer Tengstr?m writes: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. That terminology is rather confused. I think what you want is to have instances with their own attributes. > class A: > sub = dict() This binds a single object (a new empty dict) to the class attribute ?sub?. Every instance of class ?A? will share the same attribute, and hence that same dict. > def sub_add(self, cls): This defines a function which will be bound to the class attribute ?sub_add?. It will, when later called as a method, receive the instance as the first parameter, bound to the local name ?self?. > obj = cls() > self.sub[obj.id] = obj Here, ?self? will be an instance of the ?A? class. Each instance has no ?sub? attribute, so Python will find the class attribute ?A.sub?, shared by all ?A? instances. You're then modifying that class attribute ?A.sub?. [?] > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? I hope the above explains it. > What I want is for them to be two separate objects, but it seems like > they are the same one. Yes. Anything you talk about in the class definition scope cannot know about any instance of that class, since the instances don't exist yet. Instead, instance attributes need to be bound to a particular instance, which means you need to have a reference to the instance; that's what ?self? is for. The class initialiser is a method named ?__init__?, and is called on each newly-created instance before that instance is returned from the constructor. I advise you to work through the Python tutorial, beginning to end, which will give you a good grounding in these and other fundamental Python topics . Work through each example, understand it by experimenting, and then proceed to the next, until you've done the lot. -- \ ?If history and science have taught us anything, it is that | `\ passion and desire are not the same as truth.? ?E. O. Wilson, | _o__) _Consilience_, 1998 | Ben Finney From bex.lewis at gmail.com Mon Sep 5 05:01:05 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Mon, 5 Sep 2011 02:01:05 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> Message-ID: > > > Possibly. > > I tried this: > > server.py -n -c config.ini > > Once again, the server is up and running and when I am logging in with my > > browser (10.0.0.140:8081) I can see information showing up at the command > > prompt, showing somebody is logging is, but the same error: > > "fshandler:get_data: \Webdav not found". During starting up the server > > mentioned: "pywebdav:Serving data from \Webdav". > > > In the config file it says: > > "# main directory > > directory = \Webdav" > > > Perhaps my Python configuration is at fault. > > > Fokke > > Is the path supposed to be absolute? In which case you'd need to have: > directory=C:\path\to\Webdav > > instead of just > directory=\Webdav > > I tried: > directory=D:\Webdav > directory=D:/Webdav > > To no avail. > It didn.t make any difference. > > I surely believe my WebDAV installation is at fault. > > Fokke Interestingly, looking at the code that returns the "fshandler:get_data: \Webdav not found" message, it looks like it tests that the path given exists and then tries an os.path.isfile, then an os.path.isdir. If both fail you get the message that you see. This might be a bit of a shot in the dark but could you try the path with and without a trailing '/' or '\'? I don't currently have a windows box available to test on and figure out why it would be detected as existing but not test true for either a file or directory. Becky Lewis From hnsri49 at gmail.com Mon Sep 5 05:34:22 2011 From: hnsri49 at gmail.com (srinivas hn) Date: Mon, 5 Sep 2011 15:04:22 +0530 Subject: Need help with simple OOP Python question In-Reply-To: References: Message-ID: Hi, You are getting same object because you are overriding the dictionary update. Its printing the proper value with the last updated instance of B. If you want to see the two different instances of class B give print self.sub inside the sub_add method in class A. CHEERS CNA 9986229891 On Mon, Sep 5, 2011 at 12:17 PM, Kristofer Tengstr?m wrote: > Hi, I'm having trouble creating objects that in turn can have custom > objects as variables. The code looks like this: > > --------------------------------------------- > > class A: > sub = dict() > def sub_add(self, cls): > obj = cls() > self.sub[obj.id] = obj > > class B(A): > id = 'inst' > > base = A() > base.sub_add(B) > base.sub['inst'].sub_add(B) > > print # prints a blank line > print base.sub['inst'] > print base.sub['inst'].sub['inst'] > > ---------------------------------------------- > > Now, what I get from this is the following: > <__main__.B instance at 0x01FC20A8> > <__main__.B instance at 0x01FC20A8> > Why is this? What I want is for them to be two separate objects, but > it seems like they are the same one. I've tried very hard to get this > to work, but as I've been unsuccessful I would really appreciate some > comments on this. I'm sure it's something really easy that I just > haven't thought of. > > Python version is 2.6.5 (I'm using Panda3D to create a 2?D game). > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From simoncropper at fossworkflowguides.com Mon Sep 5 06:07:05 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 20:07:05 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e6477f0$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E649F49.5050103@fossworkflowguides.com> On 05/09/11 17:19, Steven D'Aprano wrote: > On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote: > >> I am looking for the ability to create dynamic grids in a window but >> can't for the life of me find how to do this. > > What GUI toolkit are you using? > > I have looked at wxGlade, Boa Constructor, wxFormBuilder, tkinder, I have also looked through the Python website many times looking for commands that would allow me to create a GUI from scratch. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From t at jollybox.de Mon Sep 5 06:40:07 2011 From: t at jollybox.de (Thomas Jollans) Date: Mon, 05 Sep 2011 12:40:07 +0200 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E645BA6.4070500@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> Message-ID: <4E64A707.9090006@jollybox.de> On 05/09/11 07:18, Simon Cropper wrote: > I am looking for the ability to create dynamic grids in a window but > can't for the life of me find how to do this. It depends on which windowing toolkit you're planning to use. If you use PyGTK, you'd want a TreeView widget to display the list. Fill a ListStore instance with your data and give that to the TreeView. You can implement filtering and sorting on top of that using TreeModelFilter and TreeModelSort. LibreOffice and OpenOffice have database management components (I haven't used them, I assume they're somewhat similar to MS Access) - and they can be scripted using Python. Depending on what you're doing, and what you're planning to do in the future (re learning investment), that might be worth looking into. Thomas From simoncropper at fossworkflowguides.com Mon Sep 5 06:52:40 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 20:52:40 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E64A707.9090006@jollybox.de> References: <4E645BA6.4070500@fossworkflowguides.com> <4E64A707.9090006@jollybox.de> Message-ID: <4E64A9F8.3000501@fossworkflowguides.com> On 05/09/11 20:40, Thomas Jollans wrote: > It depends on which windowing toolkit you're planning to use. If you use > PyGTK, you'd want a TreeView widget to display the list. Fill a > ListStore instance with your data and give that to the TreeView. You can > implement filtering and sorting on top of that using TreeModelFilter and > TreeModelSort. I have look at most. I have no preference. Are you able to point me to some resource material explaining how this can be done - e.g. a tutorial or manual? > LibreOffice and OpenOffice have database management components (I > haven't used them, I assume they're somewhat similar to MS Access) - and > they can be scripted using Python. Depending on what you're doing, and > what you're planning to do in the future (re learning investment), that > might be worth looking into. 'Base' is of no value in this regard. It is not really designed for this and there is a raging debate at the moment whether it will be maintained in the future. It also fails in that it requires predefined connections and forms to be established. It would not be possible to dynamically link to a table in a database (I have established ODBC links to a SQLite database, but the driver is an un-maintained draft). I also believe that the 'base' component in libreoffice/openoffice is a java implementation not python. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From krille012 at gmail.com Mon Sep 5 09:15:40 2011 From: krille012 at gmail.com (=?ISO-8859-1?Q?Kristofer_Tengstr=F6m?=) Date: Mon, 5 Sep 2011 06:15:40 -0700 (PDT) Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> Message-ID: <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Thanks everyone, moving the declaration to the class's __init__ method did the trick. Now there's just one little problem left. I'm trying to create a list that holds the parents for each instance in the hierarchy. This is what my code looks like now: ----------------------------------------- class A: def __init__(self, parents=None): self.sub = dict() if parents: self.parents = parents else: self.parents = [] def sub_add(self, cls): hierarchy = self.parents hierarchy.append(self) obj = cls(hierarchy) self.sub[obj.id] = obj class B(A): id = 'inst' base = A() base.sub_add(B) base.sub['inst'].sub_add(B) print print vars(base) print print vars(base.sub['inst']) print print vars(base.sub['inst'].sub['inst']) --------------------------------------------- The output from this program is the following: {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794B8>}} {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794E0>}} {'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance at 0x021794B8>], 'sub': {}} As you can see, the problem looks similar to the one before: All the instances have an identical parent list. However, I don't understand why as self.parents is declared in the __init__ method. Any ideas? What I want is for the first instance to have an empty list, the second to have one element in the list and the third to have two parent elements. From python at bdurham.com Mon Sep 5 09:23:51 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 05 Sep 2011 09:23:51 -0400 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E645BA6.4070500@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> Message-ID: <1315229031.32028.140258137504765@webmail.messagingengine.com> Hi Simon, > I am a applications developer - originally from Windows using primarily Visual Foxpro, although I am familiar with a variety of other xbase derivatives. Check out dabodev.com. Dabo is a Python framework created by former VFP developers. Highly recommended. Malcolm From simoncropper at fossworkflowguides.com Mon Sep 5 09:33:31 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Mon, 05 Sep 2011 23:33:31 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <1315229031.32028.140258137504765@webmail.messagingengine.com> References: <4E645BA6.4070500@fossworkflowguides.com> <1315229031.32028.140258137504765@webmail.messagingengine.com> Message-ID: <4E64CFAB.70804@fossworkflowguides.com> On 05/09/11 23:23, python at bdurham.com wrote: > Check out dabodev.com. Dabo is a Python framework created by former VFP > developers. > Dabo is a great product. Spoke extensively with Ed Leafe and Paul McNett. Unfortunately the framework is not 'dynamic'. If you have an fixed database and tables it can quite quickly create a basic data entry setup and menu. Looks great when it runs. The problem is creating the window and grid on the fly. I want a program that can be used to open any database and 'data mine' and extract table content. Dabo allows RAD for an established relational databases not unknown ones. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From piet at vanoostrum.org Mon Sep 5 10:15:01 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Mon, 05 Sep 2011 16:15:01 +0200 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Torek writes: [snip] > Instead, we have a syntax where you, the programmer, write out the > name of the local variable that binds to the first parameter. This > means the first parameter is visible. Except, it is only visible > at the function definition -- when you have the instance and call > the instance or class method: > > black_knight = K() > black_knight.meth1('a', 1) > black_knight.meth2(2) > > the first parameters (black_knight, and black_knight.__class__, > respectively) are magic, and invisible. > > Thus, Python is using the "explicit is better than implicit" rule > in the definition, but not at the call site. I have no problem with > this. Sometimes I think implicit is better than explicit. In this > case, there is no need to distinguish, at the calls to meth1() and > meth2(), as to whether they are "class" or "instance" methods. At > the *calls* they would just be distractions. It *is* explicit also at the call site. It only is written at the left of the dot rather than at the right of the parenthesis. And that is necessary to locate which definition of the method applies. It would be silly to repeat this information after the parenthesis. Not only silly, it would be stupid as it would be a source of errors, and an example of DRY. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From piet at vanoostrum.org Mon Sep 5 10:23:24 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Mon, 05 Sep 2011 16:23:24 +0200 Subject: Closures and Partial Function Application References: <9cd48486-acd9-4888-9677-0e54fd1eedfd@k15g2000yqd.googlegroups.com> Message-ID: Travis Parks writes: > I also like partial function application. What is the easiest way of > achieving this in Python? Would it look something like this: > > def foo(x, y): > return x + y > > xFoo = lambda y: foo(10, y) from functools import partial xfoo = partial(foo, 10) -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From wuwei23 at gmail.com Mon Sep 5 10:40:15 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 5 Sep 2011 07:40:15 -0700 (PDT) Subject: Hello, and request for help with 'dynamic grids' References: Message-ID: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> On Sep 5, 3:18?pm, Simon Cropper wrote: > My investigations have generally found that windows/forms/data entry > screen can be created for a specific table or view, but these are > hard-wired during development. Is there anyway of rapidly defining the > grid during runtime so any table can be viewed? The commercial product Resolver One provides a grid/spreadsheet style interface with Python scripting capabilities. I'm not sure of its current licensing status but I believe it used to be free if used on open source projects. http://www.resolversystems.com/products/resolver-one/ Each spreadsheet itself is Python code; I think it should be quite do- able to take something with introspective SQL capabilities like SQLAlchemy and have it title columns and fill them with the correct fields accordingly. Hope this helps. From __peter__ at web.de Mon Sep 5 10:43:02 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 16:43:02 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: Kristofer Tengstr?m wrote: > Thanks everyone, moving the declaration to the class's __init__ method > did the trick. Now there's just one little problem left. I'm trying to > create a list that holds the parents for each instance in the > hierarchy. This is what my code looks like now: > > ----------------------------------------- > > class A: > def __init__(self, parents=None): > self.sub = dict() > if parents: You should explicitly test for None here; otherwise in a call like ancestors = [] a = A(anchestors) the list passed as an argument will not be used, which makes fore confusing behaviour. > self.parents = parents > else: > self.parents = [] > def sub_add(self, cls): > hierarchy = self.parents > hierarchy.append(self) Here you are adding self to the parents (that should be called ancestors) and pass it on to cls(...). Then -- because it's non-empty -- it will be used by the child, too, and you end up with a single parents list. > obj = cls(hierarchy) > self.sub[obj.id] = obj While the minimal fix is to pass a copy def sub_add(self, cls): obj = cls(self.parents + [self]) self.sub[obj.id] = obj I suggest that you modify your node class to keep track only of the direct parent instead of all ancestors. That makes the implementation more robust when you move a node to another parent. From fnautaNO at SPAMsolfon.nl Mon Sep 5 10:51:00 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Mon, 5 Sep 2011 16:51:00 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> Message-ID: <9ck5upFlpnU1@mid.individual.net> "becky_lewis" wrote in message news:a7cd34d7-ed2b-4449-8edc-a6a45b59ecde at hb5g2000vbb.googlegroups.com... > > >> > Possibly. >> > I tried this: >> > server.py -n -c config.ini >> > Once again, the server is up and running and when I am logging in with >> > my >> > browser (10.0.0.140:8081) I can see information showing up at the >> > command >> > prompt, showing somebody is logging is, but the same error: >> > "fshandler:get_data: \Webdav not found". During starting up the server >> > mentioned: "pywebdav:Serving data from \Webdav". >> >> > In the config file it says: >> > "# main directory >> > directory = \Webdav" >> >> > Perhaps my Python configuration is at fault. >> >> > Fokke >> >> Is the path supposed to be absolute? In which case you'd need to have: >> directory=C:\path\to\Webdav >> >> instead of just >> directory=\Webdav >> >> I tried: >> directory=D:\Webdav >> directory=D:/Webdav >> >> To no avail. >> It didn.t make any difference. >> >> I surely believe my WebDAV installation is at fault. >> >> Fokke > > Interestingly, looking at the code that returns the > "fshandler:get_data: \Webdav not found" message, it looks like it > tests that the path given exists and then tries an os.path.isfile, > then an os.path.isdir. If both fail you get the message that you see. > This might be a bit of a shot in the dark but could you try the path > with and without a trailing '/' or '\'? I don't currently have a > windows box available to test on and figure out why it would be > detected as existing but not test true for either a file or directory. > Hi Becky, I tried it straight away: directory=D:\Webdav\ directory=D:/Webdav/ Didn't work, in both cases the same error "fshandler:get_data: \Webdav not found". I have the opinion that my WebDAV installation is at fault. The database is not created either. To have set up Python, I used python-2.7.2.msi. To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both Unix/Linux. To install the, I used " >> You dont install from "Python GUI", use normal cmd, navigate to the >> folder >> you downloaded PyXML and PyWebDAV and run "python setup.py install" >> (python.exe has to be in your PATH). Then you have to find the >> startup-script "davserver". Find your python installation directory and >> look into/Tools/Scripts, in my computer this is >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have >> to >> look for "davserver" there..." Shall I re?nstall the whole lot? Would it make a difference if in that case I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi? Fokke From joncle at googlemail.com Mon Sep 5 10:59:31 2011 From: joncle at googlemail.com (Jon Clements) Date: Mon, 5 Sep 2011 07:59:31 -0700 (PDT) Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: <9bda87ee-ac0a-4b8f-b9a9-aa0cefd1bd04@k9g2000vbd.googlegroups.com> On Sep 5, 3:43?pm, Peter Otten <__pete... at web.de> wrote: > Kristofer Tengstr?m wrote: > > Thanks everyone, moving the declaration to the class's __init__ method > > did the trick. Now there's just one little problem left. I'm trying to > > create a list that holds the parents for each instance in the > > hierarchy. This is what my code looks like now: > > > ----------------------------------------- > > > class A: > > ? ? def __init__(self, parents=None): > > ? ? ? ? self.sub = dict() > > ? ? ? ? if parents: > > You should explicitly test for None here; otherwise in a call like > > ancestors = [] > a = A(anchestors) > > the list passed as an argument will not be used, which makes fore confusing > behaviour. > > > ? ? ? ? ? ? self.parents = parents > > ? ? ? ? else: > > ? ? ? ? ? ? self.parents = [] > > ? ? def sub_add(self, cls): > > ? ? ? ? hierarchy = self.parents > > ? ? ? ? hierarchy.append(self) > > Here you are adding self to the parents (that should be called ancestors) > and pass it on to cls(...). Then -- because it's non-empty -- it will be > used by the child, too, and you end up with a single parents list. > > > ? ? ? ? obj = cls(hierarchy) > > ? ? ? ? self.sub[obj.id] = obj > > While the minimal fix is to pass a copy > > def sub_add(self, cls): > ? ? obj = cls(self.parents + [self]) > ? ? self.sub[obj.id] = obj > > I suggest that you modify your node class to keep track only of the direct > parent instead of all ancestors. That makes the implementation more robust > when you move a node to another parent. I may not be understanding the OP correctly, but going by what you've put here, I might be tempted to take this kind of stuff out of the class's and using a graph library (such as networkx) - that way if traversal is necessary, it might be a lot easier. But once again, I must say I'm not 100% sure what the OP wants to achieve... Jon. From mdekauwe at gmail.com Mon Sep 5 11:06:10 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 08:06:10 -0700 (PDT) Subject: Best way to print a module? Message-ID: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Hi, If I wanted to print an entire module, skipping the attributes starting with "__" is there an *optimal* way? Currently I am doing something like this. Note I am just using sys here to make the point import sys data = [] for attr in sys.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(sys, attr) data.append((attr, attr_val)) data.sort() for i in data: print "%s = %s" % (i[0], i[1]) Clearly this would be quicker if I didn't store it and sort the output, i.e. for attr in sys.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(sys, attr) print "%s = %s" % (attr, attr_val) Anyway if there is a better way it would be useful to hear it... Many thanks, Martin From wolftracks at invalid.com Mon Sep 5 11:15:24 2011 From: wolftracks at invalid.com (W. eWatson) Date: Mon, 05 Sep 2011 08:15:24 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? Message-ID: See Subject. From rosuav at gmail.com Mon Sep 5 11:24:19 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 6 Sep 2011 01:24:19 +1000 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: > See Subject. > -- > http://mail.python.org/mailman/listinfo/python-list > To what extent "familiar"? I have it installed on several computers, but only because it comes with Open Wat C/C++. With something off-topic like this, it might be better to have a real email address, so the responses can be off-list. ChrisA From __peter__ at web.de Mon Sep 5 11:28:43 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 17:28:43 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> <9bda87ee-ac0a-4b8f-b9a9-aa0cefd1bd04@k9g2000vbd.googlegroups.com> Message-ID: Jon Clements wrote: > I > must say I'm not 100% sure what the OP wants to achieve... Learn Python? ;) From wolftracks at invalid.com Mon Sep 5 12:15:20 2011 From: wolftracks at invalid.com (W. eWatson) Date: Mon, 05 Sep 2011 09:15:20 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 9/5/2011 8:24 AM, Chris Angelico wrote: > On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: >> See Subject. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > To what extent "familiar"? I have it installed on several computers, > but only because it comes with Open Wat C/C++. > > With something off-topic like this, it might be better to have a real > email address, so the responses can be off-list. > > ChrisA sierra_mtnview @ sbcglobal.net Here's the story. As far as I can tell F77 1.8 is not available. I've Googled quite a bit for it. My source for 1.9 is . It gives me: open-watcom-f77-win32-1.9.exe. When I install, there are only choices: Custom, which presumably will ask a lot of questions, and some one shot do-it without any intervention. I took the latter. ..., XP, and no Win7? I use Win7. Trouble?? Something is amiss with my install. I downloaded 1.9. I did not use any customization. I can bring up the IDE easily. Using it is a different matter. The only Getting Started in F77 manual I can find is shown as v1.8. If 1.9 is needed, I can't find it. If I use the 1.8 manual, then the contents don't match up with what I find in the F77 IDE. For example, the manual talks about a Kitchen project on page 15. Not found anywhere in the install folder. From dannagle at verizon.net Mon Sep 5 12:22:51 2011 From: dannagle at verizon.net (Dan Nagle) Date: Mon, 5 Sep 2011 12:22:51 -0400 Subject: [OT] Anyone here familiar with installing Open Watcom F77? References: Message-ID: Hello, On 2011-09-05 16:15:20 +0000, W. eWatson said: > On 9/5/2011 8:24 AM, Chris Angelico wrote: >> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson wrote: >>> See Subject. >>> To what extent "familiar"? I have it installed on several computers, >> but only because it comes with Open Wat C/C++. >> >> With something off-topic like this, >> sierra_mtnview @ sbcglobal.net > Here's the story. > > As far as I can tell F77 1.8 is not available. I've Googled quite a > bit for it. My source for 1.9 is > . It gives me: > open-watcom-f77-win32-1.9.exe. On Usenet, comp.lang.fortran might be the best source of help for this. There's a good chance one of the regulars there can answer you within one or two posts. (I'll not cross-post, you can choose for yourself.) HTH -- Cheers! Dan Nagle From k.sahithi2862 at gmail.com Mon Sep 5 12:23:00 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Mon, 5 Sep 2011 09:23:00 -0700 (PDT) Subject: FOR FAST UPDATES IN TELUGU FILM INDUSTRY Message-ID: <9da5ae2b-4615-4bb6-bcd6-8b6ef68962bf@p37g2000prp.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From rantingrick at gmail.com Mon Sep 5 12:30:19 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 5 Sep 2011 09:30:19 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <0460d27a-ce73-40f5-a31a-6772eacb7784@l7g2000vbz.googlegroups.com> On Sep 5, 10:06?am, Martin De Kauwe wrote: > Hi, > > If I wanted to print an entire module, skipping the attributes > starting with "__" is there an *optimal* way? Currently I am doing > something like this. Note I am just using sys here to make the point > > import sys > > data = [] > for attr in sys.__dict__.keys(): > ? ? if not attr.startswith('__') and not attr.endswith('__'): > ? ? ? ? attr_val = getattr(sys, attr) > ? ? ? ? data.append((attr, attr_val)) > data.sort() > for i in data: > ? ? print "%s = %s" % (i[0], i[1]) > > Clearly this would be quicker if I didn't store it and sort the > output, i.e. > > for attr in sys.__dict__.keys(): > ? ? if not attr.startswith('__') and not attr.endswith('__'): > ? ? ? ? attr_val = getattr(sys, attr) > ? ? ? ? print "%s = %s" % (attr, attr_val) > > Anyway if there is a better way it would be useful to hear it... > > Many thanks, > > Martin Martin, have you considered that your custom function is just re- inventing the built-in dir() function? I would suggest using a list comprehension against the dir() function with a predicate to remove anything that startswith '_'. Here's some Ruby code to solve the problem. I'll let you figure out the Python equivalent. rb> ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'} ["whatsup"] From cjw at ncf.ca Mon Sep 5 12:36:59 2011 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 05 Sep 2011 12:36:59 -0400 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 05-Sep-11 12:22 PM, Dan Nagle wrote: > Hello, > > On 2011-09-05 16:15:20 +0000, W. eWatson said: > >> On 9/5/2011 8:24 AM, Chris Angelico wrote: >>> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson >>> wrote: >>>> See Subject. > > > >>>> To what extent "familiar"? I have it installed on several computers, >>> but only because it comes with Open Wat C/C++. >>> >>> With something off-topic like this, > > > >>> sierra_mtnview @ sbcglobal.net >> Here's the story. >> >> As far as I can tell F77 1.8 is not available. I've Googled quite a >> bit for it. My source for 1.9 is >> . It gives me: >> open-watcom-f77-win32-1.9.exe. > > On Usenet, comp.lang.fortran might be the best source of help for this. > There's a good chance one of the regulars there can answer you > within one or two posts. (I'll not cross-post, you can choose for > yourself.) > > HTH > You might get in touch with someone at Waterloo University, which is located in Kitchener/Waterloo. This could have come from the 60's or 70's. Good luck. Colin W. From tjreedy at udel.edu Mon Sep 5 13:38:08 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 13:38:08 -0400 Subject: Need help with simple OOP Python question In-Reply-To: <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: On 9/5/2011 9:15 AM, Kristofer Tengstr?m wrote: > Thanks everyone, moving the declaration to the class's __init__ method > did the trick. Now there's just one little problem left. I'm trying to > create a list that holds the parents for each instance in the > hierarchy. This is what my code looks like now: > > ----------------------------------------- > > class A: > def __init__(self, parents=None): > self.sub = dict() > if parents: > self.parents = parents > else: > self.parents = [] > def sub_add(self, cls): > hierarchy = self.parents > hierarchy.append(self) > obj = cls(hierarchy) > self.sub[obj.id] = obj Indexing objects by their internal id is usually useless. Considier whether you should be using sets rather than dicts. -- Terry Jan Reedy From noreply at domain.invalid Mon Sep 5 13:45:25 2011 From: noreply at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 13:45:25 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/4/2011 9:13 AM, rusi wrote: > On Sep 3, 9:15 pm, William Gill wrote: >> During some recent research, and re-familiarization with Python, I came >> across documentation that suggests that programming using functions, and >> programming using objects were somehow opposing techniques. > > Staying with (for the moment) the suggestion that OO-P and F-P are > complementary, I believe it is worthwhile to distinguish syntactic OO- > P vs F-P from semantic OO-P vs F-P. > > Syntactically: f(x) is functional x.f() is object oriented. > Semantically if f's return value depends only on x ie does not depend > on state it is functional (in the math sense) -- the jargon is that f > is referentially transparent. Not to split hairs, but syntactically f(x) is a function in many programming paradigms. As I understand it functional programming places specific requirements on functions, i.e.referential transparency. So f(x) may or may not be "functional". x.f() is also a function, but it is a member of the object x, is referred to as a 'method' of x, and uses the syntactical "dot" notation object"dot"function for identification. > Referential opaqueness is usually such a source of problems that it > turns out good to contain the problem somewhat -- hence the wish for > encapsulation. > > One can find in the python library itself all 4 combinations: > syntactically and semantically OO : sort > syntactically and semantically FP: sorted > syntactically OO semantically FP: join From nospam at domain.invalid Mon Sep 5 14:58:29 2011 From: nospam at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 14:58:29 -0400 Subject: Functions vs OOP In-Reply-To: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e625508$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/3/2011 12:25 PM, Steven D'Aprano wrote: > William Gill wrote: > >> Are they suggesting that any function that takes an object as an >> argument should always be a method of that object? > > Yes. I can think of times when a special application, such as a converter, would take an object as an argument, but the somewhat unique nature of the application wouldn't justify changing the class to make the behavior into a method. I could extend the underlying class to include the new behavior (method), but that would mean existing instances of the base class would need conversion to the new class, requiring yet another method. Seems to me, that would be POOP (Puristic Object Oriented Programming) ;-) From jeanmichel at sequans.com Mon Sep 5 15:04:37 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 05 Sep 2011 21:04:37 +0200 Subject: Functions vs OOP In-Reply-To: References: Message-ID: <4E651D45.4020602@sequans.com> William Gill wrote: > > Not to split hairs, but syntactically f(x) is a function in many > programming paradigms. > > As I understand it functional programming places specific requirements > on functions, i.e.referential transparency. So f(x) may or may not be > "functional". > > x.f() is also a function, but it is a member of the object x, is > referred to as a 'method' of x, and uses the syntactical "dot" > notation object"dot"function for identification. > Functional programming is not about writing a programm with functions (google it for more info). This may cause some confusion. Your original post was about functions vs methods, which are identical except some syntax detail. FYI, in python x.f() is equivalent to f(x). In an OOP world one will prefer the x.f() form. JM From timr at probo.com Mon Sep 5 16:07:15 2011 From: timr at probo.com (Tim Roberts) Date: Mon, 05 Sep 2011 13:07:15 -0700 Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: Martin De Kauwe wrote: > >If I wanted to print an entire module, skipping the attributes >starting with "__" is there an *optimal* way? Your question is somewhat ambiguous. When I read "print an entire module", I assumed you were asking for a way to print the source code, perhaps with syntax coloring. Surely there is no reason to have an "optimal" method of doing this -- this is never going to be in an inner loop. If you have a method that works, there is little justification to optimize... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jredgrave at capisco.com Mon Sep 5 16:38:18 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Mon, 5 Sep 2011 13:38:18 -0700 (PDT) Subject: One line command line filter Message-ID: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> It seems unreasonably hard to write simple one-line unix command line filters in python: eg: ls | python -c " print x.upper()" to get at sys.stdin or similar needs an import, which makes a subsequent for-loop illegal. python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError Am I missing something obvious? The best I've come up with is to use sitecustomize.py to add to __builtin__ def stdin(): import sys for x in sys.stdin(): if not x: return yield x.strip() import __builtin__ __builtin__.stdin = stdin This allows ls | python -c "for x in stdin(): print x.upper()" Is there a better solution - if not is this worth a PEP? From t at jollybox.de Mon Sep 5 16:47:23 2011 From: t at jollybox.de (Thomas Jollans) Date: Mon, 05 Sep 2011 22:47:23 +0200 Subject: One line command line filter In-Reply-To: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4E65355B.8040503@jollybox.de> On 05/09/11 22:38, Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError > > Am I missing something obvious? ls | python -c "for line in __import__('sys').stdin: print (line.upper())" From jredgrave at capisco.com Mon Sep 5 17:32:08 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Mon, 5 Sep 2011 14:32:08 -0700 (PDT) Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> > > Am I missing something obvious? > > ls | python -c "for line in __import__('sys').stdin: print (line.upper())" Ah, so I am missing something - it is possible - but 'obvious'? Do people think it should be more accessible From pythonfiddle at gmail.com Mon Sep 5 18:00:36 2011 From: pythonfiddle at gmail.com (Python Fiddle Admin) Date: Mon, 5 Sep 2011 15:00:36 -0700 (PDT) Subject: Running Python Demo on the Web? Message-ID: Python has been ported to the web browser at pythonfiddle.com. Python Fiddle can import snippets of code that you are reading on a web page and run them in the browser. It supports a few popular libraries. Another common usage is to post code on the site to allow other people to play around with it. Also, it can be used to demonstrate a working program. From tjreedy at udel.edu Mon Sep 5 18:21:56 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 18:21:56 -0400 Subject: One line command line filter In-Reply-To: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: On 9/5/2011 4:38 PM, Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x"<<- SyntaxError > > Am I missing something obvious? The doc says "-c Execute the Python code in command. command can be one or more statements separated by newlines," However, I have no idea how to put newlines into a command-line string. Changing '; ' to '\n' does not work, at least not in Windows. The '\n' is passed on to Python as 2 chars, and the '\' is seen as the line-continuation char and the 'n' as illegal following it. Will a *nix shell 'cook' the string and convert '\n' to a literal newline before passing it to Python? For *nix, I would expect the <", line 1, in EOFError: EOF when reading a line Perhaps tolerable if Python is at the end of the pipe, not otherwise. > Is there a better solution - if not is this worth a PEP? PEPs have to propose a concrete solution, preferably with some previous discussion. I take is that your proposal would be to add another builtin means to access stdin. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 5 18:55:36 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 18:55:36 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/5/2011 1:45 PM, William Gill wrote: > On 9/4/2011 9:13 AM, rusi wrote: >> On Sep 3, 9:15 pm, William Gill wrote: >>> During some recent research, and re-familiarization with Python, I came >>> across documentation that suggests that programming using functions, and >>> programming using objects were somehow opposing techniques. >> >> Staying with (for the moment) the suggestion that OO-P and F-P are >> complementary, I believe it is worthwhile to distinguish syntactic OO- >> P vs F-P from semantic OO-P vs F-P. >> >> Syntactically: f(x) is functional x.f() is object oriented. >> Semantically if f's return value depends only on x ie does not depend >> on state it is functional (in the math sense) -- the jargon is that f >> is referentially transparent. > > Not to split hairs, but syntactically f(x) is a function in many > programming paradigms. > > As I understand it functional programming places specific requirements > on functions, i.e.referential transparency. So f(x) may or may not be > "functional". In Python, it may be a parameterized procedure. Some languages separate functions and procedures (also called subroutines). Python does not. (Or you could say that it makes procedures into functions with side-effects by returning None by default). > x.f() is also a function, but it is a member of the object x, is > referred to as a 'method' of x, and uses the syntactical "dot" notation > object"dot"function for identification. > >> Referential opaqueness is usually such a source of problems that it >> turns out good to contain the problem somewhat -- hence the wish for >> encapsulation. >> >> One can find in the python library itself all 4 combinations: >> syntactically and semantically OO : sort >> syntactically and semantically FP: sorted >> syntactically OO semantically FP: join > -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 5 19:02:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 19:02:04 -0400 Subject: One line command line filter In-Reply-To: <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <39f1dbdb-9e25-43b8-b293-395ccfc76e50@p10g2000yqi.googlegroups.com> Message-ID: On 9/5/2011 5:32 PM, Jon Redgrave wrote: >>> Am I missing something obvious? >> >> ls | python -c "for line in __import__('sys').stdin: print (line.upper())" > > Ah, so I am missing something - it is possible - but 'obvious'? > Do people think it should be more accessible __import__ is well-documented and is listed in the index of the builtin functions chapter. "Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime." could be explanded to include "or where you want to import as part of an expression" Every Python programmer should peruse that chapter to learn what is available for possible future use. -- Terry Jan Reedy From mdekauwe at gmail.com Mon Sep 5 19:02:41 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 16:02:41 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <9c0733c8-875b-425a-9021-5f22bf75d1a6@m4g2000pri.googlegroups.com> Hi, Tim yes I had a feeling my posting might be read as ambiguous! Sorry I was trying to quickly think of a good example. Essentially I have a set of .ini parameter files which I read into my program using configobj, I then replace the default module parameters if the user file is different (in my program). When it comes to writing the data back out I need to potentially loop over 5 module files and I need to ignore the superfluous information. My guess is that the way I am doing it might be a little on the slow side, hence the posting. Like you said it might be that the way I am doing it is "fine", I just wanted to see if there was a better way that is all. Rantingrick I did actually try the dir() to start with, I can't remember why I changed back. I will try your suggestion and see (thanks) So instead of sys as per my example my module more realistically looks like this: params.py apples = 12.0 cats = 14.0 dogs = 1.3 so my fuller example then import sys sys.path.append("/Users/mdekauwe/Desktop/") import params #params.py contains #apples = 12.0 #cats = 14.0 #dogs = 1.3 fname = "test.asc" try: ofile = open(fname, 'w') except IOError: raise IOError("Can't open %s file for write" % fname) data = [] for attr in params.__dict__.keys(): if not attr.startswith('__') and not attr.endswith('__'): attr_val = getattr(params, attr) data.append((attr, attr_val)) data.sort() try: ofile.write("[params]\n") for i in data: ofile.write("%s = %s\n" % (i[0], i[1])) except IOError: raise IOError("Error writing params files, params section") etc, etc thanks From simoncropper at fossworkflowguides.com Mon Sep 5 19:09:17 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Tue, 06 Sep 2011 09:09:17 +1000 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> References: <624f5caf-e3c1-4a88-9861-606f7e2705e8@x14g2000prn.googlegroups.com> Message-ID: <4E65569D.9000603@fossworkflowguides.com> On 06/09/11 00:40, alex23 wrote: > On Sep 5, 3:18 pm, Simon Cropper > wrote: >> My investigations have generally found that windows/forms/data entry >> screen can be created for a specific table or view, but these are >> hard-wired during development. Is there anyway of rapidly defining the >> grid during runtime so any table can be viewed? > > The commercial product Resolver One provides a grid/spreadsheet style > interface with Python scripting capabilities. I'm not sure of its > current licensing status but I believe it used to be free if used on > open source projects. > > http://www.resolversystems.com/products/resolver-one/ > > Each spreadsheet itself is Python code; I think it should be quite do- > able to take something with introspective SQL capabilities like > SQLAlchemy and have it title columns and fill them with the correct > fields accordingly. > > Hope this helps. > > Alex, The Resolver Package looks good. Not exactly open source though. I equate it to a proprietary package that can at times be used for free by select groups. The product creates spreadsheets with python code in the background (instead of say VBA in Excel or Basic in Calc). Access to a database still needs to be hard-wired, so it does not act as a 'dynamic' viewer. The product works pretty much like Excel and Calc in this manner. Sheets can be shared, although the Resolver Exchange website does not clarify the licence under which samples are released (GPL, CC, etc), so it is debatable how any of this could reliably be used in creation of derivatives. From what I can glean from this page... http://www.resolversystems.com/opensource/ ... Resolver will allow you to use the package if you are an open source project to create spreadsheets that can be redistributed. For people to use these sheets they need to download the viewer or purchase the package. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From steve+comp.lang.python at pearwood.info Mon Sep 5 19:18:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:18:37 +1000 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > The doc says "-c > Execute the Python code in command. command can be one or more > statements separated by newlines," > > However, I have no idea how to put newlines into a command-line string. I imagine that it depends on the shell you are using, but bash on Linux makes it simple: double quotes "..." are like Python's triple-quoted strings in that they can include newlines. [steve at sylar python]$ ls f*.py | python -c "import sys > print sys.stdin.read()" factorial.py fetchqm.py fib.py fileutils.py findsingle.py fixascii.py fix.py frange.py frequencies.py Other shells may be different. -- Steven From mdekauwe at gmail.com Mon Sep 5 19:20:42 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Mon, 5 Sep 2011 16:20:42 -0700 (PDT) Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> <9c0733c8-875b-425a-9021-5f22bf75d1a6@m4g2000pri.googlegroups.com> Message-ID: <5de6e076-f25a-4a44-ba9b-2c99ff006565@e20g2000prn.googlegroups.com> Trying to follow the suggestion this would be the alternate implementation. import sys sys.path.append("/Users/mdekauwe/Desktop/") import params #params.py contains #apples = 12.0 #cats = 14.0 #dogs = 1.3 fname = "test.asc" try: ofile = open(fname, 'w') except IOError: raise IOError("Can't open %s file for write" % fname) attributes = [attr for attr in dir(params) if not attr.startswith('__')] attributes.sort() try: ofile.write("[params]\n") for i in attributes: ofile.write("%s = %s\n" % (i, getattr(params, i))) except IOError: raise IOError("Error writing params files, params section") Is that a better version? I honestly don't know. thanks From steve+comp.lang.python at pearwood.info Mon Sep 5 19:29:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:29:00 +1000 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: <4e655b3e$0$29982$c3e8da3$5496439d@news.astraweb.com> Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" Python is neither bash nor Perl. It is not intended to compete in the "quick and dirty one-liner commands" stakes. However, you might like to consider ipython, which is intended as a complete Python shell, not just an interactive interpreter. http://ipython.org/ [...] > The best I've come up with is to use sitecustomize.py to add to > __builtin__ If you're a system administrator who wants to replace bash one-liners at the command line with Python one-liners, sure, why not? If you build up a useful collection of sys admin tools or recipes, you might like to consider sharing them. Perhaps if Python was used more by sys admins, there might be less resistance to making it easier to compete with bash one-liners. -- Steven From steve+comp.lang.python at pearwood.info Mon Sep 5 19:46:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 09:46:16 +1000 Subject: Best way to print a module? References: <00c3e9d0-9c15-4d69-8b7f-ee0e6ecff508@m4g2000pri.googlegroups.com> Message-ID: <4e655f4a$0$29965$c3e8da3$5496439d@news.astraweb.com> Tim Roberts wrote: > Martin De Kauwe wrote: >> >>If I wanted to print an entire module, skipping the attributes >>starting with "__" is there an *optimal* way? > > Your question is somewhat ambiguous. When I read "print an entire > module", I assumed you were asking for a way to print the source code, > perhaps with syntax coloring. > > Surely there is no reason to have an "optimal" method of doing this -- > this is never going to be in an inner loop. Regardless of an inner loop or not, the time required for IO (reading the file from disk, writing it to a printer) will be much larger than the time required to skip dunder (double-underscore) objects. > If you have a method that works, > there is little justification to optimize... Pretty much. HOWEVER, having agreed with you in general, in this specific case it is obvious to me from context that the OP doesn't want to print the source code of the module, but the module's names and their values. I'd try a couple of approaches: - use dir() or vars() to get the module's names, then loop and print each one; - make a shallow copy of the module __dict__, less dunder names, and pass it to the prettyprint module for printing. -- Steven From nospam at domain.invalid Mon Sep 5 20:30:47 2011 From: nospam at domain.invalid (William Gill) Date: Mon, 05 Sep 2011 20:30:47 -0400 Subject: Functions vs OOP In-Reply-To: References: Message-ID: On 9/5/2011 3:04 PM, Jean-Michel Pichavant wrote: > William Gill wrote: >> >> Not to split hairs, but syntactically f(x) is a function in many >> programming paradigms. >> >> As I understand it functional programming places specific requirements >> on functions, i.e.referential transparency. So f(x) may or may not be >> "functional". >> >> x.f() is also a function, but it is a member of the object x, is >> referred to as a 'method' of x, and uses the syntactical "dot" >> notation object"dot"function for identification. >> > > Functional programming is not about writing a programm with functions > . This may cause some confusion. It can, and it did. That was the impression I (incorrectly) got from the documentation. Which didn't make sense to me. > (google it for more info). I can, and I did. That, and the answers I got in this ng are how I corrected my misconception. > > Your original post was about functions vs methods, which are identical > except some syntax detail. FYI, in python x.f() is equivalent to f(x). > In an OOP world one will prefer the x.f() form. > No, my original post was about how (based on the aforementioned misconception) the documentation seemed to suggest that OOP should never have free standing functions, only methods. From nospam at torek.net Mon Sep 5 21:10:40 2011 From: nospam at torek.net (Chris Torek) Date: 6 Sep 2011 01:10:40 GMT Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: >Chris Torek writes: >[snip] >> when you have [an] instance and call [an] instance or class method: [note: I have changed the names very slightly here, and removed additional arguments, on purpose] >> black_knight = K() >> black_knight.spam() >> black_knight.eggs() >> >> the first parameters ... are magic, and invisible. >> >> Thus, Python is using the "explicit is better than implicit" rule >> in the definition, but not at the call site. ... In article Piet van Oostrum wrote: >It *is* explicit also at the call site. It only is written at the left >of the dot rather than at the right of the parenthesis. It cannot possibly be explicit. The first parameter to one of the method functions is black_knight, but the first parameter to the other method is black_knight.__class__. Which one is which? Is spam() the instance method and eggs() the class method, or is spam() the class method and eggs the instance method? (One does not, and should not, have to *care*, which is kind of the point here. :-) ) >And that is necessary to locate which definition of the method >applies. By "that" I assume you mean the name "black_knight" here. But the name is not required to make the call; see the last line of the following code fragment: funclist = [] ... black_knight = K() funclist.append(black_knight.spam) funclist.append(black_knight.eggs) ... # At this point, let's say len(funclist) > 2, # and some number of funclist[i] entries are ordinary # functions that have no special first parameter. random.choice(funclist)() >It would be silly to repeat this information after the parenthesis. >Not only silly, it would be stupid as it would be a source of errors, >and an example of DRY. Indeed. But I believe the above is a demonstration of how the "self" or "cls" parameter is in fact implicit, not explicit. (I am using python 2.x, and doing this in the interpreter: random.choice(funclist) -- without the parentheses to call the function -- produces: > > The first is the instance method, whose name I am still keeping secret; the second is the class method; and the third is the ordinary function I added to the list. The actual functions print their own name and their parameters if any, and one can see that the class and instance methods get one parameter, and the ordinary function gets none.) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From tjreedy at udel.edu Mon Sep 5 21:25:44 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 05 Sep 2011 21:25:44 -0400 Subject: One line command line filter In-Reply-To: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/5/2011 7:18 PM, Steven D'Aprano wrote: > Terry Reedy wrote: > >> The doc says "-c >> Execute the Python code in command. command can be one or more >> statements separated by newlines," >> >> However, I have no idea how to put newlines into a command-line string. > > I imagine that it depends on the shell you are using, but bash on Linux > makes it simple: double quotes "..." are like Python's triple-quoted > strings in that they can include newlines. > > [steve at sylar python]$ ls f*.py | python -c "import sys >> print sys.stdin.read()" > factorial.py > fetchqm.py I was guessing that whoever wrote the doc could do something like that. As far as I know, there is no way to escape a newline with Windows cmd.exe. (Someone please tell me if I am wrong!) An "unmatched" quote is either ignored or matched by the newline! C:\Programs\Python32> python -c "print('haha') haha -- Terry Jan Reedy From jabba.laci at gmail.com Mon Sep 5 21:36:46 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Mon, 5 Sep 2011 21:36:46 -0400 Subject: download pages using a cookies.txt file Message-ID: Hi, I would like to download a page that requires authentication with cookies. I've already figured out how to do it with wget (blog post here: http://bit.ly/pp25LP). In short: (1) extract cookies from Firefox's cookies.sqlite and store them in a text file (2) wget --cookies=on --load-cookies=cookies.txt --keep-session-cookies "http://..." My question is: how to do it from Python? If possible, I want to avoid making external calls to wget. Thanks, Laszlo From sahil at FreeBSD.org Mon Sep 5 21:45:02 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Mon, 5 Sep 2011 21:45:02 -0400 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: <20110906014502.GE254@magic.hamla.org> On Mon, 2011-09-05 at 21:36:46 -0400, Jabba Laci wrote: > I would like to download a page that requires authentication with > cookies. I've already figured out how to do it with wget (blog post > here: http://bit.ly/pp25LP). In short: > (1) extract cookies from Firefox's cookies.sqlite and store them in a text file > (2) wget --cookies=on --load-cookies=cookies.txt > --keep-session-cookies "http://..." > > My question is: how to do it from Python? If possible, I want to avoid > making external calls to wget. Have you already explored the cookielib (known as http.cookiejar in Python 3.0) module? -- Sahil Tandon From clp2 at rebertia.com Mon Sep 5 22:19:17 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 5 Sep 2011 19:19:17 -0700 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: On Mon, Sep 5, 2011 at 6:36 PM, Jabba Laci wrote: > Hi, > > I would like to download a page that requires authentication with > cookies. I've already figured out how to do it with wget (blog post > here: http://bit.ly/pp25LP). In short: > (1) extract cookies from Firefox's cookies.sqlite and store them in a text file > (2) wget --cookies=on --load-cookies=cookies.txt > --keep-session-cookies "http://..." > > My question is: how to do it from Python? http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar Cheers, Chris From rantingrick at gmail.com Mon Sep 5 23:58:30 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 5 Sep 2011 20:58:30 -0700 (PDT) Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: <90128a68-1a3c-433a-8cf8-efa3b130d7ea@hb5g2000vbb.googlegroups.com> On Aug 31, 9:35?am, "T. Goodchild" wrote: > I?m new to Python, and I love it. ?The philosophy of the language (and > of the community as a whole) is beautiful to me. Welcome aboard mate! > But one of the things that bugs me Oh here we go! :-) > is the requirement that all class > methods have 'self' as their first parameter. ?On a gut level, to me > this seems to be at odds with Python?s dedication to simplicity. It will will seem odd at first. I too hated typing all those "selfs" all the time. But believe me my new friend in no time those selfs will roll of your fingers with great ease. You'll forget how much you hate them and find much more to complain about. Like for instance: I really lament the missing redundancy of Explicit Lexical Scoping in python. For me global variables should have to be qualified. > For example, consider Python?s indent-sensitive syntax. ? > [...] > and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. Yes, forced indention is my favorite aspect of Python! > So why is 'self' necessary on class methods? It could be that Guido has a exaggerated self importance and just liked the sound of all those selfs whist reading source code. However i believe the real reason is really readability! It takes a while to understand this aspect because the natural human response is to be lazy (for instance i could have used "used to" in the previous sentence if i was slothful). We are all inherently lazy beings who need structure to keep us from spiraling out of control into the abyss of selfishness. GvR: Computer Scientist and Behavioral psychologist. From steve+comp.lang.python at pearwood.info Tue Sep 6 00:31:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 14:31:25 +1000 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> <4e5e5628$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e65a21e$0$29969$c3e8da3$5496439d@news.astraweb.com> On Tue, 6 Sep 2011 11:10 am Chris Torek wrote: >>> black_knight = K() >>> black_knight.spam() >>> black_knight.eggs() >>> >>> the first parameters ... are magic, and invisible. >>> >>> Thus, Python is using the "explicit is better than implicit" rule >>> in the definition, but not at the call site. ... > > In article > Piet van Oostrum wrote: >>It *is* explicit also at the call site. It only is written at the left >>of the dot rather than at the right of the parenthesis. > > It cannot possibly be explicit. The first parameter to one of the > method functions is black_knight, but the first parameter to the > other method is black_knight.__class__. I think you are expecting more explicitness than actually required. There are degrees of explicitness: - The current President of the United States is a black man. - On 6th September 2011, the duly constituted President of the United States of America is a black man. - On 6th September 2011, the duly constituted government official with the title of President of the nation known as the United States of America is an individual member of the species Homo sapiens with XY chromosomes and of recent African ancestry. As opposed to implicit: - He is a black guy. There is no requirement for every last gory detail to be overtly specified in full. I quote from WordNet: explicit adj 1: precisely and clearly expressed or readily observable; leaving nothing to implication; "explicit instructions"; "she made her wishes explicit"; "explicit sexual scenes" [syn: expressed] [ant: implicit] 2: in accordance with fact or the primary meaning of a term [syn: denotative] Note the second definition in particular: in accordance with the primary meaning of a term: the primary meaning of "class method" is that it receives the class rather than the instance as first argument. The "explicit is better than implicit" Zen should, in my opinion, be best understood as a recommendation that code should, in general, avoid getting input from context. In general, functions should avoid trying to decide which behaviour is wanted according to context or the environment: def func(x): if running_in_a_terminal(): print "The answer is", (x+1)/2 else: printer = find_a_printer() if printer is not None: printer.send((x+1)/2, header="func(%r)"%x, footer="Page 1") else: # Try sending email to the current user, the default user, # postmaster or root in that order. msg = make_email("The answer is", (x+1)/2) for user in [get_current_user(), DEFAULT_USER, "root at localhost.localdomain", ...]: result = send_mail(msg, to=user) if result == 0: break else: # Fall back on beeping the speakers in Morse code ... (what if I want to beep the speakers from the terminal?), but not as a prohibition against code like this: def factorial(x): # Return the factorial of the integer part of x. n = int(x) if n <= 1: return 1 return n*factorial(n-1) There's no need to require the user to explicitly call int(x) before calling factorial just to satisfy the Zen. A function is free to process arguments as required, even to throw out information (e.g. float -> int, instance -> class). What it shouldn't do is *add* information implied by context (or at least, it should be very cautious in doing so, and document it carefully, and preferably allow the caller to easily override such implied data). > Which one is which? Is spam() the instance method and eggs() the > class method, or is spam() the class method and eggs the instance > method? (One does not, and should not, have to *care*, which is > kind of the point here. :-) ) You can't tell just from the syntax used to call them: function(arg) bound_method(arg) builtin_function_or_method(arg) callable_instance(arg) type(arg) all use the same syntax. There is no requirement that you should be able to tell *everything* about a line of code just from the syntax used. If you want to know whether black_knight.spam is an instance method or a class method, or something else, use introspection to find out. > By "that" I assume you mean the name "black_knight" here. But the > name is not required to make the call; see the last line of the > following code fragment: > > funclist = [] > ... > black_knight = K() > funclist.append(black_knight.spam) > funclist.append(black_knight.eggs) > ... > # At this point, let's say len(funclist) > 2, > # and some number of funclist[i] entries are ordinary > # functions that have no special first parameter. > random.choice(funclist)() Irrelevant. The instance used for the bound method is explicitly specified when you create it. But there's no requirement that you need to explicitly specify the instance every single time you *use* the bound method. The instance is part of the bound method, it isn't implied by context or history or guessed from the environment. Contrast what Python actually does with a hypothetical language where bound methods' instances are implicitly assigned according to the most recent instance created: black_knight = Knight() funclist.append(spam) # refers to black_knight.spam white_knight = Knight() funclist.append(spam) # refers to white_knight.spam baldrick = Knave() funclist.append(eggs) # oops, Knaves don't have an eggs attribute -- Steven From haoxinfenshou98 at yahoo.com.cn Tue Sep 6 01:51:43 2011 From: haoxinfenshou98 at yahoo.com.cn (shoestrade) Date: Mon, 5 Sep 2011 22:51:43 -0700 (PDT) Subject: When it comes to the Air Force Message-ID: When it comes to the Air Force 1 {1}{/1}a lot of you might imagine that it would be quite hard to continue improving and innovating on the design of it, but leave it to Nike to surprise you at just about every turn. Those of you that know Nike?s reputation know that they always have new tricks hidden up their sleeves to keep t? We well know that the Nike Air Force 1{2}{/2} is one of the most versatile models that we have seen hosting a custom program called the Nike Bespoke. Since the last pair of Nike Harajuku customs plus a couple more designs done by different individuals, the AF1 has been off the scene. Yet no worries because it ishttp://www.jordanshoesoutletnet.com/ From xyzhtml at 163.com Tue Sep 6 01:57:31 2011 From: xyzhtml at 163.com (xyz) Date: Tue, 6 Sep 2011 13:57:31 +0800 Subject: Floating point multiplication in python Message-ID: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> hi all: As we know , 1.1 * 1.1 is 1.21 . But in python ,I got following : >>> 1.1 * 1.1 1.2100000000000002 why python get wrong result? Who can tell me where's the 0.0000000000000002 from? From clp2 at rebertia.com Tue Sep 6 02:18:30 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 5 Sep 2011 23:18:30 -0700 Subject: Floating point multiplication in python In-Reply-To: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: On Mon, Sep 5, 2011 at 10:57 PM, xyz wrote: > hi all: > > As we know , ?1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? It's not Python's fault per se, rather it's the inherent nature of binary floating-point arithmetic. Try the equivalent in most other languages and you'll get the same "error". Please read http://docs.python.org/tutorial/floatingpoint.html Cheers, Chris From jwiegley at gmail.com Tue Sep 6 02:51:17 2011 From: jwiegley at gmail.com (John Wiegley) Date: Tue, 06 Sep 2011 01:51:17 -0500 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: >>>>> Jon Redgrave writes: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > eg: ls | python -c " print x.upper()" [...] > Is there a better solution - if not is this worth a PEP? Have you looked at PyP (http://code.google.com/p/pyp)? John From gherron at islandtraining.com Tue Sep 6 03:00:39 2011 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 06 Sep 2011 00:00:39 -0700 Subject: Floating point multiplication in python In-Reply-To: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: <4E65C517.2080601@islandtraining.com> On 09/05/2011 10:57 PM, xyz wrote: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? Who can tell me where's the 0.0000000000000002 from? It's not a python error It's the nature of floating point arithmetic to be inaccurate on *ANY* computer. Python just allows you to see the inaccuracies. (But try: print 1.1*1.1 and see that the print statement does hide the roundoff error from you.) Read this for more info: http://pyfaq.infogami.com/why-are-floating-point-calculations-so-inaccurate From steve+comp.lang.python at pearwood.info Tue Sep 6 03:11:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 06 Sep 2011 17:11:10 +1000 Subject: Floating point multiplication in python References: Message-ID: <4e65c78f$0$29974$c3e8da3$5496439d@news.astraweb.com> On Tue, 6 Sep 2011 03:57 pm xyz wrote: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 The problem is that 1.1 is a *decimal* number, but computers use *binary*, and it is impossible to express 1.1 exactly as a binary number. So when you type 1.1 into nearly all computer languages, what you are actually getting is a tiny bit more than 1.1: >>> repr(1.1) '1.1000000000000001' which is the closest number to 1.1 that is possible using a C double floating point number. Normally you don't see it, because Python truncates the result when printing: >>> str(1.1) '1.1' but the difference is there. -- Steven From pierre.quentel at gmail.com Tue Sep 6 03:18:16 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Tue, 6 Sep 2011 00:18:16 -0700 (PDT) Subject: Relative seeks on string IO Message-ID: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Hi, I am wondering why relative seeks fail on string IO in Python 3.2 Example : from io import StringIO txt = StringIO('Favourite Worst Nightmare') txt.seek(8) # no problem with absolute seek but txt.seek(2,1) # 2 characters from current position raises "IOError: Can't do nonzero cur-relative seeks" (tested with Python3.2.2 on WindowsXP) A seek relative to the end of the string IO raises the same IOError However, it is not difficult to simulate a class that performs relative seeks on strings : ==================== class FakeIO: def __init__(self,value): self.value = value self.pos = 0 def read(self,nb=None): if nb is None: return self.value[self.pos:] else: return self.value[self.pos:self.pos+nb] def seek(self,offset,whence=0): if whence==0: self.pos = offset elif whence==1: # relative to current position self.pos += offset elif whence==2: # relative to end of string self.pos = len(self.value)+offset txt = FakeIO('Favourite Worst Nightmare') txt.seek(8) txt.seek(2,1) txt.seek(-8,2) ===================== Is there any reason why relative seeks on string IO are not allowed in Python3.2, or is it a bug that could be fixed in a next version ? - Pierre From __peter__ at web.de Tue Sep 6 03:53:07 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Sep 2011 09:53:07 +0200 Subject: One line command line filter References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> Message-ID: Jon Redgrave wrote: > It seems unreasonably hard to write simple one-line unix command line > filters in python: > > eg: ls | python -c " print x.upper()" > > to get at sys.stdin or similar needs an import, which makes a > subsequent for-loop illegal. > python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError > > Am I missing something obvious? > > The best I've come up with is to use sitecustomize.py to add to > __builtin__ > def stdin(): > import sys > for x in sys.stdin(): > if not x: return > yield x.strip() > import __builtin__ > __builtin__.stdin = stdin > > This allows > ls | python -c "for x in stdin(): print x.upper()" > > Is there a better solution - if not is this worth a PEP? $ touch alpha beta gamma omega $ ls | python -c 'import sys; sys.stdout.writelines(s.upper() for s in sys.stdin if s.startswith(("a", "o")))' ALPHA OMEGA If you are doing this a lot, why don't you write a helper script and invoke that? $ ls | pyfilter.py -f '"m" in line' -s 'lines = (line + line[::-1] for line in map(str.strip, lines))' -s'import re' -p 're.compile(r"(([a- z])\2)").sub(lambda m: m.group(1).upper(), line)' alphAAhpla betAAteb gaMMAAMMag omegAAgemo This relies on the convention that a single line of input is accessible as "line" and the complete input is called "lines". Of course the same can be done with python -c ..., -- and it is even more readable: $ ls | python -c 'import re, sys for line in sys.stdin: > line = line.strip() > line = line + line[::-1] > print re.compile(r"(([a-z])\2)").sub(lambda m: m.group(1).upper(), line) > ' alphAAhpla betAAteb gaMMAAMMag omegAAgemo > Is there a better solution - if not is this worth a PEP? The python interpreter could accept multiple -c arguments, but to see how this will be received a post on python-ideas should be sufficient. For the sake of completeness here's the script I used to produce the example above: $ cat pyfilter.py #!/usr/bin/env python import sys def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument( "-s", "--setup", action="append", default=[], dest="setups", metavar="SETUP") parser.add_argument( "-f", "--filter", action="append", default=[], dest="filters", metavar="FILTER") parser.add_argument("-p", "--print", dest="format") args = parser.parse_args() lines = sys.stdin for setup in args.setups: exec setup for line in lines: line = line.rstrip("\n") for filter in args.filters: if not eval(filter): continue if args.format: line = eval(args.format) try: print line except IOError as e: if e.errno == 32: # broken pipe break raise if __name__ == "__main__": main() From 1248283536 at qq.com Tue Sep 6 04:18:41 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 6 Sep 2011 16:18:41 +0800 Subject: strang thing: Message-ID: i found stange thing that i can't solve import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): print row[0], row[1], row[2], row[3],row[4], row[5], row[6] it's ok, when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) change the code into import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] the wrong output is : file = open(filename,'r') TypeError: 'str' object is not callable i don't know why?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Sep 6 04:22:37 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 6 Sep 2011 18:22:37 +1000 Subject: strang thing: In-Reply-To: References: Message-ID: 2011/9/6 ???? <1248283536 at qq.com>: > ??? file = open(filename,'r') > when i? add??? (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA From wolfgang at rohdewald.de Tue Sep 6 04:24:59 2011 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Tue, 6 Sep 2011 10:24:59 +0200 Subject: strang thing: In-Reply-To: References: Message-ID: <201109061024.59596.wolfgang@rohdewald.de> On Dienstag 06 September 2011, ???? wrote: > (date,open,high,low,close,vol,adjclose) = (row[0], > row[1], row[2], row[3],row[4], row[5], row[6]) print > row[0], row[1], row[2], row[3],row[4], row[5], row[6] > > > the wrong output is : > file = open(filename,'r') > TypeError: 'str' object is not callable you reassigned "open" to be a string -- Wolfgang From duncan.booth at invalid.invalid Tue Sep 6 04:30:53 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Sep 2011 08:30:53 GMT Subject: Floating point multiplication in python References: <3348A754-2874-4E18-9E90-F9DB131E6AA0@163.com> Message-ID: Gary Herron wrote: > (But try: > print 1.1*1.1 > and see that the print statement does hide the roundoff error from you.) That varies according to the version of Python you are using. On my system: Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(1.1*1.1) 1.21 >>> ^Z C:\Python27>cd \python32 C:\Python32>python Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(1.1*1.1) 1.2100000000000002 -- Duncan Booth http://kupuguy.blogspot.com From k.sahithi2862 at gmail.com Tue Sep 6 05:20:38 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Tue, 6 Sep 2011 02:20:38 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From sinisa.segvic at fer.hr Tue Sep 6 05:59:07 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 02:59:07 -0700 (PDT) Subject: Portable locale usage Message-ID: Hi, I am musing on how to write portable Python3 code which would take advantage of the standard locale module. For instance, it would be very nice if we could say something like: # does not work! myISOCountryCode='hr' locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) Up to now, I have found ways to set locale on Linux and Windows: import locale locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # works on linux locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows I have noticed that locale defines a dictionary locale.locale_alias, and that it contains the following promising keys: 'hr_hr', 'hrvatski', 'hr'. Unfortunately, both on Windows and Linux all these keys are bound to the same outdated string 'hr_HR.ISO8859-2'. My questions are the following: 1. Is there a way for writing portable Python code dealing with locales (as sketched in the beginning)? 2. If not, is there anything wrong with that idea? 3. What is the status of locale.locale_alias (official documentation does not mention it)? Cheers, Sinisa http://www.zemris.fer.hr/~ssegvic/index_en.html From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Tue Sep 6 06:14:57 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Tue, 06 Sep 2011 12:14:57 +0200 Subject: Floating point multiplication in python In-Reply-To: References: Message-ID: Am 06.09.2011 07:57 schrieb xyz: > hi all: > > As we know , 1.1 * 1.1 is 1.21 . > But in python ,I got following : > >>>> 1.1 * 1.1 > 1.2100000000000002 > > why python get wrong result? Who can tell me where's the 0.0000000000000002 from? 1.1 does not fit in a binary floating point number. It is approximated - in binary! - as 1.000110011001100110011 ... (periodically). Note that, while in the decimal system we normally use, only numbers which have other components in the denominator than 2 or 5 are periodically, in the binary systems only components with 2 are allowed in order not to be periodically. Example: 3.453 is not periodically, because it is 3453/100 and 100 has only the factors 2 and 5, each twice. 1/3 = .3333333... is periodically, because it has the factor 3. The same applies to 1/6, which has 2 and 3 as factors. The latter destroys the non-periodical behaviour. As said, in the dual system, only the 2 is allowed. .5 (10) = 2** -1 = .1 (2). .25 (10) = 2 ** -2 = .01 (2). .75 (10) = their sum = .11 (2). But .1 (1/10) is more complicated, -2 would be as well. As the IEEE floating point representation is limited, there is a slight error value which makes the stored value differ from the intended one. Look here: >>> x=(1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1) >>> a=0 >>> for n,i in enumerate(x): a += i*2**-n; print a, a-1.1, i*2**-n, a-olda ... 1 -0.1 1 1 1.0 -0.1 0.0 0.0 1.0 -0.1 0.0 0.0 1.0 -0.1 0.0 0.0 1.0625 -0.0375 0.0625 0.0625 1.09375 -0.00625 0.03125 0.03125 1.09375 -0.00625 0.0 0.0 1.09375 -0.00625 0.0 0.0 1.09765625 -0.00234375 0.00390625 0.00390625 1.099609375 -0.000390625 0.001953125 0.001953125 1.099609375 -0.000390625 0.0 0.0 1.099609375 -0.000390625 0.0 0.0 1.09985351562 -0.000146484375 0.000244140625 0.000244140625 1.09997558594 -2.44140625001e-05 0.0001220703125 0.0001220703125 1.09997558594 -2.44140625001e-05 0.0 0.0 1.09997558594 -2.44140625001e-05 0.0 0.0 1.09999084473 -9.15527343759e-06 1.52587890625e-05 1.52587890625e-05 1.09999847412 -1.52587890634e-06 7.62939453125e-06 7.62939453125e-06 1.09999847412 -1.52587890634e-06 0.0 0.0 1.09999847412 -1.52587890634e-06 0.0 0.0 1.0999994278 -5.72204589933e-07 9.53674316406e-07 9.53674316406e-07 1.09999990463 -9.53674317294e-08 4.76837158203e-07 4.76837158203e-07 1.09999990463 -9.53674317294e-08 0.0 0.0 1.09999990463 -9.53674317294e-08 0.0 0.0 1.09999996424 -3.57627869541e-08 5.96046447754e-08 5.96046447754e-08 1.09999999404 -5.96046456636e-09 2.98023223877e-08 2.98023223877e-08 1.09999999404 -5.96046456636e-09 0.0 0.0 1.09999999404 -5.96046456636e-09 0.0 0.0 1.09999999776 -2.23517426789e-09 3.72529029846e-09 3.72529029846e-09 1.09999999963 -3.72529118664e-10 1.86264514923e-09 1.86264514923e-09 1.09999999963 -3.72529118664e-10 0.0 0.0 1.09999999963 -3.72529118664e-10 0.0 0.0 1.09999999986 -1.3969847501e-10 2.32830643654e-10 2.32830643654e-10 1.09999999998 -2.32831531832e-11 1.16415321827e-10 1.16415321827e-10 1.09999999998 -2.32831531832e-11 0.0 0.0 1.09999999998 -2.32831531832e-11 0.0 0.0 1.09999999999 -8.73123795486e-12 1.45519152284e-11 1.45519152284e-11 1.1 -1.45528034068e-12 7.27595761418e-12 7.27595761418e-12 1.1 -1.45528034068e-12 0.0 0.0 1.1 -1.45528034068e-12 0.0 0.0 1.1 -5.45785638906e-13 9.09494701773e-13 9.09494701773e-13 1.1 -9.10382880193e-14 4.54747350886e-13 4.54747350886e-13 1.1 -9.10382880193e-14 0.0 0.0 1.1 -9.10382880193e-14 0.0 0.0 1.1 -3.41948691585e-14 5.68434188608e-14 5.68434188608e-14 1.1 -5.77315972805e-15 2.84217094304e-14 2.84217094304e-14 1.1 -5.77315972805e-15 0.0 0.0 1.1 -5.77315972805e-15 0.0 0.0 1.1 -2.22044604925e-15 3.5527136788e-15 3.5527136788e-15 1.1 -4.4408920985e-16 1.7763568394e-15 1.7763568394e-15 1.1 -4.4408920985e-16 0.0 0.0 1.1 -4.4408920985e-16 0.0 0.0 1.1 -2.22044604925e-16 2.22044604925e-16 2.22044604925e-16 1.1 0.0 1.11022302463e-16 2.22044604925e-16 1.1 0.0 0.0 0.0 1.1 0.0 0.0 0.0 1.1 0.0 1.38777878078e-17 0.0 1.1 0.0 6.93889390391e-18 0.0 So here we have reached the point where the maximum precision is reached - a doesn't change anymore, although it should. The error is about 1E-16. Now if you multiply two values with an error, the error also propagates into the result - PLUs the result can have its own error source - in the same order of magnitude. (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e or (2*a + e) * e. From donstockbauer at hotmail.com Tue Sep 6 06:46:38 2011 From: donstockbauer at hotmail.com (Don Stockbauer) Date: Tue, 6 Sep 2011 03:46:38 -0700 (PDT) Subject: When it comes to the Air Force References: Message-ID: On Sep 6, 12:51?am, shoestrade wrote: > When it comes to the Air Force 1 {1}{/1}a lot of you might imagine > that it would be quite hard to continue improving and innovating on > the design of it, but leave it to Nike to surprise you at just about > every turn. Those of you that know Nike?s reputation know that they > always have new tricks hidden up their sleeves to keep t? > We well know that the Nike Air Force 1{2}{/2} is one of the most > versatile models that we have seen hosting a custom program called the > Nike Bespoke. Since the last pair of Nike Harajuku customs plus a > couple more designs done by different individuals, the AF1 has been > off the scene. Yet no worries because it ishttp://www.jordanshoesoutletnet.com/ But how does the Air Force relate to Skynet????? From hansmu at xs4all.nl Tue Sep 6 07:15:10 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 06 Sep 2011 13:15:10 +0200 Subject: One line command line filter In-Reply-To: <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4725b2c3-d930-4fb0-9fe7-a286d150f9c5@d18g2000yqm.googlegroups.com> <4e6558ce$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6600be$0$2480$e4fe514c@news2.news.xs4all.nl> On 6/09/11 01:18:37, Steven D'Aprano wrote: > Terry Reedy wrote: > >> The doc says "-c >> Execute the Python code in command. command can be one or more >> statements separated by newlines," >> >> However, I have no idea how to put newlines into a command-line string. > > I imagine that it depends on the shell you are using, but bash on Linux > makes it simple: double quotes "..." are like Python's triple-quoted > strings in that they can include newlines. Single quotes in bash are more similar to triple quotes in Python, in that some shell syntax is recognized within double quoted string, but not within single quoted strings: $ python -c 'import sys print `sys.version`' '2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. build 5664)]' $ python -c "import sys > print `sys.copyright`" -bash: sys.copyright: command not found When using single quotes, the `` are passed to Python, which interprets them as a call to repr(). With double quotes, the shell interprets `` as a sub-command. > Other shells may be different. Most *nix shells are similar to bash. The ones that are different are csh and tcsh: they require a backslash before each newline: $ tcsh % ls f*.py | python -c 'import sys \ ? print sys.stdin.read()' filecmp.py fileinput.py fnmatch.py formatter.py fpformat.py fractions.py ftplib.py functools.py % Sometimes you need two backslashes, one for csh and one for Python: % python -c 'print "spam spam spam spam spam spam spam spam " \\ ? "spam spam spam spam spam"' spam spam spam spam spam spam spam spam spam spam spam spam spam % Hope this helps, -- HansM From t at jollybox.de Tue Sep 6 07:16:50 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 06 Sep 2011 13:16:50 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: <4E660122.3000507@jollybox.de> On 06/09/11 11:59, ssegvic wrote: > Hi, > > I am musing on how to write portable Python3 code which would > take advantage of the standard locale module. > > For instance, it would be very nice if we could say something like: > > # does not work! Doesn't it? > myISOCountryCode='hr' This is a language code. (there also happens to be a country code 'hr', but you're referring to the Croatian language, 'hr') > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > locale.getpreferredencoding())) As far as I can tell, this does work. Can you show us a traceback? > Up to now, I have found ways to set locale on Linux and Windows: > > import locale > locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # works on linux > locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows > > I have noticed that locale defines a dictionary locale.locale_alias, > and that it contains the following promising keys: 'hr_hr', > 'hrvatski', 'hr'. > Unfortunately, both on Windows and Linux all these keys > are bound to the same outdated string 'hr_HR.ISO8859-2'. It looks like you don't actually care about the encoding: in your first example, you use the default system encoding, which you do not control, and in your second example, you're using two different encodings on the two platforms. So why do you care whether or not the default uses ISO 8859-2 ? > My questions are the following: > > 1. Is there a way for writing portable Python code dealing with > locales > (as sketched in the beginning)? > > 2. If not, is there anything wrong with that idea? As I said, I believe the above code should work. It works on my Linux system. What are you attempting to achieve with this setting of the locale, without even setting the encoding? Doesn't it make more sense to simply use the user's usual locale, and interact with them on their own terms? > 3. What is the status of locale.locale_alias (official documentation > does not mention it)? I don't know, but I'd assume it's not considered part of the public API, and you that shouldn't assume that it'll exist in future versions of Python. Thomas From bex.lewis at gmail.com Tue Sep 6 07:46:20 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 6 Sep 2011 04:46:20 -0700 (PDT) Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> Message-ID: On Sep 5, 3:51 pm, "Fokke Nauta" wrote: > > Hi Becky, > > I tried it straight away: > directory=D:\Webdav\ > directory=D:/Webdav/ > > Didn't work, in both cases the same error "fshandler:get_data: \Webdav not > found". > > I have the opinion that my WebDAV installation is at fault. The database is > not created either. > To have set up Python, I used python-2.7.2.msi. > To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both > Unix/Linux. > To install the, I used > " > > >> You dont install from "Python GUI", use normal cmd, navigate to the > >> folder > >> you downloaded PyXML and PyWebDAV and run "python setup.py install" > >> (python.exe has to be in your PATH). Then you have to find the > >> startup-script "davserver". Find your python installation directory and > >> look into/Tools/Scripts, in my computer this is > >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the > >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have > >> to > >> look for "davserver" there..." > > Shall I re?nstall the whole lot? Would it make a difference if in that case > I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi? > > Fokke You could try that but I'd imagine you'll end up with the same issue. My best guess is that something is preventing os.path.isdir from detecting the path as a directory under windows. I can't reproduce it on my Linux system but may have a working windows installation later. If I were you I'd fire up a python shell (execute python and get the >>> prompt), import os.path and manually try os.path.isdir(path_name) to try and find out what the actualy problem is. From santosh.dumbre at gmail.com Tue Sep 6 07:58:04 2011 From: santosh.dumbre at gmail.com (Santosh Dumbre) Date: Tue, 6 Sep 2011 17:28:04 +0530 Subject: Beginner's query - What is scope of Python for Embedded Programming(C, C++) ? Message-ID: Hi, Please consider a beginner's query - I am 9 -years experienced in C++. Currently working in Automation domain. Will Python help me to work in Automation/Embedded domain ? Your advice is highly appreciated. Please reply. Thanks a lot, Santosh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bex.lewis at gmail.com Tue Sep 6 08:01:33 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 6 Sep 2011 05:01:33 -0700 (PDT) Subject: Running Python Demo on the Web? References: Message-ID: On Sep 5, 11:00?pm, Python Fiddle Admin wrote: > Python has been ported to the web browser at pythonfiddle.com. Python > Fiddle can import snippets of code that you are reading on a web page > and run them in the browser. It supports a few popular libraries. > > Another common usage is to post code on the site to allow other people > to play around with it. Also, it can be used to demonstrate a working > program. Looks interesting but you don't appear to have support for most (any?) of the python core libs. Are you planning on adding more libraries? From cjw at ncf.ca Tue Sep 6 08:10:16 2011 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 06 Sep 2011 08:10:16 -0400 Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: On 05-Sep-11 18:00 PM, Python Fiddle Admin wrote: > Python has been ported to the web browser at pythonfiddle.com. Python > Fiddle can import snippets of code that you are reading on a web page > and run them in the browser. It supports a few popular libraries. > > Another common usage is to post code on the site to allow other people > to play around with it. Also, it can be used to demonstrate a working > program. A neat idea. import brian dir(brian) Responds "scipy not available" Colin W. From zdoor at xs4all.nl Tue Sep 6 08:42:39 2011 From: zdoor at xs4all.nl (Alex van der Spek) Date: Tue, 6 Sep 2011 08:42:39 -0400 Subject: HDF5 tree walker Message-ID: <4e661540$0$2439$e4fe514c@news2.news.xs4all.nl> Is there an equivalent to os.path.walk() for HDF5 file trees accessed through h5py? Thanks! Alex van der Spek From dreyemi at gmail.com Tue Sep 6 09:02:24 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 14:02:24 +0100 Subject: Python marks an instance of my class undefined Message-ID: Is there anything I need to do to create an instance of a class? I have this simple code(The class is in a package core.fleet): class Fleet(object): def __init__(self): """ no-arg constructor """ def fleet_file_upload(self, filename, type=None): if type == 'user': return 'photos/%Y/%m/%d' return 'images' def fleet_get_fleet(self): """ Get all fleet """ return db.db_get_fleet() def fleet_get_fleet_type(self): """ Get fleet by type or category """ For Python shell, I did this: >>> import core.fleet >>> f = Fleet() Traceback (most recent call last): File "", line 1, in NameError: name 'Fleet' is not defined What am I doing wrong? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Tue Sep 6 09:13:17 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 6 Sep 2011 15:13:17 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: 2011/9/6 ssegvic : > Hi, > > I am musing on how to write portable Python3 code which would > take advantage of the standard locale module. > > For instance, it would be very nice if we could say something like: > > # does not work! > myISOCountryCode='hr' > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > locale.getpreferredencoding())) > > Up to now, I have found ways to set locale on Linux and Windows: > > import locale > locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') ? ? ?# works on linux > locale.setlocale(locale.LC_ALL, 'hrv_HRV.1250') # works on windows > > I have noticed that locale defines a dictionary locale.locale_alias, > and that it contains the following promising keys: 'hr_hr', > 'hrvatski', 'hr'. > Unfortunately, both on Windows and Linux all these keys > are bound to the same outdated string 'hr_HR.ISO8859-2'. > > My questions are the following: > > 1. Is there a way for writing portable Python code dealing with > locales > ? ?(as sketched in the beginning)? > > 2. If not, is there anything wrong with that idea? > > 3. What is the status of locale.locale_alias (official documentation > does not mention it)? > > > Cheers, > > Sinisa > > http://www.zemris.fer.hr/~ssegvic/index_en.html > -- > http://mail.python.org/mailman/listinfo/python-list > There may be some differences btween OSes end the versions, but using python 2.7 and 3.2 on Win XP and Win7 (Czech) I get the following results for setlocale: >>> locale.setlocale(locale.LC_ALL,'Croatian') 'Croatian_Croatia.1250' >>> locale.getlocale() ('Croatian_Croatia', '1250') >>> locale.getpreferredencoding(do_setlocale=False) 'cp1250' >>> However, "hr" is not recognised on this systems: >>> locale.setlocale(locale.LC_ALL, "hr") Traceback (most recent call last): File "", line 1, in File "locale.pyc", line 531, in setlocale Error: unsupported locale setting >>> regards, vbr From wxjmfauth at gmail.com Tue Sep 6 09:37:51 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 6 Sep 2011 06:37:51 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) Message-ID: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> This is just an attempt to put the http://groups.google.com/group/comp.lang.python/browse_thread/thread/a008af1ac2968833# discussion at a correct level. With Python 2.7 a new float number representation (the David Gay's algorithm) has been introduced. If this is well honored in Python 2.7, it seems to me, there are some missmatches in the Py3 series. >>> sys.version '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]' >>> 0.1 0.10000000000000001 >>> print 0.1 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> >>> sys.version 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] >>> >>> 0.1 0.1 >>> print 0.1 0.1 >>> 1.1 * 1.1 1.21 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> >>> sys.version '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]' >>> 0.1 0.1 >>> print(0.1) 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print(1.1 * 1.1) 1.21 >>> print(repr(1.1 * 1.1)) 1.2100000000000002 >>> '{:g}'.format(1.1 * 1.1) '1.21' >>> sys.version '3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' >>> 0.1 0.1 >>> print(0.1) 0.1 >>> 1.1 * 1.1 1.2100000000000002 >>> print (1.1 * 1.1) 1.2100000000000002 >>> print(repr((1.1 * 1.1))) 1.2100000000000002 >>> >>> '{:g}'.format(1.1 * 1.1) '1.21' >>> jmf From dreyemi at gmail.com Tue Sep 6 09:42:54 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 14:42:54 +0100 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: I was able to get this solved by calling class like this: >>> from core.fleet import Fleet >>> f = Fleet() Thanks to a thread from the list titled "TypeError: 'module' object is not callable" On Tue, Sep 6, 2011 at 2:02 PM, Kayode Odeyemi wrote: > Is there anything I need to do to create an instance of a class? > > I have this simple code(The class is in a package core.fleet): > > class Fleet(object): > def __init__(self): > """ no-arg constructor """ > def fleet_file_upload(self, filename, type=None): > if type == 'user': > return 'photos/%Y/%m/%d' > return 'images' > > def fleet_get_fleet(self): > """ Get all fleet """ > return db.db_get_fleet() > > def fleet_get_fleet_type(self): > """ Get fleet by type or category """ > > For Python shell, I did this: > > >>> import core.fleet > >>> f = Fleet() > Traceback (most recent call last): > File "", line 1, in > NameError: name 'Fleet' is not defined > > What am I doing wrong? > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Tue Sep 6 10:18:32 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 06 Sep 2011 16:18:32 +0200 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: <4E662BB8.6050102@shopzeus.com> On 2011-09-06 15:42, Kayode Odeyemi wrote: > I was able to get this solved by calling class like this: > > >>> from core.fleet import Fleet > >>> f = Fleet() > > Thanks to a thread from the list titled "TypeError: 'module' object is > not callable" Or you can also do this: import core.fleet # import module core.fleet under the name core.fleet f = core.fleet.Fleet() Please note that the import statement imports the module with the given name. So for example import x.y.z will import the name "x.y.z". Anything that is in module "z" will be available through its module, that is "x.y.z". Whenever you use "import ", you have to access module contents through "". You can change the name: import core.fleet as c # import module core.fleet under the name c f = c.Fleet() From dreyemi at gmail.com Tue Sep 6 10:32:19 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 6 Sep 2011 15:32:19 +0100 Subject: Python marks an instance of my class undefined In-Reply-To: <4E662BB8.6050102@shopzeus.com> References: <4E662BB8.6050102@shopzeus.com> Message-ID: On Tue, Sep 6, 2011 at 3:18 PM, Laszlo Nagy wrote: > On 2011-09-06 15:42, Kayode Odeyemi wrote: > >> I was able to get this solved by calling class like this: >> >> >>> from core.fleet import Fleet >> >>> f = Fleet() >> >> Thanks to a thread from the list titled "TypeError: 'module' object is not >> callable" >> > Or you can also do this: > > import core.fleet # import module core.fleet under the name core.fleet > f = core.fleet.Fleet() > > Please note that the import statement imports the module with the given > name. > > So for example > > import x.y.z > > will import the name "x.y.z". Anything that is in module "z" will be > available through its module, that is "x.y.z". > Whenever you use "import ", you have to access module contents > through "". > > You can change the name: > > import core.fleet as c # import module core.fleet under the name c > f = c.Fleet() > > That is, import [package-name] .[class-name] If using from, that can take the form of [package-name].[pymodule] import [pymodule] or [class-name] I just got to understand it. Thanks. This explanation really simplifies it further. Can I do: from [pymodule] import [class-name], assuming the pymodule as a class instance? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From fnautaNO at SPAMsolfon.nl Tue Sep 6 10:46:17 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Tue, 6 Sep 2011 16:46:17 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net><9c6n4oFsnbU1@mid.individual.net><9c9578F5eaU2@mid.individual.net> <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> Message-ID: <9cmq1vFk6fU1@mid.individual.net> "becky_lewis" wrote in message news:f5b9ec16-de9a-4365-81a8-860dc27a985e at d25g2000yqh.googlegroups.com... On Sep 5, 3:51 pm, "Fokke Nauta" wrote: > > Hi Becky, > > I tried it straight away: > directory=D:\Webdav\ > directory=D:/Webdav/ > > Didn't work, in both cases the same error "fshandler:get_data: \Webdav not > found". > > I have the opinion that my WebDAV installation is at fault. The database > is > not created either. > To have set up Python, I used python-2.7.2.msi. > To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both > Unix/Linux. > To install the, I used > " > > >> You dont install from "Python GUI", use normal cmd, navigate to the > >> folder > >> you downloaded PyXML and PyWebDAV and run "python setup.py install" > >> (python.exe has to be in your PATH). Then you have to find the > >> startup-script "davserver". Find your python installation directory and > >> look into/Tools/Scripts, in my computer this is > >> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the > >> site-packages folder i.e. E:\python27\Lib/site-packages. You might have > >> to > >> look for "davserver" there..." > > Shall I re?nstall the whole lot? Would it make a difference if in that > case > I would use ActivePython-2.7.2.5-win32-x86.msi instead of > python-2.7.2.msi? > > Fokke You could try that but I'd imagine you'll end up with the same issue. My best guess is that something is preventing os.path.isdir from detecting the path as a directory under windows. I can't reproduce it on my Linux system but may have a working windows installation later. If I were you I'd fire up a python shell (execute python and get the >>> prompt), import os.path and manually try os.path.isdir(path_name) to try and find out what the actualy problem is. I'm not familiar with Python, but I entered "import os.path " (nothing happened) and "os.path.isdir(path_name) " in the shell. I guess what I did was not correct. Underneath I copied what showed up in the shell. ------------------------------------------- Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import os.path >>> os.path.isdir(path_name) Traceback (most recent call last): File "", line 1, in os.path.isdir(path_name) NameError: name 'path_name' is not defined >>> ------------------------------------------- Fokke From sinisa.segvic at fer.hr Tue Sep 6 10:46:46 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 07:46:46 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> On 6 ruj, 13:16, Thomas Jollans wrote: > > locale.setlocale(locale.LC_ALL, (myISOCountryCode, > > locale.getpreferredencoding())) > > As far as I can tell, this does work. Can you show us a traceback? Sorry, I was imprecise. I wanted to say that the above snippet does not work both on Windows and Linux. This is what I get on Windows: >>> import sys >>> sys.version '3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]' >>> myISOCountryCode='hr' >>> locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) Traceback (most recent call last): File "", line 1, in locale.setlocale(locale.LC_ALL, (myISOCountryCode, locale.getpreferredencoding())) File "C:\apps\Python32\lib\locale.py", line 538, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting The snippet actually works on Linux, as you note. > It looks like you don't actually care about the encoding: in your first > example, you use the default system encoding, which you do not control, > and in your second example, you're using two different encodings on the > two platforms. That's true. That's because currently I care most about lists of strings being sorted properly (see below). Nevertheless, it *appears* to me that, in the Unicode era, the locales could well be decoupled from particular encodings. But this is another topic. > So why do you care whether or not the default uses ISO 8859-2 ? It's not that I care about encoding, it's that Windows throws locale.Error at me :-) > > My questions are the following: > > > 1. Is there a way for writing portable Python code dealing with > > locales > > ? ? (as sketched in the beginning)? > > > 2. If not, is there anything wrong with that idea? > > As I said, I believe the above code should work. It works on my Linux > system. > > What are you attempting to achieve with this setting of the locale, > without even setting the encoding? Doesn't it make more sense to simply > use the user's usual locale, and interact with them on their own terms? For the moment, I only wish to properly sort a Croatian text file both on Windows and Linux (I am a cautious guy, I like reachable goals). When the locale is properly set, sorting works like a charm with mylist.sort(key=locale.strxfrm). My current solution to the portability problem is: import locale try: locale.setlocale(locale.LC_ALL, 'hr_HR.utf8') # linux except locale.Error: locale.setlocale(locale.LC_ALL, 'Croatian_Croatia.1250') # windows Thanks for your feedback! Sinisa From hansmu at xs4all.nl Tue Sep 6 11:12:59 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Tue, 06 Sep 2011 17:12:59 +0200 Subject: Python marks an instance of my class undefined In-Reply-To: References: Message-ID: <4e66387b$0$2499$e4fe514c@news2.news.xs4all.nl> On 6/09/11 16:18:32, Laszlo Nagy wrote: > On 2011-09-06 15:42, Kayode Odeyemi wrote: >> I was able to get this solved by calling class like this: >> >> >>> from core.fleet import Fleet >> >>> f = Fleet() >> >> Thanks to a thread from the list titled "TypeError: 'module' object is >> not callable" > Or you can also do this: > > import core.fleet # import module core.fleet under the name core.fleet > f = core.fleet.Fleet() > > Please note that the import statement imports the module with the given > name. > > So for example > > import x.y.z > > will import the name "x.y.z". Anything that is in module "z" will be > available through its module, that is "x.y.z". > Whenever you use "import ", you have to access module contents > through "". > > You can change the name: > > import core.fleet as c # import module core.fleet under the name c > f = c.Fleet() An import statement always imports a module, but Python also has the from...import statement to import one item from a module: from core.fleet import Fleet f = Fleet() The convention is to use the name "Fleet" (with an initial capital) for the class and "fleet" (all lower case) for the module. This makes it easier to not confuse the class and the module. Hope this helps, -- HansM From sinisa.segvic at fer.hr Tue Sep 6 11:31:59 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Tue, 6 Sep 2011 08:31:59 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <13b9a70f-9e40-43a3-8198-0d84c8484fb8@z18g2000yqb.googlegroups.com> On 6 ruj, 15:13, Vlastimil Brom wrote: > There may be some differences btween OSes end the versions, but using > python 2.7 and 3.2 on Win XP and Win7 (Czech) > I get the following results for setlocale: > > >>> locale.setlocale(locale.LC_ALL,'Croatian') > > 'Croatian_Croatia.1250'>>> locale.getlocale() > > ('Croatian_Croatia', '1250') > > >>> locale.getpreferredencoding(do_setlocale=False) > 'cp1250' > > However, "hr" is not recognised on this systems: > > >>> locale.setlocale(locale.LC_ALL, "hr") > > Traceback (most recent call last): > ? File "", line 1, in > ? File "locale.pyc", line 531, in setlocale > Error: unsupported locale setting Thanks for your feedback! So this works only on Linux (in concordance with the documentation): locale.setlocale(locale.LC_ALL, ('croatian', locale.getpreferredencoding())) And this works only on Windows (incomplete locale spec probably filled in by Windows API): locale.setlocale(locale.LC_ALL, 'croatian') Obviously, there is a misunderstanding between Python which uses standard (IANA) language codes and Windows which, as usual, have their own ways :-( One possible solution would be to change locale.locale_alias on Windows so that it honors the custom Windows conventions: 'hr' -> 'Croatian_Croatia.1250' instead of 'hr' -> 'hr_HR.ISO8859-2' In addition, locale.getpreferredencoding() should probably be changed in order to return valid Windows encodings ('1250' instead of 'cp1250'). Cheers, Sinisa From t at jollybox.de Tue Sep 6 11:53:37 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 06 Sep 2011 17:53:37 +0200 Subject: Portable locale usage In-Reply-To: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <4E664201.1010806@jollybox.de> On 06/09/11 16:46, ssegvic wrote: > For the moment, I only wish to properly sort a Croatian text file > both on Windows and Linux (I am a cautious guy, I like reachable > goals). > When the locale is properly set, sorting works like a charm > with mylist.sort(key=locale.strxfrm). The problem with that is of course that a Croatian locale has to be installed. Many Linux systems don't have locales that aren't used. From PointedEars at web.de Tue Sep 6 12:07:42 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Tue, 06 Sep 2011 18:07:42 +0200 Subject: Floating point multiplication in python References: Message-ID: <2204592.egLE2XKegd@PointedEars.de> Thomas Rachel wrote: > Now if you multiply two values with an error, the error also propagates > into the result - PLUs the result can have its own error source - in the > same order of magnitude. > > (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e > or (2*a + e) * e. Your explanation about floating-point precision, which I already knew about but have only scanned here ? so it might be flawed as well ?, notwithstanding, it is not clear to me at all what you are trying to prove there. Computers (well, perhaps outside of mathematical software) do NOT compute an equation as humans would do, so the binomial theorem does NOT apply. In an algorithm of the real implementation, (a + e) * (a + e) would be computed as follows: b := a + e c := b * b or c := b + ? + b [add the value of `b' to the value of `b' (b?1) times, since binary logic does not support multiplication] IOW, the error does propagate into the result indeed, but not as you described. Indeed, thanks to rounding on assignment and multiplication (i. e., setting register values or IEEE-754 floating-point mantissa and exponent), the error will be different, probably greater than you compute here. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From josepharmbruster at gmail.com Tue Sep 6 12:17:19 2011 From: josepharmbruster at gmail.com (Joseph Armbruster) Date: Tue, 6 Sep 2011 12:17:19 -0400 Subject: PEP 20 - Silly Question? Message-ID: I have used Python for some time and ran a windows build-bot for a bit. This morning, I told a fellow developer "There should be only one obvious way to do it." and then I proceeded to forward him to the Zen of Python and sent him a link to: http://www.python.org/dev/peps/pep-0020/ I noticed that it says only 19 of 20 have been written down. Which one was not written down? Thank You, Joseph Armbruster -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericsnowcurrently at gmail.com Tue Sep 6 12:26:05 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Tue, 6 Sep 2011 10:26:05 -0600 Subject: PEP 20 - Silly Question? In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 10:17 AM, Joseph Armbruster wrote: > I have used Python for some time and ran a windows build-bot for a bit. > ?This morning, I told a fellow developer "There should be only one obvious > way to do it." and then I proceeded to forward him to the Zen of Python and > sent him a link to: > http://www.python.org/dev/peps/pep-0020/ > I noticed that it says only 19 of 20 have been written down. ?Which one was > not written down? I'm not sure there ever was a 20th. Apparently Tim Peters was going to leave the last one for Guido to fill in: http://mail.python.org/pipermail/python-list/1999-June/616160.html (from http://www.wefearchange.org/2010/06/import-this-and-zen-of-python.html) -eric > Thank You, > Joseph Armbruster > > -- > http://mail.python.org/mailman/listinfo/python-list > > From schesis at gmail.com Tue Sep 6 12:27:27 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 6 Sep 2011 12:27:27 -0400 Subject: PEP 20 - Silly Question? In-Reply-To: References: Message-ID: : On 6 September 2011 12:17, Joseph Armbruster wrote: > I noticed that it says only 19 of 20 have been written down. ?Which one was > not written down? The last one. -[]z. From __peter__ at web.de Tue Sep 6 12:54:42 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 06 Sep 2011 18:54:42 +0200 Subject: PEP 20 - Silly Question? References: Message-ID: Joseph Armbruster wrote: > I have used Python for some time and ran a windows build-bot for a bit. > This morning, I told a fellow developer "There should be only one obvious > way to do it." and then I proceeded to forward him to the Zen of Python > and sent him a link to: > http://www.python.org/dev/peps/pep-0020/ > > I noticed that it says only 19 of 20 have been written down. Which one > was not written down? Whoever offers a $1 billion sponsorship to the PSF gets to decide that one. Expect something like "Keep your baby real dry with black whole diapers". From Tim.Arnold at sas.com Tue Sep 6 13:18:07 2011 From: Tim.Arnold at sas.com (Tim Arnold) Date: Tue, 06 Sep 2011 13:18:07 -0400 Subject: sqlite3 with context manager In-Reply-To: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> References: <7dbe35af-9cc7-42a8-9288-465e542b9ea6@glegroupsg2000goo.googlegroups.com> Message-ID: On 9/3/2011 3:03 AM, Carl Banks wrote: > On Friday, September 2, 2011 11:43:53 AM UTC-7, Tim Arnold wrote: >> Hi, >> I'm using the 'with' context manager for a sqlite3 connection: >> >> with sqlite3.connect(my.database,timeout=10) as conn: >> conn.execute('update config_build set datetime=?,result=? >> where id=?', >> (datetime.datetime.now(), success, >> self.b['id'])) >> >> my question is what happens if the update fails? Shouldn't it throw an >> exception? > > If you look at the sqlite3 syntax documentation, you'll see it has a SQL extension that allows you to specify error semantics. It looks something like this: > > UPDATE OR IGNORE > UPDATE OR FAIL > UPDATE OR ROLLBACK > > I'm not sure exactly how this interacts with pysqlite3, but using one of these might help it throw exceptions when you want it to. > > > Carl Banks I see now. You can use 'update or fail' if you have the extensions built in: http://docs.python.org/library/sqlite3.html#f1 example of use, line 76: http://projects.developer.nokia.com/TECwidget/browser/data/montreal/updsqlite.py?rev=7ca2ebd301ed1eff0e2c28283470db060b872cd6 For my case, however, I'll follow Ian's advice and check on the rowcount after the update. thanks for the explanation and advice, --Tim From xnews2 at fredp.lautre.net Tue Sep 6 14:27:41 2011 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 06 Sep 2011 18:27:41 GMT Subject: Advice on how to get started with 2D-plotting ? Message-ID: Hi, I'm a Python long-timer, but I've never had to use tools like Matplotlib & others before. Now, for my work, I would need to learn the basics fast, for a one-time quick-n-dirty job. This involves a graphic comparison of RFC1918 IP subnets allocation across several networks. The idea is to draw parallel lines, with segments (subnets) coloured green, yellow or red depending on the conflicts between the networks. What would be the simplest/fastest way of getting this done ? (the graphic parts, the IP stuff I know how to handle) Alternately, if someone knows of a ready-made and accessible tool that does just that, I'm all ears :-) TIA, fp From fnautaNO at SPAMsolfon.nl Tue Sep 6 15:26:12 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Tue, 6 Sep 2011 21:26:12 +0200 Subject: Installing WebDAV server References: <9c9578F5eaU2@mid.individual.net><9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net> Message-ID: <9cnaekF5nfU1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.809.1315328739.27778.python-list at python.org... > On Tue, 6 Sep 2011 16:46:17 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > > >> ------------------------------------------- >> Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] >> on >> win32 >> Type "copyright", "credits" or "license()" for more information. >> >>> import os.path >> >>> os.path.isdir(path_name) >> >> Traceback (most recent call last): >> File "", line 1, in >> os.path.isdir(path_name) >> NameError: name 'path_name' is not defined >> >>> >> ------------------------------------------- >> > "path_name" is a placeholder -- you're supposed to put in the exact > string(s) you have been trying in the configuration file (wrap the > string in quotes). > >>>> import os.path >>>> os.path.isdir("e:\webdav") > False >>>> os.mkdir("e:\webdav") >>>> os.path.isdir("e:\webdav") > True >>>> os.path.isdir("e:\webdav\\") > Traceback ( File "", line 1 > os.path.isdir("e:\webdav\") > ^ > SyntaxError: EOL while scanning single-quoted string >>>> os.path.isdir("e:\webdav\\") > True >>>> os.path.isdir("e:\webdav/") > True >>>> os.path.isdir("e:/webdav/") > True >>>> os.path.isdir("e:/webdav") > True >>>> os.rmdir("e:/webdav") >>>> os.path.isdir("e:\webdav") > False >>>> > > Note that Python itself (and the C-runtime) doesn't care if the > separator is \ or / or even mixed; it is just the Windows command line > that uses \ for separator and / for options. (Python, however, uses \ as > an escape and \" is treated first, hence the need for \\" to escape the > \ itself) Thanks, this is clear. This is my Python shell: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import os.path >>> os.path.isdir("d:\webdav") True >>> So Python recognizes the directory d:\webdav This is the command shell: D:\Python27\WebDAV\PyWebDAV\DAVServer>server.py -n -c config.ini INFO:pywebdav:Starting up PyWebDAV server INFO:pywebdav:chunked_http_response feature ON INFO:pywebdav:http_request_use_iterator feature OFF INFO:pywebdav :http_response_use_iterator feature OFF INFO:fshandler:Initialized with D:/Webdav-http://10.0.0.140:8081/ WARNING:pywebdav:Authentication disabled! INFO:pywebdav:Serving data from D:/Webdav Listening on 10.0.0.140 <8081> (here I try to login the WebDAV server with the local IE browser) INFO:fshandler :get_data: D:\Webdav not found server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; Windows N T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; Windows N T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - So - I'm a bit lost now. Thinking seriously that my webdav installation is at fault. Fokke From bkasterm at gmail.com Tue Sep 6 16:15:03 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 14:15:03 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> Message-ID: <87obyx4ed4.fsf@gmail.com> I build on the suggestion by rantingrick, but took it in a bit different direction. I now have working code that performs reasonable. The reason for the class lines (as opposed to just a function) is b/c font.measure appears not that fast. So I want to remember between different calls to lines.count where the cutoff was, and then start looking from there. This one step of "optimization" was enough to make it run reasonable on my system. There are one important thing skipped, Tkinter.Label takes whitespace into account. This code does not yet. Also I just hacked this together as an example solution to work further from. import Tkinter as Tk import tkFont import random import sys def genstr (j): rno = random.randint(4,50) ret_val = str(j) + ":" for i in range (0, rno): ret_val += "hello" + str(i) return ret_val def gendata (lh): ret_val = [] for i in range(0,lh): ret_val.append (genstr (i)) return ret_val data = gendata (100) root = Tk.Tk() font = tkFont.Font(family='times', size=13) class lines: def __init__ (self): self.lastct = 1 # remember where the cutoff was last work from there def count (self, text, cutoff = 400): global font no_lines = 1 start_idx = 0 idx = self.lastct while True: if idx > len (text): idx = len (text) # shrink from guessed value while font.measure (text[start_idx:idx - 1]) > cutoff: if idx <= start_idx: print "error" sys.exit () else: idx -= 1 self.lastct = idx - start_idx # adjust since was too big # increase from guessed value (note: if first shrunk then done) while (idx < len (text) and font.measure (text[start_idx:idx]) < cutoff): idx += 1 self.lastct = idx - start_idx # adjust since was too small # next line has been determined print "*" + text[start_idx:idx-1] + "*" if idx == len(text) and font.measure (text[start_idx:]) < cutoff: return no_lines elif idx == len(text): return no_lines + 1 else: no_lines += 1 start_idx = idx - 1 idx = start_idx + self.lastct lin = lines() # for testing speed compute for all data for i in range(0,len(data)): lin.count(data[i], 450) # show only first 10 for i in range(0,min(len(data),10)): l = Tk.Label(root) l.pack() l['text'] = data[i] print i no = lin.count (data[i], 450) print "computed lines", no l['width'] = 50 l['justify'] = Tk.LEFT l['anchor'] = 'w' l['wraplength'] = 450 l['padx']=10 l['pady'] = 5 l['height'] = no l['font'] = font if i % 2 == 0: l['background'] = 'grey80' else: l['background'] = 'grey70' root.mainloop() From tjreedy at udel.edu Tue Sep 6 16:49:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 06 Sep 2011 16:49:19 -0400 Subject: Relative seeks on string IO In-Reply-To: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> References: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Message-ID: On 9/6/2011 3:18 AM, Pierre Quentel wrote: > I am wondering why relative seeks fail on string IO in Python 3.2 Good question. > from io import StringIO > txt = StringIO('Favourite Worst Nightmare') > txt.seek(8) # no problem with absolute seek Please post code without non-code indents, like so: from io import StringIO txt = StringIO('Favourite Worst Nightmare') txt.seek(8,0) # no problem with absolute seek txt.seek(0,1) # 0 characters from current position ok, and useless txt.seek(-2,2) # end-relative gives error message for cur-relative so someone can copy and paste without deleting indents. I verified with 3.2.2 on Win7. I am curious what 2.7 and 3.1 do. What system are you using? Does it have a narrow or wide unicode build? (IE, what is the value of sys.maxunicode?) > txt.seek(2,1) # 2 characters from current position > > raises "IOError: Can't do nonzero cur-relative seeks" (tested with > Python3.2.2 on WindowsXP) > > A seek relative to the end of the string IO raises the same IOError > Is there any reason why relative seeks on string IO are not allowed in > Python3.2, or is it a bug that could be fixed in a next version ? Since StringIO seeks by fixed-size code units (depending on the build), making seeking from the current position and end trivial, I consider this a behavior bug. At minimum, it is a doc bug. I opened http://bugs.python.org/issue12922 As noted there, I suspect the limitation in inherited from TextIOBase. But I challenge that it should be. I was somewhat surprised that seeking (from the start) is not limited to the existing text. Seeking past the end fills in with nulls. (They are typically a nuisance though.) from io import StringIO txt = StringIO('0123456789') txt.seek(15,0) # no problem with absolute seek txt.write('xxx') s = txt.getvalue() print(ord(s[12])) # 0 -- Terry Jan Reedy From garabik-news-2005-05 at kassiopeia.juls.savba.sk Tue Sep 6 16:58:09 2011 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Tue, 6 Sep 2011 20:58:09 +0000 (UTC) Subject: Portable locale usage References: Message-ID: Thomas Jollans wrote: > It looks like you don't actually care about the encoding: in your first > example, you use the default system encoding, which you do not control, > and in your second example, you're using two different encodings on the > two platforms. So why do you care whether or not the default uses ISO > 8859-2 ? > Maybe because using 8859-2 locale, (unicode) strings not representable in the encodings will be sorted - how? I would care, I prefer not to have undefined behaviour. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From rantingrick at gmail.com Tue Sep 6 16:59:41 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 13:59:41 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: <27d7b2a8-1a24-4066-b603-13c935c42af1@fd21g2000vbb.googlegroups.com> On Sep 6, 1:27?pm, Fred Pacquier wrote: > I'm a Python long-timer, but I've never had to use tools like Matplotlib & > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. ################## ## START SCRIPT ## ################## # # Easy_as.py # import Tkinter as tk # Create a main window and a canvas. app = tk.Tk() can = tk.Canvas( app, width=500, height=500, #bd=1, #relief=tk.SOLID, ) can.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) # Create some gridlines on the canvas. W,H = 500, 500 row, col = 0,0 for _ in range(10): can.create_line(0, row, W, row, fill='red') print 0, row, W, row can.create_line(col, 0, col, H, fill='green') row += 50 col += 50 can.create_line( 0,500,300,300, 350,200,400,450, fill='magenta', width=5, ) # Start the event loop. app.mainloop() ################ ## END SCRIPT ## ################ Any questions? From rantingrick at gmail.com Tue Sep 6 17:23:50 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 14:23:50 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> Message-ID: <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Hmm, i can replace all that code with this... # # Easy_as.py # import Tkinter as tk from ScrolledText import ScrolledText import tkFont import random # Create some puesdo data. data = [ '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) for x in range(100) ] ##print data # Create the main window and a scrolled text widget. root = tk.Tk() font = tkFont.Font(family='times', size=13) textbox = ScrolledText( root, width=60, height=20, font=('Times', 10), wrap=tk.WORD, ) textbox.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) textbox.insert(1.0, '\n\n'.join(data)) # Start the event loop. root.mainloop() # # End # From jabba.laci at gmail.com Tue Sep 6 17:25:32 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Tue, 6 Sep 2011 17:25:32 -0400 Subject: import os or import os.path Message-ID: Hi, If I want to use the 'os.path' module, it's enought to import 'os': import os if os.path.isfile('/usr/bin/bash'): print 'got it' In other source codes I noticed that people write 'import os.path' in this case. Which is better practice? Thanks, Laszlo From rantingrick at gmail.com Tue Sep 6 17:37:57 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 14:37:57 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Message-ID: Or if you prefer the alternating background approach... ################## # Easy_as.py ################## import Tkinter as tk from ScrolledText import ScrolledText import tkFont import random END = 'end' INSERT = 'insert' # # Create some puesdo data. data = [ '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) for x in range(100) ] ##print data # # Create the main window and a scrolled text widget. root = tk.Tk() font = tkFont.Font(family='times', size=13) textbox = ScrolledText( root, width=60, height=20, font=('Times', 10), wrap=tk.WORD, ) textbox.pack( fill=tk.BOTH, expand=True, padx=5, pady=5, ) # # Add a tag to the very end of the widget and # configure the tag only once! textbox.tag_add('one', END) textbox.tag_config('one', background='gray') # # Iterate over the lines stuffing them into the textbox. idata = iter(data) sidx = 1.0 while True: try: textbox.insert(END, idata.next()+"\n") textbox.tag_add('one', sidx, INSERT) textbox.insert(END, idata.next()+"\n") print sidx, textbox.index(END) sidx = textbox.index(INSERT) except StopIteration: break # # Start the event loop. root.mainloop() ################## # End ################## From ian.g.kelly at gmail.com Tue Sep 6 17:47:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 6 Sep 2011 15:47:57 -0600 Subject: import os or import os.path In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci wrote: > Hi, > > If I want to use the 'os.path' module, it's enought to import 'os': > > import os > if os.path.isfile('/usr/bin/bash'): > ? ?print 'got it' > > In other source codes I noticed that people write 'import os.path' in > this case. Which is better practice? "import os.path" is better practice. There is no guarantee in general that the os module will automatically import os.path, and in future versions or different implementations it might not. Cheers, Ian From neubyr at gmail.com Tue Sep 6 17:52:52 2011 From: neubyr at gmail.com (neubyr) Date: Tue, 6 Sep 2011 16:52:52 -0500 Subject: MIMEText encode error - Python 2.6.6 Message-ID: I am trying to write a program which can email file's content using smtplib. I am getting following error while using Python 2.6.6 version. {{{ File "./killed_jobs.py", line 88, in sendmail msg = MIMEText(ipfile.read, 'plain') File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", line 30, in __init__ self.set_payload(_text, _charset) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", line 224, in set_payload self.set_charset(charset) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", line 266, in set_charset cte(self) File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", line 73, in encode_7or8bit orig.encode('ascii') AttributeError: 'builtin_function_or_method' object has no attribute 'encode' }}} I am referring to email examples on the doc site http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples . Following is the msg object part in my code: {{{ ... ... def sendmail(inputfile): ipfile = open(inputfile, 'r') msg = MIMEText(ipfile.read, 'plain') ipfile.close() ... ... }}} I have tried setting subtype and chartype separately as mentioned here - http://docs.python.org/release/2.6.6/library/email.mime.html, but the error remains same. Any help on what might be wrong here? thanks, neuby.r From bkasterm at gmail.com Tue Sep 6 18:00:51 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 16:00:51 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> Message-ID: <87k49l49gs.fsf@gmail.com> rantingrick writes: > Hmm, i can replace all that code with this... Because I stupidly forgot to repeat the original problem I had, and my code doesn't show it (and doesn't show the correct use of the function I wrote). The code shows that I now know how to compute the number of lines and item will have; in the actual program I am developing I will take the max of these numbers and make all items that height. This means the code I should have shown is as follows (here I first compute the maximum height needed for any item, and then show all items using this height). Also in the actual program there will be scrolling options to change the item shown by the different labels. import Tkinter as Tk import tkFont import random import sys def genstr (j): rno = random.randint(4,50) ret_val = str(j) + ":" for i in range (0, rno): ret_val += "hello" + str(i) return ret_val def gendata (lh): ret_val = [] for i in range(0,lh): ret_val.append (genstr (i)) return ret_val data = gendata (100) root = Tk.Tk() font = tkFont.Font(family='times', size=13) class lines: def __init__ (self): self.lastct = 1 # remember where the cutoff was last work from there def count (self, text, cutoff = 400): global font no_lines = 1 start_idx = 0 idx = self.lastct while True: if idx > len (text): idx = len (text) # shrink from guessed value while font.measure (text[start_idx:idx - 1]) > cutoff: if idx <= start_idx: print "error" sys.exit () else: idx -= 1 self.lastct = idx - start_idx # adjust since was too big # increase from guessed value (note: if first shrunk then done) while (idx < len (text) and font.measure (text[start_idx:idx]) < cutoff): idx += 1 self.lastct = idx - start_idx # adjust since was too small # next line has been determined print "*" + text[start_idx:idx-1] + "*" if idx == len(text) and font.measure (text[start_idx:]) < cutoff: return no_lines elif idx == len(text): return no_lines + 1 else: no_lines += 1 start_idx = idx - 1 idx = start_idx + self.lastct lin = lines() max_ht = 0 for i in range(0,len(data)): ct = lin.count(data[i], 450) if ct > max_ht: max_ht = ct for i in range(0,min(len(data),5)): l = Tk.Label(root) l.pack() l['text'] = data[i] l['width'] = 50 l['justify'] = Tk.LEFT l['anchor'] = 'w' l['wraplength'] = 450 l['padx']=10 l['pady'] = 5 l['height'] = max_ht l['font'] = font if i % 2 == 0: l['background'] = 'grey80' else: l['background'] = 'grey70' root.mainloop() > > # > # Easy_as.py > # > import Tkinter as tk > from ScrolledText import ScrolledText > import tkFont > import random > # Create some puesdo data. > data = [ > '{0}.{1}'.format(x, 'blah'*random.randint(4, 50)) > for x in range(100) > ] > ##print data > # Create the main window and a scrolled text widget. > root = tk.Tk() > font = tkFont.Font(family='times', size=13) > textbox = ScrolledText( > root, > width=60, > height=20, > font=('Times', 10), > wrap=tk.WORD, > ) > textbox.pack( > fill=tk.BOTH, > expand=True, > padx=5, > pady=5, > ) > textbox.insert(1.0, '\n\n'.join(data)) > # Start the event loop. > root.mainloop() > # > # End > # From python at mrabarnett.plus.com Tue Sep 6 18:05:20 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 06 Sep 2011 23:05:20 +0100 Subject: MIMEText encode error - Python 2.6.6 In-Reply-To: References: Message-ID: <4E669920.3010704@mrabarnett.plus.com> On 06/09/2011 22:52, neubyr wrote: > I am trying to write a program which can email file's content using > smtplib. I am getting following error while using Python 2.6.6 > version. > > {{{ > File "./killed_jobs.py", line 88, in sendmail > msg = MIMEText(ipfile.read, 'plain') > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", > line 30, in __init__ > self.set_payload(_text, _charset) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", > line 224, in set_payload > self.set_charset(charset) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", > line 266, in set_charset > cte(self) > File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", > line 73, in encode_7or8bit > orig.encode('ascii') > AttributeError: 'builtin_function_or_method' object has no attribute 'encode' > > }}} > > > I am referring to email examples on the doc site > http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples > . Following is the msg object part in my code: > > {{{ > ... > ... > def sendmail(inputfile): > ipfile = open(inputfile, 'r') > msg = MIMEText(ipfile.read, 'plain') > ipfile.close() > > ... > ... > }}} > > I have tried setting subtype and chartype separately as mentioned here > - http://docs.python.org/release/2.6.6/library/email.mime.html, but > the error remains same. Any help on what might be wrong here? > The docs say: MIMEText(_text[, _subtype[, _charset]]) ... _text is the string for the payload ... You're passing ipfile.read, which is the read method of the file. You should be passing the string returned by calling ipfile.read, ie ipfile.read(). From rantingrick at gmail.com Tue Sep 6 18:40:08 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 15:40:08 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: On Sep 6, 5:00?pm, Bart Kastermans wrote: > rantingrick writes: > > Hmm, i can replace all that code with this... > > Because I stupidly forgot to repeat the original problem I had, and my > code doesn't show it (and doesn't show the correct use of the function I > wrote). Oh NOW i see! This new code you posted is like night and day compared to the original :o) Anyway, i did not read the code to find the difference because i want to know why you insist on using multiple labels for this when a scrolled text will suffice. Are you trying to create some sort of textual "animation frames" that you can flip through on demand? If not i would use the scrolled text (and even the scrolled text can "feel" like animation frames whist scrolling). Take your input data and replace ALL single newlines with null strings (thereby preserving paragraphs) and let the textbox control the line wrapping. The benefits are enormous using my way; your way is limited and requires re-inventing the wheel. Tell me WHY the textbox approach is not a viable solution and THEN i'll listen to you. Until then; you can lead a horse to water... From rantingrick at gmail.com Tue Sep 6 18:43:58 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 6 Sep 2011 15:43:58 -0700 (PDT) Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: <700374dd-49ff-4f0a-8c22-198bff6b7b42@k15g2000yqd.googlegroups.com> On Sep 6, 5:40?pm, rantingrick wrote: > On Sep 6, 5:00?pm, Bart Kastermans wrote: > Take your input data and replace ALL single newlines with null strings CORRECTION: Take your input data and replace ALL single newlines with A SINGLE SPACE From bkasterm at gmail.com Tue Sep 6 20:33:32 2011 From: bkasterm at gmail.com (Bart Kastermans) Date: Tue, 06 Sep 2011 18:33:32 -0600 Subject: Tkinter label height to fit content References: <87mxelgtmx.fsf@gmail.com> <69ce4e11-5ef4-4b81-b66b-87d1017b1ec3@s7g2000yqk.googlegroups.com> <87obz0w0ze.fsf@gmail.com> <8d7cf6e4-5794-4f57-88ae-b0d0dcfd68a6@d25g2000yqh.googlegroups.com> <87obyx4ed4.fsf@gmail.com> <8777abed-e2b1-469e-96e5-662c535220be@y21g2000yqy.googlegroups.com> <87k49l49gs.fsf@gmail.com> Message-ID: <8762l5jin7.fsf@gmail.com> rantingrick writes: > On Sep 6, 5:00?pm, Bart Kastermans wrote: >> rantingrick writes: >> > Hmm, i can replace all that code with this... >> >> Because I stupidly forgot to repeat the original problem I had, and my >> code doesn't show it (and doesn't show the correct use of the function I >> wrote). > > Oh NOW i see! This new code you posted is like night and day compared > to the original :o) Quite, I should know better (I deal with students thinking what is in their mind should be clear to me all the time): ############################################## # run through all the data we have, compute the maximum height max_ht = 0 for i in range(0,len(data)): # lin.count is the line counting function ct = lin.count(data[i], 450) if ct > max_ht: max_ht = ct for i in range(0,min(len(data),5)): # l is the Tkinter.Label with all formatting applied and data[i] # set for text l['height'] = max_ht # use this maximum height for all Labels. ############################################### Thinking on this some more, the first computation should surely be max_ht = max (map (lambda x: lin.count(x, 450), data)) The second one could then be labels = map (label_prepare_pack, data[:5]) where label_prepare_pack prepares (sets all attributes and data), packs, and returns the new label. The first (for max_ht) is a clear improvement to me, the second (for labels) uses too many side-effects to be very appealing to me. > Anyway, i did not read the code to find the difference because i want > to know why you insist on using multiple labels for this when a > scrolled text will suffice. Are you trying to create some sort of > textual "animation frames" that you can flip through on demand? I don't follow precisely, but I am indeed looking to flip through all of data while showing only 5 or 10 at a time. The problem I wanted to solve was that my window kept changing size while doing this. > If not > i would use the scrolled text (and even the scrolled text can "feel" > like animation frames whist scrolling). > > Take your input data and replace ALL single newlines with null strings > (thereby preserving paragraphs) and let the textbox control the line > wrapping. The benefits are enormous using my way; your way is limited > and requires re-inventing the wheel. Tell me WHY the textbox approach > is not a viable solution and THEN i'll listen to you. The reason I thought this, was that I didn't realize I could bind actions to tags (to get different actions for different bits of text). Now that I do know this I could use code like my lin.count to get the maximum height still (to get a constant location for the i-th item as the items are changed; more importantly to get a constant height for the whole list of items), and then use tags to bind the corresponding actions. > Until then; you can lead a horse to water... I certainly appreciate your trying. I might not see the fresh stream yet, but I do see liquid (possibly a shallow muddy pool, but big progress from the dry sandy dunes before). I will keep both approaches in mind as I further develop. Again, thanks for the help, greatly appreciated. From ben+python at benfinney.id.au Tue Sep 6 20:36:05 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 07 Sep 2011 10:36:05 +1000 Subject: PEP 20 - Silly Question? References: Message-ID: <877h5lnq8a.fsf@benfinney.id.au> Zero Piraeus writes: > On 6 September 2011 12:17, Joseph Armbruster wrote: > > I noticed that it says only 19 of 20 have been written down. ?Which > > one was not written down? > > The last one. I always thought it was the first one. Or the 6.25th one, I forget. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From nobody at nowhere.com Tue Sep 6 21:01:11 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 07 Sep 2011 02:01:11 +0100 Subject: Can't use subprocess.Popen() after os.chroot() - why? References: Message-ID: On Sun, 04 Sep 2011 07:22:07 -0700, Erik wrote: > I'm trying to do the following: > os.chroot("/tmp/my_chroot") > p = Popen("/bin/date", stdin=PIPE, stdout=PIPE, stderr=PIPE) > but the Popen call is dying with the following exception: > LookupError: unknown encoding: string-escape > > Am I missing something here? does the chroot environment need to be > populated with more than just the date executable in this case? Yes. It also needs to include any parts of the Python run-time which Python will try to load while executing subsequent code. In this case, the module which implements the string-escape encoding. But fixing that will probably show up yet more files which need to exist within the pseudo-root. E.g. any shared libraries which the executable needs (probably at least libc), and any data files which those libraries need (in the case of /bin/date, it may need /etc/timezone; many programs may require locale data if you aren't in the "C" locale, and so on). Whether from Python or from C, chroot() requires a good understanding of the low-level details of your operating system. If you don't know how to build a minimal Linux distribution from scratch, you're going to have to learn many of those details in order to use chroot(). For any non-trivial chroot() usage, it's often easier to install a small newlib+busybox-based Linux distribution under the pseudo-root than to try to re-use files from and existing (presumably glibc+coreutils-based) desktop/server distribution. From skippy.hammond at gmail.com Tue Sep 6 21:11:55 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 07 Sep 2011 11:11:55 +1000 Subject: import os or import os.path In-Reply-To: References: Message-ID: <4E66C4DB.7080008@gmail.com> On 7/09/2011 7:47 AM, Ian Kelly wrote: > On Tue, Sep 6, 2011 at 3:25 PM, Jabba Laci wrote: >> Hi, >> >> If I want to use the 'os.path' module, it's enought to import 'os': >> >> import os >> if os.path.isfile('/usr/bin/bash'): >> print 'got it' >> >> In other source codes I noticed that people write 'import os.path' in >> this case. Which is better practice? > > "import os.path" is better practice. There is no guarantee in general > that the os module will automatically import os.path, and in future > versions or different implementations it might not. That's probably a matter of opinion - eg, http://docs.python.org/tutorial/interpreter.html has an example of importing the os module then accessing os.path. Personally I think directly importing os.path is a waste of precious keystrokes ;) Cheers, Mark. From python at mrabarnett.plus.com Tue Sep 6 21:25:56 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 07 Sep 2011 02:25:56 +0100 Subject: PEP 20 - Silly Question? In-Reply-To: <877h5lnq8a.fsf@benfinney.id.au> References: <877h5lnq8a.fsf@benfinney.id.au> Message-ID: <4E66C824.6010008@mrabarnett.plus.com> On 07/09/2011 01:36, Ben Finney wrote: > Zero Piraeus writes: > >> On 6 September 2011 12:17, Joseph Armbruster wrote: >>> I noticed that it says only 19 of 20 have been written down. Which >>> one was not written down? >> >> The last one. > > I always thought it was the first one. Or the 6.25th one, I forget. > Or the zeroth one. From milleja46 at gmail.com Tue Sep 6 21:31:52 2011 From: milleja46 at gmail.com (Joshua Miller) Date: Tue, 6 Sep 2011 21:31:52 -0400 Subject: PEP 20 - Silly Question? In-Reply-To: <4E66C824.6010008@mrabarnett.plus.com> References: <877h5lnq8a.fsf@benfinney.id.au> <4E66C824.6010008@mrabarnett.plus.com> Message-ID: You sure it wasn't the invisible one? you know the one in the white text that blends into the background? On Tue, Sep 6, 2011 at 9:25 PM, MRAB wrote: > On 07/09/2011 01:36, Ben Finney wrote: >> >> Zero Piraeus ?writes: >> >>> On 6 September 2011 12:17, Joseph Armbruster >>> ?wrote: >>>> >>>> I noticed that it says only 19 of 20 have been written down. ?Which >>>> one was not written down? >>> >>> The last one. >> >> I always thought it was the first one. Or the 6.25th one, I forget. >> > Or the zeroth one. > -- > http://mail.python.org/mailman/listinfo/python-list > From tyler at tysdomain.com Tue Sep 6 22:19:37 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Tue, 06 Sep 2011 20:19:37 -0600 Subject: Looking for open-source Python projects to help out with Message-ID: <4E66D4B9.9050402@tysdomain.com> Hello: I've got a bit of time on my hands, so I'm curious what sorts of projects there are that people needs help with. I'd like to choose something that doesn't have a ton of red tape, but is stable, which is why I ask here instead of just Googling open source projects. My main interests lie in accessibility, Utilities and security. -- Take care, ~Ty Web: http://tds-solutions.net Sent from my toaster. From wolftracks at invalid.com Tue Sep 6 22:43:23 2011 From: wolftracks at invalid.com (W. eWatson) Date: Tue, 06 Sep 2011 19:43:23 -0700 Subject: strange thing: In-Reply-To: References: Message-ID: CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in my spam on the net. From rosuav at gmail.com Tue Sep 6 22:48:21 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 7 Sep 2011 12:48:21 +1000 Subject: strange thing: In-Reply-To: References: Message-ID: On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson wrote: > CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in > my spam on the net. No, I didn't; as someone else pointed out, you'll get better results asking on a dedicated Fortran list. ChrisA From goon12 at gmail.com Tue Sep 6 23:49:34 2011 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 6 Sep 2011 23:49:34 -0400 Subject: import os or import os.path In-Reply-To: References: Message-ID: On Tue, Sep 6, 2011 at 5:25 PM, Jabba Laci wrote: > Hi, > > If I want to use the 'os.path' module, it's enought to import 'os': > > import os > if os.path.isfile('/usr/bin/bash'): > ? ?print 'got it' > > In other source codes I noticed that people write 'import os.path' in > this case. Which is better practice? I just followed what the help said: "" DESCRIPTION Instead of importing this module directly, import os and refer to this module as os.path. "" From casevh at gmail.com Tue Sep 6 23:58:29 2011 From: casevh at gmail.com (casevh) Date: Tue, 6 Sep 2011 20:58:29 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> Message-ID: <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> On Sep 6, 6:37?am, jmfauth wrote: > This is just an attempt to put thehttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > discussion at a correct level. > > With Python 2.7 a new float number representation (the David Gay's > algorithm) > has been introduced. If this is well honored in Python 2.7, it > seems to me, there are some missmatches in the Py3 series. > > >>> sys.version > > '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit > (Intel)]' > > >>> 0.1 > 0.10000000000000001 > >>> print 0.1 > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print 1.1 * 1.1 > 1.21 > >>> print repr(1.1 * 1.1) > 1.2100000000000002 > > >>> sys.version > > 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] > > > > >>> 0.1 > 0.1 > >>> print 0.1 > 0.1 > >>> 1.1 * 1.1 > 1.21 > >>> print 1.1 * 1.1 > 1.21 > >>> print repr(1.1 * 1.1) > 1.2100000000000002 > I tried this with the same version of Python and I get: >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> 1.1 * 1.1 1.2100000000000002 >>> print 1.1 * 1.1 1.21 >>> print repr(1.1 * 1.1) 1.2100000000000002 >>> > >>> sys.version > > '3.1.4 (default, Jun 12 2011, 15:05:44) [MSC v.1500 32 bit (Intel)]'>>> 0.1 > 0.1 > >>> print(0.1) > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print(1.1 * 1.1) > 1.21 > >>> print(repr(1.1 * 1.1)) > 1.2100000000000002 > >>> '{:g}'.format(1.1 * 1.1) > > '1.21' > > >>> sys.version > > '3.2.2 (default, Sep ?4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' > > >>> 0.1 > 0.1 > >>> print(0.1) > 0.1 > >>> 1.1 * 1.1 > 1.2100000000000002 > >>> print (1.1 * 1.1) > 1.2100000000000002 > >>> print(repr((1.1 * 1.1))) > 1.2100000000000002 > > >>> '{:g}'.format(1.1 * 1.1) > '1.21' > I get same results as you do for Python 3.1.4 and 3.2.2. IIRC, Python 3.2 changed (for floats) __str__ to call __repr__. That should explain the difference between 3.1.4 and 3.2.2 Also note that 1.1 * 1.1 is not the same as 1.21. >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301, 4503599627370496) >>> (1.21).as_integer_ratio() (1362338887279575, 1125899906842624) This doesn't explain why 2.7.2 displayed a different result on your computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and (1.21)? casevh > jmf From steve+comp.lang.python at pearwood.info Wed Sep 7 00:51:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 07 Sep 2011 14:51:13 +1000 Subject: Floating point multiplication in python References: <2204592.egLE2XKegd@PointedEars.de> Message-ID: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> On Wed, 7 Sep 2011 02:07 am Thomas 'PointedEars' Lahn wrote: > Thomas Rachel wrote: > >> Now if you multiply two values with an error, the error also propagates >> into the result - PLUs the result can have its own error source - in the >> same order of magnitude. >> >> (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e >> or (2*a + e) * e. > > Your explanation about floating-point precision, which I already knew > about but have only scanned here ? so it might be flawed as well ?, > notwithstanding, it is not clear to me at all what you are trying to prove > there. > > Computers (well, perhaps outside of mathematical software) do NOT compute > an equation as humans would do, so the binomial theorem does NOT apply. I think you have misunderstood. The binomial theorem always applies. Any time you multiply two numbers, both numbers can always be re-written as a sum of two numbers: 10*5 = (6+4)*(2+3) So a perfect square can always be re-written in the form where the binomial theorem applies: 5*5 = (2+3)*(2+3) 25 = 2*2 + 2*3 + 3*2 + 3*3 25 = 4 + 6 + 6 + 9 25 = 25 The binomial theorem is not a part of the algorithm for performing multiplication. It is part of the analysis of the errors that occur during multiplication. The actual mechanics of how bits are flipped is irrelevant. Any floating point number x should be considered as equal to (a+e), where a is the number actually wanted by the user, and e the error term forced upon the user by the use of binary floats. (If you're lucky, e=0.) Generally, both a and e are unknown, but of course their sum is known -- it's just the float x. So given a float x, when you square it you get this: Exact values: a*a = a**2 Float values: x*x = (a+e)(a+e) = a**2 + 2*a*e + e**2 So the error term has increased from e to (2*a*e+e**2). It is usual to assume that e**2 is small enough that it underflows to zero, so we have the error term e increasing to 2*a*e as a fairly simple estimate of the new error. > In an algorithm of the real implementation, > > (a + e) * (a + e) > > would be computed as follows: > > b := a + e > c := b * b > or > c := b + ? + b > > [add the value of `b' to the value of `b' (b?1) times, since binary logic > does not support multiplication] What you probably mean to say is that binary hardware usually implements multiplication via repeated addition. http://en.wikipedia.org/wiki/Binary_multiplier If you don't mean that, I can't imagine what you are trying to say. Multiplication of numbers exists in any base, binary no less than decimal. > IOW, the error does propagate into the result indeed, but not as you > described. Indeed, thanks to rounding on assignment and multiplication > (i. e., setting register values or IEEE-754 floating-point mantissa and > exponent), the error will be different, probably greater than you compute > here. There may be other sources of error, particularly when multiplying two numbers of greatly different magnitudes, but that doesn't invalidate Thomas Rachel's point (which is only an estimate, of course). We can see how much error is actually there by using exact arithmetic: Error in float 1.1: >>> from fractions import Fraction as F >>> >>> a = F(11, 10) >>> x = F.from_float(1.1) >>> e = x - a >>> print e 1/11258999068426240 Error in float 1.1*1.1: >>> b = F(11, 10)**2 >>> y = F.from_float(1.1**2) >>> f = y - b >>> print f 21/112589990684262400 which is slightly more than double e above, and slightly less than our estimate of 2*a*e = 11/56294995342131200 So we can conclude that, at least for 1.1**2, Python floats are more accurate than we would expect from a simple application of the binomial theorem. (For implementations using IEEE doubles.) -- Steven From wolftracks at invalid.com Wed Sep 7 01:08:11 2011 From: wolftracks at invalid.com (W. eWatson) Date: Tue, 06 Sep 2011 22:08:11 -0700 Subject: strange thing: In-Reply-To: References: Message-ID: On 9/6/2011 7:48 PM, Chris Angelico wrote: > On Wed, Sep 7, 2011 at 12:43 PM, W. eWatson wrote: >> CA, Did you respond to my off-NG msg about FORTRAN? Perhaps it's caught in >> my spam on the net. > > No, I didn't; as someone else pointed out, you'll get better results > asking on a dedicated Fortran list. > > ChrisA OK. From cmpython at gmail.com Wed Sep 7 01:56:10 2011 From: cmpython at gmail.com (CM) Date: Tue, 6 Sep 2011 22:56:10 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) AFAIK, probably Matplotlib. I'm not sure what quite to imagine for your plot but below is code that makes an attempt at (maybe) something like you are describing, shown here: http://www.flickr.com/photos/67254913 at N07/6123112552/in/photostream#/ There are smarter ways to do this in matplotlib, but this is pretty quick and dirty. I'm just plotting lines over-top other lines. The pic I put is the plot as a .png, which matplotlib makes if you want, but you can also view it in a frame that matplotlib generates and then pan/zoom/etc... from pylab import * x = [1,2,3,4,5,6,7,8] y = [2 for num in x] #plot the parallel lines themselves in green for num in range(6): y = [num for item in x] plot(x,y,color='g',lw='4') #plot any conflict sections in red or yellow #some hard data to give the idea: x2 = [3,4] y2 = [2 for num in x2] x3 = [5,6,7] y3 = [4 for num in x3] x4 = [2,3] y4 = [3 for num in x4] #plot these three colored parts over the green lines plot(x2,y2,color='r',lw='12') plot(x3,y3,color='yellow',lw='12') plot(x4,y4,color='r',lw='12') pos = arange(6) yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6')) show() #------------------------- Che From cmpython at gmail.com Wed Sep 7 02:00:58 2011 From: cmpython at gmail.com (CM) Date: Tue, 6 Sep 2011 23:00:58 -0700 (PDT) Subject: Advice on how to get started with 2D-plotting ? References: Message-ID: On Sep 6, 2:27?pm, Fred Pacquier wrote: > Hi, > > I'm a Python long-timer, but I've never had to use tools like Matplotlib & > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) One fairly simple way is with Matplotlib. Not sure what quite to imagine for your plot but below is code that makes an attempt at (maybe) something like you are describing, shown here: http://www.flickr.com/photos/67254913 at N07/6123112552/in/photostream#/ There are fancier ways to do this in Matplotlib, but this is pretty quick and dirty--I'm just plotting lines over-top other lines. The pic I put is the plot as a .png, which matplotlib makes if you want, but you can also view it in a frame that matplotlib generates and then pan/zoom/etc... This is using the pylab module, but you could also embed your plots in a GUI if you prefer. from pylab import * #plot the parallel lines in green x = [1,2,3,4,5,6,7,8] y = [2 for num in x] for num in range(6): y = [num for item in x] plot(x,y,color='g',lw='4') #plot any conflict sections in red or yellow #...some data to give the idea: x2 = [3,4] y2 = [2 for num in x2] x3 = [5,6,7] y3 = [4 for num in x3] x4 = [2,3] y4 = [3 for num in x4] #plot three colored parts over the green lines plot(x2,y2,color='r',lw='12') plot(x3,y3,color='yellow',lw='12') plot(x4,y4,color='r',lw='12') #change y labels to meaningful labels pos = arange(6) yticks(pos, ('net1', 'net2', 'net3', 'net4', 'net5', 'net6')) show() #------------------------- Che From wxjmfauth at gmail.com Wed Sep 7 02:32:07 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 6 Sep 2011 23:32:07 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> Message-ID: <6091df75-58e4-4316-8f3c-957b53c24490@dq7g2000vbb.googlegroups.com> On 7 sep, 05:58, casevh wrote: > ... > > Also note that 1.1 * 1.1 is not the same as 1.21. > > >>> (1.1 * 1.1).as_integer_ratio() > > (5449355549118301, 4503599627370496)>>> (1.21).as_integer_ratio() > > (1362338887279575, 1125899906842624) > > This doesn't explain why 2.7.2 displayed a different result on your > computer. What do you get for as_integer_ratio() for (1.1 * 1.1) and > (1.21)? > Sure. I just picked up these numbers/expressions by chance. They came to my mind following the previous discussion. Sticking with the latest versions: >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301L, 4503599627370496L) >>> (1.21).as_integer_ratio() (1362338887279575L, 1125899906842624L) >>> >>> sys.version '3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]' >>> (1.1 * 1.1).as_integer_ratio() (5449355549118301, 4503599627370496) >>> (1.21).as_integer_ratio() (1362338887279575, 1125899906842624) >>> Has "long" not disappeared 2.7? I have not the skill to dive into the machinery. I have only some theroretical understanding and I'm a little bit confused and have to face "there something strange somewhere". Test on Windows 7, 32 bits. jmf From mdickinson at enthought.com Wed Sep 7 02:56:42 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Tue, 6 Sep 2011 23:56:42 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> Message-ID: <6aec0187-2fa1-49ae-b2c0-fb0a10ec443c@br5g2000vbb.googlegroups.com> On Sep 7, 4:58?am, casevh wrote: > IIRC, Python > 3.2 changed (for floats) __str__ to call __repr__. Yes, exactly: str and repr of a float are identical in Python 3.2 + I'm also puzzled by the 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] [...] >>> 1.1 * 1.1 1.21 in jmf's message. Cut-and-paste typo? -- Mark From pierre.quentel at gmail.com Wed Sep 7 03:00:24 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Wed, 7 Sep 2011 00:00:24 -0700 (PDT) Subject: Relative seeks on string IO References: <48a795dc-992f-4665-9ada-60b2807fc3b8@u19g2000vbm.googlegroups.com> Message-ID: <30c6f7f0-b846-47a9-be49-e234a8bb8c16@e9g2000yqb.googlegroups.com> > > Please post code without non-code indents, like so: > Sorry about that. After the line "Example :" I indented the next block, out of habit ;-) > > What system are you using? Does it have a narrow or wide unicode build? > (IE, what is the value of sys.maxunicode?) > I use Windows XP Pro, version 2002, SP3. sys.maxunicode is 65535 I have the same behaviour with 3.1.1 and with 2.7 I don't understand why variable sized code units would cause problems. On text file objects, read(nb) reads nb characters, regardless of the number of bytes used to encode them, and tell() returns a position in the text stream just after the next (unicode) character read As for SringIO, a wrapper around file objects simulates a correct behaviour for relative seeks : ==================== txt = "abcdef" txt += "????? ??? ??????" txt += "?????" txt += "endof file" out = open("test.txt","w",encoding="utf-8") out.write(txt) out.close() fobj = open("test.txt",encoding="utf-8") fobj.seek(3) try: fobj.seek(2,1) except IOError: print('raises IOError') class _file: def __init__(self,file_obj): self.file_obj = file_obj def read(self,nb=None): if nb is None: return self.file_obj.read() else: return self.file_obj.read(nb) def seek(self,offset,whence=0): if whence==0: self.file_obj.seek(offset) else: if whence==2: # read till EOF while True: buf = self.file_obj.read() if not buf: break self.file_obj.seek(self.file_obj.tell()+offset) fobj = _file(open("test.txt",encoding="utf-8")) fobj.seek(3) fobj.seek(2,1) fobj.seek(-5,2) print(fobj.read(3)) ========================== - Pierre From herbert.weinhandl at oeaw.ac.at Wed Sep 7 03:14:57 2011 From: herbert.weinhandl at oeaw.ac.at (Weinhandl Herbert) Date: Wed, 07 Sep 2011 09:14:57 +0200 Subject: Advice on how to get started with 2D-plotting ? In-Reply-To: References: Message-ID: <4e6719f1$0$38260$3b214f66@aconews.univie.ac.at> Am 06.09.2011 20:27, schrieb Fred Pacquier: > Hi, > > I'm a Python long-timer, but I've never had to use tools like Matplotlib& > others before. > > Now, for my work, I would need to learn the basics fast, for a one-time > quick-n-dirty job. > > This involves a graphic comparison of RFC1918 IP subnets allocation across > several networks. > maybe networkx http://pypi.python.org/pypi/networkx/1.5 http://networkx.lanl.gov/ is a better solution for your problem or http://pypi.python.org/pypi/graphcanvas/4.0.0 > The idea is to draw parallel lines, with segments (subnets) coloured green, > yellow or red depending on the conflicts between the networks. > > What would be the simplest/fastest way of getting this done ? > (the graphic parts, the IP stuff I know how to handle) > > Alternately, if someone knows of a ready-made and accessible tool that does > just that, I'm all ears :-) > > TIA, > fp hth Herbert From Shambhu.Rajak at kpitcummins.com Wed Sep 7 03:25:28 2011 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Wed, 7 Sep 2011 07:25:28 +0000 Subject: Prequisites required to learn Django frame work Message-ID: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> Hi, I have been doing python development since last year, I think I should learn the famous Django frame work. Can any one suggest what are the perquisite required to setup django on my local home machine. Please suggest something that does not require a separate server, as this is a personal interest of mine. Thanks, Shambhu -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Wed Sep 7 03:39:51 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 7 Sep 2011 17:39:51 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: Hi Tyler, I'm currently working on building a new kind of social-network for Users-Groups, Game-Clans & Student-Groups. Building it using DJango with Pinax. Detailed Feature-Set (planned): ? Event management ? Conference management (including ticketing with payment-gateway integration) ? Video+Audio Conferencing of event, with online interaction possibilitiy (great for webinars) ? Join/create/delete/list groups ? Sitewide calendar ? Sitewide feed from non-private groups ? SSO integration (facebook, twitter & linkedin) ? Wall (+feed) for each group ? Listing of who's in which group ? PM group members I will probably be releasing it under the New BSD license, although I'm happy to consider others given a good argument. Interested? On Wed, Sep 7, 2011 at 12:19 PM, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of projects > there are that people needs help with. I'd like to choose something that > doesn't have a ton of red tape, but is stable, which is why I ask here > instead of just Googling open source projects. My main interests lie in > accessibility, Utilities and security. > > -- > > Take care, > ~Ty > Web: http://tds-solutions.net > > Sent from my toaster. > > -- > http://mail.python.org/mailman/listinfo/python-list > From wxjmfauth at gmail.com Wed Sep 7 04:21:20 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Wed, 7 Sep 2011 01:21:20 -0700 (PDT) Subject: Representation of floats (-> Mark Dickinson?) References: <2baa3e30-cfa4-4ada-b881-9f94674c5b9f@l4g2000vbv.googlegroups.com> <6c2f34a4-8a0a-4744-89f1-32cf1c0dee27@o9g2000vbo.googlegroups.com> <6aec0187-2fa1-49ae-b2c0-fb0a10ec443c@br5g2000vbb.googlegroups.com> Message-ID: On 7 sep, 08:56, Mark Dickinson wrote: > On Sep 7, 4:58?am, casevh wrote: > > > IIRC, Python > > 3.2 changed (for floats) __str__ to call __repr__. > > Yes, exactly: ?str and repr of a float are identical in Python 3.2 + > > I'm also puzzled by the > > 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] > [...]>>> 1.1 * 1.1 > > 1.21 > > in jmf's message. ?Cut-and-paste typo? > > -- > Mark No. But, it's *my* mistake. I'm using a modified sys.displayhook which uses a print statement (mainly for language reason). If forgot to reset to the initial/default state for these tests when working with too many opened interactive interpreters. Sorry for the noise. >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> >>> 1.1 * 1.1 1.21 >>> '?l?phant' ?l?phant >>> >>> sys.displayhook = sys.__displayhook__ >>> 1.1 * 1.1 1.2100000000000002 >>> '?l?phant' '\xe9l\xe9phant' >>> sys.version '2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]' >>> jmf From fayaz.yusuf.khan at gmail.com Wed Sep 7 04:32:48 2011 From: fayaz.yusuf.khan at gmail.com (Fayaz Yusuf Khan) Date: Wed, 7 Sep 2011 14:02:48 +0530 Subject: Looking for open-source Python projects to help out with In-Reply-To: References: <4E66D4B9.9050402@tysdomain.com> Message-ID: <201109071403.00915.fayaz@dexetra.com> On Wednesday, September 07, 2011 01:09:51 PM Alec Taylor wrote: > Hi Tyler, > > I'm currently working on building a new kind of social-network for > Users-Groups, Game-Clans & Student-Groups. > > Building it using DJango with Pinax. > > Detailed Feature-Set (planned): > ? Event management > ? Conference management (including ticketing with payment-gateway > integration) ? Video+Audio Conferencing of event, with online interaction > possibilitiy (great for webinars) > ? Join/create/delete/list groups > ? Sitewide calendar > ? Sitewide feed from non-private groups > ? SSO integration (facebook, twitter & linkedin) > ? Wall (+feed) for each group > ? Listing of who's in which group > ? PM group members > > I will probably be releasing it under the New BSD license, although > I'm happy to consider others given a good argument. > > Interested? The project page and mailing list? -- Fayaz Yusuf Khan Cloud developer and designer Dexetra SS, Kochi, India fayaz.yusuf.khan_AT_gmail_DOT_com fayaz_AT_dexetra_DOT_com +91-9746-830-823 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 316 bytes Desc: This is a digitally signed message part. URL: From gelonida at gmail.com Wed Sep 7 04:57:53 2011 From: gelonida at gmail.com (Gelonida N) Date: Wed, 07 Sep 2011 10:57:53 +0200 Subject: Floating point multiplication in python In-Reply-To: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <2204592.egLE2XKegd@PointedEars.de> <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/07/2011 06:51 AM, Steven D'Aprano wrote: 11258999068426240 > > Error in float 1.1*1.1: > >>>> b = F(11, 10)**2 >>>> y = F.from_float(1.1**2) >>>> f = y - b >>>> print f > 21/112589990684262400 > > which is slightly more than double e above, and slightly less than our > estimate of 2*a*e = 11/56294995342131200 > > So we can conclude that, at least for 1.1**2, Python floats are more > accurate than we would expect from a simple application of the binomial > theorem. (For implementations using IEEE doubles.) The reason why the error is different from the 2*a*e is, that we encounter two problems. first problem is, that x = a + e e exists because a float does have a limited number (let's call it N) of digits and a has an infinite amount of non zero digits in the binary format. second problem is, that the result of the multiplication is not (a+e) * (a+e) but a 'rounded' version of it, because the floating point representation of the result would require about 2*N digits, whereas only N digits will be stored in the result. depending on the rounding which happened (up or down) the error will be bigger or smaller than the estimated one. From gelonida at gmail.com Wed Sep 7 05:06:25 2011 From: gelonida at gmail.com (Gelonida N) Date: Wed, 07 Sep 2011 11:06:25 +0200 Subject: Prequisites required to learn Django frame work In-Reply-To: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> References: <408F64D89899604FB24015E64E10490C02F3F1@KCHJEXMB02.kpit.com> Message-ID: Hi Shambhu, On 09/07/2011 09:25 AM, Shambhu Rajak wrote: > Hi, > > I have been doing python development since last year, I think I should > learn the famous Django frame work. > > > > Can any one suggest what are the perquisite required to setup django on > my local home machine. > Just easyinstall django This is enough for learning and midsize home grown projects not requiring a very secure setup. Django comes with a built in server, which is good enough for learning. However It should not be used for deployment. As database engine you can use sqlite3, which is also good enough for learning. My above mentioned setup will be working under windows and under linux. If you want to have something with a better performance, then you have two things to look at. Change the data base engine to mysql or postgres. mysql / postgres should be installable under Windows Use a real web server (apache / nginx with uwsgi plugins) As an intermediate step you could instead of installing a 'real' web server you could also use a python twisted server From alec.taylor6 at gmail.com Wed Sep 7 05:09:53 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 7 Sep 2011 19:09:53 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: <201109071403.00915.fayaz@dexetra.com> References: <4E66D4B9.9050402@tysdomain.com> <201109071403.00915.fayaz@dexetra.com> Message-ID: The project page is: http://SamuelMarks.GitHub.com/groupHub /me is thinking a rename to "groupSwitch", thoughts? The project is currently in planning stage. All help is appreciated. On Wed, Sep 7, 2011 at 6:32 PM, Fayaz Yusuf Khan wrote: > On Wednesday, September 07, 2011 01:09:51 PM Alec Taylor wrote: >> Hi Tyler, >> >> I'm currently working on building a new kind of social-network for >> Users-Groups, Game-Clans & Student-Groups. >> >> Building it using DJango with Pinax. >> >> Detailed Feature-Set (planned): >> ? Event management >> ? Conference management (including ticketing with payment-gateway >> integration) ? Video+Audio Conferencing of event, with online interaction >> possibilitiy (great for webinars) >> ? Join/create/delete/list groups >> ? Sitewide calendar >> ? Sitewide feed from non-private groups >> ? SSO integration (facebook, twitter & linkedin) >> ? Wall (+feed) for each group >> ? Listing of who's in which group >> ? PM group members >> >> I will probably be releasing it under the New BSD license, although >> I'm happy to consider others given a good argument. >> >> Interested? > The project page and mailing list? > > -- > Fayaz Yusuf Khan > Cloud developer and designer > Dexetra SS, Kochi, India > fayaz.yusuf.khan_AT_gmail_DOT_com > fayaz_AT_dexetra_DOT_com > +91-9746-830-823 > > -- > http://mail.python.org/mailman/listinfo/python-list > > From fnautaNO at SPAMsolfon.nl Wed Sep 7 05:17:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Wed, 7 Sep 2011 11:17:03 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> Message-ID: <9cor4gFk15U1@mid.individual.net> "Dennis Lee Bieber" wrote in message news:mailman.823.1315377607.27778.python-list at python.org... > On Tue, 6 Sep 2011 21:26:12 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> (here I try to login the WebDAV server with the local IE browser) >> >> INFO:fshandler :get_data: D:\Webdav not found > > At this point my best suggestion is to study the source code of > fshandler to see what it is doing at this moment in time (offhand, is > there any content IN the directory to be "served"?) There is a file indeed, in d:\Webdav >> server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; >> Windows N >> T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - >> server - - [06/Sep/2011 21:05:35] - Mozilla/4.0 (compatible; MSIE 8.0; >> Windows N >> T 5.1; Trident/4.0> - "GET / HTTP/1.1" 404 - >> > That almost looks like something is trying to retrieve a default > page for 404 (not found) page. > > To save you some time: > > -=-=-=- > if os.path.exists(path): > if os.path.isfile(path): > file_size = os.path.getsize(path) > if range == None: > ## REST SNIPPED > else: > # also raise an error for collections > # don't know what should happen then.. > log.info('get_data: %s not found' % path) I have seen this part. Do I need to alter it? > Note that at this point in the system, it is looking for a FILE, not > a directory. > -- I have re-installed Python and the setuptool, and tried the Python version of Active, but it did not make a difference. So now I use the "old" Python 2.7 again. Used easy_install to install PyWebDAV. I now run davserver.exe from the Script directory. Still the same problem. What I found, however, was that if I specify the directory from the command line (like davserver -D d:\Webdav -n) there is no error message as "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still the 404 error. The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs when I specify the "-c config.ini" in the command line. I didn't expect it to be this so tricky. It looked easy to set up an experimental webdav server. Fokke From tjreedy at udel.edu Wed Sep 7 05:37:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 05:37:32 -0400 Subject: Floating point multiplication in python In-Reply-To: <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <2204592.egLE2XKegd@PointedEars.de> <4e66f843$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/7/2011 12:51 AM, Steven D'Aprano wrote: > So given a float x, when you square it you get this: > > Exact values: a*a = a**2 > > Float values: x*x = (a+e)(a+e) > = a**2 + 2*a*e + e**2 > > So the error term has increased from e to (2*a*e+e**2). It is usual to > assume that e**2 is small enough that it underflows to zero, so we have the > error term e increasing to 2*a*e as a fairly simple estimate of the new > error. And the relative error, which is what is often important, increases from e/a to 2e/a. -- Terry Jan Reedy From bex.lewis at gmail.com Wed Sep 7 06:31:35 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Wed, 7 Sep 2011 03:31:35 -0700 (PDT) Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> Message-ID: > I have re-installed Python and the setuptool, and tried the Python version > of Active, but it did not make a difference. > So now I use the "old" Python 2.7 again. Used easy_install to install > PyWebDAV. I now run davserver.exe from the Script directory. Still the same > problem. > What I found, however, was that if I specify the directory from the command > line (like davserver -D d:\Webdav -n) there is no error message as > "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still the > 404 error. > The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs when I > specify the "-c config.ini" in the command line. > > I didn't expect it to be this so tricky. It looked easy to set up an > experimental webdav server. > > Fokke How are you trying to access the webdav server? I've been hacking on the server for several days now (unrelated reasons) and have found that it's a little unforgiving when it comes to configuration errors. You need to be accessing the webdav server via the correct port (I think it's 8008 by default). If you're not doing this and something else is running on port 80 (which is where a webdav client will go to by default) then this would explain the 404 errors. From sinisa.segvic at fer.hr Wed Sep 7 06:39:14 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 03:39:14 -0700 (PDT) Subject: Portable locale usage References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> On 6 ruj, 17:53, Thomas Jollans wrote: > On 06/09/11 16:46, ssegvic wrote: > > > For the moment, I only wish to properly sort a Croatian text file > > both on Windows and Linux (I am a cautious guy, I like reachable > > goals). > > When the locale is properly set, sorting works like a charm > > with mylist.sort(key=locale.strxfrm). > > The problem with that is of course that a Croatian locale has to be > installed. Many Linux systems don't have locales that aren't used. It appears we did not understand each other completely. Python locales on Linux work as advertised, I have no problems with locales on Linux whatsoever (yes, the Croatian locale had to be manually installed). On the other hand, it appears that Python locales on Windows do not work as advertised. Consider for instance my initial example: locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) The code above does not work on Windows even though the fine manual says: http://docs.python.org/py3k/library/locale.html ''' locale.setlocale(category, locale=None) ... If (the locale) is a tuple, it is converted to a string using the locale aliasing engine. ... ''' I do not believe my troubles could be solved by installing anything, since the OS support for Croatian apperas to be present: locale.setlocale(locale.LC_ALL, 'Croatian_Croatia.1250') To conclude, it seems to me that the Windows implementation of the locale aliasing engine has some space for improvement. All further comments shall be greatly appreciated :-) Cheers, Sinisa From sinisa.segvic at fer.hr Wed Sep 7 07:02:18 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 04:02:18 -0700 (PDT) Subject: Portable locale usage References: Message-ID: <6b6671a8-8e92-4ace-a1ed-63e900246000@gz5g2000vbb.googlegroups.com> On 6 ruj, 22:58, garabik-news-2005... at kassiopeia.juls.savba.sk wrote: > Thomas Jollans wrote: > > It looks like you don't actually care about the encoding: in your first > > example, you use the default system encoding, which you do not control, > > and in your second example, you're using two different encodings on the > > two platforms. So why do you care whether or not the default uses ISO > > 8859-2 ? > > Maybe because using 8859-2 locale, (unicode) strings not representable in the > encodings will be sorted - how? Exactly. Additionally, fonts supporting 8859-2 are scarce. My favourite fonts were never available in 8859-2. Sinisa From sinisa.segvic at fer.hr Wed Sep 7 07:17:52 2011 From: sinisa.segvic at fer.hr (ssegvic) Date: Wed, 7 Sep 2011 04:17:52 -0700 (PDT) Subject: Portable locale usage References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> Message-ID: <16cabd28-d195-4689-9a28-374671a030ba@gz5g2000vbb.googlegroups.com> On 6 ruj, 17:53, Thomas Jollans wrote: > On 06/09/11 16:46, ssegvic wrote: > > > For the moment, I only wish to properly sort a Croatian text file > > both on Windows and Linux (I am a cautious guy, I like reachable > > goals). > > When the locale is properly set, sorting works like a charm > > with mylist.sort(key=locale.strxfrm). > > The problem with that is of course that a Croatian locale has to be > installed. Many Linux systems don't have locales that aren't used. I already concluded that on Linux there are no problems whatsoever (the Croatian locale was kindly installed by the distribution setup). Since my initial snippet does not work on Windows, I would conclude that the locale aliasing engine on Windows should be improved. Any opposing views will be appreciated :-) For convenience, I repeat the snippet here: import locale locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) Cheers, Sinisa From mohammedimran107 at gmail.com Wed Sep 7 08:49:57 2011 From: mohammedimran107 at gmail.com (mohammed imran) Date: Wed, 7 Sep 2011 05:49:57 -0700 (PDT) Subject: mohammedimran Message-ID: <7d838612-c5a0-43d7-b852-4a84c35b183f@l4g2000vbz.googlegroups.com> http://123maza.com/65/fun564/ From t at jollybox.de Wed Sep 7 09:15:53 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 15:15:53 +0200 Subject: Portable locale usage In-Reply-To: <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> References: <6abee826-23f3-4d5e-948e-f2a436bf0ac0@t3g2000vbe.googlegroups.com> <2ecebe91-9d4d-4ce9-8e0a-2efbaf026273@l4g2000vbv.googlegroups.com> Message-ID: <4E676E89.4010506@jollybox.de> On 07/09/11 12:39, ssegvic wrote: > On 6 ruj, 17:53, Thomas Jollans wrote: >> On 06/09/11 16:46, ssegvic wrote: >> >>> For the moment, I only wish to properly sort a Croatian text file >>> both on Windows and Linux (I am a cautious guy, I like reachable >>> goals). >>> When the locale is properly set, sorting works like a charm >>> with mylist.sort(key=locale.strxfrm). >> >> The problem with that is of course that a Croatian locale has to be >> installed. Many Linux systems don't have locales that aren't used. > > It appears we did not understand each other completely. Yes we did. I was just pointing out that your code wouldn't be portable to systems that don't have that specific locale. From mohammedimran107 at gmail.com Wed Sep 7 09:27:22 2011 From: mohammedimran107 at gmail.com (mohammed imran) Date: Wed, 7 Sep 2011 06:27:22 -0700 (PDT) Subject: mohammedimran Message-ID: <43cb58c7-1b7b-4e61-a53a-7eb5603396ff@et6g2000vbb.googlegroups.com> http://123maza.com/65/fun564/ From t at jollybox.de Wed Sep 7 09:45:30 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 15:45:30 +0200 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: <4E67757A.6070701@jollybox.de> On 07/09/11 04:19, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of > projects there are that people needs help with. I'd like to choose > something that doesn't have a ton of red tape, but is stable, which is > why I ask here instead of just Googling open source projects. My main > interests lie in accessibility, Utilities and security. > How about Python itself? Much of the standard library is written in Python, and there are almost certainly bugs that need fixing. From fnautaNO at SPAMsolfon.nl Wed Sep 7 09:52:20 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Wed, 7 Sep 2011 15:52:20 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> Message-ID: <9cpbddFtidU1@mid.individual.net> "becky_lewis" wrote in message news:d26f81b2-f87e-46f1-bb4e-8ef1943dfe7f at c29g2000yqd.googlegroups.com... >> I have re-installed Python and the setuptool, and tried the Python >> version >> of Active, but it did not make a difference. >> So now I use the "old" Python 2.7 again. Used easy_install to install >> PyWebDAV. I now run davserver.exe from the Script directory. Still the >> same >> problem. >> What I found, however, was that if I specify the directory from the >> command >> line (like davserver -D d:\Webdav -n) there is no error message as >> "INFO:fshandler :get_data: D:\Webdav not found". The browser shows still >> the >> 404 error. >> The error "INFO:fshandler :get_data: D:\Webdav not found" only occurs >> when I >> specify the "-c config.ini" in the command line. >> >> I didn't expect it to be this so tricky. It looked easy to set up an >> experimental webdav server. >> >> Fokke > > How are you trying to access the webdav server? By IE 8 and Firefox, on the same system as well as on another system. Firefox doesn't show the 404 error but shows a blank screen. I bound the davserver to the local adress of the system where it's on (10.0.0.140). The port was 8081 but I changed it to 8008 as you said it's the default. No difference. > I've been hacking on > the server for several days now (unrelated reasons) and have found > that it's a little unforgiving when it comes to configuration errors. > You need to be accessing the webdav server via the correct port (I > think it's 8008 by default). If you're not doing this and something > else is running on port 80 (which is where a webdav client will go to > by default) then this would explain the 404 errors. I certainly use the correct IP address and port number. Underneath is my command shell. The 1st time I specified the config file (davserver.ini), the 2nd time I specified on the command line. Here I logged in with Firefox from system XXX (replaced the name by XXX). (Here I started the server with the the config file (davserver.ini) D:Python27\Scripts>davserver -m -c davserver.ini INFO:pywebdav:Starting up PyWebDAV server INFO:pywebdav:chunked_http_response feature ON INFO:pywebdav:http_request_use_iterator feature OFF INFO:pywebdav:http_response_use_iterator feature OFF INFO:DAVServer.fshandler:Initialized with d:\webdav-http://10.0.0.140:8081/ WARNING:pywebdav:Authentication disabled! INFO:pywebdav:Serving data from d:\webdav Listening on 10.0.0.140 <8081> (browser logging in) INFO:DAVServer.fshandler:get_data: d:\webdav not found XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - ^C D:\Python27\Scripts>INFO:pywebdav:Killed by user (Here I started the server with command line options) davserver -D d:\webdav -H 10.0.0.140 -P 8081 -n WARNING:pywebdav:Authentication disabled! Listening on 10.0.0.140 <8081> XXX --- [07/Sep/2011 11:58:49] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - XXX --- [07/Sep/2011 11:58:54] - Mozilla/5.0 Gecko/ 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - ^C D:\Python27\Scripts>INFO:pywebdav:Killed by user From d_vineet at yahoo.com Wed Sep 7 09:58:26 2011 From: d_vineet at yahoo.com (Vineet Deodhar) Date: Wed, 7 Sep 2011 06:58:26 -0700 (PDT) Subject: web2py In-Reply-To: References: Message-ID: <1315403906.49408.YahooMailNeo@web160511.mail.bf1.yahoo.com> >>>------------------------------------------ Hi, I have been doing python development since last year, I think I should learn the famous Django frame work. Can any one suggest what are the perquisite required to setup django on my local home machine. Please suggest something that does not require a separate server, as this is a personal interest of mine. Thanks, Shambhu I'm currently working on building a new kind of social-network for Users-Groups, Game-Clans & Student-Groups. Building it using DJango with Pinax. Detailed Feature-Set (planned): ? Event management ? Conference management (including ticketing with payment-gateway integration) ? Video+Audio Conferencing of event, with online interaction possibilitiy (great for webinars) ? Join/create/delete/list groups ? Sitewide calendar ? Sitewide feed from non-private groups ? SSO integration (facebook, twitter & linkedin) ? Wall (+feed) for each group ? Listing of who's in which group ? PM group members >>>------------------------------------------ I don't want to undermine django. It is a good framework. But still, my advise would be to go for 'web2py'. http://web2py.com/ It is simple yet powerful. Full stack MVC framework. Low learning curve; simple syntax. Good docs & community. Everything works out of the box (including web-server, DAL, sqlite, etc) No dependencies; plug&play. etc. etc. ---Vineet -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at shopzeus.com Wed Sep 7 10:51:20 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 07 Sep 2011 16:51:20 +0200 Subject: Portable locale usage In-Reply-To: References: Message-ID: <4E6784E8.2040206@shopzeus.com> > 1. Is there a way for writing portable Python code dealing with > locales > (as sketched in the beginning)? I usually do this at the top of my main program, before importing other modules: import locale locale.setlocale(locale.LC_ALL, '') This is absolutely portable. The above snippet works for different operating systems with different default encodings. You can always setup some environment variable before starting up the program if you really have to. And yes, that setting will be OS dependent, but your program will still be portable. I have no access to Croatian Windows, but I bet that the above code would set the locale to the correct thing on both Linux and Windows. It would be a bad idea to set the locale from anywhere else than your main program anyway. There are also some notes in the docs about this ( http://docs.python.org/library/locale.html#locale.setlocale ): > setlocale() > is not > thread-safe on most systems. Applications typically start with a call of > > import locale > locale.setlocale(locale.LC_ALL, '') > > This sets the locale for all categories to the user's default setting > (typically specified in the *LANG* environment variable). If the > locale is not changed thereafter, using multithreading should not > cause problems. > Why are you trying to force a specific locale to your program anyway? L -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericsnowcurrently at gmail.com Wed Sep 7 11:12:20 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 7 Sep 2011 09:12:20 -0600 Subject: Looking for open-source Python projects to help out with In-Reply-To: <4E66D4B9.9050402@tysdomain.com> References: <4E66D4B9.9050402@tysdomain.com> Message-ID: On Tue, Sep 6, 2011 at 8:19 PM, Littlefield, Tyler wrote: > Hello: > I've got a bit of time on my hands, so I'm curious what sorts of projects > there are that people needs help with. I'd like to choose something that > doesn't have a ton of red tape, but is stable, which is why I ask here > instead of just Googling open source projects. My main interests lie in > accessibility, Utilities and security. An interesting one that I haven't had time to help on yet is the "extensions for unittest" project: https://code.google.com/p/unittest-ext/issues/list Basically it's adding an extensions framework to the stdlib unittest module. I'm sure Michael Foord wouldn't mind the help. Like I said, a very interesting project, though not directly related to accessibility or security. -eric > > -- > > Take care, > ~Ty > Web: http://tds-solutions.net > > Sent from my toaster. > > -- > http://mail.python.org/mailman/listinfo/python-list > From bclark76 at gmail.com Wed Sep 7 11:56:32 2011 From: bclark76 at gmail.com (bclark76) Date: Wed, 7 Sep 2011 08:56:32 -0700 (PDT) Subject: How to structure packages Message-ID: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> I'm learning python, and was playing with structuring packages. Basically I want to have a package called mypackage that defines a number of classes and functions. so I create: mypackage __init__.py myfunc.py MyClass.py my __init__.py is blank. my MyClass.py looks like: import blah class MyClass(blahblah): blah blah blah then I have a run.py that looks like from mypackage import MyClass x = MyClass() This doesn't work because MyClass is mypackage.MyClass.MyClass. There's this MyClass module 'in the way'. I'm trying to follow the rule that every file defines only one class. I could define MyClass in __init__.py, but then what if I wanted to define more classes in the mypackage package? My one class per file rule goes out the window. Is this rule wrongheaded, or is there another way to do this? Thanks. From alec.taylor6 at gmail.com Wed Sep 7 12:09:41 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 8 Sep 2011 02:09:41 +1000 Subject: Looking for open-source Python projects to help out with In-Reply-To: References: <4E66D4B9.9050402@tysdomain.com> Message-ID: Accessibility? Hmm, you could look at http://groups.google.com/group/django-users/browse_thread/thread/44a4dbf8771e0f4f (https://groups.google.com/forum/#!topic/django-users/RKTb-HceD08) On Thu, Sep 8, 2011 at 1:12 AM, Eric Snow wrote: > On Tue, Sep 6, 2011 at 8:19 PM, Littlefield, Tyler wrote: >> Hello: >> I've got a bit of time on my hands, so I'm curious what sorts of projects >> there are that people needs help with. I'd like to choose something that >> doesn't have a ton of red tape, but is stable, which is why I ask here >> instead of just Googling open source projects. My main interests lie in >> accessibility, Utilities and security. > > An interesting one that I haven't had time to help on yet is the > "extensions for unittest" project: > > https://code.google.com/p/unittest-ext/issues/list > > Basically it's adding an extensions framework to the stdlib unittest > module. ?I'm sure Michael Foord wouldn't mind the help. ?Like I said, > a very interesting project, though not directly related to > accessibility or security. > > -eric > >> >> -- >> >> Take care, >> ~Ty >> Web: http://tds-solutions.net >> >> Sent from my toaster. >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From gordon at panix.com Wed Sep 7 12:11:11 2011 From: gordon at panix.com (John Gordon) Date: Wed, 7 Sep 2011 16:11:11 +0000 (UTC) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: In <2a4f542c-a8c1-46c7-9899-a3fad0940cf6 at x11g2000yqc.googlegroups.com> bclark76 writes: > mypackage > __init__.py > myfunc.py > MyClass.py > from mypackage import MyClass Try this instead: from mypackage.MyClass import MyClass -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rafadurancastaneda at gmail.com Wed Sep 7 13:18:43 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Wed, 07 Sep 2011 19:18:43 +0200 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4E67A773.6070304@gmail.com> Check python pep8: http://www.python.org/dev/peps/pep-0008/ And you will see than you shouldn't named modules as you did, so you should do something like: mypackage __init__.py mymodule ... mypackage.mymodule.MyClass On 07/09/11 18:11, John Gordon wrote: > In<2a4f542c-a8c1-46c7-9899-a3fad0940cf6 at x11g2000yqc.googlegroups.com> bclark76 writes: > >> mypackage >> __init__.py >> myfunc.py >> MyClass.py >> from mypackage import MyClass > Try this instead: > > from mypackage.MyClass import MyClass > From __peter__ at web.de Wed Sep 7 13:30:34 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Sep 2011 19:30:34 +0200 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: bclark76 wrote: > I'm learning python, and was playing with structuring packages. If you are coming from Jave you have to unlearn a thing or two. > Basically I want to have a package called mypackage that defines a > number of classes and functions. > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, Yes. > or is there another way to do this? I recommend that you always start out with a module. Once that becomes unwieldy you can convert it into a package. Let's assume that mystuff.py contains a MyClass that you want to move into a separate file. You get the following files: mystuff __init__.py descriptivename.py # MyClass here Note that all filenames are lowercase. If you add the line from .descriptivename import MyClass to __init__.py you can continue to import and use MyClass with the statement from mystuff import MyClass m = MyClass() or import mystuff m = mystuff.MyClass() The disadvantage is of course that mystuff.descriptivename will always be imported, even if you don't need the part of the mystuff package defined there. You may also have a look into unittest as an example of a module that was recently converted into a package. Classes and functions are grouped into submodules by their functionality rather than employing Java's mechanical one-class-per-file pattern. From rantingrick at gmail.com Wed Sep 7 13:56:53 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 7 Sep 2011 10:56:53 -0700 (PDT) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: On Sep 7, 10:56?am, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > so I create: > > mypackage > ? ? __init__.py > ? ? myfunc.py > ? ? MyClass.py Don't tell me you create a module called myfunc.py??? Stuff that function in __init__! Also don't name modules MyClass either. Both the spelling and grammar is incorrect. ALL modules use lowercase (and only integrate underscores in the most dire of need!) geom __init__.py vector3d.py point3d.py transformation.py from geom.transformation import Transformation from geom.vector3d import Vector3d from geom.point3d import Point3d or alternatively: geom __init__.py from __vector3d import Vector3d from __point3d import Point3d from __transformation import Transformation __vector3d.py __point3d.py __transformation.py from geom import Transformation from geom import Vector3d from geom import Point3d Although this method can be brittle due to the fact that one buggy module can break all the imported code in the __init__ module. I usually opt for specifying the module in the import path. From tyler at tysdomain.com Wed Sep 7 14:11:23 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Wed, 07 Sep 2011 12:11:23 -0600 Subject: How to structure packages In-Reply-To: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4E67B3CB.8020600@tysdomain.com> On 9/7/2011 9:56 AM, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > > so I create: > > mypackage > __init__.py > myfunc.py > MyClass.py > > > my __init__.py is blank. > > my MyClass.py looks like: > > import blah > > class MyClass(blahblah): > blah > blah > blah > > > then I have a run.py that looks like > > from mypackage import MyClass > > > x = MyClass() > > > This doesn't work because MyClass is mypackage.MyClass.MyClass. > There's this MyClass module 'in the way'. > You can use the __init__.py to promote that class up. so: from myclass import myclass So that means that myclass will just be in mypackage.myclass, and thus your from mypackage import myclass would work perfectly. I'm not sure if this is how you're supposed to do it, but it works. > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, or is there another way to do this? > > > Thanks. > -- Take care, Ty Web: http://tds-solutions.net Sent from my toaster. From emile at fenx.com Wed Sep 7 14:21:22 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 07 Sep 2011 11:21:22 -0700 Subject: PEP 20 - Silly Question? In-Reply-To: References: <877h5lnq8a.fsf@benfinney.id.au> <4E66C824.6010008@mrabarnett.plus.com> Message-ID: On 9/6/2011 6:31 PM Joshua Miller said... > You sure it wasn't the invisible one? you know the one in the white > text that blends into the background? Aah! So _that's_ significant whitespace! :) Emile From xnews2 at fredp.lautre.net Wed Sep 7 14:24:29 2011 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 07 Sep 2011 18:24:29 GMT Subject: Advice on how to get started with 2D-plotting ? References: <4e6719f1$0$38260$3b214f66@aconews.univie.ac.at> Message-ID: Wow, what an impressive turnout ! Thanks a lot, rantingrick, CM and Herbert, for the fast answers, useful tips and especially the sample code ! Beats starting from a blank page, with a big stick, and will certainly set me on my way much faster... networkx does seem a bit over the top for my simple goal, but both the Tk (I always forget Tk !) and Matplotlib approaches seem to fit the KISS principle just fine... on to the tinkering now :-) Again, thanks to all ! fp From ssegvic at zemris.fer.hr Wed Sep 7 14:33:57 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Wed, 7 Sep 2011 20:33:57 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E6784E8.2040206@shopzeus.com> Message-ID: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "ssegvic" , python-list at python.org > Sent: Wednesday, September 7, 2011 4:51:20 PM > Subject: Re: Portable locale usage > > 1. Is there a way for writing portable Python code dealing with > > locales (as sketched in the beginning)? > I usually do this at the top of my main program, before importing > other modules: > > import locale > locale.setlocale(locale.LC_ALL, '') I have set the system-wide locale to Croatian (Croatia) on my development system as instructed by: http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale Nevertheless, your proposal produces: ('English_United States','1252') Note that I would very much like to avoid changing the system locale (this requires Administrator password and system restart). Setting the locale for my program only would be interesting, but AFAIK this can not be done on Windows (?). > Why are you trying to force a specific locale to your program anyway? Because I wish to be able to correctly sort Croatian names. I expect that most of my Windows users will not care to configure their computers with the national locale (and besides, that does not seem to work, anyway). Cheers, Sinisa From jenn.duerr at gmail.com Wed Sep 7 15:33:03 2011 From: jenn.duerr at gmail.com (noydb) Date: Wed, 7 Sep 2011 12:33:03 -0700 (PDT) Subject: Adding a ranking based on two fields References: <9b98790e-f482-48f9-93e9-80b32f6b4583@g31g2000yqh.googlegroups.com> Message-ID: <0fa8fa0d-51e7-4185-aa37-3bbf358f396b@a12g2000yqi.googlegroups.com> On Aug 25, 4:53?pm, Chris Rebert wrote: > On Thu, Aug 25, 2011 at 1:38 PM, noydb wrote: > > Hello All, > > > Looking for some advice/ideas on how to implement arankingto a > > 'scores' field I have. ?So this scores field has values ranging from > > 1.00-4. ?There is also a count field. ?I want to add a rank field such > > that all the records have a uniqueranking, 1 through the number of > > records (thousands). ?The rank isbasedon the score first, the count > > second. ?So, a record with a score of 4 and a count of 385 is ranked > > higher than a record with a score of 4 and a count of 213 AND higher > > than record with a score of 3.25 with a count of 4640. > > > My thought was to add the unique score values to a list and loop thru > > the list... sort records with score=listItem, addranking... not quite > > sure how to do this! > > things = getListOfYourThings() > things.sort(reverse=True, key=lambda item: (item.score, item.count)) > for i, thing in enumerate(things): > ? ? thing.rank = i + 1 > > Cheers, > Chris > --http://rebertia.com Thanks for this! Someone passed this along, too - helpful http://wiki.python.org/moin/HowTo/Sorting From neubyr at gmail.com Wed Sep 7 15:58:05 2011 From: neubyr at gmail.com (neubyr) Date: Wed, 7 Sep 2011 14:58:05 -0500 Subject: MIMEText encode error - Python 2.6.6 In-Reply-To: <4E669920.3010704@mrabarnett.plus.com> References: <4E669920.3010704@mrabarnett.plus.com> Message-ID: On Tue, Sep 6, 2011 at 5:05 PM, MRAB wrote: > On 06/09/2011 22:52, neubyr wrote: >> >> I am trying to write a program which can email file's content using >> smtplib. I am getting following error while using Python 2.6.6 >> version. >> >> {{{ >> File "./killed_jobs.py", line 88, in sendmail >> ? ?msg = MIMEText(ipfile.read, 'plain') >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/mime/text.py", >> line 30, in __init__ >> ? ?self.set_payload(_text, _charset) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", >> line 224, in set_payload >> ? ?self.set_charset(charset) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/message.py", >> line 266, in set_charset >> ? ?cte(self) >> ?File "/home/ssp/sge/python/2.6.6/lib/python2.6/email/encoders.py", >> line 73, in encode_7or8bit >> ? ?orig.encode('ascii') >> AttributeError: 'builtin_function_or_method' object has no attribute >> 'encode' >> >> }}} >> >> >> I am referring to email examples on the doc site >> >> http://docs.python.org/release/2.6.6/library/email-examples.html#email-examples >> . Following is the msg object part in my code: >> >> {{{ >> ... >> ... >> def sendmail(inputfile): >> ? ? ? ? ipfile = open(inputfile, 'r') >> ? ? ? ? msg = MIMEText(ipfile.read, 'plain') >> ? ? ? ? ipfile.close() >> >> ... >> ... >> }}} >> >> I have tried setting subtype and chartype separately as mentioned here >> - http://docs.python.org/release/2.6.6/library/email.mime.html, but >> the error remains same. Any help on what might be wrong here? >> > The docs say: > > ? ?MIMEText(_text[, _subtype[, _charset]]) > > ? ?... _text is the string for the payload ... > > You're passing ipfile.read, which is the read method of the file. You > should be passing the string returned by calling ipfile.read, ie > ipfile.read(). > -- > thanks got pointing that.. -- From t at jollybox.de Wed Sep 7 17:14:26 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 07 Sep 2011 23:14:26 +0200 Subject: Portable locale usage In-Reply-To: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> References: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E67DEB2.5060003@jollybox.de> On 07/09/11 20:33, Sini?a ?egvi? wrote: > I expect that most of my Windows users will not care > to configure their computers with the national locale > (and besides, that does not seem to work, anyway). Are, on Windows, the default system region/language setting, and the locale, distinct? (And, if so, why?!) From anikom15 at gmail.com Wed Sep 7 17:35:25 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 7 Sep 2011 14:35:25 -0700 Subject: How to structure packages In-Reply-To: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <20110907213525.GA6955@Smoke> First of all MyClass.py should be renamed to myclass.py. Module names should be lowercase. Secondly, put this in __init__.py: from .myclass import MyClass and there you go. On Wed, Sep 07, 2011 at 08:56:32AM -0700, bclark76 wrote: > I'm learning python, and was playing with structuring packages. > > Basically I want to have a package called mypackage that defines a > number of classes and functions. > > > so I create: > > mypackage > __init__.py > myfunc.py > MyClass.py > > > my __init__.py is blank. > > my MyClass.py looks like: > > import blah > > class MyClass(blahblah): > blah > blah > blah > > > then I have a run.py that looks like > > from mypackage import MyClass > > > x = MyClass() > > > This doesn't work because MyClass is mypackage.MyClass.MyClass. > There's this MyClass module 'in the way'. > > > I'm trying to follow the rule that every file defines only one class. > I could define MyClass in __init__.py, but then what if I wanted to > define more classes in the mypackage package? My one class per file > rule goes out the window. > > Is this rule wrongheaded, or is there another way to do this? > > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list From laurent.payot at gmail.com Wed Sep 7 17:35:41 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 14:35:41 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? Message-ID: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Hi there, What is the simplest way to check that you are at the beginning or at the end of an iterable? I'm using enumerate with Python 3.2 (see below) but I'm wondering if there would be a better way. l = ['a', 'b', 'a', 'c'] for pos, i in enumerate(l): if pos == 0: print("head =", i) else: print(i) I know that Python is not exactly a functional language but wouldn't something like "ishead()" or "istail()" be useful? From cs at zip.com.au Wed Sep 7 18:48:24 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 8 Sep 2011 08:48:24 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <20110907224824.GA29885@cskk.homeip.net> On 07Sep2011 14:35, Laurent wrote: | What is the simplest way to check that you are at the beginning or at | the end of an iterable? I'm using enumerate with Python 3.2 (see below) | but I'm wondering if there would be a better way. | | l = ['a', 'b', 'a', 'c'] | | for pos, i in enumerate(l): | if pos == 0: | print("head =", i) | else: | print(i) | | I know that Python is not exactly a functional language but wouldn't | something like "ishead()" or "istail()" be useful? There are a few reasons these do not exist out of the box (quite aside from how easy it is to do on the occasions you actually want it). Tackling ishead and istail in turn... The "ishead()" would need to be a top level function (like "len()") because if it were an iterator method, every iterator would need to have it implemented; currently the number of methods needed to roll your own iterator is just two (iter and next). ishead() could be done as a top level function, though it would need the storage cost of an additional state value to every iterator (i.e. a "first" boolean or equivalent). So you'd be proposing more memory cost and possibly a retrospective code change for all the existing planetwide code, for a minor convenient. As you note, enumerate gets you a pos value, and it is easy enough to write a for loop like this: first = True for i in iterable_thing: if first: print "head =", i else: print i first = False Your istail() is much worse. A generator would need to do lookahead to answer istail() in the general case. Consider iterating over the lines in a file, or better still the lines coming from a pipeline. Or iteraing over packets received on a network connection. You can't answer "istail()" there until you have seen the next line/packet (or EOF/connection close). And that may be an arbitrary amount of time in the future. You're going to stall your whole program for such a question? You can do this easily enough for yourself as an itertools-like thing: write a wrapper generator that answers ishead() and istail() for arbitrary iterators. Completely untested example code: class BoundSensitiveIterator(object): def __init__(self, subiter): self.sofar = 0 self.subiter = subiter self.pending = () def iter(self): return self def next(self): self.sofar += 1 if self.pending is None: raise StopIteration if self.pending: nxt = self.pending[0] self.pending = () return nxt return self.subiter.next() def ishead(self): # maybe <= 1, depending on what you want it to mean return self.sofar == 1 def istail(self): if self.pending is None: return True if self.pending: return False try: nxt = self.subiter.next() except StopIteration: self.pending = None return True else: self.pending = (nxt,) return False I = BoundSensitiveIterator(other_iterable) for n in I: print n, "ishead =", I.ishead(), "istail =", I.istail() You can see it adds some performance and storage overhead, and of course may stall if you every ask istail() of an "on demand" iterable. About the only time I do this is my personal "the()" convenience function: def the(list, context=None): ''' Returns the first element of an iterable, but requires there to be exactly one. ''' icontext="expected exactly one value" if context is not None: icontext=icontext+" for "+context first=True for elem in list: if first: it=elem first=False else: raise IndexError, "%s: got more than one element (%s, %s, ...)" \ % (icontext, it, elem) if first: raise IndexError, "%s: got no elements" % icontext return it Which I use as a definite article in places where an iterable _should_ yield exactly one result (eg SQL SELECTs that _ought_ to get exactly one hit). I can see I wrote that a long time ago - it could do with some style fixes. And a code scan shows it sees little use:-) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Electronic cardboard blurs the line between printed objects and the virtual world. - overhead by WIRED at the Intelligent Printing conference Oct2006 From piet at vanoostrum.org Wed Sep 7 18:52:20 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 00:52:20 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> <9cmq1vFk6fU1@mid.individual.net> <9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> <9cpbddFtidU1@mid.individual.net> Message-ID: "Fokke Nauta" writes: > INFO:DAVServer.fshandler:get_data: d:\webdav not found > XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> > Gecko/ > 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - > XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 > Gecko/ > 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - > >From the log it looks like you are trying to access the server with the url: http://localhost:8008/ or something similar. This won't work as you would try to access the root of your webdav directory in this way (i.e. D:/webdav). The webdav server can only serve files, not directories, so you would have to access http://localhost:8008/somefile.txt where somefile.txt is a file in D:/webdav. This only applies to acces using a browser. If you access the server through a webdav-aware client (for example the Finder on Mac OS X, or probably the Windows Explorer) it can serve the contents of the directory. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From martin.rixham at gmail.com Wed Sep 7 18:57:04 2011 From: martin.rixham at gmail.com (Martin Rixham) Date: Wed, 7 Sep 2011 23:57:04 +0100 Subject: I am confused by Message-ID: Hi all I would appreciate some help understanding something. Basically I am confused by the following: >>> a = [[0, 0], [0, 0]] >>> b = list(a) >>> b[0][0] = 1 >>> a [[1, 0], [0, 0]] I expected the last line to be [[0, 0], [0, 0]] I hope that's clear enough. Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at vanoostrum.org Wed Sep 7 19:01:07 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 01:01:07 +0200 Subject: Why do class methods always need 'self' as the first parameter? References: <0dc26f12-2541-4d41-8678-4fa53f347acf@g9g2000yqb.googlegroups.com> Message-ID: "Prasad, Ramit" writes: > It seems to me that if I add a function to the list of class attributes it will automatically wrap with "self" but adding it to the object directly will not wrap the function as a method. Can somebody explain why? I would have thought that any function added to an object would be a method (unless decorated as a class method). The special magic to transform a function into a method is only applied for functions found as attributes of the class, not for instance attributes. It is a matter of design. > Hmm, or does the decoration just tell Python not to turn an object's function into a method? I.e. Is the decorator basically just the syntactic sugar for doing the above? The classmethod decorator transforms the method (or actually the function) into a different kind of object (a class method). -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From laurent.payot at gmail.com Wed Sep 7 19:22:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 16:22:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: I totally understand the performance issue that an hypothetical "istail" would bring, even if I think it would just be the programmer's responsibility not to use it when it's not certain that an end can be detected. But I don't see why *adding* something like "ishead" would be so bad (at worse by using a boolean somewhere as you mentioned). Anyway I was just asking if there is something better than enumerate. So the answer is no? The fact that I have to create a tuple with an incrementing integer for something as simple as checking that I'm at the head just sounds awfully unpythonic to me. From laurent.payot at gmail.com Wed Sep 7 19:22:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 16:22:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: I totally understand the performance issue that an hypothetical "istail" would bring, even if I think it would just be the programmer's responsibility not to use it when it's not certain that an end can be detected. But I don't see why *adding* something like "ishead" would be so bad (at worse by using a boolean somewhere as you mentioned). Anyway I was just asking if there is something better than enumerate. So the answer is no? The fact that I have to create a tuple with an incrementing integer for something as simple as checking that I'm at the head just sounds awfully unpythonic to me. From fnautaNO at SPAMsolfon.nl Wed Sep 7 19:28:03 2011 From: fnautaNO at SPAMsolfon.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 01:28:03 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net><9cor4gFk15U1@mid.individual.net><9cpbddFtidU1@mid.individual.net> Message-ID: <9cqdb0Fpn4U1@mid.individual.net> "Piet van Oostrum" wrote in message news:m2zkigartn.fsf at cochabamba.vanoostrum.org... > "Fokke Nauta" writes: > > >> INFO:DAVServer.fshandler:get_data: d:\webdav not found >> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >> Gecko/ >> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >> Gecko/ >> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >> > From the log it looks like you are trying to access the server with the > url: > > http://localhost:8008/ or something similar. Yes, I do. > This won't work as you would try to access the root of your webdav > directory in this way (i.e. D:/webdav). The webdav server can only serve > files, not directories, so you would have to access > http://localhost:8008/somefile.txt where somefile.txt is a file in > D:/webdav. OK, thanks. I am not familiar to WebDAV. I tried. Got something different (at least something happened): "Setuptools version 0.6c9 or greater has been installed. (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" Wasn't able to find ez_setup.py yet. > This only applies to acces using a browser. If you access the server > through a webdav-aware client (for example the Finder on Mac OS X, or > probably the Windows Explorer) it can serve the contents of the directory. > -- Thanks. I am just trying to use a calendar with a webdav server. I don't have any experience with that. Simply using my browser to try it out. Fokke From gherron at digipen.edu Wed Sep 7 19:31:37 2011 From: gherron at digipen.edu (Gary Herron) Date: Wed, 07 Sep 2011 16:31:37 -0700 Subject: I am confused by In-Reply-To: References: Message-ID: <4E67FED9.7050609@digipen.edu> On 09/07/2011 03:57 PM, Martin Rixham wrote: > Hi all > I would appreciate some help understanding something. Basically I am > confused by the following: > > >>> a = [[0, 0], [0, 0]] > >>> b = list(a) > >>> b[0][0] = 1 > >>> a > [[1, 0], [0, 0]] > > I expected the last line to be > > [[0, 0], [0, 0]] > > I hope that's clear enough. > > Martin You were expecting the assignment to "b" to create a copy of the original list, and it does, but the copy is only one level deep. So a and b are different lists, but a[i] and b[i] are the same objects for each i. There is a "deepcopy" in the library which may do what you expect. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From python at mrabarnett.plus.com Wed Sep 7 19:39:02 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 00:39:02 +0100 Subject: I am confused by In-Reply-To: References: Message-ID: <4E680096.1020001@mrabarnett.plus.com> On 07/09/2011 23:57, Martin Rixham wrote: > Hi all > I would appreciate some help understanding something. Basically I am > confused by the following: > > >>> a = [[0, 0], [0, 0]] > >>> b = list(a) > >>> b[0][0] = 1 > >>> a > [[1, 0], [0, 0]] > > I expected the last line to be > > [[0, 0], [0, 0]] > > I hope that's clear enough. > What you were expecting is called a "deep copy". You should remember that a list doesn't contain objects themselves, but only _references_ to objects. "list" will copy the list itself (a "shallow copy"), including the references which are in it, but it won't copy the _actual_ objects to which they refer. Try using the "deepcopy" function from the "copy" module: >>> from copy import deepcopy >>> a = [[0, 0], [0, 0]] >>> b = deepcopy(a) >>> b[0][0] = 1 >>> a [[0, 0], [0, 0]] From python.list at tim.thechases.com Wed Sep 7 20:01:33 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 07 Sep 2011 19:01:33 -0500 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <4E6805DD.60607@tim.thechases.com> On 09/07/11 18:22, Laurent wrote: > Anyway I was just asking if there is something better than > enumerate. So the answer is no? The fact that I have to create > a tuple with an incrementing integer for something as simple > as checking that I'm at the head just sounds awfully > unpythonic to me. I've made various generators that are roughly (modulo edge-condition & error checking) something like def with_prev(it): prev = None for i in it: yield prev, i i = prev def with_next(it): prev = it.next() for i in it: yield prev, i prev = i yield prev, None which can then be used something like your original for cur, next in with_next(iterable): if next is None: do_something_with_last(cur) else: do_regular_stuff_with_non_last(cur) for prev, cur in with_prev(iterable): if prev is None: do_something_with_first(cur) else: do_something_with_others(cur) If your iterable can return None, you could create a custom object to signal the non-condition: NO_ITEM = object() and then use NO_ITEM in place of "None" in the above code. -tkc From cs at zip.com.au Wed Sep 7 20:23:14 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 8 Sep 2011 10:23:14 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: <20110908002314.GA15766@cskk.homeip.net> On 07Sep2011 16:22, Laurent wrote: | I totally understand the performance issue that an hypothetical | "istail" would bring, even if I think it would just be the programmer's | responsibility not to use it when it's not certain that an end can | be detected. The trouble with these things is that their presence leads to stallable code, often in libraries. Let the programmer write code dependent on istail() without thinking of the stall case (or even the gratuitous execution case, as in a generator with side effects in calling .next()) and have that buried in a utilities function. Facilities like feof() in C and eof in Pascal already lead to lots of code that runs happily with flat files and behaves badly in interactive or piped input. It is _so_ easy to adopt a style like: while not eof(filehandle): line = filehandle.nextline() ... that is it often thought that having offered the eof() function is a design error. (Of course in the example above the usual python idiom would win out from existing habit, but there are plenty of other situations where is would just be _easy_ to rely of istail() in whatever form.) | But I don't see why *adding* something like "ishead" would be so bad | (at worse by using a boolean somewhere as you mentioned). It is not awful, but as remarked: - extra storage cost to _every_ iterable, for a rarely used facility - extra runtime cost to maintain the state - _retroactive_ burden on _every_ iterator implementation presently existing; every iterator sudden needs to implement and offer this extra facility to be generate purpose use - it is easy to provide the facility on the rare occasions when it is needed Personally, I think point 3 above is the killer and 1 and 2 are serious counter arguments. | Anyway I was just asking if there is something better than enumerate. So | the answer is no? The fact that I have to create a tuple with an | incrementing integer for something as simple as checking that I'm at | the head just sounds awfully unpythonic to me. You can just use a boolean if you like. I have plent of loops like: first = true for i in iterable: if first: blah ... ... first = False Cheap and easy. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Bye and bye, God caught his eye, - Epitaph for a waiter by David McCord From miki.tebeka at gmail.com Wed Sep 7 20:24:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Wed, 7 Sep 2011 17:24:53 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> I guess enumerate is the best way to check for first argument. Note that if someone passes you the iterator as argument you have now way of checking if the consumed items from it. istail can be implemented using itertools.chain, see https://gist.github.com/1202260 From steve+comp.lang.python at pearwood.info Wed Sep 7 20:24:58 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 10:24:58 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Laurent wrote: > Hi there, > > What is the simplest way to check that you are at the beginning or at the > end of an iterable? I don't think this question is meaningful. There are basically two fundamental types of iterables, sequences and iterators. Sequences have random access and a length, so if the "start" and "end" of the sequence is important to you, just use indexing: beginning = sequence[0] end = sequence[-1] for i, x in enumerate(sequence): if i == 0: print("at the beginning") elif i == len(sequence)-1: print("at the end") print(x) Iterators don't have random access, and in general they don't have a beginning or an end. There may not be any internal sequence to speak of: the iterator might be getting data from a hardware device that provides values continuously, or some other series of values without a well-defined beginning or end. Example: def time(): from time import asctime while True: yield asctime() it = time() What would it even mean to say that I am at the beginning or end of it? Iterators have no memory, so in one sense you are *always* at the beginning of the iterator: next() always returns the next item, and the previous item is lost forever. So the answer to the question "Am I at the beginning of an iterator?" is always "You are now". For sequences, the question is best handled differently. For iterators, the question doesn't make sense in general. If you need an iterator that can report its internal state, write your own: import random, time class MyIter(object): def __init__(self): self.start = True self.end = False def __next__(self): if self.start: self.start = False if self.end: raise StopIteration if random.random() < 0.01: self.end = True return time.asctime() def __iter__(self): return self -- Steven From steve+comp.lang.python at pearwood.info Wed Sep 7 20:29:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 10:29:26 +1000 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> Message-ID: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Peter Otten wrote: > Classes and functions are grouped into > submodules by their functionality rather than employing Java's mechanical > one-class-per-file pattern. Surely it's an anti-pattern? I suppose "one class per file" might be useful for those using an editor with no search functionality. Other than that, is there any justification for this rule? Any Java fans want to defend this? If "one class per file", why not "one method per class" too? Why is the second rule any more silly than the first? -- Steven From cdchong at stanford.edu Wed Sep 7 20:37:51 2011 From: cdchong at stanford.edu (Christophe Chong) Date: Wed, 7 Sep 2011 17:37:51 -0700 Subject: Floating point multiplication in python In-Reply-To: References: Message-ID: And then we learned in class what happens when you're calculating "0.1" with different precision in the industry. http://www.ima.umn.edu/~arnold/disasters/patriot.html Beware. On Tue, Sep 6, 2011 at 3:14 AM, Thomas Rachel < nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de> wrote: > Am 06.09.2011 07:57 schrieb xyz: > >> hi all: >> >> As we know , 1.1 * 1.1 is 1.21 . >> But in python ,I got following : >> >> 1.1 * 1.1 >>>>> >>>> 1.2100000000000002 >> >> why python get wrong result? Who can tell me where's the >> 0.0000000000000002 from? >> > > 1.1 does not fit in a binary floating point number. It is approximated - in > binary! - as 1.000110011001100110011 ... (periodically). > > Note that, while in the decimal system we normally use, only numbers which > have other components in the denominator than 2 or 5 are periodically, in > the binary systems only components with 2 are allowed in order not to be > periodically. > > Example: 3.453 is not periodically, because it is 3453/100 and 100 has only > the factors 2 and 5, each twice. > > 1/3 = .3333333... is periodically, because it has the factor 3. The same > applies to 1/6, which has 2 and 3 as factors. The latter destroys the > non-periodical behaviour. > > As said, in the dual system, only the 2 is allowed. > > .5 (10) = 2** -1 = .1 (2). > .25 (10) = 2 ** -2 = .01 (2). > .75 (10) = their sum = .11 (2). > > But .1 (1/10) is more complicated, -2 would be as well. > > As the IEEE floating point representation is limited, there is a slight > error value which makes the stored value differ from the intended one. > > Look here: > > > > x=(1,0,0,0,1,1,0,0,1,1,0,0,1,**1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,** >>>> 1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,**0,1,1,0,0,1,1,0,0,1,1,0,0,1,1) >>>> a=0 >>>> for n,i in enumerate(x): a += i*2**-n; print a, a-1.1, i*2**-n, a-olda >>>> >>> ... > 1 -0.1 1 1 > 1.0 -0.1 0.0 0.0 > 1.0 -0.1 0.0 0.0 > 1.0 -0.1 0.0 0.0 > 1.0625 -0.0375 0.0625 0.0625 > 1.09375 -0.00625 0.03125 0.03125 > 1.09375 -0.00625 0.0 0.0 > 1.09375 -0.00625 0.0 0.0 > 1.09765625 -0.00234375 0.00390625 0.00390625 > 1.099609375 -0.000390625 0.001953125 0.001953125 > 1.099609375 -0.000390625 0.0 0.0 > 1.099609375 -0.000390625 0.0 0.0 > 1.09985351562 -0.000146484375 0.000244140625 0.000244140625 > 1.09997558594 -2.44140625001e-05 0.0001220703125 0.0001220703125 > 1.09997558594 -2.44140625001e-05 0.0 0.0 > 1.09997558594 -2.44140625001e-05 0.0 0.0 > 1.09999084473 -9.15527343759e-06 1.52587890625e-05 1.52587890625e-05 > 1.09999847412 -1.52587890634e-06 7.62939453125e-06 7.62939453125e-06 > 1.09999847412 -1.52587890634e-06 0.0 0.0 > 1.09999847412 -1.52587890634e-06 0.0 0.0 > 1.0999994278 -5.72204589933e-07 9.53674316406e-07 9.53674316406e-07 > 1.09999990463 -9.53674317294e-08 4.76837158203e-07 4.76837158203e-07 > 1.09999990463 -9.53674317294e-08 0.0 0.0 > 1.09999990463 -9.53674317294e-08 0.0 0.0 > 1.09999996424 -3.57627869541e-08 5.96046447754e-08 5.96046447754e-08 > 1.09999999404 -5.96046456636e-09 2.98023223877e-08 2.98023223877e-08 > 1.09999999404 -5.96046456636e-09 0.0 0.0 > 1.09999999404 -5.96046456636e-09 0.0 0.0 > 1.09999999776 -2.23517426789e-09 3.72529029846e-09 3.72529029846e-09 > 1.09999999963 -3.72529118664e-10 1.86264514923e-09 1.86264514923e-09 > 1.09999999963 -3.72529118664e-10 0.0 0.0 > 1.09999999963 -3.72529118664e-10 0.0 0.0 > 1.09999999986 -1.3969847501e-10 2.32830643654e-10 2.32830643654e-10 > 1.09999999998 -2.32831531832e-11 1.16415321827e-10 1.16415321827e-10 > 1.09999999998 -2.32831531832e-11 0.0 0.0 > 1.09999999998 -2.32831531832e-11 0.0 0.0 > 1.09999999999 -8.73123795486e-12 1.45519152284e-11 1.45519152284e-11 > 1.1 -1.45528034068e-12 7.27595761418e-12 7.27595761418e-12 > 1.1 -1.45528034068e-12 0.0 0.0 > 1.1 -1.45528034068e-12 0.0 0.0 > 1.1 -5.45785638906e-13 9.09494701773e-13 9.09494701773e-13 > 1.1 -9.10382880193e-14 4.54747350886e-13 4.54747350886e-13 > 1.1 -9.10382880193e-14 0.0 0.0 > 1.1 -9.10382880193e-14 0.0 0.0 > 1.1 -3.41948691585e-14 5.68434188608e-14 5.68434188608e-14 > 1.1 -5.77315972805e-15 2.84217094304e-14 2.84217094304e-14 > 1.1 -5.77315972805e-15 0.0 0.0 > 1.1 -5.77315972805e-15 0.0 0.0 > 1.1 -2.22044604925e-15 3.5527136788e-15 3.5527136788e-15 > 1.1 -4.4408920985e-16 1.7763568394e-15 1.7763568394e-15 > 1.1 -4.4408920985e-16 0.0 0.0 > 1.1 -4.4408920985e-16 0.0 0.0 > 1.1 -2.22044604925e-16 2.22044604925e-16 2.22044604925e-16 > 1.1 0.0 1.11022302463e-16 2.22044604925e-16 > 1.1 0.0 0.0 0.0 > 1.1 0.0 0.0 0.0 > 1.1 0.0 1.38777878078e-17 0.0 > 1.1 0.0 6.93889390391e-18 0.0 > > So here we have reached the point where the maximum precision is reached - > a doesn't change anymore, although it should. The error is about 1E-16. > > Now if you multiply two values with an error, the error also propagates > into the result - PLUs the result can have its own error source - in the > same order of magnitude. > > (a+e) * (a+e) = a*a + 2*a*e + e*e. So your new error term is 2*a*e + e*e or > (2*a + e) * e. > > -- > http://mail.python.org/**mailman/listinfo/python-list > -- Christophe Chong Department of Economics Stanford University -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurent.payot at gmail.com Wed Sep 7 20:53:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 17:53:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: Yes of course the use of a boolean variable is obvious but I'm mixing python code with html using Mako templates. In Mako for code readability reasons I try to stick to simple "for" and "if" constructions, and I try to avoid variables declarations inside the html, that's all. Thanks anyway. From laurent.payot at gmail.com Wed Sep 7 20:53:36 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 17:53:36 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: Yes of course the use of a boolean variable is obvious but I'm mixing python code with html using Mako templates. In Mako for code readability reasons I try to stick to simple "for" and "if" constructions, and I try to avoid variables declarations inside the html, that's all. Thanks anyway. From laurent.payot at gmail.com Wed Sep 7 21:05:17 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:05:17 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: > I don't think this question is meaningful. There are basically two > fundamental types of iterables, sequences and iterators. > > Sequences have random access and a length, so if the "start" and "end" of > the sequence is important to you, just use indexing: > > beginning = sequence[0] > end = sequence[-1] > for i, x in enumerate(sequence): > if i == 0: print("at the beginning") > elif i == len(sequence)-1: print("at the end") > print(x) > > > Iterators don't have random access, and in general they don't have a > beginning or an end. There may not be any internal sequence to speak of: > the iterator might be getting data from a hardware device that provides > values continuously, or some other series of values without a well-defined > beginning or end. Maybe I should have said "best way to check that you didn't start the iteration process yet" but you see what I mean. Well I guess I have to unlearn my bad lisp/scheme habits... From laurent.payot at gmail.com Wed Sep 7 21:06:53 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:06:53 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> Message-ID: Yes, I was just hoping for something already included that I wouldn't know (i'm new to Python). From tjreedy at udel.edu Wed Sep 7 21:06:56 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 21:06:56 -0400 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <20110908002314.GA15766@cskk.homeip.net> References: <20110908002314.GA15766@cskk.homeip.net> Message-ID: On 9/7/2011 8:23 PM, Cameron Simpson wrote: > On 07Sep2011 16:22, Laurent wrote: > | I totally understand the performance issue that an hypothetical > | "istail" would bring, even if I think it would just be the programmer's > | responsibility not to use it when it's not certain that an end can > | be detected. > > The trouble with these things is that their presence leads to stallable > code, often in libraries. Let the programmer write code dependent on > istail() without thinking of the stall case (or even the gratuitous > execution case, as in a generator with side effects in calling .next()) > and have that buried in a utilities function. > > Facilities like feof() in C and eof in Pascal already lead to lots of > code that runs happily with flat files and behaves badly in interactive > or piped input. It is _so_ easy to adopt a style like: > > while not eof(filehandle): > line = filehandle.nextline() > ... > > that is it often thought that having offered the eof() function is a > design error. (Of course in the example above the usual python idiom > would win out from existing habit, but there are plenty of other > situations where is would just be _easy_ to rely of istail() in whatever > form.) > > | But I don't see why *adding* something like "ishead" would be so bad > | (at worse by using a boolean somewhere as you mentioned). > > It is not awful, but as remarked: > - extra storage cost to _every_ iterable, for a rarely used facility > - extra runtime cost to maintain the state > - _retroactive_ burden on _every_ iterator implementation presently > existing; every iterator sudden needs to implement and offer this > extra facility to be generate purpose use > - it is easy to provide the facility on the rare occasions when it is > needed > > Personally, I think point 3 above is the killer and 1 and 2 are serious > counter arguments. The iterator protocol is intentionally as simple as sensibly possible. > | Anyway I was just asking if there is something better than enumerate. So > | the answer is no? The fact that I have to create a tuple with an > | incrementing integer for something as simple as checking that I'm at > | the head just sounds awfully unpythonic to me. > > You can just use a boolean if you like. I have plent of loops like: > > first = true > for i in iterable: > if first: > blah ... > ... > first = False > > Cheap and easy. Cheers, Or grab and process the first item separately from the rest. it = iter(iterable) try: first = next(it) except StopIteration: raise ValueError("Empty iterable not allowed") for i in it: -- Terry Jan Reedy From tjreedy at udel.edu Wed Sep 7 21:08:11 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 07 Sep 2011 21:08:11 -0400 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <4e680b5b$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/7/2011 8:24 PM, Steven D'Aprano wrote: > I don't think this question is meaningful. There are basically two > fundamental types of iterables, sequences and iterators. And non-sequence iterables like set and dict. > Sequences have random access and a length, so if the "start" and "end" of > the sequence is important to you, just use indexing: > > beginning = sequence[0] > end = sequence[-1] > for i, x in enumerate(sequence): > if i == 0: print("at the beginning") > elif i == len(sequence)-1: print("at the end") > print(x) And finite non-sequences can be turned into sequences with list(iterable). -- Terry Jan Reedy From laurent.payot at gmail.com Wed Sep 7 21:08:51 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:08:51 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Interesting. I will check that yield functionality out. Thanks. From laurent.payot at gmail.com Wed Sep 7 21:08:51 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:08:51 -0700 (PDT) Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Interesting. I will check that yield functionality out. Thanks. From jenn.duerr at gmail.com Wed Sep 7 21:32:21 2011 From: jenn.duerr at gmail.com (noydb) Date: Wed, 7 Sep 2011 18:32:21 -0700 (PDT) Subject: how to make fxn argument work with setting a field value Message-ID: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> What do I need to do to line 14 code below to get it to recognize the field name and not the argument name? I get this error with below code at line 13, the print row.rankFld line >RuntimeError: Row: Field rankFld does not exist A field called rankFld does not, should not exist. rankFld is "RANKa" (in this first iteration), which does exist (gets added in line 6, verified). Line 14 fails too, if 13 is commented out. ## import arcpy fc = r"C:\test\scratch.gdb\sort_test1" def rank(inFC, outFC, scoreFld, popFld, rankFld): arcpy.AddField_management(inFC, rankFld, "LONG") arcpy.management.Sort(inFC, outFC, [[scoreFld, "DESCENDING"], [popFld, "DESCENDING"]]) i = 0 print rankFld # >RANKa rows = arcpy.UpdateCursor(fc) for row in rows: i = i + 1 print row.rankFld row.rankFld = i ## line 14 rows.updateRow(row) return sortedFC # out1 = r"C:\test\scratch.gdb\rankfxn6" out2 = r"C:\test\scratch.gdb\rankfxn7" rank(fc, out1, "SCOREa", "COUNT1", "RANKa") rank(out1, out2, "SCOREb", "COUNT2", "RANKb") ## From laurent.payot at gmail.com Wed Sep 7 21:40:23 2011 From: laurent.payot at gmail.com (Laurent) Date: Wed, 7 Sep 2011 18:40:23 -0700 (PDT) Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: Neat. But I can see some "print(x)" and some "print x". What is the Python version? From python at mrabarnett.plus.com Wed Sep 7 22:11:07 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 03:11:07 +0100 Subject: how to make fxn argument work with setting a field value In-Reply-To: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: <4E68243B.7060104@mrabarnett.plus.com> On 08/09/2011 02:32, noydb wrote: > What do I need to do to line 14 code below to get it to recognize the > field name and not the argument name? > > I get this error with below code at line 13, the print row.rankFld > line >> RuntimeError: Row: Field rankFld does not exist > A field called rankFld does not, should not exist. rankFld is > "RANKa" (in this first iteration), which does exist (gets added in > line 6, verified). > Line 14 fails too, if 13 is commented out. > > > ## > import arcpy > > fc = r"C:\test\scratch.gdb\sort_test1" > > def rank(inFC, outFC, scoreFld, popFld, rankFld): > arcpy.AddField_management(inFC, rankFld, "LONG") > arcpy.management.Sort(inFC, outFC, [[scoreFld, "DESCENDING"], > [popFld, "DESCENDING"]]) > i = 0 > print rankFld #>RANKa > rows = arcpy.UpdateCursor(fc) > for row in rows: > i = i + 1 > print row.rankFld > row.rankFld = i ## line 14 > rows.updateRow(row) > > return sortedFC > # > > out1 = r"C:\test\scratch.gdb\rankfxn6" > out2 = r"C:\test\scratch.gdb\rankfxn7" > > rank(fc, out1, "SCOREa", "COUNT1", "RANKa") > rank(out1, out2, "SCOREb", "COUNT2", "RANKb") > ## The documentation mentions "getValue" and "setValue": http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z0000001q000000 From clp2 at rebertia.com Wed Sep 7 22:27:09 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 7 Sep 2011 19:27:09 -0700 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> <7d4ab46b-d37e-4851-bea3-11ce040815d5@glegroupsg2000goo.googlegroups.com> Message-ID: On Wed, Sep 7, 2011 at 5:24 PM, Miki Tebeka wrote: > I guess enumerate is the best way to check for first argument. Note that if someone passes you the iterator as argument you have now way of checking if the consumed items from it. > > istail can be implemented using itertools.chain, see https://gist.github.com/1202260 For the archives, if Gist ever goes down: from itertools import chain def istail(it): '''Check if iterator has one more element. Return True/False and iterator.''' try: i = next(it) except StopIteration: return False, it try: j = next(it) return False, chain([i, j], it) except StopIteration: return True, chain([i], it) t, it = istail(iter([])) print t, list(it) t, it = istail(iter([1])) print t, list(it) t, it = istail(iter([1, 2])) print t, list(it) From rosuav at gmail.com Wed Sep 7 22:39:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 8 Sep 2011 12:39:16 +1000 Subject: How to structure packages In-Reply-To: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Sep 8, 2011 at 10:29 AM, Steven D'Aprano wrote: > Peter Otten wrote: > >> Classes and functions are grouped into >> submodules by their functionality rather than employing Java's mechanical >> one-class-per-file pattern. > > Surely it's an anti-pattern? I don't think that's true; Java merely enforces one _public_ class per source file. A file can have non-public classes, although one .class file has only one class in it (so javac will sometimes make multiple object files from one source file). I'm not wholly sure of the significance of public classes, though, and whether or not it's possible to do your logical grouping and just let them be non-public. BTW, I am not a Java fan, and I don't have any defense prepared. I haven't actually written any serious Java code for a number of years. Used to use it back when IBM reckoned that Java would be the big thing that sells OS/2. ChrisA From sahil at FreeBSD.org Thu Sep 8 00:00:20 2011 From: sahil at FreeBSD.org (Sahil Tandon) Date: Thu, 8 Sep 2011 00:00:20 -0400 Subject: Running Python Demo on the Web? In-Reply-To: References: Message-ID: <20110908040019.GH3046@magic.hamla.org> On Wed, 2011-09-07 at 18:40:23 -0700, Laurent wrote: > Neat. But I can see some "print(x)" and some "print x". What is the > Python version? See: http://docs.python.org/release/3.2.2/whatsnew/3.0.html#print-is-a-function http://www.python.org/dev/peps/pep-3105/ -- Sahil Tandon From 1248283536 at qq.com Thu Sep 8 00:24:15 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 12:24:15 +0800 Subject: my multi-download program can't finish Message-ID: here is the program, # basic structure,omit something import Queue import httplib2 import threading jobs = Queue.Queue() name=something #omit ,it is a web list to download for x in name: jobs.put(x) def download(): while not jobs.empty(): try: url = jobs.get() hx = httplib2.Http() resp, content = hx.request(url, headers=headers) jobs.task_done() except: print "wrong" , url if __name__ == '__main__': for i in range(10): threading.Thread(target=download).start() jobs.join() when it run ,it can download someting , it is strang:there is wrong output ,some web can't get,but the program can't stop,it stay ,run ,can't fininsh, i don't know why? -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Thu Sep 8 00:50:52 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 12:50:52 +0800 Subject: multi-down in threading module Message-ID: i want to download data in multiprocess ,i know the threading structure,but i can't finish it, would you mind to revise it ? any advice appreciated. [code] import urllib import threading URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv" symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN') url =[ URL % '+'.join(sym) for sym in symbols] num=rang(3) def down(url): print urllib.urlopen(url).read() for i in num: #these code i can't finish t=threading.Thread(target=down,args= ) threads.append(t) for i in nmu: threads[i].start() for i in num: threads[i].join() [/code] -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 8 01:08:38 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 15:08:38 +1000 Subject: my multi-download program can't finish References: Message-ID: <4e684dd8$0$29970$c3e8da3$5496439d@news.astraweb.com> On Thu, 8 Sep 2011 02:24 pm ???? wrote: [...] > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the program > can't stop,it stay ,run ,can't fininsh, i don't know why? If you read the helpful error messages that Python provides, instead of hiding them and printing a useless message "wrong", you might find out why the failures are happening. Get rid of the try...except and see what exceptions you get. Then you will be in a better situation to decide which exceptions should be caught, and which are bugs that need to be fixed, and which should be allowed through. -- Steven From k.sahithi2862 at gmail.com Thu Sep 8 02:46:13 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Wed, 7 Sep 2011 23:46:13 -0700 (PDT) Subject: FOR EXCLUSIVE HOT ASIN PICS Message-ID: <1bceb162-850e-4ab8-bfe1-dc7658b8c7bc@r40g2000prf.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS SAMANTHA HOT EXCLUSIVE PHOTOS http://southactresstou.blogspot.com/2011/09/south-actress-samantha.html FOR EXCLUSIVE HOT ASIN PICS http://southactresstou.blogspot.com/2011/09/asin.html KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From jialiuonlineshoe03 at 163.com Thu Sep 8 03:29:14 2011 From: jialiuonlineshoe03 at 163.com (ms amy) Date: Thu, 8 Sep 2011 00:29:14 -0700 (PDT) Subject: paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) Message-ID: <0f6e0dd9-b138-4279-90db-f640daf66913@e34g2000prn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale lv shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale NBA shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale antick jeans (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale artful dudger (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hour-buy.com/) paypal wholesale clothing (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Prada (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Puma (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Sand (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Shox (paypal payment)( http://www.24hour-buy.com/) paypal wholesale soccer (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Versace (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Y-3 (paypal payment)( http://www.24hour-buy.com/ ) From 1248283536 at qq.com Thu Sep 8 03:46:55 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 8 Sep 2011 15:46:55 +0800 Subject: =?gbk?B?u9i4tKO6IG15ICBtdWx0aS1kb3dubG9hZCBwcm9n?= =?gbk?B?cmFtIGNhbid0IGZpbmlzaA==?= Message-ID: sometimes,the output is: error: [Errno 104] Connection reset by peer ------------------ ???? ------------------ ???: "Steven D'Aprano"; ????: 2011?9?8?(???) ??1:08 ???: "python-list"; ??: Re: my multi-download program can't finish On Thu, 8 Sep 2011 02:24 pm ???? wrote: [...] > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the program > can't stop,it stay ,run ,can't fininsh, i don't know why? If you read the helpful error messages that Python provides, instead of hiding them and printing a useless message "wrong", you might find out why the failures are happening. Get rid of the try...except and see what exceptions you get. Then you will be in a better situation to decide which exceptions should be caught, and which are bugs that need to be fixed, and which should be allowed through. -- Steven -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jenn.duerr at gmail.com Thu Sep 8 03:59:41 2011 From: jenn.duerr at gmail.com (noydb) Date: Thu, 8 Sep 2011 00:59:41 -0700 (PDT) Subject: how to make fxn argument work with setting a field value References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: > The documentation mentions "getValue" and "setValue": > > http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z00...- Hide quoted text - > > - Show quoted text - I have tried row.setValue(rankFld) = i for line 14. Get syntax error - cant assign to function call From gandalf at shopzeus.com Thu Sep 8 04:41:22 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 08 Sep 2011 10:41:22 +0200 Subject: Portable locale usage In-Reply-To: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> References: <1040759144.28661.1315420437334.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E687FB2.9020908@shopzeus.com> > I have set the system-wide locale to Croatian (Croatia) > on my development system as instructed by: > http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale > > Nevertheless, your proposal produces: > ('English_United States','1252') This is what I see on my Hungarian Windows: C:\Users\User>python Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'Hungarian_Hungary.1250' >>> locale.getlocale() ('Hungarian_Hungary', '1250') >>> So I'm 100% sure that the problem is with your system locale settings, not Python. > Note that I would very much like > to avoid changing the system locale > (this requires Administrator password and system restart). All right. But you understand, that Croatian ISO8859-2 is not supported on windows? So you will not be able to sort names with that under a windows system? (And it is not a limitation of Python.) >> Why are you trying to force a specific locale to your program anyway? > Because I wish to be able to correctly sort Croatian names. Well, all right. If you want to sort Croatian names from a program that runs on an English (or whatever) system, then you will have to check the platform and use a locale that is supported by the platform. (But again, this is not Python's limitation. Python doesn't know what encodings are supported, in advance, and you cannot use a locale that is not supported...) > I expect that most of my Windows users will not care > to configure their computers with the national locale > (and besides, that does not seem to work, anyway). Croatian users will most likely use a Croatian Windows, out of the box. And on those systems, using locale.setlocale(locale.LC_ALL, '') will work perfectly. I'm not sure why it doesn't work on an English Windows with locale changed... I'm not a big fan of Windows, but I remember once I had to install a language pack for Windows before I could use a localized program. This might be what you need? Best, Laszlo From dan at tombstonezero.net Thu Sep 8 05:51:58 2011 From: dan at tombstonezero.net (Dan Sommers) Date: Thu, 8 Sep 2011 09:51:58 +0000 (UTC) Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 08 Sep 2011 10:29:26 +1000, Steven D'Aprano wrote: > I suppose "one class per file" might be useful for those using an editor > with no search functionality. Other than that, is there any > justification for this rule? Any Java fans want to defend this? Back in the dark ages known as the 1980s, we had a one-C-function-per- file rule on a project with tens of thousands of C functions. The big benefit was that we always knew which source file contained which function. Computers could search a directory tree much more quickly than that much source code. (The exception was the so-called Information Cluster, a collection of functions surrounding a data store, the predecessor to the modern day object-with-state and/or closure). Not a Java fan'ly yours, Dan From egbertum at xs4all.nl Thu Sep 8 05:55:02 2011 From: egbertum at xs4all.nl (egbert) Date: Thu, 8 Sep 2011 11:55:02 +0200 Subject: DRY and class variables Message-ID: <20110908095502.GA3637@xs4all.nl> My classes correspond to sql tables. In these classes I want to have several class variables that refer to data that are common to all instances. The assignment statements for the class variables are the same in all classes, except that of these instructions needs the name of the class itself. That name is used to read a file with meta-data. So what I have now is something like this (simplified): class TableOne(object): m = Metadata('TableOne') m.do_something() def __init__(self): etc class TableTwo(object): m = Metadata('TableTwo') m.do_something() def __init__(self): etc I have tried: - to eliminate the class name argument, but in this phase of the object creation __class__ and __name__ are not available - to move the two statements to a superclass, but the class variables come in the superclass namespace, not in the subclass namespace. Any ideas ? e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From tartley at tartley.com Thu Sep 8 06:22:05 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 8 Sep 2011 03:22:05 -0700 (PDT) Subject: How to structure packages In-Reply-To: <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thursday, September 8, 2011 1:29:26 AM UTC+1, Steven D'Aprano wrote: > Steven D'Aprano wrote: > > Other than that, is there any justification > for this rule? Any Java fans want to defend this? > > If "one class per file", why not "one method per class" too? Why is the > second rule any more silly than the first? Hey. I'm not a Java fan but I'll give it a go. One method per class is not a good idea because a class is a bunch of code that forms a coherent conceptual bundle of functionality. Often, to provide such a bundle, it requires more than one method. To split these methods across several classes would be splitting up a single coherent entity, which makes it harder to understand the purpose and identity of the entity, and more fiddly to delineate the boundary between one such entity and the next. On the other hand, IMHO one class per file is often a good idea. Since a class is a single coherent bundle, then the natural way to split a program into files is often to divide it into these same coherent bundles. Sometimes you have two or more classes that are conceptually very tightly coupled, and it makes sense to gather them up into a single file. However, for me, this is the exception rather than the rule, so in the general case, I usually end up with code that has one class per file. It's only a rule-of-thumb though, and should be broken whenever it seems appropriate. From t at jollybox.de Thu Sep 8 06:22:33 2011 From: t at jollybox.de (Thomas Jollans) Date: Thu, 08 Sep 2011 12:22:33 +0200 Subject: DRY and class variables In-Reply-To: <20110908095502.GA3637@xs4all.nl> References: <20110908095502.GA3637@xs4all.nl> Message-ID: <4E689769.3050701@jollybox.de> On 08/09/11 11:55, egbert wrote: > My classes correspond to sql tables. > In these classes I want to have several class variables > that refer to data that are common to all instances. > > The assignment statements for the class variables are the same > in all classes, except that of these instructions needs the name > of the class itself. That name is used to read a file with meta-data. > > So what I have now is something like this (simplified): > > class TableOne(object): > m = Metadata('TableOne') > m.do_something() > def __init__(self): > etc > > class TableTwo(object): > m = Metadata('TableTwo') > m.do_something() > def __init__(self): > etc > > I have tried: > - to eliminate the class name argument, but in this phase of the > object creation __class__ and __name__ are not available > - to move the two statements to a superclass, but the class variables > come in the superclass namespace, not in the subclass namespace. > > Any ideas ? You should be able to do this with a metaclass (almost certainly overkill), or with a class decorator (Python 2.6+): def with_metadata (cls): cls.m = Metadata (cls.__name__) cls.m.do_something () return cls @with_metadata class TableOne: # foo pass From adam.jorgensen.za at gmail.com Thu Sep 8 06:30:21 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Thu, 8 Sep 2011 12:30:21 +0200 Subject: [Python-ideas] relaxing keyword usage restrictions In-Reply-To: References: <20110906164103.772ed18b@resist.wooz.org> <20110906183346.2bcdfbf8@resist.wooz.org> <20110906215717.62adf161@resist.wooz.org> Message-ID: About the only keyword I can think of this being even slightly useful for would be class and even then I think that clazz is a pretty acceptable substitute. -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at vanoostrum.org Thu Sep 8 06:53:45 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 12:53:45 +0200 Subject: Need help with simple OOP Python question References: <87sjobo3es.fsf@benfinney.id.au> <93d65d9e-8a15-4423-94c0-3d385def24ed@et6g2000vbb.googlegroups.com> Message-ID: Terry Reedy writes: > Indexing objects by their internal id is usually useless. obj.id is not the internal id. -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From piet at vanoostrum.org Thu Sep 8 07:01:10 2011 From: piet at vanoostrum.org (Piet van Oostrum) Date: Thu, 08 Sep 2011 13:01:10 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net> <86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com> <9ccoqkF5efU1@mid.individual.net> <9ck5upFlpnU1@mid.individual.net> <9cmq1vFk6fU1@mid.individual.net> <9cnaekF5nfU1@mid.individual.net> <9cor4gFk15U1@mid.individual.net> <9cpbddFtidU1@mid.individual.net> <9cqdb0Fpn4U1@mid.individual.net> Message-ID: "Fokke Nauta" writes: > "Piet van Oostrum" wrote in message > news:m2zkigartn.fsf at cochabamba.vanoostrum.org... >> "Fokke Nauta" writes: >> >> >>> INFO:DAVServer.fshandler:get_data: d:\webdav not found >>> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >>> Gecko/ >>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >>> Gecko/ >>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>> >> From the log it looks like you are trying to access the server with the >> url: >> >> http://localhost:8008/ or something similar. > > Yes, I do. > >> This won't work as you would try to access the root of your webdav >> directory in this way (i.e. D:/webdav). The webdav server can only serve >> files, not directories, so you would have to access >> http://localhost:8008/somefile.txt where somefile.txt is a file in >> D:/webdav. > > OK, thanks. I am not familiar to WebDAV. > I tried. Got something different (at least something happened): > "Setuptools version 0.6c9 or greater has been installed. > (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" > > Wasn't able to find ez_setup.py yet. > Google for it and install. But I don't understand. You already had WebDav installed, so why do you need ez_setup.py? >> This only applies to acces using a browser. If you access the server >> through a webdav-aware client (for example the Finder on Mac OS X, or >> probably the Windows Explorer) it can serve the contents of the directory. >> -- > > Thanks. I am just trying to use a calendar with a webdav server. I don't > have any experience with that. > Simply using my browser to try it out. Did you try the calendar with the WebDav server running? Dit you put a file in D:\webdav and try to get it with the browser? -- Piet van Oostrum WWW: http://pietvanoostrum.com/ PGP key: [8DAE142BE17999C4] From rosuav at gmail.com Thu Sep 8 08:12:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 8 Sep 2011 22:12:59 +1000 Subject: lfun and such In-Reply-To: <4E68B08D.2090800@dirix.nu> References: <4E68AC0D.6010007@dirix.nu> <4E68B08D.2090800@dirix.nu> Message-ID: On Thu, Sep 8, 2011 at 10:09 PM, Marc Dirix wrote: > scratch that. > > Silly me. > Heh. I'm curious now as to what was wrong, but am glad it's all working! I just switched back from my test run where I made a minimal class implementing `[]() and `[]=() to see if there was something weirdly wrong. ChrisA From simoncropper at fossworkflowguides.com Thu Sep 8 08:26:31 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Thu, 08 Sep 2011 22:26:31 +1000 Subject: Create an index from a webpage Message-ID: <4E68B477.9020703@fossworkflowguides.com> Hi, I am getting dizzy on google. I am after a way of pointing a python routine to my website and have it create a tree, represented as a hierarchical HTML list in a webpage, of all the pages in that website (recursive list of internal links to HTML documents; ignore images, etc.). It is essentially a contents page or sitemap for the site. Interestingly, despite trying quite a few keyword combinations, I was unable to find such a script. Anyone have any ideas? -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From PointedEars at web.de Thu Sep 8 08:38:53 2011 From: PointedEars at web.de (Thomas 'PointedEars' Lahn) Date: Thu, 08 Sep 2011 14:38:53 +0200 Subject: Create an index from a webpage References: Message-ID: <1537032.qVoOGUtdWV@PointedEars.de> Simon Cropper wrote: > I am after a way of pointing a python routine to my website and have it > create a tree, represented as a hierarchical HTML list in a webpage, of > all the pages in that website (recursive list of internal links to HTML > documents; ignore images, etc.). > > It is essentially a contents page or sitemap for the site. If all else fails, use markup parsers like - - and write it yourself. It is not hard to do. -- PointedEars Bitte keine Kopien per E-Mail. / Please do not Cc: me. From fnautaNO at SPAMiae.nl Thu Sep 8 09:57:48 2011 From: fnautaNO at SPAMiae.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 15:57:48 +0200 Subject: Installing WebDAV server References: <9cbvupFjr3U3@mid.individual.net><86b084e0-09a8-4997-9e0c-4526d7851e1d@s2g2000vby.googlegroups.com><9ccoqkF5efU1@mid.individual.net><9ck5upFlpnU1@mid.individual.net><9cmq1vFk6fU1@mid.individual.net><9cnaekF5nfU1@mid.individual.net><9cor4gFk15U1@mid.individual.net><9cpbddFtidU1@mid.individual.net><9cqdb0Fpn4U1@mid.individual.net> Message-ID: <9crvuvFpt2U1@mid.individual.net> "Piet van Oostrum" wrote in message news:m2mxefb8nd.fsf at cochabamba.vanoostrum.org... > "Fokke Nauta" writes: > >> "Piet van Oostrum" wrote in message >> news:m2zkigartn.fsf at cochabamba.vanoostrum.org... >>> "Fokke Nauta" writes: >>> >>> >>>> INFO:DAVServer.fshandler:get_data: d:\webdav not found >>>> XXX --- [07/Sep/2011 11:57:48] - Mozilla/5.0 UJindows NT 5.1; rv:6.0.1> >>>> Gecko/ >>>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>>> XXX --- [07/Sep/2011 11:57:52] - Mozilla/5.0 >>>> Gecko/ >>>> 20100101 Firefox/6.0.1 - "GET / HTTP/1.1" 404 - >>>> >>> From the log it looks like you are trying to access the server with the >>> url: >>> >>> http://localhost:8008/ or something similar. >> >> Yes, I do. >> >>> This won't work as you would try to access the root of your webdav >>> directory in this way (i.e. D:/webdav). The webdav server can only serve >>> files, not directories, so you would have to access >>> http://localhost:8008/somefile.txt where somefile.txt is a file in >>> D:/webdav. >> >> OK, thanks. I am not familiar to WebDAV. >> I tried. Got something different (at least something happened): >> "Setuptools version 0.6c9 or greater has been installed. >> (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" >> >> Wasn't able to find ez_setup.py yet. >> > Google for it and install. I did. > But I don't understand. You already had WebDav installed, so why do you > need ez_setup.py? Well, that was my mistake. I entered in the browser http://10.0.0.140:8081/a.txt (one of the textfiles in the directory d:\webdav on the server) and got the message: "Setuptools version 0.6c9 or greater has been installed. (Run "ez_setup.py -U setuptools" to reinstall or upgrade.)" At first I thought this came from the webdav server. That's why I searched for the ez_setup.py script. Once it was there, I ran it. It took me some time before I realized it was the actual content of the document a.txt on the webdav server what I saw. So it worked! Different that I expected, but it works. >>> This only applies to acces using a browser. If you access the server >>> through a webdav-aware client (for example the Finder on Mac OS X, or >>> probably the Windows Explorer) it can serve the contents of the >>> directory. >>> -- >> >> Thanks. I am just trying to use a calendar with a webdav server. I don't >> have any experience with that. >> Simply using my browser to try it out. > > Did you try the calendar with the WebDav server running? Not yet. The next step is the calendar. > Dit you put a file in D:\webdav and try to get it with the browser? Yes, and that worked! I am able to see the contents of text files. In my unfamiliarity with WebDAV I expected to open the directory and see the files in there. Many thanks for your help. Fokke From fnautaNO at SPAMiae.nl Thu Sep 8 10:10:37 2011 From: fnautaNO at SPAMiae.nl (Fokke Nauta) Date: Thu, 8 Sep 2011 16:10:37 +0200 Subject: Installing WebDAV server References: <9c4trjFcfmU1@mid.individual.net> Message-ID: <9cs0mvFoaU1@mid.individual.net> "Fokke Nauta" wrote in message news:9c4trjFcfmU1 at mid.individual.net... > Hi all, > > I am completely new to Python, but I'm confronted with a problem I can't > solve. > This is my question: > > I'm running a PC with XP Pro32, which acts as a file server/print > server/FTP server and web server. The web server is facilitated by the > Aprelium Abyss X2 server, and has Perl and PHP support on http and https. > It all works fine. > To do some research with some calender systems and to share the Outlook > calendar I need a WebDAV server. After googling I found the Python WebDAV > server. > I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. > Now I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 > and PyXML-0.8.4. In the PyWebDAV README it says: > > Installation and setup of server can be as easy as follows: > > $ easy_install PyWebDAV > $ davserver -D /tmp -n -J > > But of course it doesn't work like that. When I start up Python GUI I see > the ">>>" prompt instead of the "$" prompt. But where do I place the two > directories? And there is no easy_install script in the PyXML-0.8.4 > directory, only a setup.py and ez_setup.py script. I guess the latter is > the one to use. But how? > > How do I proceed next? > > Any help will be appreciated. > Thanks in advance. > > With regards, > Fokke Nauta > I have my webdav server up and running. Many thanks for all who contributed to solving this problem. With regards, Fokke Nauta From wolftracks at invalid.com Thu Sep 8 10:10:54 2011 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 08 Sep 2011 07:10:54 -0700 Subject: [OT] Anyone here familiar with installing Open Watcom F77? In-Reply-To: References: Message-ID: On 9/5/2011 9:36 AM, Colin J. Williams wrote: > On 05-Sep-11 12:22 PM, Dan Nagle wrote: >> Hello, >> >> On 2011-09-05 16:15:20 +0000, W. eWatson said: >> >>> On 9/5/2011 8:24 AM, Chris Angelico wrote: >>>> On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson >>>> wrote: >>>>> See Subject. >> >> >> >>>>> To what extent "familiar"? I have it installed on several computers, >>>> but only because it comes with Open Wat C/C++. >>>> >>>> With something off-topic like this, >> >> >> >>>> sierra_mtnview @ sbcglobal.net >>> Here's the story. >>> >>> As far as I can tell F77 1.8 is not available. I've Googled quite a >>> bit for it. My source for 1.9 is >>> . It gives me: >>> open-watcom-f77-win32-1.9.exe. >> >> On Usenet, comp.lang.fortran might be the best source of help for this. >> There's a good chance one of the regulars there can answer you >> within one or two posts. (I'll not cross-post, you can choose for >> yourself.) >> >> HTH >> > > You might get in touch with someone at Waterloo University, which is > located in Kitchener/Waterloo. > > This could have come from the 60's or 70's. > > Good luck. > > Colin W. > Left a message on Tuesday. No return call. I'm starting to make progress on this. From 1248283536 at qq.com Thu Sep 8 10:12:19 2011 From: 1248283536 at qq.com (=?utf-8?B?YWxpYXM=?=) Date: Thu, 8 Sep 2011 22:12:19 +0800 Subject: wrap the queue to multiprocess download Message-ID: here is my part of program,you can see main structure,i want to wrap it in class , class webdata(object): def __init__(self,arg): jobs = Queue.Queue() for x in name: jobs.put(self.url) def download(self): while not self.jobs.empty(): url = self.jobs.get() hx = httplib2.Http() resp, content = hx.request(url, headers=headers).read() self.jobs.task_done() def myrun(self): for i in range(30): threading.Thread(target=self.download).start() self.jobs.join() if __name__=="__main__": s=webdata('quote') s.myrun() when it run ,the output is : Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) File "/home/pengtao/workspace/try.py", line 75, in download resp, content = hx.request(url, headers=headers).read() File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1288, in request (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 201, in urlnorm (scheme, authority, path, query, fragment) = parse_uri(uri) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 197, in parse_uri groups = URI.match(uri).groups() TypeError: expected string or buffer when i use the same structrue, don't wrap it ,it can run . -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at torek.net Thu Sep 8 10:21:23 2011 From: nospam at torek.net (Chris Torek) Date: 8 Sep 2011 14:21:23 GMT Subject: Best way to check that you are at the beginning (the end) of an iterable? References: Message-ID: In article Cameron Simpson wrote: >Facilities like feof() in C and eof in Pascal already lead to lots of >code that runs happily with flat files and behaves badly in interactive >or piped input. It is _so_ easy to adopt a style like: > > while not eof(filehandle): > line = filehandle.nextline() > ... Minor but important point here: eof() in Pascal is predictive (uses a "crystal ball" to peer into the future to see whether EOF is is about to occur -- which really means, reads ahead, causing that interactivity problem you mentioned), but feof() in C is "post-dictive". The feof(stream) function returns a false value if the stream has not yet encountered an EOF, but your very next attempt to read from it may (or may not) immediately encounter that EOF. Thus, feof() in C is sort of (but not really) useless. (The actual use cases are to distinguish between "EOF" and "error" after a failed read from a stream -- since C lacks exceptions, getc() just returns EOF to indicate "failed to get a character due to end of file or error" -- or in some more obscure cases, such as the nonstandard getw(), to distinguish between a valid -1 value and having encountered an EOF. The companion ferror() function tells you whether an earlier EOF value was due to an error.) -- In-Real-Life: Chris Torek, Wind River Systems Intel require I note that my opinions are not those of WRS or Intel Salt Lake City, UT, USA (40?39.22'N, 111?50.29'W) +1 801 277 2603 email: gmail (figure it out) http://web.torek.net/torek/index.html From rosuav at gmail.com Thu Sep 8 10:26:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 00:26:03 +1000 Subject: wrap the queue to multiprocess download In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 12:12 AM, alias <1248283536 at qq.com> wrote: > ??? def? __init__(self,arg): > ??????? for? x? in? name: > > ??? s=webdata('quote') What you're doing here is iterating over the letters in the string 'quote'. It's adding one job for each letter. Is that your intention? ChrisA From python at mrabarnett.plus.com Thu Sep 8 11:06:11 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 16:06:11 +0100 Subject: how to make fxn argument work with setting a field value In-Reply-To: References: <7732a253-c834-4578-93eb-930346247e57@b20g2000vbz.googlegroups.com> Message-ID: <4E68D9E3.8060403@mrabarnett.plus.com> On 08/09/2011 08:59, noydb wrote: >> The documentation mentions "getValue" and "setValue": >> >> http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z00...- Hide quoted text - >> >> - Show quoted text - > > I have tried row.setValue(rankFld) = i for line 14. Get syntax error > - cant assign to function call Of course you can't assign to a function call! It's: row.setValue(rankFld, value) and: value = row.getValue(rankFld) From steve+comp.lang.python at pearwood.info Thu Sep 8 11:11:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 01:11:28 +1000 Subject: Create an index from a webpage References: <1537032.qVoOGUtdWV@PointedEars.de> Message-ID: <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Thomas 'PointedEars' Lahn wrote: > [climbs up on the soapbox and begins rant] Please don't use lmgtfy. The joke, such as it is, stopped being funny about three years ago. It's just annoying, and besides, it doesn't even work without Javascript. Kids today have no respect, get off my lawn, grump grump grump... It's no harder to put the search terms into a google URL, which still gets the point across without being a dick about it: www.google.com/search?q=python+sitemap [ends rant, climbs back down off soapbox] Or better still, use a search engine that doesn't track and bubble your searches: https://duckduckgo.com/html/?q=python+sitemap You can even LMDDGTFY if you insist. http://lmddgtfy.com/ Completely-undermining-my-own-message-ly y'rs, -- Steven From python at mrabarnett.plus.com Thu Sep 8 11:25:53 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 16:25:53 +0100 Subject: my multi-download program can't finish In-Reply-To: References: Message-ID: <4E68DE81.5060809@mrabarnett.plus.com> On 08/09/2011 05:24, ???? wrote: > here is the program, > > # basic structure,omit something > import Queue > import httplib2 > import threading > jobs = Queue.Queue() > name=something #omit ,it is a web list to download > for x in name: > jobs.put(x) > > def download(): > while not jobs.empty(): > try: > url = jobs.get() > hx = httplib2.Http() > resp, content = hx.request(url, headers=headers) > jobs.task_done() > except: > print "wrong" , url > > if __name__ == '__main__': > > for i in range(10): > threading.Thread(target=download).start() > jobs.join() > > when it run ,it can download someting , > it is strang:there is wrong output ,some web can't get,but the > program can't stop,it stay ,run ,can't fininsh, > i don't know why? > The line: jobs.join() will wait until every job has been marked as done by: jobs.task_done() In function "download", if there's an exception, it will go to the exception handler and print a message, but there's no: jobs.task_done() there to tell the queue that the job has been done. You need to tell it when a job has been processed. It doesn't care whether a job succeeded or failed, only whether it has been processed. From ssegvic at zemris.fer.hr Thu Sep 8 11:39:42 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Thu, 8 Sep 2011 17:39:42 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E687FB2.9020908@shopzeus.com> Message-ID: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "Sini?a ?egvi?" , python-list at python.org > Sent: Thursday, September 8, 2011 10:41:22 AM > Subject: Re: Portable locale usage > > I have set the system-wide locale to Croatian (Croatia) > > on my development system as instructed by: > > http://windows.microsoft.com/en-US/windows-vista/Change-the-system-locale > > > > Nevertheless, your proposal produces: > > ('English_United States','1252') > This is what I see on my Hungarian Windows: > > > C:\Users\User>python > Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit > (AMD64)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import locale > >>> locale.setlocale(locale.LC_ALL, '') > 'Hungarian_Hungary.1250' > >>> locale.getlocale() > ('Hungarian_Hungary', '1250') > >>> > > So I'm 100% sure that the problem is with your system locale settings, > not Python. I've just found out how to set the user locale on Windows. One has to go to Control panel -> Regional and language options, then select the tab named Formats, and finally set the box Current format to the desired language, which is in my case Croatian (Croatia). The whole tab says nothing about locales, I found this by try and test. This recipe is not affected by the system locale (which I was setting before)! Now locale.setlocale(locale.LC_ALL, '') sets the Croatian locale. > > I expect that most of my Windows users will not care > > to configure their computers with the national locale > > (and besides, that does not seem to work, anyway). > Croatian users will most likely use a Croatian Windows, out of the > box. > And on those systems, using locale.setlocale(locale.LC_ALL, '') will > work perfectly. Yes it's true, you were right, I was setting the Croatian language at the wrong place (I am not a Windows fan neither, I normally work on Linux). However, I am not completely happy with this. OK, no need for system restart, but still, it would be nice if Python program could manage around this by itself, of course, provided that the required locale is installed. > > Note that I would very much like > > to avoid changing the system locale > > (this requires Administrator password and system restart). > All right. But you understand, that Croatian ISO8859-2 is not > supported on windows? Yes I do understand that. I have commented that the Python's locale aliasing engine should not propose iso8859-2 on Windows systems, exactly for the reason you mention. > >> Why are you trying to force a specific locale to your program > >> anyway? > > Because I wish to be able to correctly sort Croatian names. > Well, all right. If you want to sort Croatian names from a program that > runs on an English (or whatever) system, then you will have to check the > platform and use a locale that is supported by the platform. (But again, > this is not Python's limitation. Python doesn't know what encodings are > supported, in advance, and you cannot use a locale that is not supported...) I fully agree. I commented that, if a proper locale is installed, the following should work on any system: locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) Currently the above does not work on Windows, and that is because the locale_alias for 'hr' is bound to 'hr_HR.ISO8859-2'. Check the source: .../Python-3.2.2/Lib/locale.py, line 537 I was arguing that, on a Windows system, the locale_alias for 'hr' should be bound to 'Croatian_Croatia.1250'. Cheers, Sinisa From ericsnowcurrently at gmail.com Thu Sep 8 12:44:04 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 8 Sep 2011 10:44:04 -0600 Subject: DRY and class variables In-Reply-To: <20110908095502.GA3637@xs4all.nl> References: <20110908095502.GA3637@xs4all.nl> Message-ID: On Thu, Sep 8, 2011 at 3:55 AM, egbert wrote: > My classes correspond to sql tables. > In these classes I want to have several class variables > that refer to data that are common to all instances. > > The assignment statements for the class variables are the same > in all classes, except that of these instructions needs the name > of the class itself. That name is used to read a file with meta-data. > > So what I have now is something like this (simplified): > > class TableOne(object): > ? ?m = Metadata('TableOne') > ? ?m.do_something() > ? ?def __init__(self): > ? ? ? ?etc > > class TableTwo(object): > ? ?m = Metadata('TableTwo') > ? ?m.do_something() > ? ?def __init__(self): > ? ? ? ?etc > > I have tried: > - to eliminate the class name argument, but in this phase of the > ?object creation __class__ and __name__ are not available > - to move the two statements to a superclass, but the class variables > ?come in the superclass namespace, not in the subclass namespace. > > Any ideas ? Definitely an interesting problem I've run into before. Here are two solutions: 1. in Python 3, use the metaclass __prepare__() (see http://code.activestate.com/recipes/577813/); 2. in Python 2 or 3, use a descriptor to defer creating your Metadata objects until after the class object is available (see http://code.activestate.com/recipes/577745/). HTH -eric > e > -- > Egbert Bouwman - Keizersgracht 197 II - 1016 DS ?Amsterdam - 020 6257991 > ======================================================================== > -- > http://mail.python.org/mailman/listinfo/python-list > From tavares at fe.up.pt Thu Sep 8 15:29:57 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 8 Sep 2011 12:29:57 -0700 (PDT) Subject: =?windows-1252?Q?Symposium_=93Experimental_and_Computational_Bio=2DImag?= =?windows-1252?Q?ing_and_Visualization=94_within_ICEM15_=96_Announce_=26_Call_f?= =?windows-1252?Q?or_Papers?= Message-ID: <839676a0-6525-4d74-8232-205ca9100001@cd4g2000vbb.googlegroups.com> Dear Colleague, Within the 15th International Conference on Experimental Mechanics (ICEM15), to be held in Faculty of Engineering, University of Porto, Porto, Portugal, in July 22-27, 2012, (www.fe.up.pt/clme/icem15/ index.htm), we are organizing a Symposium on ?Experimental and Computational Bio-Imaging and Visualization?. The main goal of the Symposium ?Experimental and Computational Bio- Imaging and Visualization? is to bring together researchers, developers and clinicians involved in the related fields of Bio- Imaging and Visualization, including Biomechanics, Experimental Biomechanics, Image Processing and Analysis, Medical Imaging, Mechanobiology, Tissues Engineering, Scientific Visualization and Software and Hardware Development, in order to set the major lines of development for the near future and establish a bridge between them. INSTRUCTIONS & SUBMISSION: - For instructions and submission, please access to the conference website at: www.fe.up.pt/clme/icem15/index.htm; - Please, note that, when submitting your work, you should indicate the Symposium ?Experimental and Computational Bio-Imaging and Visualization?. IMPORTANT DATES: - Submission of abstracts: 30 November, 2011; - Notification of acceptance: 13 January, 2012; - Submission of full-papers: 16 March, 2012. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Yongjie Zhang (Carnegie Mellon University, USA, jessicaz at andrew.cmu.edu) (Symposium organizers) From georgeryoung at gmail.com Thu Sep 8 15:51:17 2011 From: georgeryoung at gmail.com (gry) Date: Thu, 8 Sep 2011 12:51:17 -0700 (PDT) Subject: replace random matches of regexp Message-ID: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> [Python 2.7] I have a body of text (~1MB) that I need to modify. I need to look for matches of a regular expression and replace a random selection of those matches with a new string. There may be several matches on any line, and a random selection of them should be replaced. The probability of replacement should be adjustable. Performance is not an issue. E.g: if I have: SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = sqrt((0.02 + PUBLIC_TT_1.F))) OR I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but only with probability 0.7. I looked and looked for some computed thing in re's that I could stick and expression, but could not find such(for good reasons, I know). Any ideas how to do this? I would go for simple, even if it's wildly inefficient, though elegance is always admired... From python at mrabarnett.plus.com Thu Sep 8 16:12:34 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 08 Sep 2011 21:12:34 +0100 Subject: replace random matches of regexp In-Reply-To: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: <4E6921B2.2010300@mrabarnett.plus.com> On 08/09/2011 20:51, gry wrote: > [Python 2.7] > I have a body of text (~1MB) that I need to modify. I need to look > for matches of a regular expression and replace a random selection of > those matches with a new string. There may be several matches on any > line, and a random selection of them should be replaced. The > probability of replacement should be adjustable. Performance is not > an issue. E.g: if I have: > > SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN > PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, > PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM > (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) > =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = > sqrt((0.02 + PUBLIC_TT_1.F))) OR > > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... re.sub can accept a function as the replacement. It'll call the function when it finds a match, and the string returned by that function will be the replacement. You could write a function which returns either the original substring which was found or a different substring. From ndparker at gmail.com Thu Sep 8 16:18:00 2011 From: ndparker at gmail.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Thu, 08 Sep 2011 22:18:00 +0200 Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: <10875052.MZNQO6iqsQ@news.perlig.de> * gry wrote: > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... You can run a re.sub() with a function as replacement value. This function then either returns the replacement or the original match based on a weighted random value. nd -- "Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)" -- aus einer Rezension From __peter__ at web.de Thu Sep 8 16:43:15 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 22:43:15 +0200 Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: gry wrote: > [Python 2.7] > I have a body of text (~1MB) that I need to modify. I need to look > for matches of a regular expression and replace a random selection of > those matches with a new string. There may be several matches on any > line, and a random selection of them should be replaced. The > probability of replacement should be adjustable. Performance is not > an issue. E.g: if I have: > > SELECT max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN > PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, > PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM > (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (ceil(0.46) > =sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = > sqrt((0.02 + PUBLIC_TT_1.F))) OR > > I might want to replace '(max|min|cos|sqrt|ceil' with "public.\1", but > only with probability 0.7. I looked and looked for some computed > thing in re's that I could stick and expression, but could not find > such(for good reasons, I know). > Any ideas how to do this? I would go for simple, even if it's wildly > inefficient, though elegance is always admired... def make_sub(text, probability): def sub(match): if random.random() < probability: return text + match.group(1) return match.group(1) return sub print re.compile("(max|min|cos|sqrt|ceil)").sub(make_sub(r"public.", .7), sample) or even def make_sub(text, probability): def sub(match): if random.random() < probability: def group_sub(m): return match.group(int(m.group(1))) return re.compile(r"[\\](\d+)").sub(group_sub, text) return match.group(0) return sub print re.compile("(max|min|cos|sqrt|ceil)").sub(make_sub(r"public.\1", .7), sample) From egbertum at xs4all.nl Thu Sep 8 16:53:35 2011 From: egbertum at xs4all.nl (egbert) Date: Thu, 8 Sep 2011 22:53:35 +0200 Subject: DRY and class variables In-Reply-To: <4E689769.3050701@jollybox.de> References: <20110908095502.GA3637@xs4all.nl> <4E689769.3050701@jollybox.de> Message-ID: <20110908205335.GA18306@xs4all.nl> On Thu, Sep 08, 2011 at 12:22:33PM +0200, Thomas Jollans wrote: > You should be able to do this with a metaclass (almost certainly > overkill), or with a class decorator (Python 2.6+): > > def with_metadata (cls): > cls.m = Metadata (cls.__name__) > cls.m.do_something () > return cls > > @with_metadata > class TableOne: > # foo > pass Overnight I have become a decorator fan. I can postpone the study of metaclasses. Thanks. e -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From georgeryoung at gmail.com Thu Sep 8 17:19:29 2011 From: georgeryoung at gmail.com (gry) Date: Thu, 8 Sep 2011 14:19:29 -0700 (PDT) Subject: replace random matches of regexp References: <32cb758a-77de-4c56-9d7d-6f6db77b822f@u19g2000vbm.googlegroups.com> Message-ID: On Sep 8, 3:51?pm, gry wrote: To elaborate(always give example of desired output...) I would hope to get something like: SELECT public.max(PUBLIC.TT.I) AS SEL_0 FROM (SCHM.T RIGHT OUTER JOIN PUBLIC.TT ON (SCHM.T.I IS NULL)) WHERE (NOT(NOT((power(PUBLIC.TT.F, PUBLIC.TT.F) = cast(ceil(( SELECT 22 AS SEL_0 FROM (PUBLIC.TT AS PUBLIC_TT_0 JOIN PUBLIC.TT AS PUBLIC_TT_1 ON (public.ceil(0.46) =public.sin(PUBLIC_TT_1.F))) WHERE ((zeroifnull(PUBLIC_TT_0.I) = public.sqrt((0.02 + PUBLIC_TT_1.F))) OR notice the 'ceil' on the third line did not get changed. From paul.hermeneutic at gmail.com Thu Sep 8 18:29:39 2011 From: paul.hermeneutic at gmail.com (Paul Watson) Date: Thu, 08 Sep 2011 16:29:39 -0600 Subject: Django or web2py Message-ID: <9cstuhFnm0U1@mid.individual.net> I have read some of the talk around these two frameworks. Would you say that web2py is more geared toward the enterprise? Which one do you believe will be on Python 3 more quickly? From cs at zip.com.au Thu Sep 8 18:39:44 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 9 Sep 2011 08:39:44 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: Message-ID: <20110908223944.GA28756@cskk.homeip.net> On 08Sep2011 14:21, Chris Torek wrote: | In article | Cameron Simpson wrote: | >Facilities like feof() in C and eof in Pascal already lead to lots of | >code that runs happily with flat files and behaves badly in interactive | >or piped input. It is _so_ easy to adopt a style like: | > | > while not eof(filehandle): | > line = filehandle.nextline() | > ... | | Minor but important point here: eof() in Pascal is predictive (uses | a "crystal ball" to peer into the future to see whether EOF is is | about to occur -- which really means, reads ahead, causing that | interactivity problem you mentioned), but feof() in C is "post-dictive". | The feof(stream) function returns a false value if the stream has | not yet encountered an EOF, but your very next attempt to read from | it may (or may not) immediately encounter that EOF. Thanks. I had forgotten this nuance. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ "Where am I?" "In the Village." "What do you want?" "Information." "Whose side are you on?" "That would be telling. We want information. Information. Information!" "You won't get it!" "By hook or by crook, we will." "Who are you?" "The new number 2." "Who is number 1?" "You are number 6." "I am not a number, I am a free man!" [Laughter] From abhishek.vit at gmail.com Thu Sep 8 18:49:51 2011 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Thu, 8 Sep 2011 15:49:51 -0700 Subject: Processing a file using multithreads Message-ID: Hi Guys My experience with python is 2 days and I am looking for a slick way to use multi-threading to process a file. Here is what I would like to do which is somewhat similar to MapReduce in concept. # test case 1. My input file is 10 GB. 2. I want to open 10 file handles each handling 1 GB of the file 3. Each file handle is processed in by an individual thread using the same function ( so total 10 cores are assumed to be available on the machine) 4. There will be 10 different output files 5. once the 10 jobs are complete a reduce kind of function will combine the output. Could you give some ideas ? So given a file I would like to read it in #N chunks through #N file handles and process each of them separately. Best, -Abhi From simoncropper at fossworkflowguides.com Thu Sep 8 19:40:42 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 09:40:42 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E69527A.20608@fossworkflowguides.com> On 09/09/11 01:11, Steven D'Aprano wrote: > [SNIP] > It's no harder to put the search terms into a google URL, which still gets > the point across without being a dick about it: > [SNIP] [RANT] OK I was not going to say anything but... 1. Being told to google-it when I explicitly stated in my initial post that I had been doing this and had not been able to find anything is just plain rude. It is unconstructive and irritating. 2. I presume that python-list is a mail list for python users - beginners, intermediate and advanced. If it is not then tell me and I will go somewhere else. 3. Some searches, particularly for common terms throw millions of hits. 'Python' returns 147,000,000 results on google, 'Sitemap' returns 1,410,000,000 results. Even 'Python AND Sitemap' still returns 5,020 results. Working through these links takes you round and round with no clear solutions. Asking for help on the primary python mail list -- after conducting a preliminary investigation for tools, libraries, code snippets seemed legitimate. 4. AND YES, I could write a program but why recreate code when there is a strong likelihood that code already exists. One of the advantages of python is that a lot of code is redistributed under licences that promote reuse. So why reinvent the wheel when their is a library full of code. Sometimes you just need help finding the door. 4. If someone is willing to help me, rather than lecture me (or poke me to see if they get a response), I would appreciate it. [END RANT] For people that are willing to help. My original request was... I am after a way of pointing a python routine to my website and have it create a tree, represented as a hierarchical HTML list in a webpage, of all the pages in that website (recursive list of internal links to HTML documents; ignore images, etc.). In subsequent notes to Thomas 'PointedEars'... I pointed to an example of the desired output here http://lxml.de/sitemap.html -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From cs at zip.com.au Thu Sep 8 20:03:34 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 9 Sep 2011 10:03:34 +1000 Subject: killing a script In-Reply-To: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110909000334.GA9300@cskk.homeip.net> On 30Aug2011 14:13, Steven D'Aprano wrote: | On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote: | >> Yes, but if I am not mistaken, that will require me to put a line or | >> two after each os.system call. That's almost like whack-a-mole at the | >> code level rather than the Control-C level. OK, not a huge deal for | >> one script, but I was hoping for something simpler. I was hoping I | >> could put one line at the top of the script and be done with it. | > | > Write a function! That's what they're for after all :) | | I'm not sure that this is actually as simple as that, especially using | os.system. | | As I understand it, the scenario is this: | | The main script looks something like this: | | for x in whatever: | os.system('something.py x') | | Each time through the loop, a new Python process is started. Each process | runs in the foreground, capturing standard input, and so hitting Ctrl-C | kills *that* process, not the main script. Unless, by chance, the Ctrl-C | happens after the system call returns, but before the next one starts, it | is completely invisible to the parent process (the main script). Wrapping | os.system in a function does nothing to fix that. Presuming you're talking about UNIX, this is not correct. Ctrl-C at the terminal delivers SIGINT to _every_ process in the controlling process group for the terminal. It also has _nothing_ to do with the standard input. When you run a script, yea even a Python script, thus: myscript ... then job control capable shells (all of them, these days) put the python process running "myscript" in its own process group as the leader (being, initially, the only process in the group). If myscript forks other processes, as happens in os.system(), they are _also_ in that process group. _ALL_ of them receive the SIGINT from your Ctrl-C. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ DRM: the functionality of refusing to function. - Richard Stallman From greg.ewing at canterbury.ac.nz Thu Sep 8 20:03:45 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 09 Sep 2011 12:03:45 +1200 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: <9ct3f4FuvnU1@mid.individual.net> Abhishek Pratap wrote: > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) Are you expecting the processing to be CPU bound or I/O bound? If it's I/O bound, multiple cores won't help you, and neither will threading, because it's the disk doing the work, not the CPU. If it's CPU bound, multiple threads in one Python process won't help, because of the GIL. You'll have to fork multiple OS processes in order to get Python code running in parallel on different cores. -- Greg From rhodri at wildebst.demon.co.uk Thu Sep 8 20:32:42 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 09 Sep 2011 01:32:42 +0100 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 00:40:42 +0100, Simon Cropper wrote: > On 09/09/11 01:11, Steven D'Aprano wrote: >> [SNIP] >> It's no harder to put the search terms into a google URL, which still >> gets >> the point across without being a dick about it: > > [SNIP] > > [RANT] > > OK I was not going to say anything but... Ahem. You should expect a certain amount of ribbing after admitting that your Google-fu is weak. So is mine, but hey. > 4. If someone is willing to help me, rather than lecture me (or poke me > to see if they get a response), I would appreciate it. The Google Python Sitemap Generator (http://www.smart-it-consulting.com/article.htm?node=166&page=128, fourth offering when you google "map a website with Python") looks like a promising start. At least it produces something in XML -- filtering that and turning it into HTML should be fairly straightforward. -- Rhodri James *-* Wildebeest Herder to the Masses From nobody at nowhere.com Thu Sep 8 20:45:42 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 09 Sep 2011 01:45:42 +0100 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 08 Sep 2011 10:29:26 +1000, Steven D'Aprano wrote: > I suppose "one class per file" might be useful for those using an editor > with no search functionality. Other than that, is there any justification > for this rule? Any Java fans want to defend this? Not a Java fan, but: The Java compiler also acts as a "make" program. If it doesn't find a .class file for a needed class, it will search for the corresponding .java file and compile that. So to compile a complex program, you only need to compile the top-level file (e.g. HelloWorld.java), and it will compile everything which is required. No Makefile is needed, as the relationship between classes, object files and source files is fixed. From prachar at gmail.com Thu Sep 8 21:09:31 2011 From: prachar at gmail.com (papu) Date: Thu, 8 Sep 2011 18:09:31 -0700 (PDT) Subject: Python: Deleting specific words from a file. Message-ID: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Hello, I have a data file (un-structed messy file) from which I have to scrub specific list of words (delete words). Here is what I am doing but with no result: infile = "messy_data_file.txt" outfile = "cleaned_file.txt" delete_list = ["word_1","word_2"....,"word_n"] new_file = [] fin=open(infile,"") fout = open(outfile,"w+") for line in fin: for word in delete_list: line.replace(word, "") fout.write(line) fin.close() fout.close() I have put the code above in a file. When I execute it, I dont see the result file. I am not sure what the error is. Please let me know what I am doing wrong. From python at mrabarnett.plus.com Thu Sep 8 21:31:23 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 09 Sep 2011 02:31:23 +0100 Subject: Python: Deleting specific words from a file. In-Reply-To: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: <4E696C6B.7080609@mrabarnett.plus.com> On 09/09/2011 02:09, papu wrote: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > > Here is what I am doing but with no result: > > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] > fin=open(infile,"") > fout = open(outfile,"w+") > for line in fin: > for word in delete_list: > line.replace(word, "") > fout.write(line) > fin.close() > fout.close() > > I have put the code above in a file. When I execute it, I dont see the > result file. I am not sure what the error is. Please let me know what > I am doing wrong. The .replace method _returns_ its result. Strings are immutable, they can't be changed in-place. From davea at ieee.org Thu Sep 8 21:34:16 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 08 Sep 2011 21:34:16 -0400 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: <4E696D18.807@ieee.org> On 01/-10/-28163 02:59 PM, Abhishek Pratap wrote: > Hi Guys > > My experience with python is 2 days and I am looking for a slick way > to use multi-threading to process a file. Here is what I would like to > do which is somewhat similar to MapReduce in concept. > > # test case > > 1. My input file is 10 GB. > 2. I want to open 10 file handles each handling 1 GB of the file > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) > 4. There will be 10 different output files > 5. once the 10 jobs are complete a reduce kind of function will > combine the output. > > Could you give some ideas ? > > So given a file I would like to read it in #N chunks through #N file > handles and process each of them separately. > > Best, > -Abhi > You should probably forget threads, and simply do them as 10 separate processes, all launched by a single parent. Since they don't share any state, there's no need to get the inefficiency of threads. DaveA From rosuav at gmail.com Thu Sep 8 21:37:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 11:37:44 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: > The Java compiler also acts as a "make" program. If it doesn't find > a .class file for a needed class, it will search for the corresponding > .java file and compile that. So to compile a complex program, you only > need to compile the top-level file (e.g. HelloWorld.java), and it will > compile everything which is required. No Makefile is needed, as the > relationship between classes, object files and source files is fixed. > If that's the entire benefit, then I think this is a rather hefty price to pay for the elimination of a makefile. Oh wow, I can type "javac MyClass.java" and it picks up all the others! If you're dividing a project into multiple files already, is it that hard to have one more that defines the relationships between the others? Chris Angelico From simoncropper at fossworkflowguides.com Thu Sep 8 22:09:58 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 12:09:58 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E697576.5030301@fossworkflowguides.com> On 09/09/11 10:32, Rhodri James wrote: > On Fri, 09 Sep 2011 00:40:42 +0100, Simon Cropper > > Ahem. You should expect a certain amount of ribbing after admitting that > your Google-fu is weak. So is mine, but hey. I did not admit anything. I consider my ability to find this quite good actually. Others assumed that my "Google-fu is weak". > >> 4. If someone is willing to help me, rather than lecture me (or poke >> me to see if they get a response), I would appreciate it. > > The Google Python Sitemap Generator > (http://www.smart-it-consulting.com/article.htm?node=166&page=128, > fourth offering when you google "map a website with Python") looks like > a promising start. At least it produces something in XML -- filtering > that and turning it into HTML should be fairly straightforward. > I saw this in my original search. My conclusions were.. 1. The last update was in 2005. That is 6 years ago. In that time we have had numerous upgrades to HTML, Logs, etc. 2. The script expects to run on the webserver. I don't have the ability to run python on my webserver. 3. There are also a number of dead-links and redirects to Google Webmaster Central / Tools, which then request you submit a sitemap (as I alluded we get into a circular confusing cross-referencing situation) 4. The ultimate product - if you can get the package to work - would be a XML file you would need to massage to extract what you needed. To me this seems like overkill. I assume you could import the parent html file, scrap all the links on the same domain, dump these to a hierarchical list and represent this in HTML using BeautifulSoup or something similar. Certainly doable but considering the shear commonality of this task I don't understand why a simple script does not already exist - hence my original request for assistance. It would appear from the feedback so far this 'forum' is not the most appropriate to ask this question. Consequently, I will take your advice and keep looking... and if I don't find something within a reasonable time frame, just write something myself. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From steve+comp.lang.python at pearwood.info Thu Sep 8 22:14:55 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 12:14:55 +1000 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> Simon Cropper wrote: > 1. Being told to google-it when I explicitly stated in my initial post > that I had been doing this and had not been able to find anything is > just plain rude. It is unconstructive and irritating. Why so you did. Even though I wasn't the one who told you to google it, I'll apologise too because I was thinking the same thing. Sorry about that. > 3. Some searches, particularly for common terms throw millions of hits. > 'Python' returns 147,000,000 results on google, 'Sitemap' returns > 1,410,000,000 results. Even 'Python AND Sitemap' still returns 5,020 > results. How about "python generate a site map"? The very first link on DuckDuckGo is this: http://www.conversationmarketing.com/2010/08/python-sitemap-crawler-1.htm Despite the domain, there is actual Python code on the page. Unfortunately it looks like crappy code with broken formatting and a mix of <\br> tags, but it's a start. Searching for "site map" on PyPI returns a page full of hits: http://pypi.python.org/pypi?%3Aaction=search&term=site+map&submit=search Most of them seem to rely on a framework like Django etc, but you might find something useful. > 4. AND YES, I could write a program but why recreate code when there is > a strong likelihood that code already exists. "Strong" likelihood? Given how hard it is to find an appropriate sitemap generator written in Python, I'd say there is a strong likelihood that one that meets your needs and is publicly available under an appropriate licence is vanishingly small. If you do decide to write your own, please consider uploading it to PyPI under a FOSS licence. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 8 22:16:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 12:16:12 +1000 Subject: Create an index from a webpage [RANT, DNFTT] References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6976ec$0$29987$c3e8da3$5496439d@news.astraweb.com> Simon Cropper wrote: > Certainly doable but > considering the shear commonality of this task I don't understand why a > simple script does not already exist Perhaps it isn't as common or as simple as you believe. -- Steven From simoncropper at fossworkflowguides.com Thu Sep 8 22:43:58 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 12:43:58 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E697D6E.4010101@fossworkflowguides.com> On 09/09/11 12:14, Steven D'Aprano wrote: > If you do decide to write your own, please consider uploading it to PyPI > under a FOSS licence. At present I am definitely getting the impression that my assumption that something like this' must out there', is wrong. I am following people's links and suggestions (as well as my own; I have spent 1-2 hours looking) but have not found anything that is able to be used with only minor adjustments. I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, this page allows you to create the XML files that can be uploaded to google. But as stated I don't actually want what people now call 'sitemaps' I want a automatically updated 'index / contents page' to my website. For example, if I add a tutorial or update any of my links I want the 'global contents page' to be updated when the python script is run. I am now considering how I might address this requirement. If I create a python script I will post it on PyPI. As with all my work it will be released under the GPLv3 licence. Thanks for your help. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From chinakr at gmail.com Thu Sep 8 22:47:04 2011 From: chinakr at gmail.com (chinakr) Date: Thu, 8 Sep 2011 19:47:04 -0700 (PDT) Subject: Using web2py and deck.js to make HTML5 presentation Message-ID: web2py is one of the most popular Web Frameworks. web2py has MVC architecture, offering us excellent development efficiency and extensibility. web2py is very suitable for Web application development. deck.js is a JavaScript library for making HTML5 presentation. It supports keyboard navigation, themes switching and extensions. With deck.js, making HTML5 presentation becomes easy, beautiful and convinient. SEO Brief Guide is a HTML5 presentation developing with web2py and deck.js, wich is free and open source. Demo? http://openclass.vstudy.cn/seo/training Source code? http://vstudy.htexam.net/soft/download/web2py.app.openclass.w2p From rosuav at gmail.com Thu Sep 8 22:59:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 12:59:09 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4E697D6E.4010101@fossworkflowguides.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> Message-ID: On Fri, Sep 9, 2011 at 12:43 PM, Simon Cropper wrote: > At present I am definitely getting the impression that my assumption that > something like this' must out there', is wrong. > > I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, > this page allows you to create the XML files that can be uploaded to google. > But as stated I don't actually want what people now call 'sitemaps' I want a > automatically updated 'index / contents page' to my website. For example, if > I add a tutorial or update any of my links I want the 'global contents page' > to be updated when the python script is run. What you're looking at may be closer to autogenerated documentation than to a classic site map. There are a variety of tools that generate HTML pages on the basis of *certain information found in* all the files in a directory (as opposed to the entire content of those files). What you're trying to do may be sufficiently specific that it doesn't already exist, but it might be worth having a quick look at autodoc/doxygen - at least for some ideas. Chris Angelico From gordon at panix.com Thu Sep 8 23:16:13 2011 From: gordon at panix.com (John Gordon) Date: Fri, 9 Sep 2011 03:16:13 +0000 (UTC) Subject: Python: Deleting specific words from a file. References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: In <30f9b718-bb3c-4c92-8a03-0f760c993939 at a12g2000yqi.googlegroups.com> papu writes: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > Here is what I am doing but with no result: > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] What does new_file do? I don't see it used anywhere. > fin=open(infile,"") There should be an "r" inside those quotes. In fact this is an error and it will stop your program from running. > fout = open(outfile,"w+") What is the "+" supposed to do? > for line in fin: > for word in delete_list: > line.replace(word, "") replace() returns the modified string; it does not alter the existing string. Do this instead: line = line.replace(word, "") > fout.write(line) > fin.close() > fout.close() > I have put the code above in a file. When I execute it, I dont see the > result file. I am not sure what the error is. Please let me know what > I am doing wrong. When you say you don't see the result file, do you mean it doesn't get created at all? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From jack.bates at gmail.com Thu Sep 8 23:18:54 2011 From: jack.bates at gmail.com (Jack Bates) Date: Thu, 8 Sep 2011 20:18:54 -0700 Subject: buffer() as argument to ctypes function which expects c_void_p? Message-ID: How do you pass a Python buffer() value as an argument to a ctypes function, which expects a c_void_p argument? I keep getting TypeError: ctypes.ArgumentError: argument 2: : wrong type From simoncropper at fossworkflowguides.com Thu Sep 8 23:20:01 2011 From: simoncropper at fossworkflowguides.com (Simon Cropper) Date: Fri, 09 Sep 2011 13:20:01 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> Message-ID: <4E6985E1.9050009@fossworkflowguides.com> On 09/09/11 12:59, Chris Angelico wrote: > On Fri, Sep 9, 2011 at 12:43 PM, Simon Cropper > wrote: >> At present I am definitely getting the impression that my assumption that >> something like this' must out there', is wrong. >> >> I have found a XML-Sitemaps Generator at http://www.xml-sitemaps.com, >> this page allows you to create the XML files that can be uploaded to google. >> But as stated I don't actually want what people now call 'sitemaps' I want a >> automatically updated 'index / contents page' to my website. For example, if >> I add a tutorial or update any of my links I want the 'global contents page' >> to be updated when the python script is run. > > What you're looking at may be closer to autogenerated documentation > than to a classic site map. There are a variety of tools that generate > HTML pages on the basis of *certain information found in* all the > files in a directory (as opposed to the entire content of those > files). What you're trying to do may be sufficiently specific that it > doesn't already exist, but it might be worth having a quick look at > autodoc/doxygen - at least for some ideas. > > Chris Angelico Chris, You assessment is correct. Working through the PyPI I am having better luck with using different terms than the old-term 'sitemap'. I have found a link to funnelweb which uses the transmogrify library (yeah, as if I would have typed this term into google!) that is described as "Crawl and parse static sites and import to Plone". http://pypi.python.org/pypi/funnelweb/1.0 As funnelweb is modular, using a variety of the transmogrify tools, maybe I could modify this to create a 'non-plone' version. -- Cheers Simon Simon Cropper - Open Content Creator / Website Administrator Free and Open Source Software Workflow Guides ------------------------------------------------------------ Introduction http://www.fossworkflowguides.com GIS Packages http://gis.fossworkflowguides.com bash / Python http://scripting.fossworkflowguides.com From rosuav at gmail.com Thu Sep 8 23:46:25 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 13:46:25 +1000 Subject: Create an index from a webpage [RANT, DNFTT] In-Reply-To: <4E6985E1.9050009@fossworkflowguides.com> References: <1537032.qVoOGUtdWV@PointedEars.de> <4e68db21$0$30002$c3e8da3$5496439d@news.astraweb.com> <4e69769f$0$29987$c3e8da3$5496439d@news.astraweb.com> <4E697D6E.4010101@fossworkflowguides.com> <4E6985E1.9050009@fossworkflowguides.com> Message-ID: On Fri, Sep 9, 2011 at 1:20 PM, Simon Cropper wrote: > Chris, > > You assessment is correct. Working through the PyPI I am having better luck > with using different terms than the old-term 'sitemap'. > > I have found a link to funnelweb which uses the transmogrify library (yeah, > as if I would have typed this term into google!) that is described as "Crawl > and parse static sites and import to Plone". > And once again, python-list has turned a rant into a useful, informative, and productive thread :) ChrisA From aspineux at gmail.com Fri Sep 9 00:44:34 2011 From: aspineux at gmail.com (aspineux) Date: Thu, 8 Sep 2011 21:44:34 -0700 (PDT) Subject: Processing a file using multithreads References: Message-ID: On Sep 9, 12:49?am, Abhishek Pratap wrote: > Hi Guys > > My experience with python is 2 days and I am looking for a slick way > to use multi-threading to process a file. Here is what I would like to > do which is somewhat similar to MapReduce in concept. > > # test case > > 1. My input file is 10 GB. > 2. I want to open 10 file handles each handling 1 GB of the file > 3. Each file handle is processed in by an individual thread using the > same function ( so total 10 cores are assumed to be available on the > machine) > 4. There will be 10 different output files > 5. once the 10 jobs are complete a reduce kind of function will > combine the output. > > Could you give some ideas ? You can use "multiprocessing" module instead of thread to bypass the GIL limitation. First cut your file in 10 "equal" parts. If it is line based search for the first line close to the cut. Be sure to have "start" and "end" for each parts, start is the address of the first character of the first line and end is one line too much (== start of the next block) Then use this function to handle each part . def handle(filename, start, end) f=open(filename) f.seek(start) for l in f: start+=len(l) if start>=end: break # handle line l here print l Do it first in a single process/thread to be sure this is ok (easier to debug) then split in multi processes > > So given a file I would like to read it in #N chunks through #N file > handles and process each of them separately. > > Best, > -Abhi From vineet.deodhar at gmail.com Fri Sep 9 00:52:26 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Thu, 8 Sep 2011 21:52:26 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> Message-ID: <72da7d9b-ca04-4597-8670-22a954481e40@b9g2000prd.googlegroups.com> On Sep 9, 3:29?am, Paul Watson wrote: > I have read some of the talk around these two frameworks. > > Would you say that web2py is more geared toward the enterprise? > > Which one do you believe will be on Python 3 more quickly? Both Django & web2py are good frameworks. I have tried both of them + others & then chosen a hybrid of web2py + DABO bizobj for my work. (DABO is a desktop app framework; so I have chosen only the BizObj layer from it, which can do its job in any other python web or desktop framework). Typically, my apps are data-centric business apps. web2py wins in simplycity yet powerfullness, no install, no dependencies, good docs & community, low learning curve, etc. DABO BizObj excels in managing the business logic aspect (including managing multiple tables insert/update/delete, rollback, before insert, after save, ... the list is quite long) http://web2py.com www.web2pyclices.com http://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.Bizobj.html http://dabodev.com/ Also, there are threads in stackoverflow.com which discuss in-depth the +1 & -1 for these frameworks. Contributors to these threads include the lead developers including Massimo himself. Hope this helps. ---Vineet From jialiuonlineshoe04 at 163.com Fri Sep 9 01:29:03 2011 From: jialiuonlineshoe04 at 163.com (amy) Date: Thu, 8 Sep 2011 22:29:03 -0700 (PDT) Subject: wholesale all brand(UGGBOOTS, SHOES, CLOTHES, HANDBAG, WATCH, JEANS, JERSEY, T-SHIRT, SHIRTS, HOODY, EYEGLASS, CAP, SHAWL, WALLT) and so on. Message-ID: <111713be-0e9f-404f-ac46-1b7747c90f94@f31g2000prj.googlegroups.com> wholesale all brand shoes(NIKE,ADIDAS,LV,GUCCI,CHANEL,PRADA,POLO,UGG BOOTS,D&G,DIOR )and so on. paypal payment wholesale all brand clothing(T- SHIRT,JEANS,JERSEY,HOODIES,JACKETS,HARDY,SWEATER,SHIRTS )and so on . http://www.24hour-buy.com/ paypal payment all brand watch(ROLEX,OMEGA,CHANEL,LV,CARTIER,IWC,GUCCI,RADO )and so on. paypal payment all brand handbag(LV,GUCCI,CHANEL,PRADA,POLO,COACH,FENDI,CHLOE,BUBERRY,JUICY) and so on. paypal payment brand CAP,SHAWL,BELT,WALLET,UNDER WEAR)and so on. More detail land,address: http://www.24hour-buy.com/ From wildeskraut at googlemail.com Fri Sep 9 01:47:34 2011 From: wildeskraut at googlemail.com (Oliver) Date: Thu, 8 Sep 2011 22:47:34 -0700 (PDT) Subject: TypeError: object.__init__() takes no parameters Message-ID: Hello together, let me be honest with you, I am a poor programmer who can only do Perl. I tried to code a program in Perl, but found that another guy already finished this job in Python. Unlucky for me, this guy is now CEO of a company, not really interested in supporting his old code. If I want to run shapes.py I receive this error message: === error message === C:\Documents and Settings\mhg\Desktop\palcalc>shapes.py EE... ====================================================================== ERROR: test_fits (__main__.containerTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 265, in test_fits cont = Container() File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 90, in __init__ super(Container, self).__init__(xsize, ysize) TypeError: object.__init__() takes no parameters ====================================================================== ERROR: test_place_bin (__main__.containerTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 257, in test_place_bin cont = Container() File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line 90, in __init__ super(Container, self).__init__(xsize, ysize) TypeError: object.__init__() takes no parameters ---------------------------------------------------------------------- Ran 5 tests in 0.032s FAILED (errors=2) === end of error message === Snippets of source code: Line 264 - 268 def test_fits(self): cont = Container() cont.place_bin(0, 0, 210, 280) self.assertEqual(False, cont.fits(Rectangle(0, 210, 280, 420))) self.assertEqual(True, cont.fits(Rectangle(0, 280, 280, 490))) Line 87 - 93 class Container(object): """Container to store a number of non-overlapping rectangles.""" def __init__(self, xsize=1200, ysize=800): super(Container, self).__init__(xsize, ysize) self.rect = Rectangle(0, 0, xsize, ysize) self.boxes = [] self.last_placement_strategy = 0 Line 254 - 262 class containerTests(unittest.TestCase): """Tests for container objects.""" def test_place_bin(self): cont = Container() cont.place_bin(0, 0, 40, 40) self.failUnlessRaises(RuntimeError, cont.place_bin, 0, 0, 40, 40) cont = Container() cont.place_bin(0, 0, 210, 280) self.failUnlessRaises(RuntimeError, cont.place_bin, 0, 210, 280, 420) I think this is the main function: if __name__ == '__main__': unittest.main() I do not know if I posted what you need to help me, it just would ease my life a lot. If you need more information please let me know - if you want you can even be unfriendly to me :) From tjreedy at udel.edu Fri Sep 9 02:04:15 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 02:04:15 -0400 Subject: Python: Deleting specific words from a file. In-Reply-To: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: On 9/8/2011 9:09 PM, papu wrote: > Hello, I have a data file (un-structed messy file) from which I have > to scrub specific list of words (delete words). > > Here is what I am doing but with no result: > > infile = "messy_data_file.txt" > outfile = "cleaned_file.txt" > > delete_list = ["word_1","word_2"....,"word_n"] > new_file = [] > fin=open(infile,"") > fout = open(outfile,"w+") > for line in fin: > for word in delete_list: > line.replace(word, "") > fout.write(line) > fin.close() > fout.close() If you have very many words (and you will need all possible forms of each word if you do exact matches), The following (untested and incomplete) should run faster. delete_set = {"word_1","word_2"....,"word_n"} ... for line in fin: for word in line.split() if word not in delete_set: fout.write(word) # also write space and nl. Depending on what your file is like, you might be better with re.split('(\W+)', line). An example from the manual: >>> re.split('(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', ''] so all non-word separator sequences are preserved and written back out (as they will not match delete set). -- Terry Jan Reedy From mimohammedimran41 at gmail.com Fri Sep 9 02:20:06 2011 From: mimohammedimran41 at gmail.com (mohammed imran) Date: Thu, 8 Sep 2011 23:20:06 -0700 (PDT) Subject: reshma Message-ID: http://123maza.com/65/fun564/ From ben+python at benfinney.id.au Fri Sep 9 02:44:37 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 09 Sep 2011 16:44:37 +1000 Subject: TypeError: object.__init__() takes no parameters References: Message-ID: <87sjo6mcyy.fsf@benfinney.id.au> Oliver writes: > let me be honest with you, I am a poor programmer who can only do > Perl. I strongly suspect you could do more than that. Welcome to the Python discussion forum. > I tried to code a program in Perl, but found that another guy already > finished this job in Python. Unlucky for me, this guy is now CEO of a > company, not really interested in supporting his old code. Then he can hardly complain if someone else re-writes it in their language of choice, can he? :-) > C:\Documents and Settings\mhg\Desktop\palcalc>shapes.py > EE... This, and the rest of your output, is from the call to ?unittest.main?, Python's standard-library module for unit testing. > File "C:\Documents and Settings\mhg\Desktop\palcalc\shapes.py", line > 90, in __init__ > super(Container, self).__init__(xsize, ysize) > TypeError: object.__init__() takes no parameters The ?super(Container, self)? call asks for a ?super? object representing the (next) superclass of the type of ?self?. In this case, as the error message indicates, the next superclass type is ?object? ? the base type of all objects. Also as the error message indicates, the initialiser for ?object? doesn't accept the parameters being passed. > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) > self.rect = Rectangle(0, 0, xsize, ysize) > self.boxes = [] > self.last_placement_strategy = 0 So, there's no sense in calling the superclass's ?__init__? method with parameters which won't be accepted because of the function signature. The next thing to do is to ask about the design of these classes (what is the intention of this initialiser?). But you say you're entirely new to it, and that the designer has no interest in it. What are your options for getting their interest and participating in this thread? -- \ ?I cannot conceive that anybody will require multiplications at | `\ the rate of 40,000 or even 4,000 per hour ?? ?F. H. Wales, 1936 | _o__) | Ben Finney From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 9 02:57:31 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 09 Sep 2011 08:57:31 +0200 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: References: Message-ID: Am 09.09.2011 07:47 schrieb Oliver: > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) And this is the nonsense: Container derives from object and tries to call its superclass's constructor with 2 parameters - which won't work. Write this as super(Container, self).__init__(). HTH, Thomas From nmarais at ska.ac.za Fri Sep 9 03:00:21 2011 From: nmarais at ska.ac.za (Neilen Marais) Date: Fri, 9 Sep 2011 00:00:21 -0700 (PDT) Subject: Unittesting SocketServer.StreamRequestHandler subclasses Message-ID: Hi, Is there a recommended way for writing unittests of SocketServer.StreamRequestHandler subclasses? I've tried making a server stub class and a connection stub class with a recv() method that immediately raises socket.error(errno.ECONNRESET, ). This works OK, but it means that whatever unittests I run always happens after the handler's handle() method has already been called. Is there a way to avoid this? Thanks Neilen From vineet.deodhar at gmail.com Fri Sep 9 03:47:37 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Fri, 9 Sep 2011 00:47:37 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> Message-ID: <203ea707-5a86-436e-816b-9f91d5971d82@y8g2000prd.googlegroups.com> On Sep 9, 3:29?am, Paul Watson wrote: > I have read some of the talk around these two frameworks. > > Would you say that web2py is more geared toward the enterprise? > > Which one do you believe will be on Python 3 more quickly? Both Django & web2py are good frameworks. I have tried both of them + others & then chosen a hybrid of web2py + DABO bizobj for my work. (DABO is a desktop app framework; so I have chosen only the BizObj layer from it, which can do its job in any other python web or desktop framework). Typically, my apps are data-centric business apps. web2py wins in simplicity, flexibility, no install, no dependencies, good docs & community, low learning curve, etc. DABO BizObj excels in managing the business logic aspect. With DABO bizobj layer, apart from the business logic, managing multiple tables insert/update/delete, rollback, before-insert, after- save, etc. is very handy... the list is quite long) (I know you will say that every framework has got its own DAL. It's true. But most of them are designed for basic database functions.) Some useful links--- http://web2py.com www.web2pyclices.com http://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.B... http://dabodev.com/ Also, there are threads in stackoverflow.com which discuss in-depth the +1 & -1 for these frameworks. Contributors to these threads include the lead developers including Massimo himself. Hope this helps. ---Vineet From steve+comp.lang.python at pearwood.info Fri Sep 9 04:33:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 18:33:48 +1000 Subject: TypeError: object.__init__() takes no parameters References: Message-ID: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Thomas Rachel wrote: > Am 09.09.2011 07:47 schrieb Oliver: >> class Container(object): >> """Container to store ?a number of non-overlapping rectangles.""" >> def __init__(self, xsize=1200, ysize=800): >> super(Container, self).__init__(xsize, ysize) > > And this is the nonsense: Container derives from object and tries to > call its superclass's constructor with 2 parameters - which won't work. Not nonsense. Merely a backward-incompatible change: [steve at sylar ~]$ python2.2 Python 2.2.3 (#1, Aug 12 2010, 01:08:27) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> object("two", "parameters") In Python 2.2, the default object constructor accepts, and ignores, any parameters. In Python 2.3 on up, that becomes an error. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 9 05:07:24 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 19:07:24 +1000 Subject: killing a script References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 30Aug2011 14:13, Steven D'Aprano > wrote: > | On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote: > | >> Yes, but if I am not mistaken, that will require me to put a line or > | >> two after each os.system call. That's almost like whack-a-mole at the > | >> code level rather than the Control-C level. OK, not a huge deal for > | >> one script, but I was hoping for something simpler. I was hoping I > | >> could put one line at the top of the script and be done with it. > | > > | > Write a function! That's what they're for after all :) > | > | I'm not sure that this is actually as simple as that, especially using > | os.system. > | > | As I understand it, the scenario is this: > | > | The main script looks something like this: > | > | for x in whatever: > | os.system('something.py x') > | > | Each time through the loop, a new Python process is started. Each > | process runs in the foreground, capturing standard input, and so hitting > | Ctrl-C kills *that* process, not the main script. Unless, by chance, the > | Ctrl-C happens after the system call returns, but before the next one > | starts, it is completely invisible to the parent process (the main > | script). Wrapping os.system in a function does nothing to fix that. > > Presuming you're talking about UNIX, this is not correct. > > Ctrl-C at the terminal delivers SIGINT to _every_ process in the > controlling process group for the terminal. It also has _nothing_ to do > with the standard input. There may be something to what you say, but the behaviour experienced by the Original Poster still needs explaining. See below. > When you run a script, yea even a Python script, thus: > > myscript ... > > then job control capable shells (all of them, these days) put the python > process running "myscript" in its own process group as the leader > (being, initially, the only process in the group). If myscript forks > other processes, as happens in os.system(), they are _also_ in that > process group. _ALL_ of them receive the SIGINT from your Ctrl-C. I can replicate to OP's problem with these two simple Python scripts: [steve at sylar ~]$ cat script.py #!/usr/bin/python print "inside script.py" print "type Ctrl-C to exit" while True: pass [steve at sylar ~]$ cat test.py import os print "calling script.py with os.system" for i in range(3): os.system('./script.py') And now run them: [steve at sylar ~]$ python test.py calling script.py with os.system inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 4, in while True: KeyboardInterrupt inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 5, in pass KeyboardInterrupt inside script.py type Ctrl-C to exit Traceback (most recent call last): File "./script.py", line 4, in while True: KeyboardInterrupt Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of script.py. While script.py is running, it receives the Ctrl-C, the calling process does not. -- Steven From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 9 05:11:06 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 09 Sep 2011 11:11:06 +0200 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 09.09.2011 10:33 schrieb Steven D'Aprano: > Not nonsense. Merely a backward-incompatible change: [1] > In Python 2.2, the default object constructor accepts, and ignores, any > parameters. In Python 2.3 on up, that becomes an error. Thanks, I wasn't aware of that. My first contact with Python was with 2.3... Thomas [1] Another example why backward-incompatible change are bad. Why was it necessary in this case? :-( From vineet.deodhar at gmail.com Fri Sep 9 05:39:31 2011 From: vineet.deodhar at gmail.com (Vineet) Date: Fri, 9 Sep 2011 02:39:31 -0700 (PDT) Subject: Django or web2py References: <9cstuhFnm0U1@mid.individual.net> <203ea707-5a86-436e-816b-9f91d5971d82@y8g2000prd.googlegroups.com> Message-ID: On Sep 9, 12:47?pm, Vineet wrote: > On Sep 9, 3:29?am, Paul Watson wrote: > > > I have read some of the talk around these two frameworks. > > > Would you say that web2py is more geared toward the enterprise? > > > Which one do you believe will be on Python 3 more quickly? > > Both Django & web2py are good frameworks. > I have tried both of them + others & then chosen a hybrid of web2py + > DABO bizobj for my work. > (DABO is a desktop app framework; so I have chosen only the BizObj > layer from it, which can do its job in any other python web or desktop > framework). > > Typically, my apps are data-centric business apps. > web2py wins in simplicity, flexibility, no install, no dependencies, > good docs & community, low learning curve, etc. > > DABO BizObj excels in managing the business logic aspect. > With DABO bizobj layer, apart from the business logic, managing > multiple tables insert/update/delete, rollback, before-insert, after- > save, etc. is very handy... the list is quite long) > (I know you will say that every framework has got its own DAL. It's > true. But most of them are designed for basic database functions.) > > Some useful links---http://web2py.comwww.web2pyclices.comhttp://thewinecellarbook.com/daboDocTestAlt/dabo.lib.datanav.Bizobj.B...http://dabodev.com/ > > Also, there are threads in stackoverflow.com which discuss in-depth > the +1 & -1 for these frameworks. > Contributors to these threads include the lead developers including > Massimo himself. > > Hope this helps. > > ---Vineet Re. your point about porting from py2 to py3, the following thread makes it clear. http://groups.google.com/group/web2py/browse_thread/thread/5fcd0e97452e9ab8/d38f99b959778cfb?lnk=gst&q=python+3#d38f99b959778cfb ---Vineet From gandalf at shopzeus.com Fri Sep 9 05:39:52 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 09 Sep 2011 11:39:52 +0200 Subject: Portable locale usage In-Reply-To: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> References: <1468943535.28842.1315496382655.JavaMail.root@mail.zemris.fer.hr> Message-ID: <4E69DEE8.9050803@shopzeus.com> >>>> Why are you trying to force a specific locale to your program >>>> anyway? >>> Because I wish to be able to correctly sort Croatian names. >> Well, all right. If you want to sort Croatian names from a program that >> runs on an English (or whatever) system, then you will have to check the >> platform and use a locale that is supported by the platform. (But again, >> this is not Python's limitation. Python doesn't know what encodings are >> supported, in advance, and you cannot use a locale that is not supported...) > I fully agree. > > I commented that, if a proper locale is installed, > the following should work on any system: > > locale.setlocale(locale.LC_ALL, ('hr', locale.getpreferredencoding())) > > Currently the above does not work on Windows, > and that is because the locale_alias for 'hr' > is bound to 'hr_HR.ISO8859-2'. > Check the source: .../Python-3.2.2/Lib/locale.py, line 537 > > I was arguing that, on a Windows system, > the locale_alias for 'hr' should be bound > to 'Croatian_Croatia.1250'. Looks like you have found a bug! :-) Why don't you post a bug report? L From duncan.booth at invalid.invalid Fri Sep 9 05:49:33 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 09:49:33 GMT Subject: TypeError: object.__init__() takes no parameters References: Message-ID: Thomas Rachel wrote: > Am 09.09.2011 07:47 schrieb Oliver: >> class Container(object): >> """Container to store a number of non-overlapping rectangles.""" >> def __init__(self, xsize=1200, ysize=800): >> super(Container, self).__init__(xsize, ysize) > > And this is the nonsense: Container derives from object and tries to > call its superclass's constructor with 2 parameters - which won't work. > > Write this as super(Container, self).__init__(). > It isn't nonsense, just poor and outdated practice. You might subclass Container with something that puts another base class into the mro between Container and object and in that case calling super(Container, self). __init__() would be wrong. object.__init__() used to accept and silently ignore any parameters. This meant you could safely pass any constructor parameters along in case there was an intervening base class that wanted them. However that was changed (presumably after this code was written) and now you have to be a bit more careful with your initialisation parameters. This would be better in general, though if there is actually any code depending on xsize,ysize being passed up to a base class it will still need changing at the call site: def __init__(self, xsize=1200, ysize=800, *args, **kw): super(Container, self).__init__(*args, **kw) That way any xsize and ysize arguments are removed but any additional arguments for other base classes are passed through. -- Duncan Booth http://kupuguy.blogspot.com From hansmu at xs4all.nl Fri Sep 9 06:13:45 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 09 Sep 2011 12:13:45 +0200 Subject: killing a script In-Reply-To: <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e69e6da$0$2551$e4fe514c@news2.news.xs4all.nl> On 9/09/11 11:07:24, Steven D'Aprano wrote: > Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of > script.py. While script.py is running, it receives the Ctrl-C, the calling > process does not. You misinterpret what you are seeing: the calling process *does* receive the ctrl-C, it just chooses to ignore it. This is documented behaviour of os.system. It you don't want this, then use the subprocess module, which does not behave this way. -- HansM From duncan.booth at invalid.invalid Fri Sep 9 06:29:47 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 10:29:47 GMT Subject: Create an index from a webpage [RANT, DNFTT] References: Message-ID: Simon Cropper wrote: > Certainly doable but > considering the shear commonality of this task I don't understand why a > simple script does not already exist - hence my original request for > assistance. I think you may have underestimated the complexity of the task in general. To do it for a remote website you need to specify what you consider to be a unique page. Here are some questions: Is case significant for URLs (technically it always is, but IIS sites tend to ignore it and to contain links with random permutations of case)? Are there any query parameters that make two pages distinct? Or any parameters that you should ignore? Is the order of parameters significant? I recently came across a site that not only had multiple links to identical pages with the query parameters in different order but also used a non- standard % to separate parameters instead of &: it's not so easy getting crawlers to handle that mess. Even after ignoring query parameters are there a finite number of pages to the site? For example, Apache has a spelling correction module that can effectively allow any number of spurious subfolders: I've seen a site where "/folder1/index.html" had a link to "folder2/index.html" and "/folder2/index.html" linked to "folder1/index.html". Apache helpfully accepted /folder2/folder1/ as equivalent to /folder1/ and therefore by extension also accepted /folder2/folder1/folder2/folder1/... Zope is also good at creating infinite folder structures. If you want to spider a remote site then there are plenty of off the shelf spidering packages, e.g. httrack. They have a lot of configuration options to try to handle the above gotchas. Your case is probably a lot simpler, but that's just a few reasons why it isn't actually a trivial task. Building a list by scanning a bunch of folders with html files is comparatively easy which is why that is almost always the preferred solution if possible. -- Duncan Booth http://kupuguy.blogspot.com From __peter__ at web.de Fri Sep 9 07:04:57 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 13:04:57 +0200 Subject: Best way to check that you are at the beginning (the end) of an iterable? References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: Cameron Simpson wrote: > About the only time I do this is my personal "the()" convenience > function: > > def the(list, context=None): > ''' Returns the first element of an iterable, but requires there to be > exactly one. > ''' > icontext="expected exactly one value" > if context is not None: > icontext=icontext+" for "+context > > first=True > for elem in list: > if first: > it=elem > first=False > else: > raise IndexError, "%s: got more than one element (%s, %s, ...)" \ > % (icontext, it, elem) > > if first: > raise IndexError, "%s: got no elements" % icontext > > return it > > Which I use as a definite article in places where an iterable should > yield exactly one result (eg SQL SELECTs that ought to get exactly > one hit). I can see I wrote that a long time ago - it could do with some > style fixes. And a code scan shows it sees little use:-) A lightweight alternative to that is unpacking: >>> [x] = "" Traceback (most recent call last): File "", line 1, in ValueError: need more than 0 values to unpack >>> [x] = "a" >>> [x] = "ab" Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack From rosuav at gmail.com Fri Sep 9 07:30:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 9 Sep 2011 21:30:03 +1000 Subject: Best way to check that you are at the beginning (the end) of an iterable? In-Reply-To: References: <264a83d7-aa43-4e36-b39e-3e67488279b6@glegroupsg2000goo.googlegroups.com> Message-ID: On Fri, Sep 9, 2011 at 9:04 PM, Peter Otten <__peter__ at web.de> wrote: >>>> [x] = "" > Traceback (most recent call last): > ?File "", line 1, in > ValueError: need more than 0 values to unpack >>>> [x] = "a" >>>> [x] = "ab" > Traceback (most recent call last): > ?File "", line 1, in > ValueError: too many values to unpack > Hey look, it's a new operator - the "assign-sole-result-of-iterable" operator! x ,= "a" :) ChrisA From esthar777 at gmail.com Fri Sep 9 07:51:04 2011 From: esthar777 at gmail.com (ESTHU ESHU) Date: Fri, 9 Sep 2011 04:51:04 -0700 (PDT) Subject: plz see this Message-ID: <3285b468-2ddf-4c65-9a1e-357da713b0d6@y8g2000prd.googlegroups.com> http://123maza.com/65/clock747/ From kandrjoshi at gmail.com Fri Sep 9 08:07:03 2011 From: kandrjoshi at gmail.com (kaustubh joshi) Date: Fri, 9 Sep 2011 14:07:03 +0200 Subject: what's the command for (cd ..) in python Message-ID: Hello friends, How do we carry out the command "*cd ..*" in python? My problem is : I have a set of folders say m=1,2,3,4. In each of these folders, I have subfolders with common name say m_5,m_6,m_7,m_8. In each of these subfolder, there is a file which I have edit. 1 2 3 4 | | | | ------------------------------------------------------------------------------------------------------------------------------------------ 1_5, 1_6, 1_7, 1_8 2_5 ,2_6, 2_7, 2_8 3_5, 3_6, 3_7, 3_8 4_5, 4_6, 4_7, 4_8 That is how I designed it When I run my script, it follows the route 1 ---> 1_5-----> do the edit job in the file. Now it need to change the subfolder from 1_5 to 1_6, which is not happening. I created the folders using variable like m for folder taking values 1,2,3,4 and m_n for subfolders with n=5,6,7,8. I am trying with os.chdir(path), but stuck with how to use m_n in it. What I am missing at the moment is something that do the job "cd .." does. Any help Karan -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 9 08:16:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:16:00 +1000 Subject: killing a script References: <4e5c6376$0$29983$c3e8da3$5496439d@news.astraweb.com> <4e69d74d$0$29979$c3e8da3$5496439d@news.astraweb.com> <4e69e6da$0$2551$e4fe514c@news2.news.xs4all.nl> Message-ID: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Hans Mulder wrote: > On 9/09/11 11:07:24, Steven D'Aprano wrote: >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of >> script.py. While script.py is running, it receives the Ctrl-C, the >> calling process does not. > > You misinterpret what you are seeing: the calling process *does* receive > the ctrl-C, it just chooses to ignore it. > > This is documented behaviour of os.system. Documented where? Neither the on-line documentation nor the function docstring mentions anything about it that I can see: http://docs.python.org/py3k/library/os.html#os.system >>> help(os.system) Help on built-in function system in module posix: system(...) system(command) -> exit_status Execute the command (a string) in a subshell. -- Steven From vlastimil.brom at gmail.com Fri Sep 9 08:34:59 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 9 Sep 2011 14:34:59 +0200 Subject: what's the command for (cd ..) in python In-Reply-To: References: Message-ID: 2011/9/9 kaustubh joshi : > Hello friends, > ???????????????????????? How do we carry out the command "cd .." in python? > > My problem is : > I have a set of folders say m=1,2,3,4. In each of these folders, I have > subfolders with common name say m_5,m_6,m_7,m_8. In each of these subfolder, > there is a file which I have edit. > ????????????????????????????????????????? 1 > ? ? ? ?? 2?????????? ? ? ? ? ? ? ? ? ? ? ? ?? 3 > ? ? ?? 4 > ???????????????????????????????????????? | > ? ? ? ? ? |????????????? ? ? ? ? ? ? ? ? ? ? ? ? | > ? ? ? ? ??? | > > ------------------------------------------------------------------------------------------------------------------------------------------ > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 1_5, 1_6, 1_7, 1_8?????????????? 2_5 ,2_6, > 2_7, 2_8?????????? 3_5, 3_6, 3_7, 3_8????????? 4_5, 4_6, 4_7, 4_8 > > That is how I designed it > > When I run my script, it follows the route 1 ---> 1_5-----> do the edit job > in the file. Now it need to change the? subfolder from 1_5 to 1_6, which is > not happening. > > I created the folders using variable like m for folder taking values 1,2,3,4 > and m_n for subfolders with n=5,6,7,8. > > I am trying with os.chdir(path), but stuck with how to use m_n in it. > > What I am missing at the moment is something that do the job "cd .." does. > > Any help > > > Karan > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > Hi, Would maybe adjusting the path like this work? >>> my_path = "c://d/e/f/g/" >>> os.path.abspath(my_path + os.pardir) 'c:\\d\\e\\f' >>> hth, vbr From steve+comp.lang.python at pearwood.info Fri Sep 9 09:03:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:03:10 +1000 Subject: what's the command for (cd ..) in python References: Message-ID: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> kaustubh joshi wrote: > Hello friends, > How do we carry out the command "*cd ..*" in > python? import os os.chdir('..') But think carefully before doing this. Some functions may be confused if you change directories while they are running. You may be better off staying in the same directory, and adjusting the path names to the files as you work with them. -- Steven From roy at panix.com Fri Sep 9 09:19:07 2011 From: roy at panix.com (Roy Smith) Date: Fri, 09 Sep 2011 09:19:07 -0400 Subject: Processing a file using multithreads References: Message-ID: In article , aspineux wrote: > On Sep 9, 12:49?am, Abhishek Pratap wrote: > > 1. My input file is 10 GB. > > 2. I want to open 10 file handles each handling 1 GB of the file > > 3. Each file handle is processed in by an individual thread using the > > same function ( so total 10 cores are assumed to be available on the > > machine) > > 4. There will be 10 different output files > > 5. once the 10 jobs are complete a reduce kind of function will > > combine the output. > > > > Could you give some ideas ? > > You can use "multiprocessing" module instead of thread to bypass the > GIL limitation. I agree with this. > First cut your file in 10 "equal" parts. If it is line based search > for the first line close to the cut. Be sure to have "start" and > "end" for each parts, start is the address of the first character of > the first line and end is one line too much (== start of the next > block) How much of the total time will be I/O and how much actual processing? Unless your processing is trivial, the I/O time will be relatively small. In that case, you might do well to just use the unix command-line "split" utility to split the file into pieces first, then process the pieces in parallel. Why waste effort getting the file-splitting-at-line-boundaries logic correct when somebody has done it for you? From duncan.booth at invalid.invalid Fri Sep 9 09:20:54 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Sep 2011 13:20:54 GMT Subject: TypeError: object.__init__() takes no parameters References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Thomas Rachel wrote: > >> Am 09.09.2011 07:47 schrieb Oliver: >>> class Container(object): >>> """Container to store ??a number of non-overlapping rectangles.""" >>> def __init__(self, xsize=1200, ysize=800): >>> super(Container, self).__init__(xsize, ysize) >> >> And this is the nonsense: Container derives from object and tries to >> call its superclass's constructor with 2 parameters - which won't work. > > Not nonsense. Merely a backward-incompatible change: > > > [steve at sylar ~]$ python2.2 > Python 2.2.3 (#1, Aug 12 2010, 01:08:27) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> object("two", "parameters") > > > > In Python 2.2, the default object constructor accepts, and ignores, any > parameters. In Python 2.3 on up, that becomes an error. > More recently than that. It only became an error in 2.6: [dbooth at localhost ~]$ python2.5 -c "object().__init__(42)" [dbooth at localhost ~]$ python2.6 -c "object().__init__(42)" Traceback (most recent call last): File "", line 1, in TypeError: object.__init__() takes no parameters -- Duncan Booth http://kupuguy.blogspot.com From steve+comp.lang.python at pearwood.info Fri Sep 9 09:41:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:41:37 +1000 Subject: TypeError: object.__init__() takes no parameters References: <4e69cf6d$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6a1791$0$29984$c3e8da3$5496439d@news.astraweb.com> Duncan Booth wrote: > Steven D'Aprano wrote: >> In Python 2.2, the default object constructor accepts, and ignores, any >> parameters. In Python 2.3 on up, that becomes an error. >> > More recently than that. It only became an error in 2.6: For __init__, sure, but it was an error for __new__ back in 2.3. Sorry for not being more clear. -- Steven From dribnairb at gmail.com Fri Sep 9 10:29:06 2011 From: dribnairb at gmail.com (Brian) Date: Fri, 9 Sep 2011 07:29:06 -0700 (PDT) Subject: Python and Outlook-style rules Message-ID: I'm about to create a system which will need to allow hundreds of users to create and maintain their own rules in a similar fashion to MS Outlook rules. ie. Each rule consists of one or more user configurable conditions and if/ when the conditions are met then one or more user configurable actions will be applied. The conditions will be things like "a specified key in a dictionary is in a specified list of values" (where the user can choose the key and the values), or "a specific record is in the specified database" (where the user chooses the primary key of the record and the database table to look in). The actions will be things like "send an email to address" (where the user chooses the address and the email template to use). The user will do their configuration in a browser. Also, I need to be able to continue to add new conditions and actions to the system over time. Is there a python module (preferably free/open source) which already does (some of) this? I can write the back-end logic easily enough (although I'd rather not re-invent the wheel) but I'd particularly like to find a widget or similar which will make the front-end look nice and be cross-browser compatible. From dreyemi at gmail.com Fri Sep 9 11:57:38 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 9 Sep 2011 16:57:38 +0100 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: You might want to have a look at this: http://www.ccs.neu.edu/home/matthias/htdc.html On Fri, Sep 9, 2011 at 2:37 AM, Chris Angelico wrote: > On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: > > The Java compiler also acts as a "make" program. If it doesn't find > > a .class file for a needed class, it will search for the corresponding > > .java file and compile that. So to compile a complex program, you only > > need to compile the top-level file (e.g. HelloWorld.java), and it will > > compile everything which is required. No Makefile is needed, as the > > relationship between classes, object files and source files is fixed. > > > > If that's the entire benefit, then I think this is a rather hefty > price to pay for the elimination of a makefile. Oh wow, I can type > "javac MyClass.java" and it picks up all the others! If you're > dividing a project into multiple files already, is it that hard to > have one more that defines the relationships between the others? > > Chris Angelico > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Fri Sep 9 12:19:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 10 Sep 2011 02:19:48 +1000 Subject: Python and Outlook-style rules In-Reply-To: References: Message-ID: Something like this? http://stackoverflow.com/questions/387606/using-user-input-to-find-information-in-a-mysql-database On Sat, Sep 10, 2011 at 12:29 AM, Brian wrote: > I'm about to create a system which will need to allow hundreds of > users to create and maintain their own rules in a similar fashion to > MS Outlook rules. ie. > Each rule consists of one or more user configurable conditions and if/ > when the conditions are met then one or more user configurable actions > will be applied. > > The conditions will be things like "a specified key in a dictionary is > in a specified list of values" (where the user can choose the key and > the values), or "a specific record is in the specified > database" (where the user chooses the primary key of the record and > the database table to look in). > > The actions will be things like "send an email to address" (where the > user chooses the address and the email template to use). > > The user will do their configuration in a browser. Also, I need to be > able to continue to add new conditions and actions to the system over > time. > > Is there a python module (preferably free/open source) which already > does (some of) this? I can write the back-end logic easily enough > (although I'd rather not re-invent the wheel) but I'd particularly > like to find a widget or similar which will make the front-end look > nice and be cross-browser compatible. > > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Fri Sep 9 12:38:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 10 Sep 2011 02:38:25 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: Kayode: Are the number of pages in that tutorial planned? :P > On Sat, Sep 10, 2011 at 1:57 AM, Kayode Odeyemi wrote: >> You might want to have a look at this: >> http://www.ccs.neu.edu/home/matthias/htdc.html >> >> On Fri, Sep 9, 2011 at 2:37 AM, Chris Angelico wrote: >>> >>> On Fri, Sep 9, 2011 at 10:45 AM, Nobody wrote: >>> > The Java compiler also acts as a "make" program. If it doesn't find >>> > a .class file for a needed class, it will search for the corresponding >>> > .java file and compile that. So to compile a complex program, you only >>> > need to compile the top-level file (e.g. HelloWorld.java), and it will >>> > compile everything which is required. No Makefile is needed, as the >>> > relationship between classes, object files and source files is fixed. >>> > >>> >>> If that's the entire benefit, then I think this is a rather hefty >>> price to pay for the elimination of a makefile. Oh wow, I can type >>> "javac MyClass.java" and it picks up all the others! If you're >>> dividing a project into multiple files already, is it that hard to >>> have one more that defines the relationships between the others? >>> >>> Chris Angelico >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> Odeyemi 'Kayode O. >> http://www.sinati.com. t: @charyorde >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > From abhishek.vit at gmail.com Fri Sep 9 13:07:41 2011 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Fri, 9 Sep 2011 10:07:41 -0700 Subject: Processing a file using multithreads In-Reply-To: References: Message-ID: Hi All @Roy : split in unix sounds good but will it be as efficient as opening 10 different file handles on a file. I haven't tried it so just wondering if you have any experience with it. Thanks for your input. Also I was not aware of the python's GIL limitation. My application is not I/O bound as far as I can understand it. Each line is read and then processed independently of each other. May be this might sound I/O intensive as #N files will be read but I think if I have 10 processes running under a parent then it might not be a bottle neck. Best, -Abhi On Fri, Sep 9, 2011 at 6:19 AM, Roy Smith wrote: > In article > , > ?aspineux wrote: > >> On Sep 9, 12:49?am, Abhishek Pratap wrote: >> > 1. My input file is 10 GB. >> > 2. I want to open 10 file handles each handling 1 GB of the file >> > 3. Each file handle is processed in by an individual thread using the >> > same function ( so total 10 cores are assumed to be available on the >> > machine) >> > 4. There will be 10 different output files >> > 5. once the 10 jobs are complete a reduce kind of function will >> > combine the output. >> > >> > Could you give some ideas ? >> >> You can use "multiprocessing" module instead of thread to bypass the >> GIL limitation. > > I agree with this. > >> First cut your file in 10 "equal" parts. If it is line based search >> for the first line close to the cut. Be sure to have "start" and >> "end" for each parts, start is the address of the first character of >> the first line and end is one line too much (== start of the next >> block) > > How much of the total time will be I/O and how much actual processing? > Unless your processing is trivial, the I/O time will be relatively > small. ?In that case, you might do well to just use the unix > command-line "split" utility to split the file into pieces first, then > process the pieces in parallel. ?Why waste effort getting the > file-splitting-at-line-boundaries logic correct when somebody has done > it for you? > > -- > http://mail.python.org/mailman/listinfo/python-list > > From tjreedy at udel.edu Fri Sep 9 13:31:21 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 13:31:21 -0400 Subject: TypeError: object.__init__() takes no parameters In-Reply-To: References: Message-ID: On 9/9/2011 1:47 AM, Oliver wrote: > If I want to run shapes.py I receive this error message: Others have explained why code that ran once now does not. > class Container(object): > """Container to store a number of non-overlapping rectangles.""" > def __init__(self, xsize=1200, ysize=800): > super(Container, self).__init__(xsize, ysize) Remove this line and the error will go away. It *never* did anything. > self.rect = Rectangle(0, 0, xsize, ysize) > self.boxes = [] > self.last_placement_strategy = 0 -- Terry Jan Reedy From dreadpiratejeff at gmail.com Fri Sep 9 13:32:19 2011 From: dreadpiratejeff at gmail.com (J) Date: Fri, 9 Sep 2011 13:32:19 -0400 Subject: A bit of a boggle about subprocess.poll() and the codes it receives from a process Message-ID: Hi, I need a bit of help sorting this out... I have a memory test script that is a bit of compiled C. The test itself can only ever return a 0 or 1 exit code, this is explicitly coded and there are no other options. I also have a wrapper test script that calls the C program that should also only return 0 or 1 on completion. The problem i'm encountering, however, involves the return code when subprocess.poll() is called against the running memory test process. The current code in my wrapper program looks like this: def run_processes(self, number, command): passed = True pipe = [] for i in range(number): pipe.append(self._command(command)) print "Started: process %u pid %u: %s" % (i, pipe[i].pid, command) sys.stdout.flush() waiting = True while waiting: waiting = False for i in range(number): if pipe[i]: line = pipe[i].communicate()[0] if line and len(line) > 1: print "process %u pid %u: %s" % (i, pipe[i].pid, line) sys.stdout.flush() if pipe[i].poll() == -1: waiting = True else: return_value = pipe[i].poll() if return_value != 0: print "Error: process %u pid %u retuned %u" % (i, pipe[i].pid, return_value) passed = False print "process %u pid %u returned success" % (i, pipe[i].pid) pipe[i] = None sys.stdout.flush() return passed So what happens here is that in the waiting loop, if pipe[i].poll returns a -1, we keep waiting, and then if it returns anything OTHER than -1, we exit and return the return code. BUT, I'm getting, in some cases, a return code of 127, which is impossible to get from the memory test program. The output from this bit of code looks like this in a failing situation: Error: process 0 pid 2187 retuned 127 process 0 pid 2187 returned success Error: process 1 pid 2188 retuned 127 process 1 pid 2188 returned success I'm thinking that I'm hitting some sort of race here where the kernel is reporting -1 while the process is running, then returns 127 or some other status when the process is being killed and then finally 0 or 1 after the process has completely closed out. I "think" that the poll picks up this intermediate exit status and immediately exits the loop, instead of waiting for a 0 or 1. I've got a modified version that I'm getting someone to test for me now that changes if pipe[i].poll() == -1: waiting = True to this if pipe[i].poll() not in [0,1]: waiting = True So my real question is: am I on the right track here, and am I correct in my guess that the kernel is reporting different status codes to subprocess.poll() during the shutdown of the polled process? -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 9 13:35:37 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 09 Sep 2011 13:35:37 -0400 Subject: what's the command for (cd ..) in python In-Reply-To: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/9/2011 9:03 AM, Steven D'Aprano wrote: > kaustubh joshi wrote: > >> Hello friends, >> How do we carry out the command "*cd ..*" in >> python? > > import os > os.chdir('..') > > But think carefully before doing this. Some functions may be confused if you > change directories while they are running. You may be better off staying in > the same directory, and adjusting the path names to the files as you work > with them. Or, use it once at the top of the main module, with an absolute path, to make sure you start at a known place where you want to start. -- Terry Jan Reedy From ray at aarden.us Fri Sep 9 16:04:30 2011 From: ray at aarden.us (ray) Date: Fri, 9 Sep 2011 13:04:30 -0700 (PDT) Subject: Installing 2.6 on Win 7 Message-ID: I have not found binaries for this install. The page http://www.python.org/download/windows/ takes me to http://www.python.org/download/releases/ which goes to http://www.python.org/download/releases/2.6.7/ Here are Gzip and Bzip tar balls. The readme files describe linux builds and the content seems to match. Are there win binaries or source files? ray From brian.curtin at gmail.com Fri Sep 9 16:14:43 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Fri, 9 Sep 2011 15:14:43 -0500 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 15:04, ray wrote: > > I have not found binaries for this install. ?The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. ?The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? As stated at the top of that page... """Python 2.6.7?is a security-fix only source release for Python 2.6.6, fixing several reported security issues. Python 2.6.7 was released on June 3, 2011.""" If you work backwards, http://www.python.org/download/releases/2.6.6/ is the last version binaries were created for. From benjamin.kaplan at case.edu Fri Sep 9 16:17:00 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 9 Sep 2011 16:17:00 -0400 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: On Sep 9, 2011 4:07 PM, "ray" wrote: > > I have not found binaries for this install. The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? > > ray > -- There is no such thing as the windows source vs. the Linux source. Just different build files, both of which are in those folders. Since 2.6 is in security-fix only mode, python.org doesn't provide binaries. You may be able to find binaries from ActiveState if you don't want to build it yourself. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tyler at tysdomain.com Fri Sep 9 17:00:32 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 15:00:32 -0600 Subject: what's the command for (cd ..) in python In-Reply-To: References: Message-ID: <4E6A7E70.1070807@tysdomain.com> On 9/9/2011 6:07 AM, kaustubh joshi wrote: > Hello friends, > How do we carry out the command "*cd ..*" in > python? > os.chdir, like so: >>> os.getcwd() '/home/tyler' >>> os.chdir("../") >>> os.getcwd() '/home' So you could do something like: os.chdir("../foo") > My problem is : > I have a set of folders say m=1,2,3,4. In each of these folders, I > have subfolders with common name say m_5,m_6,m_7,m_8. In each of these > subfolder, there is a file which I have edit. > 1 > 2 3 > 4 > | > | | > | > > ------------------------------------------------------------------------------------------------------------------------------------------ > 1_5, 1_6, 1_7, 1_8 2_5 > ,2_6, 2_7, 2_8 3_5, 3_6, 3_7, 3_8 4_5, 4_6, 4_7, 4_8 > > That is how I designed it > > When I run my script, it follows the route 1 ---> 1_5-----> do the > edit job in the file. Now it need to change the subfolder from 1_5 to > 1_6, which is not happening. > > I created the folders using variable like m for folder taking values > 1,2,3,4 and m_n for subfolders with n=5,6,7,8. > > I am trying with os.chdir(path), but stuck with how to use m_n in it. > > What I am missing at the moment is something that do the job "cd .." does. > > Any help > > > Karan > > > -- Take care, Ty Web: http://tds-solutions.net Sent from my toaster. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tyler at tysdomain.com Fri Sep 9 17:07:07 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 15:07:07 -0600 Subject: Installing 2.6 on Win 7 In-Reply-To: References: Message-ID: <4E6A7FFB.90309@tysdomain.com> On 9/9/2011 2:04 PM, ray wrote: > I have not found binaries for this install. The page > http://www.python.org/download/windows/ > takes me to > http://www.python.org/download/releases/ > which goes to > http://www.python.org/download/releases/2.6.7/ > Here are Gzip and Bzip tar balls. The readme files describe linux > builds and the content seems to match. > > Are there win binaries or source files? > http://www.python.org/getit/releases/2.6.6/ has a release for windows x86 and x64 > ray -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From stefan-usenet at bytereef.org Fri Sep 9 17:41:18 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Fri, 9 Sep 2011 23:41:18 +0200 Subject: try... except with unknown error types In-Reply-To: References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: <20110909214118.GA32405@sleipnir.bytereef.org> Chris Torek wrote: > (I have also never been sure whether something is going to raise > an IOError or an OSError for various OS-related read or write > operation failures -- such as exceeding a resource limit, for > instance -- so most places that do I/O operations on OS files, I > catch both. Still, it sure would be nice to have a static analysis > tool that could answer questions about potential exceptions. :-) ) There is an effort to fix this: http://www.python.org/dev/peps/pep-3151/ And an implementation ... http://hg.python.org/features/pep-3151/ ... together with a feature request: http://bugs.python.org/issue12555 I think the whole concept makes a lot of sense and is really worth taking a look at. Stefan Krah From cs at zip.com.au Fri Sep 9 18:29:02 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 10 Sep 2011 08:29:02 +1000 Subject: killing a script In-Reply-To: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110909222902.GA25985@cskk.homeip.net> On 09Sep2011 22:16, Steven D'Aprano wrote: | Hans Mulder wrote: | > On 9/09/11 11:07:24, Steven D'Aprano wrote: | >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation of | >> script.py. While script.py is running, it receives the Ctrl-C, the | >> calling process does not. | > | > You misinterpret what you are seeing: the calling process *does* receive | > the ctrl-C, it just chooses to ignore it. | > | > This is documented behaviour of os.system. | | Documented where? Neither the on-line documentation nor the function | docstring mentions anything about it that I can see: | | http://docs.python.org/py3k/library/os.html#os.system My copy of the 2.7 docs says: This is implemented by calling the Standard C function system(), and has the same limitations. and sure enough, "man 3 system" says: The system() function hands the argument command to the command interpreter sh(1). The calling process waits for the shell to finish executing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD. os.system() is very convenient for simple stuff, but one size does not fit all. Continuing with the Python docs for os.system: On Unix, the return value is the exit status of the process encoded in the format specified for wait(). and it is easy to inspect that value for "the subprocess died from a signal". Not inspecting the exit status correctly will always be an opportunity for incorrect app behaviour. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Mac OS X. Because making Unix user-friendly is easier than debugging Windows. - Mike Dawson, Macintosh Systems Administrator and Consultation. mdawson at mac.com http://herowars.onestop.net From Phillip.M.Feldman at gmail.com Fri Sep 9 19:45:44 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 9 Sep 2011 16:45:44 -0700 (PDT) Subject: can't generate iterator from list Message-ID: <32435519.post@talk.nabble.com> It is supposed to be possible to generate a list representation of any iterator that produces a sequence of finite length, but this doesn't always work. Here's a case where it does work: Input: from itertools import combinations list(combinations(range(4),2)) Output: [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] When I define my own classes that produce iterators, conversion to a list works for some of these classes but not for others. Here's a case where it doesn't work: In: list(balls_in_numbered_boxes(2, [3,3,3])) Out: [array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1]), array([0, 0, 1])] Note that if I apply the `next` method to the object, the output is correct: In [5]: x=balls_in_numbered_boxes(3,[3,3,3]) In [6]: x.next() Out[6]: array([3, 0, 0]) In [7]: x.next() Out[7]: array([2, 1, 0]) In [8]: x.next() Out[8]: array([1, 2, 0]) In [9]: x.next() Out[9]: array([0, 3, 0]) In [10]: x.next() Out[10]: array([0, 2, 1]) In [11]: x.next() Out[11]: array([0, 1, 2]) In [12]: x.next() Out[12]: array([0, 0, 3]) In [13]: x.next() --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) Code is attached (see below). Any suggestions as to what's going wrong will be appreciated. class balls_in_numbered_boxes(object): """ OVERVIEW This class generates an iterator that produces all distinct distributions of indistinguishable balls among numbered boxes with specified capacity limits. (This is a generalization of the most common formulation of the problem, where each box is sufficiently large to accommodate all of the balls, and is an important example of a class of combinatorics problems called 'weak composition' problems). CONSTRUCTOR INPUTS n: the number of balls limits: This argument is a list of length 1 or greater. The length of the list corresponds to the number of boxes. `limits[i]` is a positive integer that specifies the maximum capacity of the ith box. If `limits[i]` equals `n` (or greater), then the ith box can accommodate all `n` balls and thus effectively has unlimited capacity. """ def __init__(self, n=None, limits=None): if n < 0 or not isinstance(n,int): raise BadInput("The number of balls n must be a non-negative integer.") if not isinstance(limits,list) or len(limits)<1: raise BadInput("`limits` must be a non-empty list.") for limit in limits: if not isinstance(limit,int) or limit<1: raise BadInput("Items in `limits` must be positive integers.") # Copy constructor inputs to object attributes. We make a `deepcopy` of # `limits` to protect against the possibility of the calling program # modifying it before all calls to the `next` method have been completed. self.n= n self.limits= deepcopy(limits) self.distribution= None def __iter__(self): return self def next(self): # If `self.distribution` is `None`, this is the initial call to `next`, # in which case we generate the initial distribution by assigning as many # balls as possible to the first box, as many balls that remain to the # next box, and so on. if self.distribution is None: self.distribution= zeros(len(self.limits), dtype='i4') balls= self.n for box in xrange(len(self.limits)): # Store as many balls as possible in the current box: self.distribution[box]= min(balls,self.limits[box]) balls-= self.distribution[box] if balls == 0: break else: # We fell through the above loop, which means that it was impossible # to distribute all of the balls: raise BadInput("The total capacity of the boxes is less than the " "number of balls to be distributed.") # Make first box the "current" box, i.e., the box from which a ball # will be moved when the `next` method is invoked: self.box= 0 return self.distribution # `self.distribution` is not `None`, which means that this is not the # initial invocation of `next`. We create the next distribution by moving # one ball to the right, unless this is impossible. self.distribution[self.box]-= 1 for box in xrange(self.box+1,len(self.limits)): # If this box is full, advance to the next one: if self.distribution[box] == self.limits[box]: continue self.distribution[box]+= 1 break else: # We fell through the above loop, which means that it was impossible # to find a new home for the ball that we were trying to move. raise StopIteration # If the current box--the box from which we have been removing balls-- is # empty, advance to the next box: if self.distribution[self.box] == 0: self.box+= 1 return self.distribution -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32435519.html Sent from the Python - python-list mailing list archive at Nabble.com. From Phillip.M.Feldman at gmail.com Fri Sep 9 20:00:39 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 9 Sep 2011 17:00:39 -0700 (PDT) Subject: can't generate list from iterator In-Reply-To: <32435519.post@talk.nabble.com> References: <32435519.post@talk.nabble.com> Message-ID: <32435569.post@talk.nabble.com> The title should have been "can't generate list from iterator". -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32435569.html Sent from the Python - python-list mailing list archive at Nabble.com. From miki.tebeka at gmail.com Fri Sep 9 20:07:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 9 Sep 2011 17:07:54 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: Message-ID: <1fcf2318-7b76-425b-a100-57d3cd5f8e0f@glegroupsg2000goo.googlegroups.com> 1. Can you post the code somewhere where it's indented properly? (http://paste.pocoo.org/) 2. In the list example you call balls_in_numbered_boxes(2, [3,3,3]) but in the interactive example you call balls_in_numbered_boxes(3,[3,3,3]) From miki.tebeka at gmail.com Fri Sep 9 20:07:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 9 Sep 2011 17:07:54 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: Message-ID: <1fcf2318-7b76-425b-a100-57d3cd5f8e0f@glegroupsg2000goo.googlegroups.com> 1. Can you post the code somewhere where it's indented properly? (http://paste.pocoo.org/) 2. In the list example you call balls_in_numbered_boxes(2, [3,3,3]) but in the interactive example you call balls_in_numbered_boxes(3,[3,3,3]) From matthew.a.hess at gmail.com Fri Sep 9 20:19:38 2011 From: matthew.a.hess at gmail.com (matt) Date: Fri, 9 Sep 2011 17:19:38 -0700 (PDT) Subject: IOError 35 when trying to read the result of call to urllib2.urlopen Message-ID: I'm using urllib2's urlopen function to post to a service which should return a rather lengthy JSON object as the body of its response. Here's the code: {{{ ctype, body = encode_multipart(fields, files) url = 'http://someservice:8080/path/to/resource' headers = {'Content-Type': ctype, 'Content-Length': str(len(body))} req = urllib2.Request(url, body, headers) resp = urllib2.urlopen(req) resp_body = resp.read() }}} When I try to look at "resp_body" I get this error: IOError: [Errno 35] Resource temporarily unavailable I posted to the same URI using curl and it worked fine, so I don't think it has to do with the server. Any thoughts? From steve+comp.lang.python at pearwood.info Fri Sep 9 20:55:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 10:55:53 +1000 Subject: can't generate list from iterator [was: can't generate iterator from list] References: Message-ID: <4e6ab59a$0$30002$c3e8da3$5496439d@news.astraweb.com> Dr. Phillip M. Feldman wrote: > > It is supposed to be possible to generate a list representation of any > iterator that produces a sequence of finite length, but this doesn't > always work. Here's a case where it does work: > > Input: > > from itertools import combinations > list(combinations(range(4),2)) > > Output: > > [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] > > When I define my own classes that produce iterators, conversion to a list > works for some of these classes but not for others. Here's a case where it > doesn't work: > > In: list(balls_in_numbered_boxes(2, [3,3,3])) > > Out: > > [array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1])] But it does work -- it generates a list, exactly as expected. The problem is not that you can't generate a list. The problem is that the list you generate is not what you expect. What you have here is a list containing the same array, repeated three times. When you print the permutations one at a time, you don't notice, but by collecting them all at once, you see clearly that they are the same array object. Try this: combos = list(balls_in_numbered_boxes(2, [3,3,3])) [id(a) for a in combos] I expect you will see something like [123456, 123456, 123456]. The simplest fix is to fix the next() method so that it returns a copy of self.distribution instead of the array itself. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 9 21:02:08 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 11:02:08 +1000 Subject: IOError 35 when trying to read the result of call to urllib2.urlopen References: Message-ID: <4e6ab711$0$29975$c3e8da3$5496439d@news.astraweb.com> matt wrote: > When I try to look at "resp_body" I get this error: > > IOError: [Errno 35] Resource temporarily unavailable > > I posted to the same URI using curl and it worked fine, so I don't > think it has to do with the server. Are your Python code and curl both using the same proxy? It may be that one is going direct and the other is using a proxy. Or perhaps the destination is just flaky, and the resource genuinely is temporarily unavailable. Or it doesn't like your useragent string and is lying. -- Steven From ray at aarden.us Fri Sep 9 21:21:58 2011 From: ray at aarden.us (ray at aarden.us) Date: Fri, 09 Sep 2011 18:21:58 -0700 Subject: Installing 2.6 on Win 7 Message-ID: <20110909182158.1753ead7c2b35a7d15c5b99498690bcc.e87438b7a8.wbe@email11.secureserver.net> An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Fri Sep 9 21:25:40 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 11:25:40 +1000 Subject: killing a script References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 09Sep2011 22:16, Steven D'Aprano > wrote: > | Hans Mulder wrote: > | > On 9/09/11 11:07:24, Steven D'Aprano wrote: > | >> Sure enough, I now have to hit Ctrl-C repeatedly, once per invocation > | >> of script.py. While script.py is running, it receives the Ctrl-C, the > | >> calling process does not. > | > > | > You misinterpret what you are seeing: the calling process *does* > | > receive the ctrl-C, it just chooses to ignore it. > | > > | > This is documented behaviour of os.system. > | > | Documented where? Neither the on-line documentation nor the function > | docstring mentions anything about it that I can see: > | > | http://docs.python.org/py3k/library/os.html#os.system > > My copy of the 2.7 docs says: > > This is implemented by calling the Standard C function system(), and > has the same limitations. > > and sure enough, "man 3 system" says: I don't consider having to look up documentation for a function in a completely different language (in this case, C) as "documented behaviour of os.system". Does the C standard define the behaviour of system(), or is that implementation dependent? It sounds to me that the Python developers are implicitly refusing responsibility for the detailed behaviour of os.system by noting that it depends on the C function. What do Jython, PyPy and IronPython do? Perhaps the docs for os.system should explicitly note that the behaviour is implementation dependent, rather than just hint at it. Either that or explicitly state what os.system does. > os.system() is very convenient for simple stuff, but one size does not > fit all. I never said it does. Back in my first comment on this thread, I said "Possibly using the subprocess module may help." > Continuing with the Python docs for os.system: > > On Unix, the return value is the exit status of the process encoded in > the format specified for wait(). > > and it is easy to inspect that value for "the subprocess died from a > signal". Not inspecting the exit status correctly will always be an > opportunity for incorrect app behaviour. Except that the subprocess can catch the KeyboardInterrupt before exiting, and there's no guarantee that it will return an appropriate error code. You're right though, os.system is good for simple stuff and not much more. -- Steven From rosuav at gmail.com Fri Sep 9 21:37:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 10 Sep 2011 11:37:53 +1000 Subject: killing a script In-Reply-To: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 10, 2011 at 11:25 AM, Steven D'Aprano wrote: >> ? This is implemented by calling the Standard C function system(), and >> ? has the same limitations. >> >> and sure enough, "man 3 system" says: > > I don't consider having to look up documentation for a function in a > completely different language (in this case, C) as "documented behaviour of > os.system". > The Python docs chain to the C docs. It'd be nice to have a link somewhere, but that's platform-dependent - the online docs could link to an online man page, but local docs can't, etc. It's fairly normal for high level languages to expose a lot of C API functions, with all the concerns and features given. Not a lot of point bloating the Python docs with every little detail, imho. ChrisA From tyler at tysdomain.com Fri Sep 9 23:54:40 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Fri, 09 Sep 2011 21:54:40 -0600 Subject: using python in web applications Message-ID: <4E6ADF80.7010607@tysdomain.com> Hello all: I'm curious if there are some good solutions for using Python in web applications. I'm not feeling particularly masochistic, so I do not want to develop this project in PHP; essentially I'm looking to build a web-based MMO. I know that you can use nginx with Python with servers like Flask, but I'm not really sure how well all of those work. Since this will be a game, I can expect quite a few users; I've already got quite a lot of interest. I don't much care for PHP, but the thing that can be said for it is it's pretty quick. How does Python compare? Are there some solutions (I was told about PyPy today) that would be quicker that I could still use for the web app? I'm also curious what databases are suggested? I've always done most of my work in MYSql, but from what I understand postgresql is becoming more popular to. Thanks all for the input, -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From ben+python at benfinney.id.au Sat Sep 10 00:19:22 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 10 Sep 2011 14:19:22 +1000 Subject: using python in web applications References: Message-ID: <87mxedm3lh.fsf@benfinney.id.au> "Littlefield, Tyler" writes: > I'm curious if there are some good solutions for using Python in web > applications. Start with: and try your criteria against what you find there. -- \ ?As scarce as truth is, the supply has always been in excess of | `\ the demand.? ?Josh Billings | _o__) | Ben Finney From timr at probo.com Sat Sep 10 01:43:19 2011 From: timr at probo.com (Tim Roberts) Date: Fri, 09 Sep 2011 22:43:19 -0700 Subject: Processing a file using multithreads References: Message-ID: Abhishek Pratap wrote: > >My application is not I/O bound as far as I can understand it. Each >line is read and then processed independently of each other. May be >this might sound I/O intensive as #N files will be read but I think if >I have 10 processes running under a parent then it might not be a >bottle neck. Your conclusion doesn't follow from your premise. If you are only doing a little bit of processing on each line, then you almost certainly WILL be I/O bound. You will spend most of your time waiting for the disk to deliver more data. In that case, multithreading is not a win. The threads will all compete with each other for the disk. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zak.mc.kraken at libero.it Sat Sep 10 02:23:51 2011 From: zak.mc.kraken at libero.it (Vito 'ZeD' De Tullio) Date: Sat, 10 Sep 2011 08:23:51 +0200 Subject: FYI Message-ID: http://scummos.blogspot.com/2011/09/kdev-python-argument-type-guessing.html I'm not used to big ide/rad for python... but I think this work is excellent! Are there alternatives (pydev? others?) capable of this sort of thinks (I mean "guessing the type" and method autocomplete) -- By ZeD From __peter__ at web.de Sat Sep 10 03:05:43 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 09:05:43 +0200 Subject: can't generate iterator from list References: <32435519.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > > It is supposed to be possible to generate a list representation of any > iterator that produces a sequence of finite length, but this doesn't > always work. Here's a case where it does work: > > Input: > > from itertools import combinations > list(combinations(range(4),2)) > > Output: > > [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] > > When I define my own classes that produce iterators, conversion to a list > works for some of these classes but not for others. Here's a case where it > doesn't work: > > In: list(balls_in_numbered_boxes(2, [3,3,3])) > > Out: > > [array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1]), > array([0, 0, 1])] [snip code where excessive commenting does more bad than good] The problem is that you return the same mutable object on every next() call. Here's a simplified example: >>> def g(items): ... x = [None] ... for item in items: ... x[0] = item ... yield x ... >>> list(g("abc")) [['c'], ['c'], ['c']] When you invoke it using next() you are fooled into thinking that it works as desired: >>> it = g("abc") >>> a = next(it) >>> a ['a'] >>> b = next(it) >>> b ['b'] but only until you look back at the previous item: >>> a ['b'] Once you understand what is going on the fix is easy -- don't reuse the mutable object: >>> def g(items): ... for item in items: ... yield [item] ... >>> list(g("abc")) [['a'], ['b'], ['c']] From hetchkay at gmail.com Sat Sep 10 03:19:42 2011 From: hetchkay at gmail.com (hetchkay) Date: Sat, 10 Sep 2011 00:19:42 -0700 (PDT) Subject: Applying a function recursively Message-ID: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Hi, I want to apply a "convert" function on an object as follows: If the object is of MyType type, invoke the passed in function. If the object is a dictionary, apply on the keys and values of the dictionary recursively. If the object is a set, list or tuple, apply on each element recursively. Else, leave the object as is. I wrote the following code: def convert(obj, func): if isinstance(obj, MyType): return func(obj) elif isinstance(obj, dict): return dict((convert(key, func), convert(value, func)) for key, value in obj.iteritems()) elif isinstance(obj, (list, tuple, set)): return obj.__class__(convert(x, func) for x in obj) else: return obj Is there a better way to do this? Is there any way I can make this code faster? Regards, Krishnan From clp2 at rebertia.com Sat Sep 10 03:40:51 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 00:40:51 -0700 Subject: Applying a function recursively In-Reply-To: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Message-ID: On Sat, Sep 10, 2011 at 12:19 AM, hetchkay wrote: > Hi, > I want to apply a "convert" function on an object as follows: > If the object is of MyType type, invoke the passed in function. > If the object is a dictionary, apply on the keys and values of the > dictionary recursively. > If the object is a set, list or tuple, apply on each element > recursively. > Else, leave the object as is. > > I wrote the following code: > def convert(obj, func): > ? if isinstance(obj, MyType): > ? ? ?return func(obj) > ? elif isinstance(obj, dict): > ? ? ?return dict((convert(key, func), convert(value, func)) for key, > value in obj.iteritems()) > ? elif isinstance(obj, (list, tuple, set)): > ? ? ?return obj.__class__(convert(x, func) for x in obj) > ? else: > ? ? ?return obj > > Is there a better way to do this? None comes to mind. > Is there any way I can make this code faster? Possibly, but it involves ignoring subclasses, and may not actually be faster in your particular case (it comes down to additional function calls vs. cost of if-elif-else chain). It would be along the lines of: def convert_mytype(obj, func): return func(obj) def convert_dict(obj, func): return dict((convert(key, func), convert(value, func)) for key, value in obj.iteritems()) def dont_convert(obj, func): return obj TYPE2FUNC = {MyType : convert_mytype, dict : convert_dict, ... } def convert(obj, func): return TYPE2FUNC.get(type(obj), dont_convert)(obj, func) As they say though, premature optimization is the root of all evil. Cheers, Chris -- http://rebertia.com From ben+python at benfinney.id.au Sat Sep 10 04:13:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 10 Sep 2011 18:13:18 +1000 Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> Message-ID: <87ipp0n7c1.fsf@benfinney.id.au> hetchkay writes: > Hi, > I want to apply a "convert" function on an object as follows: > If the object is of MyType type, invoke the passed in function. > If the object is a dictionary, apply on the keys and values of the > dictionary recursively. > If the object is a set, list or tuple, apply on each element > recursively. > Else, leave the object as is. That smells like a bad design. Why are you using the same function for al of those different behaviours? That's not merely rhetorical; the design isn't absolutely wrong. But it's wrong often enough that you need to have a compelling reason to make such a complex behaviour in a single function. I suspect, if you can be explicit about the goal you're aiming for with this code, a better design can be found that doesn't require all those polymorphism-breaking type checks. -- \ ?An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.? ?Niels Bohr | _o__) | Ben Finney From cs at zip.com.au Sat Sep 10 04:49:38 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 10 Sep 2011 18:49:38 +1000 Subject: killing a script In-Reply-To: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110910084938.GA14021@cskk.homeip.net> On 10Sep2011 11:25, Steven D'Aprano wrote: | Cameron Simpson wrote: | > My copy of the 2.7 docs says: | > This is implemented by calling the Standard C function system(), and | > has the same limitations. | > and sure enough, "man 3 system" says: | | I don't consider having to look up documentation for a function in a | completely different language (in this case, C) as "documented behaviour of | os.system". You're kidding, surely? A wrapper function for a system supplied function should recite everything about the wrapped function's behaviour (including the system dependent stuff) in the wrapper doco? | Does the C standard define the behaviour of system(), or is that | implementation dependent? The standard specifies the core behaviour - the behaviour guarrenteed to be present everywhere. Plenty of stuff has platform dependent minor nuances. As long as portable code relies only on the standard behaviour everybody wins. | It sounds to me that the Python developers are | implicitly refusing responsibility for the detailed behaviour of os.system | by noting that it depends on the C function. Of course they are, and they are right to do so. But noting that it calls the standard function does guarrentee various things about what it does. | What do Jython, PyPy and | IronPython do? | | Perhaps the docs for os.system should explicitly note that the behaviour is | implementation dependent, rather than just hint at it. Either that or | explicitly state what os.system does. I find it hard to understand how anyone can read this text: This is implemented by calling the Standard C function system(), and has the same limitations and not imagine it to be dependent on the specification for system(). | > Continuing with the Python docs for os.system: | > | > On Unix, the return value is the exit status of the process encoded in | > the format specified for wait(). | > | > and it is easy to inspect that value for "the subprocess died from a | > signal". Not inspecting the exit status correctly will always be an | > opportunity for incorrect app behaviour. | | Except that the subprocess can catch the KeyboardInterrupt before exiting, This is very true, though such programs usually have a special reason to do so - the default aborting behaviour is often sufficient. | and there's no guarantee that it will return an appropriate error code. Of course. However, the subprocess should still exit with a nonzero exit status (unless it it written badly). If the caller considers success of the called program to be important, it should probably be aborting if the returned value is nonzero anyway. But yeah, people should probably be reaching for subprocess if they want to notice SIGINT specially. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ But pessimism IS realism! - D.L.Bahr From kushal.kumaran+python at gmail.com Sat Sep 10 05:19:08 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sat, 10 Sep 2011 14:49:08 +0530 Subject: A bit of a boggle about subprocess.poll() and the codes it receives from a process In-Reply-To: References: Message-ID: On Fri, Sep 9, 2011 at 11:02 PM, J wrote: > Hi, > I need a bit of help sorting this out... > I have a memory test script that is a bit of compiled C. ?The test itself > can only ever return a 0 or 1 exit code, this is explicitly coded and there > are no other options. > I also have a wrapper test script that calls the C program that should also > only return 0 or 1 on completion. > The problem i'm encountering, however, involves the return code when > subprocess.poll() is called against the running memory test process. ?The > current code in my wrapper program looks like this: > def run_processes(self, number, command): > ? ? ? ? passed = True > ? ? ? ? pipe = [] > ? ? ? ? for i in range(number): > ? ? ? ? ? ? pipe.append(self._command(command)) > ? ? ? ? ? ? print "Started: process %u pid %u: %s" % (i, pipe[i].pid, > command) > ? ? ? ? sys.stdout.flush() > ? ? ? ? waiting = True > ? ? ? ? while waiting: > ? ? ? ? ? ? waiting = False > ? ? ? ? ? ? for i in range(number): > ? ? ? ? ? ? ? ? if pipe[i]: > ? ? ? ? ? ? ? ? ? ? line = pipe[i].communicate()[0] > ? ? ? ? ? ? ? ? ? ? if line and len(line) > 1: > ? ? ? ? ? ? ? ? ? ? ? ? print "process %u pid %u: %s" % (i, pipe[i].pid, > line) > ? ? ? ? ? ? ? ? ? ? ? ? sys.stdout.flush() > ? ? ? ? ? ? ? ? ? ? if pipe[i].poll() == -1: > ? ? ? ? ? ? ? ? ? ? ? ? waiting = True > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? return_value = pipe[i].poll() > ? ? ? ? ? ? ? ? ? ? ? ? if return_value != 0: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? print "Error: process ?%u pid %u retuned %u" % > (i, pipe[i].pid, return_value) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? passed = False > ? ? ? ? ? ? ? ? ? ? ? ? print "process %u pid %u returned success" % (i, > pipe[i].pid) > ? ? ? ? ? ? ? ? ? ? ? ? pipe[i] = None > ? ? ? ? sys.stdout.flush() > ? ? ? ? return passed > So what happens here is that in the waiting loop, if pipe[i].poll returns a > -1, we keep waiting, and then if it returns anything OTHER than -1, we exit > and return the return code. Does self._command return a subprocess.Popen object? The documentation at http://docs.python.org/library/subprocess.html#subprocess.Popen.poll says that the poll method sets and returns the returncode attribute. returncode is expected to be None until the process terminates, and a negative value indicates that the subprocess has been terminated because of a signal. If poll() returns -1, it means that the process has been terminated by signal number 1 (probably SIGHUP). > BUT, I'm getting, in some cases, a return code of 127, which is impossible > to get from the memory test program. > The output from this bit of code looks like this in a failing situation: > Error: process 0 pid 2187 retuned 127 > process 0 pid 2187 returned success > Error: process 1 pid 2188 retuned 127 > process 1 pid 2188 returned success > I'm thinking that I'm hitting some sort of race here where the kernel is > reporting -1 while the process is running, then returns 127 or some other > status when the process is being killed and then finally 0 or 1 after the > process has completely closed out. ?I "think" that the poll picks up this > intermediate exit status and immediately exits the loop, instead of waiting > for a 0 or 1. > I've got a modified version that I'm getting someone to test for me now that > changes > ?if pipe[i].poll() == -1: > ? ? ?waiting = True > to this > if pipe[i].poll() not in [0,1]: > ? ? waiting = True > So my real question is: am I on the right track here, and am I correct in my > guess that the kernel is reporting different status codes to > subprocess.poll() during the shutdown of the polled process? > I'm unaware of any such race condition. It is more likely that the program you are running can return such error codes. Perhaps you should examine its stderr output. It's unclear what you're trying to do here. If you'd just like to wait until all the started processes are finished, you should use the wait() method instead of the poll() method. You should also note that the communicate() method already waits for the process to complete, so further calls to poll() and wait() are superfluous. Normally, after communicate() returns, you would simply check pipe[i].returncode and be on your way. -- regards, kushal From nobody at nowhere.com Sat Sep 10 05:33:03 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 10:33:03 +0100 Subject: try... except with unknown error types References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 31 Aug 2011 21:01:34 +0000, Chris Torek wrote: > Still, it sure would be nice to have a static analysis > tool that could answer questions about potential exceptions. :-) ) That's an impossibility in a dynamic language. If you call f.read() where f was passed in as a parameter, the exceptions which f.read() may throw depend upon exactly what f is; there's no guarantee that it will actually be a built-in file object, only that it will have a .read() method (otherwise you will get an AttributeError). Even if f was returned from open(), there's no guarantee that __builtins__.open() won't have been replaced by the time of the call. From nobody at nowhere.com Sat Sep 10 05:47:29 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 10:47:29 +0100 Subject: killing a script References: <4e6a0382$0$29982$c3e8da3$5496439d@news.astraweb.com> <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, 10 Sep 2011 11:25:40 +1000, Steven D'Aprano wrote: >> and sure enough, "man 3 system" says: > > I don't consider having to look up documentation for a function in a > completely different language (in this case, C) as "documented behaviour of > os.system". Well, tough luck. os.system() is a wrapper around the platform's system(). The authors of the Python documentation cannot possibly know what that function will do on all platforms, even less so once you factor in the user's ability to replace that function via platform-specific means. > Does the C standard define the behaviour of system(), or is that > implementation dependent? The C99 standard says: 7.20.4.5 The system function Synopsis [#1] #include int system(const char *string); Description [#2] If string is a null pointer, the system function determines whether the host environment has a command processor. If string is not a null pointer, the system function passes the string pointed to by string to that command processor to be executed in a manner which the implementation shall document; this might then cause the program calling system to behave in a non-conforming manner or to terminate. Returns [#3] If the argument is a null pointer, the system function returns nonzero only if a command processor is available. If the argument is not a null pointer, and the system function does return, it returns an implementation-defined value. It doesn't require a platform to even have a command interpreter, let alone specify its behaviour. On Unix, system() is defined to use /bin/sh, which ought to be some kind of Bourne shell; but even then, it might be a minimal shell such as dash or something with many extensions such as bash. On Windows, it uses the interpreter specified by the COMSPEC environment variable, or cmd.exe (NT-based) or command.com (DOS-based) if COMSPEC isn't set (in either case, PATH is used). > It sounds to me that the Python developers are > implicitly refusing responsibility for the detailed behaviour of os.system > by noting that it depends on the C function. Indeed. Which is the correct thing to do. Practically every function in the os module does likewise. > What do Jython, PyPy and IronPython do? I don't know, but I would expect them to use libc's system() function, except for Jython which might use java.lang.Runtime.exec(). From nobody at nowhere.com Sat Sep 10 06:11:37 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 10 Sep 2011 11:11:37 +0100 Subject: How to structure packages References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 11:37:44 +1000, Chris Angelico wrote: >> The Java compiler also acts as a "make" program. If it doesn't find >> a .class file for a needed class, it will search for the corresponding >> .java file and compile that. So to compile a complex program, you only >> need to compile the top-level file (e.g. HelloWorld.java), and it will >> compile everything which is required. No Makefile is needed, as the >> relationship between classes, object files and source files is fixed. >> > > If that's the entire benefit, then I think this is a rather hefty > price to pay for the elimination of a makefile. It also eliminates the need for TAGS files, browser database (PDB) files, etc. Once you know the class name, all of the filenames follow from that. I suspect that the one-to-one correspondence between classes and .class files is mostly technical (e.g. Java's security model). The one-to-one correspondence between class files and source files could probably be relaxed, but at the expense of complicating the IDE and toolchain. I never saw it as a problem, given that Java is fundamentally class-based: there are no global variables or functions, only classes. From __peter__ at web.de Sat Sep 10 06:17:23 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 12:17:23 +0200 Subject: try... except with unknown error types References: <4e5015ad$0$29986$c3e8da3$5496439d@news.astraweb.com> <7xty9ahb84.fsf@ruckus.brouhaha.com> Message-ID: Chris Torek wrote: > >>> import socket > >>> isinstance(socket.error, IOError) > False Here you test if the socket.error *class* is an instance of IOError; this would print True if IOError were socket.error's metaclass. However: >>> isinstance(socket.error(), IOError) True or more directly: >>> issubclass(socket.error, IOError) True >>> issubclass(socket.error, EnvironmentError) True This is a relatively recent change: $ python2.5 -c'from socket import error; print issubclass(error, IOError), issubclass(error, EnvironmentError)' False False $ python2.6 -c'from socket import error; print issubclass(error, IOError), issubclass(error, EnvironmentError)' True True From rosuav at gmail.com Sat Sep 10 06:29:57 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 10 Sep 2011 20:29:57 +1000 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 10, 2011 at 8:11 PM, Nobody wrote: > I suspect that the one-to-one correspondence between classes and .class > files is mostly technical (e.g. Java's security model). The one-to-one > correspondence between class files and source files could probably be > relaxed, but at the expense of complicating the IDE and toolchain. One class per object file isn't a problem - you can always .jar your classes if the proliferation of small files bothers you, and then it's just a different way of indexing the mound of code. One class per source file complicates the human's view in order to simplify the tools'. Not sure that's really worthwhile. > I never saw it as a problem, given that Java is fundamentally class-based: > there are no global variables or functions, only classes. Yeah... of course you can easily simulate globals with static members in a dedicated class, but it's slower. THIS, though, is where Java's security model comes in - you can assign security X to Globals1.class and security Y to Globals2.class, rather than trying to juggle security issues in a monolithic "globals" namespace. IMHO it's not worth the hassle, though. I'd rather just have globals. ChrisA From wm at localhost.localdomain Sat Sep 10 06:32:40 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sat, 10 Sep 2011 12:32:40 +0200 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 09 Sep 2011 23:03:10 +1000, Steven D'Aprano wrote: > But think carefully before doing this. Some functions may be confused if you > change directories while they are running. You may be better off staying in > the same directory, and adjusting the path names to the files as you work > with them. Curious. Do you mean multi-threaded environment or even in single thread? If the latter is the case, I'd say those functions make very nasty assumptions. Who are they, anyways? ;) Br. Waldek From mark.dufour at gmail.com Sat Sep 10 07:08:43 2011 From: mark.dufour at gmail.com (Mark Dufour) Date: Sat, 10 Sep 2011 13:08:43 +0200 Subject: [ANN] Shed Skin 0.9 Message-ID: Hi all, I have just released version 0.9 of Shed Skin, a (restricted-)Python to C++ compiler. Please see my blog for the full announcement: http://shed-skin.blogspot.com The Shed Skin homepage is located here: http://shedskin.googlecode.com Thanks! Mark Dufour. -- http://www.youtube.com/watch?v=E6LsfnBmdnk -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sat Sep 10 07:11:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 10 Sep 2011 21:11:32 +1000 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6b45e6$0$29970$c3e8da3$5496439d@news.astraweb.com> Waldek M. wrote: > On Fri, 09 Sep 2011 23:03:10 +1000, Steven D'Aprano wrote: >> But think carefully before doing this. Some functions may be confused if >> you change directories while they are running. You may be better off >> staying in the same directory, and adjusting the path names to the files >> as you work with them. > > Curious. > Do you mean multi-threaded environment or even in single thread? > If the latter is the case, I'd say those functions make > very nasty assumptions. Who are they, anyways? ;) The main one that comes to mind is os.walk, which has this to say: Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Seems like a reasonable assumption to me. -- Steven From laddosingh at gmail.com Sat Sep 10 07:20:17 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sat, 10 Sep 2011 04:20:17 -0700 (PDT) Subject: Doctest failing Message-ID: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Hi guys. I'm strugglin with some homework stuff and am hoping you can help me out here. This is the code: small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') def book_title(title): """ Takes a string and returns a title-case string. All words EXCEPT for small words are made title case unless the string starts with a preposition, in which case the word is correctly capitalized. >>> book_title('DIVE Into python') 'Dive into Python' >>> book_title('the great gatsby') 'The Great Gatsby' >>> book_title('the WORKS OF AleXANDer dumas') 'The Works of Alexander Dumas' """ new_title = [] title_split = title.strip().lower().split() for word in title_split: if title_split[0] in small_words: new_title.append(word.title()) elif word in small_words: new_title.append(word.lower()) else: new_title.append(word.title()) return(' '.join(new_title)) def _test(): import doctest, refactory return doctest.testmod(refactory) if __name__ == "__main__": _test() All tests are failing even though I am getting the correct output on the first two tests. And the last test still gives me "Of" instead of "of" Any help is appreciated. Rgds T From mwilson at the-wire.com Sat Sep 10 07:43:38 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 10 Sep 2011 07:43:38 -0400 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. > All words EXCEPT for small words are made title case > unless the string starts with a preposition, in which > case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) > return(' '.join(new_title)) > > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > > All tests are failing even though I am getting the correct output on > the first two tests. And the last test still gives me "Of" instead of > "of" > > Any help is appreciated. I don't know about doctest -- I suspect it wants a structured docstring to specify the tests -- but this if title_split[0] in small_words: new_title.append(word.title()) can't be what you want. Mel. From __peter__ at web.de Sat Sep 10 07:47:04 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 13:47:04 +0200 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Tigerstyle wrote: > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) The logic of the for-loop is flawed; the expression title_split[0] in small_words will always evaluate to True if the first word is a "small word", even when the loop is already past the first word. You can work around that with a flag along these lines first = True for word in title_split: if first: # special treatment for the first word first = False else: # put checks for all words but the first here new_title.append(fixed_word) # assuming you have stored the titlecased # or lowercased word in the fixed_word # variable From t at jollybox.de Sat Sep 10 07:50:14 2011 From: t at jollybox.de (Thomas Jollans) Date: Sat, 10 Sep 2011 13:50:14 +0200 Subject: Doctest failing In-Reply-To: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <4E6B4EF6.6050200@jollybox.de> On 10/09/11 13:20, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. > > All tests are failing even though I am getting the correct output on > the first two tests. And the last test still gives me "Of" instead of > "of" Cannot reproduce. I only get the one, expected, failure. % python -m doctest books.py ********************************************************************** File "books.py", line 12, in books.book_title Failed example: book_title('the WORKS OF AleXANDer dumas') Expected: 'The Works of Alexander Dumas' Got: 'The Works Of Alexander Dumas' ********************************************************************** 1 items had failures: 1 of 3 in books.book_title ***Test Failed*** 1 failures. > > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > What is this "refactory"? Are you testing the right code? What is the output of your test - does it make sense for the module? Thomas From dreyemi at gmail.com Sat Sep 10 07:58:35 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 10 Sep 2011 12:58:35 +0100 Subject: test if a subclass inherits a superclass method Message-ID: Hello, I'm testing Python's class abstractness and inheritance. Since interface doesn't exist, I will like to test how to have access to a superclass method from a subclass without necessary invoking or overriding the superclass method in its subclass. >>> class Equipment(object): ... def fault(): ... return "fault" ... >>> Equipment().__class__ >>> class Vehicle(Equipment): ... # Find out here if Vehicle has access to fault I want to know whether Vehicle has access to Equipment's fault() method. Just want to know if it's there(that a vehicle can also develop a fault). I know I can override it, but I want to know if I can use it directly without overriding it. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sat Sep 10 08:05:08 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 10 Sep 2011 13:05:08 +0100 Subject: test if a subclass inherits a superclass method In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 12:58 PM, Kayode Odeyemi wrote: > Hello, > > I'm testing Python's class abstractness and inheritance. Since interface > doesn't exist, I will > like to test how to have access to a superclass method from a subclass > without necessary > invoking or overriding the superclass method in its subclass. > > >>> class Equipment(object): > ... def fault(): > ... return "fault" > ... > >>> Equipment().__class__ > > >>> class Vehicle(Equipment): > ... # Find out here if Vehicle has access to fault > > I want to know whether Vehicle has access to Equipment's fault() method. > Just want to know if it's there(that a vehicle can also develop a fault). > > I know I can override it, but I want to know if I can use it directly > without overriding it. > OK! I figured it out like this: >>> v = Vehicle() >>> dir(v) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_ _weakref__', 'fault'] Cool stuff. -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.ware at ntlworld.com Sat Sep 10 08:24:25 2011 From: alister.ware at ntlworld.com (Alister Ware) Date: Sat, 10 Sep 2011 12:24:25 GMT Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sat, 10 Sep 2011 04:20:17 -0700, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me out > here. > > This is the code: > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. All words EXCEPT > for small words are made title case unless the string starts with a > preposition, in which case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) > return(' '.join(new_title)) > > def _test(): > import doctest, refactory return doctest.testmod(refactory) > if __name__ == "__main__": > _test() > > All tests are failing even though I am getting the correct output on the > first two tests. And the last test still gives me "Of" instead of "of" > > Any help is appreciated. > > Rgds > > T Ignoring the docttests my process would be to process each word & then manually capitalize he 1st word, .I would als0 use a comprehension as makes for cleaner code:- small_words=('into','the','a','of','at','in','for','on') def capitalize(word): if word in small_words: return word else: return word.title() def set_title(phrase): result=[ capitalize(x.lower()) for x in phrase.split(' ') ] result[0]=result[0].title() return " ".join(result) print set_title('the works of alexander dumas') -- ... I don't like FRANK SINATRA or his CHILDREN. From hetchkay at gmail.com Sat Sep 10 09:28:49 2011 From: hetchkay at gmail.com (hetchkay) Date: Sat, 10 Sep 2011 06:28:49 -0700 (PDT) Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> <87ipp0n7c1.fsf@benfinney.id.au> Message-ID: <4ee53496-ebec-4ee5-be0c-de344ac586c8@y39g2000prd.googlegroups.com> > > I suspect, if you can be explicit about the goal you're aiming for with > this code, a better design can be found that doesn't require all those > polymorphism-breaking type checks. > It is difficult to explain what I am trying to do, but let me try. I am mapping data from one hierarchy into another. The mapping rules are quite complex. I developed a system such that the rules could be defined as "expressions" of the source hierarchy i.e a particular entry in the target hierarchy could be represented as an expression of entries in the source hierarchy. Suppose a point is stored in x, y coordinates in the source hierarchy, and in polar coordinates in the target hierarchy, I could write (forget for the moment what sourcePt is): pointMapping = { sourcePt.key : dict( radius = Sqrt(sourcePt.value['x']**2 + sourcePt.value['y']**2), angle = Atan(sourcePt.value['y']/sourcePt.value['x']), ), } The above dictionary is delay-evaluated. sourcePt is an instance of a class that facilitates the delayed evaluation. Sqrt, Atan etc. are wrappers to the math functions to facilitate delayed evaluation. When I encounter a point object, I could 'evaluate' the above mapping for the point object to get the target dictonary. The actual requirements are much more involved than this. The motivation of the design was to enable application developers (who are not experts in python) to be able to write the mappings. The mappings also need to be readable. You could consider this to be some sort of DSL. However, because of the number of rules involved, I am trying to be as close to Python expressions as possible. If the target setting is to be a tuple, for example, I want to be able to write the tuple directly as "( expr1, expr2 )", rather than, say, "Tuple(expr1, expr2)". There is also a requirement to validate the mapping on load so that run-time errors are minimized. The system we are developing is quite reusable and we have been able to use it for three different mappings so far. At this point, I am trying to profile the code and noticed that a non-trivial amount of time is being spent in the particular function I mentioned in this thread. Regards, Krishnan From wm at localhost.localdomain Sat Sep 10 09:57:16 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sat, 10 Sep 2011 15:57:16 +0200 Subject: what's the command for (cd ..) in python References: <4e6a0e8e$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e6b45e6$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5yll66t4xv3j.dlg@localhost.localdomain> On Sat, 10 Sep 2011 21:11:32 +1000, Steven D'Aprano wrote: > The main one that comes to mind is os.walk, which has this to say: > > Caution: if you pass a relative pathname for top, don't change the > current working directory between resumptions of walk. walk never > changes the current directory, and assumes that the client doesn't > either. > > Seems like a reasonable assumption to me. Oh, that kind of functions. Yes, that *is* surely reasonable, just as mixing chdir/mkdir/remove and whatever else that affects the directory structure is not a good idea, or at least something to be done carefully. I just wouldn't think to give it some special credit. Thanks Waldek From tyler at tysdomain.com Sat Sep 10 10:04:24 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 08:04:24 -0600 Subject: How to structure packages In-Reply-To: References: <2a4f542c-a8c1-46c7-9899-a3fad0940cf6@x11g2000yqc.googlegroups.com> <4e680c67$0$29980$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E6B6E68.9010908@tysdomain.com> On 9/10/2011 4:11 AM, Nobody wrote: > On Fri, 09 Sep 2011 11:37:44 +1000, Chris Angelico wrote: > >>> The Java compiler also acts as a "make" program. If it doesn't find >>> a .class file for a needed class, it will search for the corresponding >>> .java file and compile that. So to compile a complex program, you only >>> need to compile the top-level file (e.g. HelloWorld.java), and it will >>> compile everything which is required. No Makefile is needed, as the >>> relationship between classes, object files and source files is fixed. >>> >> If that's the entire benefit, then I think this is a rather hefty >> price to pay for the elimination of a makefile. > It also eliminates the need for TAGS files, browser database (PDB) files, > etc. Once you know the class name, all of the filenames follow from that. > > I suspect that the one-to-one correspondence between classes and .class > files is mostly technical (e.g. Java's security model). The one-to-one > correspondence between class files and source files could probably be > relaxed, but at the expense of complicating the IDE and toolchain. > > I never saw it as a problem, given that Java is fundamentally class-based: > there are no global variables or functions, only classes. > Sure there are no global variables, but having one class per file is one of the big things I hate about Java. Sure it keeps things organized, but that's a bit to much for me. -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From tyler at tysdomain.com Sat Sep 10 10:08:28 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 08:08:28 -0600 Subject: test if a subclass inherits a superclass method In-Reply-To: References: Message-ID: <4E6B6F5C.8000304@tysdomain.com> On 9/10/2011 5:58 AM, Kayode Odeyemi wrote: > Hello, > > I'm testing Python's class abstractness and inheritance. Since > interface doesn't exist, I will > like to test how to have access to a superclass method from a subclass > without necessary > invoking or overriding the superclass method in its subclass. > > >>> class Equipment(object): > ... def fault(): > ... return "fault" > ... > >>> Equipment().__class__ > > >>> class Vehicle(Equipment): > ... # Find out here if Vehicle has access to fault > > I want to know whether Vehicle has access to Equipment's fault() method. > Just want to know if it's there(that a vehicle can also develop a fault). > > I know I can override it, but I want to know if I can use it directly > without overriding it. Perhaps this helps: http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Sep 10 10:12:32 2011 From: roy at panix.com (Roy Smith) Date: Sat, 10 Sep 2011 10:12:32 -0400 Subject: Applying a function recursively References: <52c256ae-81b0-4a7c-9047-42e1ae8b6eda@n19g2000prh.googlegroups.com> <87ipp0n7c1.fsf@benfinney.id.au> <4ee53496-ebec-4ee5-be0c-de344ac586c8@y39g2000prd.googlegroups.com> Message-ID: In article <4ee53496-ebec-4ee5-be0c-de344ac586c8 at y39g2000prd.googlegroups.com>, hetchkay wrote: [complicated description elided] > You could consider this to be some sort of DSL. However, because of > the number of rules involved, I am trying to be as close to Python > expressions as possible. If the target setting is to be a tuple, for > example, I want to be able to write the tuple directly as "( expr1, > expr2 )", rather than, say, "Tuple(expr1, expr2)". > There is also a requirement to validate the mapping on load so that > run-time errors are minimized. I assume by DSL you mean Domain Specific Language? Having worked with a number of DSLs, my emphatic recommendation is DON'T DO IT! What you will end up with is a language which is almost, but not quite, like some other existing language. That means the people who use it will need to learn something new. If you make it "as close to Python as possible", all that will happen is people will assume it's Python, and constantly be surprised when things don't work the same way. Whatever features of "real Python" you left out, people will invariably be clamoring for. Eventually, you will be forced to duct-tape them into the language. You will end up bogged down forever in language maintenance, adding features, fixing bugs, writing documentation, providing tech support, etc. Think of all the ecosystem stuff which grows up around a real language. Debuggers. Profilers. Language-aware editors (or plugins to emacs, eclipse, etc). Add-in libraries to do a zillion things you never thought you would want to do. Hoards of really smart and enthusiastic people on mailing lists, newsgroups, Stack Overflow, etc willing to help out with problems. Books. Professional training courses. You will end up with replicating all that, or doing without. It sounds like what you really want to do is just use Python as your scripting language. The lazy evaluation features you desire can be handled by writing some library code. From wentlv at gmail.com Sat Sep 10 11:41:20 2011 From: wentlv at gmail.com (crow) Date: Sat, 10 Sep 2011 08:41:20 -0700 (PDT) Subject: Is there anyway to use urllib2 to download a file from http server? Message-ID: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> As the title. Or is there other module that can handle this task? Many thanks in advance From stefan_ml at behnel.de Sat Sep 10 11:53:12 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 10 Sep 2011 17:53:12 +0200 Subject: Is there anyway to use urllib2 to download a file from http server? In-Reply-To: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> References: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> Message-ID: crow, 10.09.2011 17:41: > As the title. > > Or is there other module that can handle this task? Did you notice that is has documentation? http://docs.python.org/library/urllib2.html#examples Stefan From rosuav at gmail.com Sat Sep 10 11:56:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 11 Sep 2011 01:56:32 +1000 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware wrote: > Ignoring the docttests my process would be to process each word & then > manually capitalize he 1st word, .I would als0 use a comprehension as > makes for cleaner code:- > > def capitalize(word): > ? ?if word in small_words: > ? ? ? ?return word > ? ?else: > ? ? ? ?return word.title() And I'd do this with a lambda, but that's just me. Of course, if your logic is more complicated, it makes more sense to keep it in a named function, but a single conditional call can fit nicely into a lambda. ChrisA From tjreedy at udel.edu Sat Sep 10 13:34:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 13:34:19 -0400 Subject: [ANN] Shed Skin 0.9 In-Reply-To: References: Message-ID: On 9/10/2011 7:08 AM, Mark Dufour wrote: > Hi all, > > I have just released version 0.9 of Shed Skin, a (restricted-)Python to > C++ compiler. That should say "Python2.(4-6) to C++ compiler". I do not want to pick on Mark, who I think is doing great work, but I find it annoying when third-party developers use the generic 'Python' to refer to undisclosed older versions of Python. > Please see my blog for the full announcement: > > http://shed-skin.blogspot.com While Mark never reveals this crucial information anywhere on this page, > The Shed Skin homepage is located here: > > http://shedskin.googlecode.com he does specify versions in the first sentence of this page. That is much better than some other projects. -- Terry Jan Reedy From abhijeet.manohar at gmail.com Sat Sep 10 13:37:12 2011 From: abhijeet.manohar at gmail.com (Abhijeet Mahagaonkar) Date: Sat, 10 Sep 2011 23:07:12 +0530 Subject: Is there anyway to use urllib2 to download a file from http server? In-Reply-To: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> References: <6e23a17a-890f-46b8-b79f-1b0c8991b0de@g32g2000pri.googlegroups.com> Message-ID: I guess urlretrieve() would do the job -AB On Sat, Sep 10, 2011 at 9:11 PM, crow wrote: > As the title. > > Or is there other module that can handle this task? > > Many thanks in advance > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Sep 10 13:59:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 13:59:02 -0400 Subject: Doctest failing In-Reply-To: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/10/2011 7:20 AM, Tigerstyle wrote: > Hi guys. > > I'm strugglin with some homework stuff and am hoping you can help me > out here. We appreciate you saying so instead of hiding that this is homework. > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > def book_title(title): > """ Takes a string and returns a title-case string. > All words EXCEPT for small words are made title case > unless the string starts with a preposition, in which > case the word is correctly capitalized. > >>> book_title('DIVE Into python') > 'Dive into Python' > >>> book_title('the great gatsby') > 'The Great Gatsby' > >>> book_title('the WORKS OF AleXANDer dumas') > 'The Works of Alexander Dumas' > """ > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > if title_split[0] in small_words: > new_title.append(word.title()) > elif word in small_words: > new_title.append(word.lower()) > else: > new_title.append(word.title()) The key issue is that you want to treat the first word one way (.title it) and the rest differently (conditionally .title or not) . So immediately separate the first from the rest and then process each. There are at least three ways to do the split. Perhaps I should stop with this hint, and certainly you should think a bit before reading further, but here is what I consider to be the most elegant 3.2 code. . , , , . . . first, *rest = title.strip().lower().split() new_title = [first.title()] for word in rest: if word not in small_words: word = word.title() new_title.append(word) > return(' '.join(new_title)) doctest.testmod() now passes (there is no 'refactory' here) > def _test(): > import doctest, refactory > return doctest.testmod(refactory) > if __name__ == "__main__": > _test() -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 10 15:36:42 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 15:36:42 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' Message-ID: Python's iterator protocol for an iterator 'items' allows combinations of explicit "next(items)" calls with the implicit calls of a "for item in items:" loop. There are at least three situations in which this can be useful. (While the code posted here is not testable, being incomplete or having pseudocode lines, I have tested full examples of each idiom with 3.2.) 1. Process first item of an iterable separately. A traditional solution is a flag variable that is tested for each item. first = True for item in iterable: if first: first = False else: (I have seen code like this posted on this list several times, including today.) Better, to me, is to remove the first item *before* the loop. items = iter(iterable) Sometimes and can be combined in . For instance, "result = []" followed by "result.append(process_first(item))" becomes "result = [process_first(item)]". The statement containing the explicit next(items) call can optionally be wrapped to explicitly handle the case of an empty iterable in whatever manner is desired. try: except StopIteration: raise ValueError("iterable cannot be empty") For an iterable known to have a small number of items, the first item can be removed, with only a small copying penalty, with a simple assignment. first, *rest = iterable The older and harder to write version of this requires the iterable to be a sequence? first, rest = seq[0], seq[1:] 2. Process the last item of an iterable differently. As far as I know, this cannot be done for a generic iterable with a flag. It requires a look ahead. items = iter(iterable) current = next(items) for item in items: current = item To treat both first and last differently, pull off the first before binding 'current'. Wrap next() calls as desired. 3. Process the items of an iterable in pairs. items = iter(iterable) for first in items: second = next(items) This time, StopIteration is raised for an odd number of items. Catch and process as desired. One possibility is to raise ValueError("Iterable must have an even number of items"). A useful example of just sometimes pairing is iterating a (unicode) string by code points ('characters') rather than by code units. This requires combining the surrogate pairs used for supplementary characters when the units are 16 bits. chars = iter(string) for char in chars: if is_first_surrogate(char): char += next(chars) yield char -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 10 15:36:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Sep 2011 15:36:47 -0400 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/10/2011 7:47 AM, Peter Otten wrote: > You can work around that with a > flag along these lines > > first = True > for word in title_split: > if first: > # special treatment for the first word > first = False > else: > # put checks for all words but the first here > new_title.append(fixed_word) # assuming you have stored the titlecased > # or lowercased word in the fixed_word > # variable An alternative to a flag and testing every item is to remove and process the first item *before* the loop. See my response on this thread or my new thread Idioms combining 'next(items)' and 'for item in items:' -- Terry Jan Reedy From Phillip.M.Feldman at gmail.com Sat Sep 10 15:57:21 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 12:57:21 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: References: <32435519.post@talk.nabble.com> Message-ID: <32439307.post@talk.nabble.com> Very nice explanation! I've circumvented the problem by returning a `deepcopy` of the list. I've also added an acknowledgment. The revised code is attached. I'd like to see both balls in numbered boxes (this code) and balls in unnumbered (indistinguishable) boxes in Python's `itertools` module, but don't know whom to contact about this. Also, I haven't yet worked out a good algorithm for balls in unnumbered boxes. Any suggestions will be appreciated. Phillip http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py balls_in_numbered_boxes.py -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439307.html Sent from the Python - python-list mailing list archive at Nabble.com. From pgiri at yahoo.com Sat Sep 10 16:05:36 2011 From: pgiri at yahoo.com (Giridhar Pemmasani) Date: Sat, 10 Sep 2011 13:05:36 -0700 (PDT) Subject: [ANN] dispy: distribute computations and execute in parallel Message-ID: <1315685136.93773.YahooMailNeo@web160614.mail.bf1.yahoo.com> Hello, I would like to announce dispy (http://dispy.sf.net) that can distribute and parallelize computations among computing nodes over network (yes, yet another implementation of parallelization). This is useful for problems in SIMD paradigm where a computation can be executed with multiple data simultaneously. Salient features of dispy are: ?* Computations (Python functions or standalone programs) and its ? ?dependencies (files, Python functions, classes, modules) are ? ?distributed automatically as and when needed. ?* Computation nodes can be anywhere on the network. For security, ? ?either simple hash based authentication or SSL encryption can be ? ?used. ?* A computation may specify which nodes are allowed to execute it ? ?(for now, using simple patterns of IP addresses). ?* After each execution is finished, the results of execution, output, ? ?errors and exception trace are made available for further ? ?processing. ?* Nodes may become available dynamically: dispy will schedule jobs ? ?whenever a node is available and computations can use that node. If ? ?a node fails while executing scheduled jobs, those jobs may be ? ?resubmitted to other nodes if computations allow it. ?* dispy can be used in a single process to use all the nodes ? ?exclusively (simpler to use) or in multiple processes sharing the ? ?nodes. Currently dispy works with Python 2.7 and has been tested with nodes running Linux and OS X. Thanks, Giri -------------- next part -------------- An HTML attachment was scrubbed... URL: From Phillip.M.Feldman at gmail.com Sat Sep 10 16:32:49 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 13:32:49 -0700 (PDT) Subject: can't generate iterator from list In-Reply-To: <32439307.post@talk.nabble.com> References: <32435519.post@talk.nabble.com> <32439307.post@talk.nabble.com> Message-ID: <32439439.post@talk.nabble.com> I just realized that there is a defect in my algorithm, so I will try to code this using a recursive algorithm instead. -- View this message in context: http://old.nabble.com/can%27t-generate-iterator-from-list-tp32435519p32439439.html Sent from the Python - python-list mailing list archive at Nabble.com. From gelonida at gmail.com Sat Sep 10 16:43:39 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 10 Sep 2011 22:43:39 +0200 Subject: optionparse: how to add a line break to the help text Message-ID: I'm having a small question about optionparse. Normaly optionparser will format the help text according to the console's width. I just wondered if there is any way to insert a line breakk into an options help text. Example: from optparse import OptionParser parser = OptionParser() parser.add_option("-f", action="store", help="This option is really really complicated" " and I'd like to write" " a few paragrpahs to explain how it works." "\nHowever the line breaks are stripped off" " and it's thus difficult to structure the help text") args = ['-h'] parser.parse_args(args) Is there any trick to force a new paragraph/ line break before the word 'However'? Thanks in advance for suggestions. From __peter__ at web.de Sat Sep 10 16:49:13 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Sep 2011 22:49:13 +0200 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: Terry Reedy wrote: > On 9/10/2011 7:47 AM, Peter Otten wrote: > >> You can work around that with a >> flag along these lines >> >> first = True >> for word in title_split: >> if first: >> # special treatment for the first word >> first = False >> else: >> # put checks for all words but the first here >> new_title.append(fixed_word) # assuming you have stored the >> titlecased >> # or lowercased word in the fixed_word >> # variable > > An alternative to a flag and testing every item is to remove and process > the first item *before* the loop. See my response on this thread or my > new thread > Idioms combining 'next(items)' and 'for item in items:' I reckoned the approach with the flag the most beginner-friendly because you don't have to think too hard about the corner-cases, namely >>> book_title("") '' When I use the "process first item before the loop" approach I usually end up with a helper generator def _words(words, small_words={w.title(): w for w in small_words}): yield next(words) for word in words: yield small_words[word] if word in small_words else word def book_title(s): return " ".join(_words(iter(s.title().split()))) and the nagging thought that I'm making it more complex than need be. From tyler at tysdomain.com Sat Sep 10 16:53:26 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 14:53:26 -0600 Subject: using python in web applications In-Reply-To: <87mxedm3lh.fsf@benfinney.id.au> References: <87mxedm3lh.fsf@benfinney.id.au> Message-ID: <4E6BCE46.3020002@tysdomain.com> On 9/9/2011 10:19 PM, Ben Finney wrote: > "Littlefield, Tyler" writes: > >> I'm curious if there are some good solutions for using Python in web >> applications. > Start with: > > > > Awesome, will do, thanks. > and try your criteria against what you find there. > -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From matthew.a.hess at gmail.com Sat Sep 10 17:44:01 2011 From: matthew.a.hess at gmail.com (matt) Date: Sat, 10 Sep 2011 14:44:01 -0700 (PDT) Subject: IOError 35 when trying to read the result of call to urllib2.urlopen References: <4e6ab711$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0a79dcd3-92e6-4102-b202-dbb33fce634f@e34g2000prn.googlegroups.com> On Sep 9, 6:02?pm, Steven D'Aprano wrote: > matt wrote: > > When I try to look at "resp_body" I get this error: > > > IOError: [Errno 35] Resource temporarily unavailable > > > I posted to the same URI using curl and it worked fine, so I don't > > think it has to do with the server. > > Are your Python code and curl both using the same proxy? It may be that one > is going direct and the other is using a proxy. > > Or perhaps the destination is just flaky, and the resource genuinely is > temporarily unavailable. Or it doesn't like your useragent string and is > lying. > > -- > Steven No proxy. It's all local over the loopback interface (probably should have mentioned that). The service I'm POSTing to is a Python web app with CherryPy as the framework. Also, because of some dependency issues I'm using Python 2.6. From rafadurancastaneda at gmail.com Sat Sep 10 18:16:42 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 11 Sep 2011 00:16:42 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: <4E6BE1CA.9030608@gmail.com> On 10/09/11 22:43, Gelonida N wrote: > I'm having a small question about optionparse. > > Normaly optionparser will format the help text according to the > console's width. > > I just wondered if there is any way to insert a line breakk into an > options help text. > > Example: > > from optparse import OptionParser > > parser = OptionParser() > parser.add_option("-f", action="store", > help="This option is really really complicated" > " and I'd like to write" > " a few paragrpahs to explain how it works." > "\nHowever the line breaks are stripped off" > " and it's thus difficult to structure the help text") > > args = ['-h'] > parser.parse_args(args) > > Is there any trick to force a new paragraph/ line break before the word > 'However'? > > > Thanks in advance for suggestions. > > You can use """ for multiple line texts: >>> text = \ ... """fsdfsfsdfsdf ... sfsdfsfsdf ... sdfsdf s ... ... """ >>> text 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' From dribnairb at gmail.com Sat Sep 10 18:50:09 2011 From: dribnairb at gmail.com (Brian) Date: Sat, 10 Sep 2011 15:50:09 -0700 (PDT) Subject: Python and Outlook-style rules References: Message-ID: <3a160e5e-0dbe-47e3-9dba-901003041bd4@d12g2000vba.googlegroups.com> On Sep 9, 5:19?pm, Alec Taylor wrote: > Something like this? > > http://stackoverflow.com/questions/387606/using-user-input-to-find-in... > Actually, I'm looking for a framework or something similar - something more like this, only for python: http://www.codeproject.com/KB/macros/RulesWizard.aspx From laurent.payot at gmail.com Sat Sep 10 19:35:28 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 16:35:28 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> [troll] For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. [/troll] "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. From laurent.payot at gmail.com Sat Sep 10 19:35:28 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 16:35:28 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> [troll] For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. [/troll] "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. From robert.kern at gmail.com Sat Sep 10 19:44:02 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 10 Sep 2011 18:44:02 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6BE1CA.9030608@gmail.com> References: <4E6BE1CA.9030608@gmail.com> Message-ID: On 9/10/11 5:16 PM, Rafael Dur?n Casta?eda wrote: > On 10/09/11 22:43, Gelonida N wrote: >> I'm having a small question about optionparse. >> >> Normaly optionparser will format the help text according to the >> console's width. >> >> I just wondered if there is any way to insert a line breakk into an >> options help text. >> >> Example: >> >> from optparse import OptionParser >> >> parser = OptionParser() >> parser.add_option("-f", action="store", >> help="This option is really really complicated" >> " and I'd like to write" >> " a few paragrpahs to explain how it works." >> "\nHowever the line breaks are stripped off" >> " and it's thus difficult to structure the help text") >> >> args = ['-h'] >> parser.parse_args(args) >> >> Is there any trick to force a new paragraph/ line break before the word >> 'However'? >> >> >> Thanks in advance for suggestions. >> >> > You can use """ for multiple line texts: > >>> text = \ > ... """fsdfsfsdfsdf > ... sfsdfsfsdf > ... sdfsdf s > ... > ... """ > >>> text > 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' That's not the problem. OptionParser removes all of the original newlines that are in the given text when it formats the text for display. I don't think there is a simple workaround. -- 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 cs at zip.com.au Sat Sep 10 19:50:46 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 11 Sep 2011 09:50:46 +1000 Subject: what's the command for (cd ..) in python In-Reply-To: <5yll66t4xv3j.dlg@localhost.localdomain> References: <5yll66t4xv3j.dlg@localhost.localdomain> Message-ID: <20110910235046.GA12648@cskk.homeip.net> On 10Sep2011 15:57, Waldek M. wrote: | On Sat, 10 Sep 2011 21:11:32 +1000, Steven D'Aprano wrote: | > The main one that comes to mind is os.walk, which has this to say: | > | > Caution: if you pass a relative pathname for top, don't change the | > current working directory between resumptions of walk. walk never | > changes the current directory, and assumes that the client doesn't | > either. | > | > Seems like a reasonable assumption to me. | | Oh, that kind of functions. | Yes, that *is* surely reasonable, just as mixing chdir/mkdir/remove | and whatever else that affects the directory structure is not a good idea, | or at least something to be done carefully. | I just wouldn't think to give it some special credit. It's like umask and friends - they affect a program-wide implicit state. Umask affects default new file permissions, chdir affects starting point for relative pathnames, etc. All implicit. The usual biggie with chdir is that of course your program may have been handed relative file pathnames on the command line. They need resolving _before_ any chdiring happens, if chdiring is going to happen. For this kind of reason chdir, umask et al are generally best used in top level logic only rather than inside library functions. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ It's hard to believe that something as rational as the metric system was invented by the French. - Henry O. Farad From gelonida at gmail.com Sat Sep 10 20:05:13 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 02:05:13 +0200 Subject: import packet.module without importing packet.__init__ ? Message-ID: Hi, I am little shaky with how exactly python imports packages / modules etc. Is it possible to import a module from a packet without importing its __init__.py ? Full example: ============== # application.py --------------------- print "starting application" import mypacket.module1 # mypacket.__init__.py --------------------- print "importing __init__" # mypacket.module1.py --------------------- print "importing module1" The output, that I get with python 2.6 is $ python application.py > starting application > importing __init__ > importing module1 Under certain circumstances I'd like to avoid the implicit import of __init__.py Due to other constrains of my project I am obliged to have a non empty __init__.py From Phillip.M.Feldman at gmail.com Sat Sep 10 20:43:39 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 10 Sep 2011 17:43:39 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes Message-ID: <32440187.post@talk.nabble.com> I've written a recursive class that creates an iterator to solve a general formulation of the combinatorics problem known as "balls in numbered boxes" (also known as "indistinguishable balls in distinguishable boxes"). The code has been extensively tested and appears to work, but isn't terribly elegant. Any suggestions about how to improve it will be appreciated. Also, I'd like to get this functionality into the Python's `itertools` module (the present set of combinatorics functions in `itertools` does not include "balls in boxes"). Does anyone know whom I should contact about this? Phillip http://old.nabble.com/file/p32440187/balls_in_numbered_boxes.py balls_in_numbered_boxes.py -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32440187.html Sent from the Python - python-list mailing list archive at Nabble.com. From tyler at tysdomain.com Sat Sep 10 20:50:21 2011 From: tyler at tysdomain.com (Littlefield, Tyler) Date: Sat, 10 Sep 2011 18:50:21 -0600 Subject: using python in web applications In-Reply-To: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> Message-ID: <4E6C05CD.3010905@tysdomain.com> On 9/10/2011 5:35 PM, Laurent wrote: > [troll] > For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. > [/troll] > I replied to that one off list I guess, but I figured Django was way more overhead than I wanted, doesn't really fit with solving the speed issue. > "Eve Online", a well known MMORPG was developped with stackless python : http://highscalability.com/eve-online-architecture > > You mentioned nginx so I can tell you I personally use Linux + nginx + mongodb (pymongo) + Python 3 version of cherrypy (with Mako templates) and it's working fine after some tuning. Awesome, thanks. I'm new to this, so some of that flew over my head, but I'll take a look at all of them. I'm not sure of the relevance of stackless in this case; I was looking into PyPy, but I'm not really sure whether that can be connected with nginx. I guess I could just write the web server in Python and use it from that point. -- Take care, Ty Web: http://tds-solutions.net The Aspen project: a light-weight barebones mud engine http://code.google.com/p/aspenmud Sent from my toaster. From steve+comp.lang.python at pearwood.info Sat Sep 10 20:56:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 10:56:42 +1000 Subject: import packet.module without importing packet.__init__ ? References: Message-ID: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Gelonida N wrote: > Is it possible to import a module from a packet without importing its > __init__.py ? Untested, but I think so. But you shouldn't. The solution (if it does work, as I said I haven't tested it) is a hack. Suppose you have a library like this: modules/ +-- spam.py +-- ham.py +-- package/ +-- __init__.py +-- cheese.py The directory "modules" is in your Python path, so you can "import spam" or "import package". The trick is to add "modules/package" to the Python path so that "import cheese" will find cheese.py directly. You can do that by manipulating sys.path, or by setting the environment variable PYTHONPATH. Another hack would be to add a hard link to the top level: modules/ +-- spam.py +-- ham.py +-- cheese.py <------------+ +-- package/ | +-- __init__.py | +-- cheese.py <--------+ This is not a copy, it is a hard link: the same file appears in literally two places. (But note that not all file systems support hard linking.) Soft links or shortcuts might also work. Now you can "import cheese". But generally, you should design your package so that it doesn't matter whether or not __init__.py is imported first. I see three reasnable situations: (1) package.cheese should rely on package, in which case it requires package.__init__ to be imported first. (Sometimes I put code common to the entire package in __init__.py.) (2) Just don't worry about the fact that package.__init__ gets imported first. Do you have any idea how many modules get imported when Python starts up? What's one more? (3) If cheese.py truly is independent of package, then it shouldn't be part of package. Just make it a stand alone module outside the package directory, and be done. (Your installer can still treat cheese.py as a dependency of package, and ensure that they are both installed.) -- Steven From rhodri at wildebst.demon.co.uk Sat Sep 10 21:12:26 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 11 Sep 2011 02:12:26 +0100 Subject: optionparse: how to add a line break to the help text References: Message-ID: On Sat, 10 Sep 2011 23:16:42 +0100, Rafael Dur?n Casta?eda wrote: > On 10/09/11 22:43, Gelonida N wrote: >> I'm having a small question about optionparse. >> >> Normaly optionparser will format the help text according to the >> console's width. >> >> I just wondered if there is any way to insert a line breakk into an >> options help text. >> >> Example: >> >> from optparse import OptionParser >> >> parser = OptionParser() >> parser.add_option("-f", action="store", >> help="This option is really really complicated" >> " and I'd like to write" >> " a few paragrpahs to explain how it works." >> "\nHowever the line breaks are stripped off" >> " and it's thus difficult to structure the help text") >> >> args = ['-h'] >> parser.parse_args(args) >> >> Is there any trick to force a new paragraph/ line break before the word >> 'However'? >> >> >> Thanks in advance for suggestions. >> >> > You can use """ for multiple line texts: > >>> text = \ > ... """fsdfsfsdfsdf > ... sfsdfsfsdf > ... sdfsdf s > ... > ... """ > >>> text > 'fsdfsfsdfsdf\n sfsdfsfsdf\nsdfsdf s\n\n' Unfortunately the help text is formatted using textwrap, which presumes that the entire text is a single paragraph. To get paragraphs in the help text, you'll need to write an IndentedHelpFormatter subclass that splits the text on "\n\n", textwraps the split string individually, then re-joins them. _format_text() and format_option() look like the methods that would need replacing. -- Rhodri James *-* Wildebeest Herder to the Masses From gelonida at gmail.com Sat Sep 10 21:54:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 03:54:57 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: Hi James, On 09/11/2011 03:12 AM, Rhodri James wrote: > On Sat, 10 Sep 2011 23:16:42 +0100, Rafael Dur?n Casta?eda > wrote: > >> On 10/09/11 22:43, Gelonida N wrote: >>> >>> from optparse import OptionParser >>> >>> parser = OptionParser() >>> parser.add_option("-f", action="store", >>> help="This option is really really complicated" >>> " and I'd like to write" >>> " a few paragrpahs to explain how it works." >>> "\nHowever the line breaks are stripped off" >>> " and it's thus difficult to structure the help text") >>> >>> args = ['-h'] >>> parser.parse_args(args) >>> >>> Is there any trick to force a new paragraph/ line break before the word >>> 'However'? >> > > Unfortunately the help text is formatted using textwrap, which presumes > that the entire text is a single paragraph. To get paragraphs in the > help text, you'll need to write an IndentedHelpFormatter subclass that > splits the text on "\n\n", textwraps the split string individually, then > re-joins them. _format_text() and format_option() look like the methods > that would need replacing. > Thanks a lot. Good to know, that there are options, though a little more complicated than expected. I'll live withou tthe line break for the time being and will deep dive lateron, when I really want to insist on pragraphs within a help section. I like the idea of '\n\n' as paragraph markes. Long term this could probably even become an enhancement for optparse (with an explicit option to enable it in order to break no existing code) From python.list at tim.thechases.com Sat Sep 10 22:08:45 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 10 Sep 2011 21:08:45 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: Message-ID: <4E6C182D.60905@tim.thechases.com> On 09/10/11 20:54, Gelonida N wrote: >> Unfortunately the help text is formatted using textwrap, which presumes >> that the entire text is a single paragraph. To get paragraphs in the >> help text, you'll need to write an IndentedHelpFormatter subclass that >> splits the text on "\n\n", textwraps the split string individually, then >> re-joins them. _format_text() and format_option() look like the methods >> that would need replacing. > > Thanks a lot. Good to know, that there are options, though a little more > complicated than expected. Just in case you want it: http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse it's come up several times and several years ago I hacked together exactly the solution Rhodri mentions. -tkc From ting at thsu.org Sat Sep 10 22:12:37 2011 From: ting at thsu.org (ting at thsu.org) Date: Sat, 10 Sep 2011 19:12:37 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On Sep 10, 7:47?am, Peter Otten <__pete... at web.de> wrote: > Tigerstyle wrote: > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > This is the code: > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > ? ? new_title = [] > > ? ? title_split = title.strip().lower().split() > > ? ? for word in title_split: > > ? ? ? ? if title_split[0] in small_words: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? ? ? elif word in small_words: > > ? ? ? ? ? ? new_title.append(word.lower()) > > ? ? ? ? else: > > ? ? ? ? ? ? new_title.append(word.title()) > > The logic of the for-loop is flawed; the expression > > title_split[0] in small_words > > will always evaluate to True if the first word is a "small word", even when > the loop is already past the first word. You can work around that with a > flag along these lines > > first = True > for word in title_split: > ? ? if first: > ? ? ? ? # special treatment for the first word > ? ? ? ? first = False > ? ? else: > ? ? ? ? # put checks for all words but the first here > ? ? new_title.append(fixed_word) # assuming you have stored the titlecased > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# or lowercased word in the fixed_word > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# variable Another way to tackle this is to just capitalize the entire sentence before returning it. new_title = [] title_split = title.strip().lower().split() for word in title_split: if word in small_words: new_title.append(word.lower()) else: new_title.append(word.title()) return(''.join(new_title).capitalize()) However, I'm only helping with your homework, because I want to point out that doctest comments should be *readable*. Don't just throw them in, take the extra 10-15 seconds to make them easier on the eyes. In the workplace, months will pass before you review this code again, so you want to make it easier for an older version of yourself to remember it. And it takes very little effort to make it readable. Here's your doctest string, reformatted with just a tiny bit more whitespace. I even cut out a sentence. def book_title(title): """ All words EXCEPT for small words are made title case unless the string starts with a preposition, in which case the word is correctly capitalized. >>> book_title('DIVE Into python') 'Dive into Python' >>> book_title('the great gatsby') 'The Great Gatsby' >>> book_title('the WORKS OF AleXANDer dumas') 'The Works of Alexander Dumas' """ -- // T.Hsu From clp2 at rebertia.com Sat Sep 10 22:18:47 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 19:18:47 -0700 Subject: recursive algorithm for balls in numbered boxes In-Reply-To: <32440187.post@talk.nabble.com> References: <32440187.post@talk.nabble.com> Message-ID: On Sat, Sep 10, 2011 at 5:43 PM, Dr. Phillip M. Feldman wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered boxes" > (also known as "indistinguishable balls in distinguishable boxes"). ?The > code has been extensively tested and appears to work, but isn't terribly > elegant. ?Any suggestions about how to improve it will be appreciated. Significantly refactored (but untested) version: https://gist.github.com/1209079 Cheers, Chris -- http://rebertia.com From gelonida at gmail.com Sat Sep 10 23:07:28 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 05:07:28 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6C182D.60905@tim.thechases.com> References: <4E6C182D.60905@tim.thechases.com> Message-ID: Hi Tim, Thanks a lot!!! On 09/11/2011 04:08 AM, Tim Chase wrote: > On 09/10/11 20:54, Gelonida N wrote: >>> Unfortunately the help text is formatted using textwrap, which presumes >>> that the entire text is a single paragraph. To get paragraphs in the >>> help text, you'll need to write an IndentedHelpFormatter subclass that >>> splits the text on "\n\n", textwraps the split string individually, then >>> re-joins them. _format_text() and format_option() look like the methods >>> that would need replacing. > > Just in case you want it: > > http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse > It works (of course ;-) ) like a charm. Good to know, that I'm not the only one who want's to structure the help text a little nicer. > > it's come up several times and several years ago I hacked together > exactly the solution Rhodri mentions. Considering, that you posted the snippet in 2007 and this is very probably a reocurring problem for any slighty more complicated help text it is really a pity, that it did not become of part of the standard optparse library :-( Thanks again. From jabba.laci at gmail.com Sat Sep 10 23:20:26 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Sat, 10 Sep 2011 23:20:26 -0400 Subject: download pages using a cookies.txt file In-Reply-To: References: Message-ID: Hi, Thanks, I could put together the pieces and here is my solution: (1) get_cookies_in_cookiejar function to extract cookies and put them in a cookiejar: https://github.com/jabbalaci/jabbapylib/blob/master/jabbapylib/web/export_firefox_cookies.py (2) download page using urllib2 and passing the cookiejar: https://github.com/jabbalaci/jabbapylib/blob/master/jabbapylib/web/web.py See the bottom with get_page_with_cookies_using_cookiejar(url). Laszlo On Mon, Sep 5, 2011 at 22:19, Chris Rebert wrote: > On Mon, Sep 5, 2011 at 6:36 PM, Jabba Laci wrote: >> Hi, >> >> I would like to download a page that requires authentication with >> cookies. I've already figured out how to do it with wget (blog post >> here: http://bit.ly/pp25LP). In short: >> (1) extract cookies from Firefox's cookies.sqlite and store them in a text file >> (2) wget --cookies=on --load-cookies=cookies.txt >> --keep-session-cookies "http://..." >> >> My question is: how to do it from Python? > > http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar > > Cheers, > Chris > From laurent.payot at gmail.com Sat Sep 10 23:21:46 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 20:21:46 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <3c8c4056-aa89-4a7c-a22c-44baf97a02c1@glegroupsg2000goo.googlegroups.com> Well PyPy is just an implementation of Python among many others (but limited to version 2.7). It is not a web server. If you want to make PyPy interact with a web server (such as nginx) you have to use a special protocol such as WSGI or Fast-CGI. For best performances you can for instance use uWSGI that integrates well with nginx but for this you have to recompile nginx. As you see it's a bit complex, you should read the wikis. May the Force be with you. From laurent.payot at gmail.com Sat Sep 10 23:21:46 2011 From: laurent.payot at gmail.com (Laurent) Date: Sat, 10 Sep 2011 20:21:46 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <3c8c4056-aa89-4a7c-a22c-44baf97a02c1@glegroupsg2000goo.googlegroups.com> Well PyPy is just an implementation of Python among many others (but limited to version 2.7). It is not a web server. If you want to make PyPy interact with a web server (such as nginx) you have to use a special protocol such as WSGI or Fast-CGI. For best performances you can for instance use uWSGI that integrates well with nginx but for this you have to recompile nginx. As you see it's a bit complex, you should read the wikis. May the Force be with you. From gelonida at gmail.com Sat Sep 10 23:39:05 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 05:39:05 +0200 Subject: import packet.module without importing packet.__init__ ? In-Reply-To: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steven, Thanks for your answer. On 09/11/2011 02:56 AM, Steven D'Aprano wrote: > Gelonida N wrote: >> Is it possible to import a module from a packet without importing its >> __init__.py ? > > Untested, but I think so. But you shouldn't. The solution (if it does work, > as I said I haven't tested it) is a hack. > > Suppose you have a library like this: . . . . . . > The directory "modules" is in your Python path, so you can "import spam" > or "import package". The trick is to add "modules/package" to the Python > path so that "import cheese" will find cheese.py directly. > Yes it's a hack, but good to know it exists. Just in case. > Another hack would be to add a hard link to the top level: > As you said: Hard links would be a little annoying on some file systems. > > But generally, you should design your package so that it doesn't matter > whether or not __init__.py is imported first. I see three reasnable > situations: > > (1) package.cheese should rely on package, in which case it requires > package.__init__ to be imported first. (Sometimes I put code common to the > entire package in __init__.py.) > > (2) Just don't worry about the fact that package.__init__ gets imported > first. Do you have any idea how many modules get imported when Python > starts up? What's one more? > > (3) If cheese.py truly is independent of package, then it shouldn't be part > of package. Just make it a stand alone module outside the package > directory, and be done. (Your installer can still treat cheese.py as a > dependency of package, and ensure that they are both installed.) > There's still something, that I am philosophycally missing. Wy do I have to import the entire tree if I'm just interested in a leave. this is not always desired. let's imagine kitchen.__init__ kitchen.knives kitchen.pans kitchen.pots or alternatively os os.path os.wheteverelse Let's assume, that kitchen/__init__.py is importing the sub modules knives, pans and pots then I understand of course, that the next lines would import the entire kitchen > import kitchen # will import all activities > kitchen.pots.boil(egg) But if I know that I just want to boil some eggs I would really appreciate if I could just say > from kitchen.pot import boil > boil(eggs) without having the side effect of getting pans and knives also loaded into memory. Moving pots out into a separate package doesn't really feel right. I agree, that a 10 level deep package tree is not really desirable, but having every package flat on the top level doesn't sound that good either. So it seems, that developers of huge packages shouldn't really do a lot in __init__.py. Otherwise any user would always 'suck in' the entiry package with all its sub modules. To give more details about why I asked this question: The real setup looks a little different and there are some issues, that I am having: One package in question is a huge django application. Within the package is one module defining some constants and tiny functions, which I would like to reuse from some command line tools, which should start quickly without loading any of the django specific modules. (the startup penalty and the memory overhead would be noticable) I am using rpc4django, which expects, that __init__.py of the django application exports some all rpc functions which will basically import 95% of the django application and the entire django frame work (none of which were required by my command tool, support utility for this application) I could of course create a separate package just for this tiny sub module, but somehow it doesn't feel right to me. The second issue is a little more complicated. basically I end up having circular dependencies. as I have two applications that send a few customs django signals forth an back. If I wouldn't import __init__.py or if I moved the declaration of the signals into a third package then circular dependencies would disappear. So it seems, that if I can't avoid loading __init__.py in a nice way I have to create one or two tiny packages outside of my django application, or change the python path as you proposed (increases of course name space clashes) or to find a way for rpc4django of loading / locating the rpc functions without putting them in __init__.py change the rpc functions such, that they will only import the other sub modules when being called the first time (proxies / delayed imports, . . .) From rosuav at gmail.com Sat Sep 10 23:53:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 11 Sep 2011 13:53:44 +1000 Subject: using python in web applications In-Reply-To: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> Message-ID: On Sun, Sep 11, 2011 at 9:35 AM, Laurent wrote: > [troll] > For a serious web based MMO you'd rather stick to low level and forget about bloated Object Relational Mapping java-like layered kind of frameworks that are made for Rapid Applications Development, not for efficiency. > [/troll] I have been trolled. :) For any sort of web-based real-time game, here's two things to avoid: 1) Snoopability and modifiability of crucial data. Everything should be stored on the server, so that if anyone fiddles, all they do is break their own client so it has to reload from the server. 2) Massive waste of resources due to unnecessary frameworks/facilities. I play a lot of Flash games, and right now I'm playing one that has coped poorly with a miniature slashdotting. A spike in popularity resulted in a spike in server lag. I fired up a little packet sniffer, and discovered that every time you do anything in the game, the client makes a new POST request to its server. Why?! It's not that hard to hold a socket connection open! In another context, a similar issue - not a problem as yet (that I know of), but would be if the system were to be slashdotted. A server whose sole purpose is to handle script-instigated requests (using HTTP POST for its transport) sends back a Set-Cookie header with a session id. This implies that the server is holding session data for all these clients that are never going to send that cookie back. The server appears to be IIS with ASP scripts, so presumably stateful sessions are enabled by default, so it's costing memory and processing to hold, then discard, all those useless (and probably empty) session state tags. And presumably many MANY other servers have the same thing. What's YOUR framework doing that you don't need, and how much is it costing you? Yeah, I was trolled bad. :) ChrisA From bluegene8210 at gmail.com Sat Sep 10 23:54:01 2011 From: bluegene8210 at gmail.com (=?GB2312?B?wLbJq7v50vI=?=) Date: Sat, 10 Sep 2011 20:54:01 -0700 (PDT) Subject: Deadlock problem using multiprocessing Message-ID: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> This is my first touch on the multiprocessing module, and I admit not having a deep understanding of parallel programming, forgive me if there's any obvious error. This is my test code: # deadlock.py import multiprocessing class MPTask: def __init__(self): self._tseq= range(10) # task sequence self._pool= multiprocessing.Pool(2) # process pool def _exe(self, num): return num**2 def run(self): result= self._pool.map_async(self._exe, self._tseq) return result.get() result= MPTask().run() print(result) And seemingly it creates a deadlock, I have to manually kill the processes in the system monitor, yet it would be OK if the _exe() function was defined outside the MPTask class: # no_deadlock.py import multiprocessing def _exe(num): return num**2 class MPTask: def __init__(self): self._tseq= range(10) # task sequence self._pool= multiprocessing.Pool(2) # process pool def run(self): result= self._pool.map_async(_exe, self._tseq) return result.get() result= MPTask().run() print(result) This would give the correct answer without any deadlock. My questions: 1. Why is this, where did the deadlock come from? 2. Besides, is there any material I can refer to about how to avoid deadlocks when using multiple processes in the program? Thanks! From ian.g.kelly at gmail.com Sun Sep 11 00:01:02 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 10 Sep 2011 22:01:02 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: > The statement containing the explicit next(items) call can optionally be > wrapped to explicitly handle the case of an empty iterable in whatever > manner is desired. > > try: > ? ? > except StopIteration: > ? ?raise ValueError("iterable cannot be empty") The only time that's optional is when you're writing an iterator and the try-except would end up looking like this: try: # do stuff with next(items) except StopIteration: raise StopIteration And even then, it's probably a good idea to clearly document that you're allowing a StopIteration from one iterator to propagate up as a StopIteration for another. Apart from that case, whenever you call next() you should always be prepared to catch a StopIteration. Letting a StopIteration propagate up the stack to parts unknown is bad juju because it's a flow control exception, not an error-signaling exception. If it happens to propagate up to another for loop, then it will break out of the for loop, and the exception will simply be swallowed. Cheers, Ian From 1248283536 at qq.com Sun Sep 11 00:46:43 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Sun, 11 Sep 2011 12:46:43 +0800 Subject: convert time Message-ID: how can i convert "Dec 11" into 2011-12? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Sep 11 00:51:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 14:51:18 +1000 Subject: import packet.module without importing packet.__init__ ? References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> Gelonida N wrote: > There's still something, that I am philosophycally missing. > > Wy do I have to import the entire tree if I'm just interested in a leave. You don't. Python just imports the branches leading to the leaf, not the entire tree. [...] > But if I know that I just want to boil some eggs I would really > appreciate if I could just say > >> from kitchen.pot import boil >> boil(eggs) > without having the side effect of getting pans and knives also loaded > into memory. In your example, you stated that kitchen explicitly imports kitchen.pans and kitchen.knives. So in that case, take it up with the designer of the kitchen package -- it was his decision to import them, just like he imported re and math and httplib. (For example.) If kitchen is your package, then it is your choice: if you want to have control over when sub-packages get imported, then don't automatically import them in __init__.py. If you want them to be automatically imported, like os and os.path, then automatically import them. If you don't, don't. But note that you cannot expect to import kitchen.pot without importing kitchen first. > One package in question is a huge django application. > > Within the package is one module defining some constants and tiny > functions, which I would like to reuse from some command line tools, > which should start quickly without loading any of the django specific > modules. (the startup penalty and the memory overhead would be noticable) > > I am using rpc4django, which expects, that __init__.py of the django > application exports some all rpc functions > which will basically import 95% of the django application and the entire > django frame work (none of which were required by my command tool, > support utility for this application) > > > I could of course create a separate package just for this tiny sub > module, but somehow it doesn't feel right to me. Why should it be a package? Just make it a stand-alone module. Or use path manipulation from your command line tool to import it on its own. It might be somewhat of a hack, but if need to do it, do so. Or do something like this: my_app/ +-- __init__.py # lightweight, nearly empty +-- cmd_tools.py +-- module1.py +-- module2.py +-- rpc/ +-- __init__.py # huge, imports my_app.module1, my_app.module2, etc. then point rpc4django at my_app.rpc instead of my_app. -- Steven From steve+comp.lang.python at pearwood.info Sun Sep 11 01:00:55 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 15:00:55 +1000 Subject: convert time References: Message-ID: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> ???? wrote: > how can i convert "Dec 11" into 2011-12? if my_str == "Dec 11": return 1999 # 2011 - 12 Does that help? But seriously... 2011-12 is not a proper date, so the simplest way is probably something like this: def convert(date_str): month, short_year = date_str.split() if len(short_year) == 4: year = short_year else: year = '20' + short_year months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() month = months.index(month) + 1 return year + '-' + str(month) Otherwise see the time and datetime modules: http://docs.python.org/library/time.html http://docs.python.org/library/datetime.html -- Steven From clp2 at rebertia.com Sun Sep 11 01:02:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 10 Sep 2011 22:02:37 -0700 Subject: convert time In-Reply-To: References: Message-ID: 2011/9/10 ???? <1248283536 at qq.com>: > how can i convert "Dec 11" into? 2011-12? Read the fine manuals for the `time` or `datetime` modules. http://docs.python.org/library/datetime.html >>> from datetime import datetime >>> datetime.strptime("Dec 11", "%b %y") datetime.datetime(2011, 12, 1, 0, 0) >>> datetime.strptime("Dec 11", "%b %y").strftime("%Y-%m") '2011-12' Note that this code depends on an appropriate locale setting for parsing the month name abbreviations. Cheers, Chris -- http://rebertia.com From steve+comp.lang.python at pearwood.info Sun Sep 11 01:08:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 11 Sep 2011 15:08:00 +1000 Subject: killing a script References: <4e6abc95$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6c4231$0$29996$c3e8da3$5496439d@news.astraweb.com> Cameron Simpson wrote: > On 10Sep2011 11:25, Steven D'Aprano > wrote: > | Cameron Simpson wrote: > | > My copy of the 2.7 docs says: > | > This is implemented by calling the Standard C function system(), and > | > has the same limitations. > | > and sure enough, "man 3 system" says: > | > | I don't consider having to look up documentation for a function in a > | completely different language (in this case, C) as "documented behaviour > | of os.system". > > You're kidding, surely? No, I meant exactly what I said, but I suspect that you misunderstood what I said. I blame myself for not making myself more clear, sorry. > A wrapper function for a system supplied function > should recite everything about the wrapped function's behaviour (including > the system dependent stuff) in the wrapper doco? Heavens no, I certainly don't mean that. That would be silly. What I mean is that in the context of discussing Python library functions, "documented behaviour" refers to what the Python docs state, namely the function docstring and the docs at http://docs.python.org/ (or the 3.x version). Third-party documentation doesn't count: not blogs, not "some guy sent me an email", and not documentation for other tools either. So if you describe a feature of os.system as "documented", I'm going to understand that as *Python* documentation. Hence my question about where it is documented. If we're discussing external documentation, we should say so up front: not all Python users are using CPython, and not all Python coders know C and have access to the Linux man pages. -- Steven From ben+python at benfinney.id.au Sun Sep 11 01:20:07 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 11 Sep 2011 15:20:07 +1000 Subject: optionparse: how to add a line break to the help text References: <4E6C182D.60905@tim.thechases.com> Message-ID: <87aaabmz94.fsf@benfinney.id.au> Gelonida N writes: > Considering, that you posted the snippet in 2007 and this is very > probably a reocurring problem for any slighty more complicated help > text it is really a pity, that it did not become of part of the > standard optparse library :-( The ?optparse? library is, as the online documentation shows , deprecated for new code: The optparse module is deprecated and will not be developed further; development will continue with the argparse module. The standard library ?argparse? module has a feature you might prefer . -- \ ?An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.? ?Niels Bohr | _o__) | Ben Finney From ben+python at benfinney.id.au Sun Sep 11 01:30:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 11 Sep 2011 15:30:18 +1000 Subject: convert time References: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8762kzmys5.fsf@benfinney.id.au> Steven D'Aprano writes: > But seriously... 2011-12 is not a proper date It's valid by ISO 8601. The standard allows any number of parts to be dropped, from least to most significant, in order to have a value with deliberately reduced precision. > Otherwise see the time and datetime modules: >>> import datetime >>> text = "2011-12" >>> datetime.datetime.strptime(text, "%Y-%m") datetime.datetime(2011, 12, 1, 0, 0) -- \ ?It's not what you pay a man, but what he costs you that | `\ counts.? ?Will Rogers | _o__) | Ben Finney From dreyemi at gmail.com Sun Sep 11 04:18:29 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 11 Sep 2011 09:18:29 +0100 Subject: Invoke a superclass method from a subclass constructor Message-ID: Hello friends, An instance of my subclass doesn't invoke its superclass method, except when it is referenced directly. Here is what I mean: >>> class A(object): ... def log(self, module): ... return str('logged') ... >>> class B(A): ... def __init__(self, module): ... self.module = A().log(module) ... >>> c = B('system') >>> # I expect 'logged' to be printed here >>> print c.log('system') # why do I have to do this? >>> 'logged' Why do I have to make a call to c.log before log() method can be invoked? My reasoning is such that since I have passed the log() method to B's constructor, an instance of B should invoke A's log() method. What could I be missing in class A or B to have this working as expected? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Sun Sep 11 06:41:08 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 11 Sep 2011 12:41:08 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: Message-ID: <4E6C9044.5060302@jollybox.de> On 11/09/11 10:18, Kayode Odeyemi wrote: > Hello friends, > > An instance of my subclass doesn't invoke its superclass method, except > when it is referenced > directly. > > Here is what I mean: > >>>> class A(object): > ... def log(self, module): > ... return str('logged') > ... > >>>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... >>>> c = B('system') >>>> # I expect 'logged' to be printed here >>>> print c.log('system') # why do I have to do this? >>>> 'logged' > > Why do I have to make a call to c.log before log() method can be invoked? > > My reasoning is such that since I have passed the log() method to B's > constructor, an instance > of B should invoke A's log() method. > > What could I be missing in class A or B to have this working as expected? It is working: >>> class A(object): ... def log (self, module): ... return str ('logged') ... >>> class B(A): ... def __init__(self, module): ... self.module = A().log(module) ... >>> c = B('system') >>> c.module 'logged' In B's constructor, you create a new instance of A (a pointless excersise - you already have an instance of A, "self"), call its log() method, and store the return value of that method in the attribute "module". This is how you'd usually call a superclass's method: >>> class B2(A): ... def __init__(self, module): ... # This is the way to call a superclass method: ... self.log (module) ... >>> c2 = B2 ('system') >>> That's what inheritance is. If B is derived from A, any B *is* also an A. Now, something that might be closer to what you're actually heading for, to think about. Please note that I'm using Python 3: explicitly deriving a class from object is no longer necessary, and the "super" function is now simpler. If you want to use Python 2, I'll leave looking up how to use its "super" function as an excersise to the reader. >>> class ModuleLogger: ... def __init__(self, module): ... self.module = module ... print ('module logged: {0}'.format (module)) ... >>> class Foo (ModuleLogger): ... def __init__(self, module): ... # calling a superclass constructor here, in Python 3 syntax: ... super().__init__(module) ... >>> f = Foo ('system') module logged: system >>> Using super() is always necessary when calling a superclass' method that is also implemented in the subclass - self.__init__ would just invoke the Foo constructor, you need super() to get to the ModuleLogger constructor. - Thomas From python.list at tim.thechases.com Sun Sep 11 07:05:56 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 11 Sep 2011 06:05:56 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: References: <4E6C182D.60905@tim.thechases.com> Message-ID: <4E6C9614.60406@tim.thechases.com> On 09/10/11 22:07, Gelonida N wrote: >> http://bytes.com/topic/python/answers/734066-how-output-newline-carriage-return-optparse > > It works (of course ;-) ) like a charm. Good to know, that I'm > not the only one who want's to structure the help text a > little nicer. > > Considering, that you posted the snippet in 2007 and this is > very probably a reocurring problem for any slighty more > complicated help text it is really a pity, that it did not > become of part of the standard optparse library :-( Even at the time, the optparse library wasn't readily patchable as the inline documentation gave some dire warning about "don't edit this directly, as this file is generated from some other source"?I never was able to dig up that source to patch against. As Ben Finney replied, optparse is now deprecated, replaced in part by argparse. Unfortunately, argparse wasn't backported to the standard library for earlier 2.x series (I think it became available in 2.7, and may run in earlier versions if manually added like I had to do on my Debian Py2.6 install). But that makes it hard for those of us who want to use a built-in option-parsing library across a wide variety of Python versions. I don't strongly care which I use except that I want it to be broadly available with minimal fuss. -tkc From dreyemi at gmail.com Sun Sep 11 07:17:27 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 11 Sep 2011 12:17:27 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <4E6C9044.5060302@jollybox.de> References: <4E6C9044.5060302@jollybox.de> Message-ID: On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans wrote: > On 11/09/11 10:18, Kayode Odeyemi wrote: > > Hello friends, > > > > An instance of my subclass doesn't invoke its superclass method, except > > when it is referenced > > directly. > > > > Here is what I mean: > > > >>>> class A(object): > > ... def log(self, module): > > ... return str('logged') > > ... > > > >>>> class B(A): > > ... def __init__(self, module): > > ... self.module = A().log(module) > > ... > >>>> c = B('system') > >>>> # I expect 'logged' to be printed here > >>>> print c.log('system') # why do I have to do this? > >>>> 'logged' > > > > Why do I have to make a call to c.log before log() method can be invoked? > > > > My reasoning is such that since I have passed the log() method to B's > > constructor, an instance > > of B should invoke A's log() method. > > > > What could I be missing in class A or B to have this working as expected? > > It is working: > > >>> class A(object): > ... def log (self, module): > ... return str ('logged') > ... > >>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... > >>> c = B('system') > >>> c.module > 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating an instance of B. Could this be a limitation in Py2+? > In B's constructor, you create a new instance of A (a pointless > excersise - you already have an instance of A, "self"), call its log() > method, and store the return value of that method in the attribute > "module". > > This is how you'd usually call a superclass's method: > > >>> class B2(A): > ... def __init__(self, module): > ... # This is the way to call a superclass method: > ... self.log (module) > ... > >>> c2 = B2 ('system') > >>> > > That's what inheritance is. If B is derived from A, any B *is* also an A. > > Now, something that might be closer to what you're actually heading for, > to think about. Please note that I'm using Python 3: explicitly deriving > a class from object is no longer necessary, and the "super" function is > now simpler. If you want to use Python 2, I'll leave looking up how to > use its "super" function as an excersise to the reader. > > >>> class ModuleLogger: > ... def __init__(self, module): > ... self.module = module > ... print ('module logged: {0}'.format (module)) > ... > >>> class Foo (ModuleLogger): > ... def __init__(self, module): > ... # calling a superclass constructor here, in Python 3 syntax: > ... super().__init__(module) > ... > >>> f = Foo ('system') > module logged: system > >>> > > I'm on Py2.7. class ModuleLogger is not the same as class A (the one I'm using as an example). I need the log() method to be an instance of class A. I don't want it declared in class A constructor because I don't want to have access to it when class A is instantiated. Using super() is always necessary when calling a superclass' method that > is also implemented in the subclass - self.__init__ would just invoke > the Foo constructor, you need super() to get to the ModuleLogger > constructor. > Well, I did try using super(), but I got this: >>> class B(A): ... def __init__(self, module): ... super(A, self).log('system') ... >>> c = B('module') Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ AttributeError: 'super' object has no attribute 'log' I hope a reader on Py2+ can help with this. > > - Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Sun Sep 11 07:32:18 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sun, 11 Sep 2011 17:02:18 +0530 Subject: Deadlock problem using multiprocessing In-Reply-To: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> References: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> Message-ID: 2011/9/11 ???? : > This is my first touch on the multiprocessing module, and I admit not > having a deep understanding of parallel programming, forgive me if > there's any obvious error. This is my test code: > > # deadlock.py > > import multiprocessing > > class MPTask: > ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ?self._tseq= range(10) ? # task sequence > ? ? ? ? ? ? ? ?self._pool= multiprocessing.Pool(2) ? ? # process pool > ? ? ? ?def _exe(self, num): > ? ? ? ? ? ? ? ?return num**2 > ? ? ? ?def run(self): > ? ? ? ? ? ? ? ?result= self._pool.map_async(self._exe, self._tseq) > ? ? ? ? ? ? ? ?return result.get() > > result= MPTask().run() > print(result) > > And seemingly it creates a deadlock, I have to manually kill the > processes in the system monitor, yet it would be OK if the _exe() > function was defined outside the MPTask class: > > # no_deadlock.py > import multiprocessing > > def _exe(num): > ? ? ? ?return num**2 > > class MPTask: > ? ? ? ?def __init__(self): > ? ? ? ? ? ? ? ?self._tseq= range(10) ? # task sequence > ? ? ? ? ? ? ? ?self._pool= multiprocessing.Pool(2) ? ? # process pool > ? ? ? ?def run(self): > ? ? ? ? ? ? ? ?result= self._pool.map_async(_exe, self._tseq) > ? ? ? ? ? ? ? ?return result.get() > > result= MPTask().run() > print(result) > > This would give the correct answer without any deadlock. My questions: > > 1. Why is this, where did the deadlock come from? > > 2. Besides, is there any material I can refer to about how to avoid > deadlocks when using multiple processes in the program? > I get this exception when I run the first program: Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner self.run() File "/usr/lib/python3.1/threading.py", line 469, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in _handle_tasks put(task) File "/usr/lib/python3.1/pickle.py", line 1349, in dumps Pickler(f, protocol, fix_imports=fix_imports).dump(obj) _pickle.PicklingError: Can't pickle : attribute lookup builtins.method failed There is no deadlock. You are hitting this problem: http://stackoverflow.com/questions/1816958/cant-pickle-type-instancemethod-when-using-pythons-multiprocessing-pool-map -- regards, kushal From t at jollybox.de Sun Sep 11 07:32:52 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 11 Sep 2011 13:32:52 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: <4E6C9C64.3030704@jollybox.de> On 11/09/11 13:17, Kayode Odeyemi wrote: > On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans > wrote: > > It is working: > > >>> class A(object): > ... def log (self, module): > ... return str ('logged') > ... > >>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... > >>> c = B('system') > >>> c.module > 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating > an instance of B. > Could this be a limitation in Py2+? > I believe I already answered that question. You quoted my answer directly below your question: > > In B's constructor, you create a new instance of A (a pointless > excersise - you already have an instance of A, "self"), call its log() > method, and store the return value of that method in the attribute > "module". > > This is how you'd usually call a superclass's method: > > >>> class B2(A): > ... def __init__(self, module): > ... # This is the way to call a superclass method: > ... self.log (module) > ... > >>> c2 = B2 ('system') > >>> > > That's what inheritance is. If B is derived from A, any B *is* also > an A. > > Now, something that might be closer to what you're actually heading for, > to think about. Please note that I'm using Python 3: explicitly deriving > a class from object is no longer necessary, and the "super" function is > now simpler. If you want to use Python 2, I'll leave looking up how to > use its "super" function as an excersise to the reader. > > >>> class ModuleLogger: > ... def __init__(self, module): > ... self.module = module > ... print ('module logged: {0}'.format (module)) > ... > >>> class Foo (ModuleLogger): > ... def __init__(self, module): > ... # calling a superclass constructor here, in Python 3 syntax: > ... super().__init__(module) > ... > >>> f = Foo ('system') > module logged: system > >>> > > I'm on Py2.7. > > class ModuleLogger is not the same as class A (the one I'm using as an > example). I need the log() > method to be an instance of class A. I don't want it declared in class A > constructor because I don't > want to have access to it when class A is instantiated. Then do it differently. I was merely offering an example that I hoped might help you acheive your goals. > > Using super() is always necessary when calling a superclass' method that > is also implemented in the subclass - self.__init__ would just invoke > the Foo constructor, you need super() to get to the ModuleLogger > constructor. > > > Well, I did try using super(), but I got this: >>>> class B(A): > ... def __init__(self, module): > ... super(A, self).log('system') > ... >>>> c = B('module') > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in __init__ > AttributeError: 'super' object has no attribute 'log' > > I hope a reader on Py2+ can help with this. If you'd read my previous response carefully, you'd know that in this case, you don't need super(), and you'd also know how to use the superclass' method. From laddosingh at gmail.com Sun Sep 11 07:46:38 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 04:46:38 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 19:59, Terry Reedy wrote: > On 9/10/2011 7:20 AM, Tigerstyle wrote: > > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > We appreciate you saying so instead of hiding that this is homework. > > > > > > > > > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > def book_title(title): > > ? ? ?""" Takes a string and returns a title-case string. > > ? ? ?All words EXCEPT for small words are made title case > > ? ? ?unless the string starts with a preposition, in which > > ? ? ?case the word is correctly capitalized. > > ? ? ?>>> ?book_title('DIVE Into python') > > ? ? ?'Dive into Python' > > ? ? ?>>> ?book_title('the great gatsby') > > ? ? ?'The Great Gatsby' > > ? ? ?>>> ?book_title('the WORKS OF AleXANDer dumas') > > ? ? ?'The Works of Alexander Dumas' > > ? ? ?""" > > ? ? ?new_title = [] > > ? ? ?title_split = title.strip().lower().split() > > ? ? ?for word in title_split: > > ? ? ? ? ?if title_split[0] in small_words: > > ? ? ? ? ? ? ?new_title.append(word.title()) > > ? ? ? ? ?elif word in small_words: > > ? ? ? ? ? ? ?new_title.append(word.lower()) > > ? ? ? ? ?else: > > ? ? ? ? ? ? ?new_title.append(word.title()) > > The key issue is that you want to treat the first word one way (.title > it) and the rest differently (conditionally .title or not) . So > immediately separate the first from the rest and then process each. > There are at least three ways to do the split. Perhaps I should stop > with this hint, and certainly you should think a bit before reading > further, but here is what I consider to be the most elegant 3.2 code. > . > , > , > , > . > . > . > ? ? ?first, *rest = title.strip().lower().split() > ? ? ?new_title = [first.title()] > ? ? ?for word in rest: > ? ? ? ? ?if word not in small_words: > ? ? ? ? ? ? ?word = word.title() > ? ? ? ? ?new_title.append(word) > > > ? ? ?return(' '.join(new_title)) > > doctest.testmod() now passes (there is no 'refactory' here) > > > def _test(): > > ? ? ?import doctest, refactory > > ? ? ?return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? ?_test() > > -- > Terry Jan Reedy Thank you Terry, I went for this solution as it was the easiest for me to understand and comment myself keeping in mind what level I am at right now. Thanks a ton to everyone for sharing so much information and making it easy to read and understand your thoughts. This was surely very very educating read the replies from so many talented people. Thanks and looking forward to hanging around here more :) T From davea at ieee.org Sun Sep 11 07:55:31 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 11 Sep 2011 07:55:31 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: Message-ID: <4E6CA1B3.2060503@ieee.org> On 01/-10/-28163 02:59 PM, Kayode Odeyemi wrote: > Hello friends, > > An instance of my subclass doesn't invoke its superclass method, except when > it is referenced > directly. > > Here is what I mean: > >>>> class A(object): > ... def log(self, module): > ... return str('logged') > ... > >>>> class B(A): > ... def __init__(self, module): > ... self.module = A().log(module) > ... >>>> c = B('system') >>>> # I expect 'logged' to be printed here >>>> print c.log('system') # why do I have to do this? >>>> 'logged' > Why do I have to make a call to c.log before log() method can be invoked? > > My reasoning is such that since I have passed the log() method to B's > constructor, an instance > of B should invoke A's log() method. > > What could I be missing in class A or B to have this working as expected? What makes you think that A.log() was not invoked??? You have no print statement, so you can't tell that way. All the method does is to modify a temporary object of type A, so you can't tell that way. Perhaps you mean to write self.module = A.log(self, module) So that the return value could do some good. DaveA From python.list at tim.thechases.com Sun Sep 11 08:41:58 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 11 Sep 2011 07:41:58 -0500 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: <4E6CAC96.9000304@tim.thechases.com> On 09/10/11 14:36, Terry Reedy wrote: > 1. Process first item of an iterable separately. > > A traditional solution is a flag variable that is tested for each item. > > first = True > > for item in iterable: > if first: > > first = False > else: > > > (I have seen code like this posted on this list several times, including > today.) > > Better, to me, is to remove the first item *before* the loop. > > items = iter(iterable) > for item in items: > I like to use this one for processing CSV files where I need to clean up the headers: r = csv.reader(f) headers = r.next() header_map = dict( (header.strip().upper(), i) for i, header in enumerate(headers) ) for row in r: item = lambda s: row[header_map[s]].strip() thing = item("THING") whatever = item("WHATEVER") It's mostly like a DictReader, but it isn't as sensitive to the spaces/capitalization that clients love to mess with. -tkc From __peter__ at web.de Sun Sep 11 08:48:41 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 14:48:41 +0200 Subject: recursive algorithm for balls in numbered boxes References: <32440187.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered > boxes" > (also known as "indistinguishable balls in distinguishable boxes"). The > code has been extensively tested and appears to work, but isn't terribly > elegant. Any suggestions about how to improve it will be appreciated. Does the following do what you want? >>> from itertools import product >>> def binb(balls, boxsizes): ... return (fill for fill in product(*[range(bs+1) for bs in boxsizes]) if sum(fill) == balls) ... >>> for item in binb(10, [4, 3, 2, 1, 2]): ... print item ... (2, 3, 2, 1, 2) (3, 2, 2, 1, 2) (3, 3, 1, 1, 2) (3, 3, 2, 0, 2) (3, 3, 2, 1, 1) (4, 1, 2, 1, 2) (4, 2, 1, 1, 2) (4, 2, 2, 0, 2) (4, 2, 2, 1, 1) (4, 3, 0, 1, 2) (4, 3, 1, 0, 2) (4, 3, 1, 1, 1) (4, 3, 2, 0, 1) (4, 3, 2, 1, 0) If so, your implementation misses a few configurations: >>> from balls_in_numbered_boxes import balls_in_numbered_boxes as bb >>> for item in bb(10, [4, 3, 2, 1, 2]): ... print item ... [4 3 2 1 0] [3 3 2 1 1] [2 3 2 1 2] > Also, I'd like to get this functionality into the Python's `itertools` > module (the present set of combinatorics functions in `itertools` does not > include "balls in boxes"). Does anyone know whom I should contact about > this? Basically you have to convince Raymond Hettinger. I recommend that you post your suggestion on python-ideas for a general discussion rather than approaching him directly. From __peter__ at web.de Sun Sep 11 09:41:23 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 15:41:23 +0200 Subject: Idioms combining 'next(items)' and 'for item in items:' References: Message-ID: Terry Reedy wrote: > 3. Process the items of an iterable in pairs. > > items = iter(iterable) > for first in items: > second = next(items) > > > This time, StopIteration is raised for an odd number of items. Catch and > process as desired. One possibility is to raise ValueError("Iterable > must have an even number of items"). Another way is zip-based iteration: (a) silently drop the odd item items = iter(iterable) for first, second in zip(items, items): # itertools.izip in 2.x ... (b) add a fill value for first, second in itertools.zip_longest(items, items): ... (c) raise an exception Unfortunately there is no zip_exc() that guarantees that all iterables are of the same "length", but I've written a recipe some time ago http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures- that-all-iterables/ that achieves near-C speed. From gelonida at gmail.com Sun Sep 11 10:17:56 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 16:17:56 +0200 Subject: import packet.module without importing packet.__init__ ? In-Reply-To: <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> References: <4e6c074c$0$29990$c3e8da3$5496439d@news.astraweb.com> <4e6c3e47$0$29999$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hi Steven, Thanks again for your answer. On 09/11/2011 06:51 AM, Steven D'Aprano wrote: > Gelonida N wrote: > > In your example, you stated that kitchen explicitly imports kitchen.pans and > kitchen.knives. So in that case, take it up with the designer of the > kitchen package -- it was his decision to import them, just like he > imported re and math and httplib. (For example.) Exactly. Thus my conclusion, that too many imports (just for commodity) in __init__.py might not be such a good idea if one wants to allow leaf-only imports. > > If kitchen is your package, then it is your choice: if you want to have > control over when sub-packages get imported, then don't automatically > import them in __init__.py. Agreed. This is however my problem: Up to my understanding rpc4django insists on putting code into __init__.py > > >> One package in question is a huge django application. >> >> Within the package is one module defining some constants and tiny >> functions, which I would like to reuse from some command line tools, >> which should start quickly without loading any of the django specific >> modules. (the startup penalty and the memory overhead would be noticable) >> >> I am using rpc4django, which expects, that __init__.py of the django >> application exports some all rpc functions >> which will basically import 95% of the django application and the entire >> django frame work (none of which were required by my command tool, >> support utility for this application) >> >> >> I could of course create a separate package just for this tiny sub >> module, but somehow it doesn't feel right to me. > > Why should it be a package? Just make it a stand-alone module. True > Or do something like this: > > my_app/ > +-- __init__.py # lightweight, nearly empty > +-- cmd_tools.py > +-- module1.py > +-- module2.py > +-- rpc/ > +-- __init__.py # huge, imports my_app.module1, my_app.module2, etc. > > then point rpc4django at my_app.rpc instead of my_app. > Up to my knowledge rpc4django just imports all __inits__ of all django applications to find look for functions with a certain decorator. I'm not sure, whether django allows nested appllications, but this might be a solution. From gelonida at gmail.com Sun Sep 11 10:30:07 2011 From: gelonida at gmail.com (Gelonida N) Date: Sun, 11 Sep 2011 16:30:07 +0200 Subject: optionparse: how to add a line break to the help text In-Reply-To: <87aaabmz94.fsf@benfinney.id.au> References: <4E6C182D.60905@tim.thechases.com> <87aaabmz94.fsf@benfinney.id.au> Message-ID: Thanks Ben, On 09/11/2011 07:20 AM, Ben Finney wrote: > Gelonida N writes: > >> Considering, that you posted the snippet in 2007 and this is very >> probably a reocurring problem for any slighty more complicated help >> text it is really a pity, that it did not become of part of the >> standard optparse library :-( > > The ?optparse? library is, as the online documentation shows > , deprecated for new > code: > > The optparse module is deprecated and will not be developed further; > development will continue with the argparse module. This explains the reluctance to fix optparse. In 2007 however python 2.7 wasn't really that common though > > The standard library ?argparse? module has a feature you might prefer > . Most of my code has to run on python 2.5 / 2.6. I just checked, that argparse can be installed (pip install argparse) (didn't check functionality though) for python 2.5 / 2.6 So depending on the situation I had to decide whether I oblige users of my scripts to install argparse or whether I stick with optparse and just add Tim's custom formatter. Probably I'll go for optparse and Tim's custom formatter for tiny scripts with no dependencies except standard libraries and for argparse for new bigger projects with external module dependencies. From mdickinson at enthought.com Sun Sep 11 11:08:17 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Sun, 11 Sep 2011 08:08:17 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes References: Message-ID: On Sep 11, 1:43?am, "Dr. Phillip M. Feldman" wrote: > I've written a recursive class that creates an iterator to solve a general > formulation of the combinatorics problem known as "balls in numbered boxes" > (also known as "indistinguishable balls in distinguishable boxes"). ?The > code has been extensively tested and appears to work, but isn't terribly > elegant. ?Any suggestions about how to improve it will be appreciated. > > Also, I'd like to get this functionality into the Python's `itertools` > module (the present set of combinatorics functions in `itertools` does not > include "balls in boxes"). ?Does anyone know whom I should contact about > this? Note that for the version without size limits on individual boxes, the itertools.combination function already provides most of what's needed. For example: import itertools def balls_in_boxes(nballs, nboxes): n, k = nballs + nboxes - 1, nboxes - 1 for comb in itertools.combinations(range(n), k): yield [y - x - 1 for y, x in zip(comb + (n,), (-1,) + comb)] print "5 balls in 3 boxes" for combination in balls_in_boxes(5, 3): print combination assert len(combination) == 3 assert sum(combination) == 5 This is a well-known trick: to divide 5 (unlabeled) balls amongst 3 (labeled) boxes, you write down sequences of 5 o's and 2 x's, where the o's represent the 5 balls and the 'x's represent dividers: ooxooxo -> [2, 2, 1] xoooxoo -> [0, 3, 2] And 'combinations(7, 2)' yields successively all the possible different placements for the 2 dividers in the 7 symbols. This question seems to come up often enough (without the box size limit twist) that maybe it would be useful to include something like this recipe in the itertool documentation. For getting this into itertools, I'd suggest opening a feature request on bugs.python.org and assigning it to Raymond Hettinger. -- Mark From bluegene8210 at gmail.com Sun Sep 11 11:46:40 2011 From: bluegene8210 at gmail.com (Jacky Liu) Date: Sun, 11 Sep 2011 08:46:40 -0700 (PDT) Subject: Deadlock problem using multiprocessing References: <5ccb9d98-f3f8-4f86-b53c-cda4522b40fc@14g2000prv.googlegroups.com> Message-ID: > > I get this exception when I run the first program: > > Exception in thread Thread-1: > Traceback (most recent call last): > ? File "/usr/lib/python3.1/threading.py", line 516, in _bootstrap_inner > ? ? self.run() > ? File "/usr/lib/python3.1/threading.py", line 469, in run > ? ? self._target(*self._args, **self._kwargs) > ? File "/usr/lib/python3.1/multiprocessing/pool.py", line 231, in _handle_tasks > ? ? put(task) > ? File "/usr/lib/python3.1/pickle.py", line 1349, in dumps > ? ? Pickler(f, protocol, fix_imports=fix_imports).dump(obj) > _pickle.PicklingError: Can't pickle : attribute lookup > builtins.method failed > > There is no deadlock. ?You are hitting this problem:http://stackoverflow.com/questions/1816958/cant-pickle-type-instancem... > > -- > regards, > kushal You're right. I just realized that I was running the program through my Vim plug-in which would use the subprocess module to open the process, wait for its termination and get the output. It seems that multi-process program would act quite differently such that my Vim plug-in had been halted without getting any error information, so I was to falsely take it as a deadlock. The thread in stackoverflow you referenced is great, now I'm trying to fit the solution in my own program, thanks a lot! From laddosingh at gmail.com Sun Sep 11 12:36:25 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:36:25 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 13:43, Mel wrote: > Tigerstyle wrote: > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > This is the code: > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > def book_title(title): > > ? ? """ Takes a string and returns a title-case string. > > ? ? All words EXCEPT for small words are made title case > > ? ? unless the string starts with a preposition, in which > > ? ? case the word is correctly capitalized. > > ? ? >>> book_title('DIVE Into python') > > ? ? 'Dive into Python' > > ? ? >>> book_title('the great gatsby') > > ? ? 'The Great Gatsby' > > ? ? >>> book_title('the WORKS OF AleXANDer dumas') > > ? ? 'The Works of Alexander Dumas' > > ? ? """ > > ? ? new_title = [] > > ? ? title_split = title.strip().lower().split() > > ? ? for word in title_split: > > ? ? ? ? if title_split[0] in small_words: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? ? ? elif word in small_words: > > ? ? ? ? ? ? new_title.append(word.lower()) > > ? ? ? ? else: > > ? ? ? ? ? ? new_title.append(word.title()) > > ? ? return(' '.join(new_title)) > > > def _test(): > > ? ? import doctest, refactory > > ? ? return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? _test() > > > All tests are failing even though I am getting the correct output on > > the first two tests. And the last test still gives me "Of" instead of > > "of" > > > Any help is appreciated. > > I don't know about doctest -- I suspect it wants a structured docstring to > specify the tests -- but this > > ? ? ? ? if title_split[0] in small_words: > ? ? ? ? ? ? new_title.append(word.title()) > > can't be what you want. > > ? ? ? ? Mel. Agreed. Not what I need. From laddosingh at gmail.com Sun Sep 11 12:39:12 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:39:12 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 13:50, Thomas Jollans wrote: > On 10/09/11 13:20, Tigerstyle wrote: > > > Hi guys. > > > I'm strugglin with some homework stuff and am hoping you can help me > > out here. > > > All tests are failing even though I am getting the correct output on > > the first two tests. And the last test still gives me "Of" instead of > > "of" > > Cannot reproduce. I only get the one, expected, failure. > > % python -m doctest books.py > ********************************************************************** > File "books.py", line 12, in books.book_title > Failed example: > ? ? book_title('the WORKS OF AleXANDer dumas') > Expected: > ? ? 'The Works of Alexander Dumas' > Got: > ? ? 'The Works Of Alexander Dumas' > ********************************************************************** > 1 items had failures: > ? ?1 of ? 3 in books.book_title > ***Test Failed*** 1 failures. > > > > > def _test(): > > ? ? import doctest, refactory > > ? ? return doctest.testmod(refactory) > > if __name__ == "__main__": > > ? ? _test() > > What is this "refactory"? Are you testing the right code? What is the > output of your test - does it make sense for the module? > > Thomas Still struggling with my test failing. All 3 tests fail. I'm using Ecplipse and I think Eclipse is what causing this. From laddosingh at gmail.com Sun Sep 11 12:40:26 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:40:26 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 10 Sep, 17:56, Chris Angelico wrote: > On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware > > wrote: > > Ignoring the docttests my process would be to process each word & then > > manually capitalize he 1st word, .I would als0 use a comprehension as > > makes for cleaner code:- > > > def capitalize(word): > > ? ?if word in small_words: > > ? ? ? ?return word > > ? ?else: > > ? ? ? ?return word.title() > > And I'd do this with a lambda, but that's just me. Of course, if your > logic is more complicated, it makes more sense to keep it in a named > function, but a single conditional call can fit nicely into a lambda. > > ChrisA Lambda is too complicated for me to understand yet. Will get there after a little while. Where would you put this piece of code? From laddosingh at gmail.com Sun Sep 11 12:42:28 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:42:28 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <8fc2dea1-a5ef-4d7f-a0f2-e0be56e21e22@h7g2000yqm.googlegroups.com> On 11 Sep, 04:12, t... at thsu.org wrote: > On Sep 10, 7:47?am, Peter Otten <__pete... at web.de> wrote: > > > > > > > > > > > Tigerstyle wrote: > > > I'm strugglin with some homework stuff and am hoping you can help me > > > out here. > > > > This is the code: > > > > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > > > ? ? new_title = [] > > > ? ? title_split = title.strip().lower().split() > > > ? ? for word in title_split: > > > ? ? ? ? if title_split[0] in small_words: > > > ? ? ? ? ? ? new_title.append(word.title()) > > > ? ? ? ? elif word in small_words: > > > ? ? ? ? ? ? new_title.append(word.lower()) > > > ? ? ? ? else: > > > ? ? ? ? ? ? new_title.append(word.title()) > > > The logic of the for-loop is flawed; the expression > > > title_split[0] in small_words > > > will always evaluate to True if the first word is a "small word", even when > > the loop is already past the first word. You can work around that with a > > flag along these lines > > > first = True > > for word in title_split: > > ? ? if first: > > ? ? ? ? # special treatment for the first word > > ? ? ? ? first = False > > ? ? else: > > ? ? ? ? # put checks for all words but the first here > > ? ? new_title.append(fixed_word) # assuming you have stored the titlecased > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# or lowercased word in the fixed_word > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# variable > > Another way to tackle this is to just capitalize the entire sentence > before returning it. > > new_title = [] > title_split = title.strip().lower().split() > for word in title_split: > ? if word in small_words: > ? ? new_title.append(word.lower()) > ? else: > ? ? new_title.append(word.title()) > return(''.join(new_title).capitalize()) > > However, I'm only helping with your homework, because I want to point > out that doctest comments should be *readable*. Don't just throw them > in, take the extra 10-15 seconds to make them easier on the eyes. In > the workplace, months will pass before you review this code again, so > you want to make it easier for an older version of yourself to > remember it. > > And it takes very little effort to make it readable. Here's your > doctest string, reformatted with just a tiny bit more whitespace. I > even cut out a sentence. > > def book_title(title): > ? """ > ? All words EXCEPT for small words are made title case > ? unless the string starts with a preposition, in which > ? case the word is correctly capitalized. > > ? >>> book_title('DIVE Into python') > ? 'Dive into Python' > ? >>> book_title('the great gatsby') > ? 'The Great Gatsby' > ? >>> book_title('the WORKS OF AleXANDer dumas') > ? 'The Works of Alexander Dumas' > ? """ > -- > // T.Hsu It capitalises the phrase, but still the rest of the phrase is in lower case. From laddosingh at gmail.com Sun Sep 11 12:43:31 2011 From: laddosingh at gmail.com (Tigerstyle) Date: Sun, 11 Sep 2011 09:43:31 -0700 (PDT) Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <208f1e6b-66ca-4988-a41a-d83924cb8593@m18g2000vbe.googlegroups.com> On 11 Sep, 08:18, Dennis Lee Bieber wrote: > On Sat, 10 Sep 2011 16:25:42 -0700, Dennis Lee Bieber > declaimed the following in > gmane.comp.python.general: > > > > > in the language documentation... It will give you a simple way to know > > if you are looking at the first word. Basically, you want to title-case > > the word IF it is the first word OR the word is NOT in the list of > > lowercase words; anything else goes through as lower case... > > ? ? ? ? Of course, most of this can be done in a single line (including > taking into account that some words may have a punctuation mark which > would confuse the original). > > >>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on' ] > >>> punct = ".,;:?!;'\"(){}[]" > >>> def recase(str = "physicist odd-affection, or how i was taught to stop fretting and adore the weapon of mass destruction"): > > ... ? ? return " ".join( w.title() if i == 0 or w.strip(punct) not in > smalls else w > ... ? ? ? ? ? ? ? ? ? ? for i,w in enumerate(str.lower().strip().split()) ) > ...>>> recase() > > 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting And Adore > the Weapon of Mass Destruction'>>> recase("what? me worry?") > 'What? Me Worry?' > >>> recase("the end of the matter is, to be blunt, a confusion") > > 'The End of the Matter Is, To Be Blunt, a Confusion'>>> recase("the end of the matter is in, to be blunt, a confusion") > > 'The End of the Matter Is in, To Be Blunt, a Confusion'>>> smalls = ['into', 'the', 'a', 'of', 'at', 'in', 'for', 'on', "and", "is", "to" ] > >>> recase() > > 'Physicist Odd-Affection, Or How I Was Taught To Stop Fretting and Adore > the Weapon of Mass Destruction'>>> recase("the end of the matter is in, to be blunt, a confusion") > > 'The End of the Matter is in, to Be Blunt, a Confusion' > > > > ? ? ? ? Of course, explaining what this construct is doing is the trick to > justifying it for a homework assignment. > -- > ? ? ? ? Wulfraed ? ? ? ? ? ? ? ? Dennis Lee Bieber ? ? ? ? AF6VN > ? ? ? ? wlfr... at ix.netcom.com ? ?HTTP://wlfraed.home.netcom.com/ Too much destruction in this post man, and yeah I would not be able to explain the code for my homework. From tjreedy at udel.edu Sun Sep 11 12:47:08 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 12:47:08 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 12:01 AM, Ian Kelly wrote: > On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: >> The statement containing the explicit next(items) call can optionally be >> wrapped to explicitly handle the case of an empty iterable in whatever >> manner is desired. >> >> try: >> >> except StopIteration: >> raise ValueError("iterable cannot be empty") > > The only time that's optional This is an opinion, or rather, a programming philosophy based on technical facts, rather than a fact itself. You do raise an important issue. > is when you're writing an iterator and > the try-except would end up looking like this: > > try: > # do stuff with next(items) > except StopIteration: > raise StopIteration > > And even then, it's probably a good idea to clearly document that > you're allowing a StopIteration from one iterator to propagate up as a > StopIteration for another. In the yield-pairs example, def pairs(iterable): it = iter(iterable) for i in it: yield i, next(it) ignoring StopIteration from the get-even explicit next means ignoring an odd item. If pairs() were in a general purpose library, it should have a doc string that specifies that, and a test case with an odd number of items. I would consider a comment in the code itself to be optional, depending on the intended or expected human audience and the context of presentation. In this context, the explanation is in the text that surrounds the code. > Apart from that case, whenever you call next() you should always be > prepared to catch a StopIteration. To me, it depends on the contract or specification of the function. If the behavior for an empty input iterator is not specified, then there is no basis for writing the body of an except clause. While in the past few months I have written examples of all of the three explicit-next use cases I gave, I was prompted to write them up now by Tigerstyle's 'Doctest failing' thread. The specification by example (perhaps given by an instructor) did not include an empty title that would lead to an empty list of title words. Certainly, the doc for def fix_title(title): small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') twords = iter(title.strip().lower().split()) new_title = [next(twords)] for word in twords: if word not in small_words: word = word.title() new_title.append(word) return(' '.join(new_title)) should start "Given a title with at least one word, ...". The Agile Programming Test-Driven-Development maxim, 'Write the minimum code needed to pass the test' says that the extra lines needed to catch and process StopIteration should *not* be written until there is a test case leading to such. > Letting a StopIteration propagate > up the stack to parts unknown is bad juju because it's a flow control > exception, not an error-signaling exception. If it happens to > propagate up to another for loop, then it will break out of the for > loop, and the exception will simply be swallowed. What you are saying is a) that the following code for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: print(fix_title(title)) will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the worst choice of how to handle the empty title; and c) that in real world world programming, *someone* should decide whether fix_title('') returns '' or raises ValueError. A counter-argument could be 1. that when a function's contract is violated, invoking unspecified behavior, anything is allowed; or 2. that titles are checked for actual content before the case fixup is called, and the time and mental energy required to define and test behavior for impossible input is wasted and better spent on something more useful. -- Terry Jan Reedy From andreas.perstinger at gmx.net Sun Sep 11 12:47:42 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 11 Sep 2011 18:47:42 +0200 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: On 2011-09-11 13:17, Kayode Odeyemi wrote: > On Sun, Sep 11, 2011 at 11:41 AM, Thomas Jollans wrote: >> It is working: >> >> >>> class A(object): >> ... def log (self, module): >> ... return str ('logged') >> ... >> >>> class B(A): >> ... def __init__(self, module): >> ... self.module = A().log(module) >> ... >> >>> c = B('system') >> >>> c.module >> 'logged' > > Why do you have to do c.module? I'm expecting an output just by creating an > instance of B. Why do you expect an output? In B.__init__ you are just assigning the return value from A.log() to the attribute "module" and in A.log() there is no output either. Bye, Andreas From tjreedy at udel.edu Sun Sep 11 13:03:32 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 13:03:32 -0400 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: On 9/11/2011 7:46 AM, Tigerstyle wrote: > Thank you Terry, > I went for this solution as it was the easiest for me to understand > and comment myself keeping in mind what level I am at right now. > Thanks a ton to everyone for sharing so much information and making it > easy to read and understand your thoughts. This was surely very very > educating read the replies from so many talented people. You are welcome. For more, see my thread "Idioms combining 'next(items)' and 'for item in items:'" and the responses. -- Terry Jan Reedy From tjreedy at udel.edu Sun Sep 11 14:09:18 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 14:09:18 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 9:41 AM, Peter Otten wrote: > Terry Reedy wrote: > >> 3. Process the items of an iterable in pairs. >> >> items = iter(iterable) >> for first in items: >> second = next(items) >> >> >> This time, StopIteration is raised for an odd number of items. Catch and >> process as desired. One possibility is to raise ValueError("Iterable >> must have an even number of items"). > > Another way is zip-based iteration: > > (a) silently drop the odd item > > items = iter(iterable) > for first, second in zip(items, items): # itertools.izip in 2.x > ... In practice, I would use this rather than the loop above. However, I wanted to introduce the idea then used in the intermittent pairing of surrogates. > (b) add a fill value > > for first, second in itertools.zip_longest(items, items): > ... > > (c) raise an exception > > Unfortunately there is no zip_exc() that guarantees that all iterables are > of the same "length", but I've written a recipe some time ago > > http://code.activestate.com/recipes/497006-zip_exc-a-lazy-zip-that-ensures- > that-all-iterables/ > > that achieves near-C speed. Interesting. It took a moment to see the general idea. For some reason, you timeit examples in the comment now all have "data = [range(1000)]3", missing '*'. -- Terry Jan Reedy From ethan at stoneleaf.us Sun Sep 11 14:43:38 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 11 Sep 2011 11:43:38 -0700 Subject: Doctest failing In-Reply-To: References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> Message-ID: <4E6D015A.3070500@stoneleaf.us> Chris Angelico wrote: > On Sat, Sep 10, 2011 at 10:24 PM, Alister Ware > wrote: >> Ignoring the docttests my process would be to process each word & then >> manually capitalize he 1st word, .I would als0 use a comprehension as >> makes for cleaner code:- >> >> def capitalize(word): >> if word in small_words: >> return word >> else: >> return word.title() > > And I'd do this with a lambda, but that's just me. Of course, if your > logic is more complicated, it makes more sense to keep it in a named > function, but a single conditional call can fit nicely into a lambda. Lambdas are great when needed, but if don't *need* it, and you have more than a few, debugging can be a nightmare... "Okay, so this is function ... and that is function ... and over here we also have function ... ARGH!" ~Ethan~ From timr at probo.com Sun Sep 11 14:48:01 2011 From: timr at probo.com (Tim Roberts) Date: Sun, 11 Sep 2011 11:48:01 -0700 Subject: using python in web applications References: Message-ID: "Littlefield, Tyler" wrote: > >I don't much care for PHP, but the thing that can be said for it is it's >pretty quick. How does Python compare? PHP is quick for development, in that you can slap together some schlock and have it mostly work. The result, however, is usually schlock. The performance of the language itself is almost entirely irrelevant; the execution time is swamped by the network overhead. >I'm also curious what databases are suggested? I've always >done most of my work in MYSql, but from what I understand postgresql is >becoming more popular to. Well, that's a religious argument. Personally, I've always been confused by the draw of MySql. From the very beginning, Postgres has always been more powerful, more reliable, more standard-compliant, and more professional. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ethan at stoneleaf.us Sun Sep 11 15:01:53 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 11 Sep 2011 12:01:53 -0700 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: <4E6D05A1.5010506@stoneleaf.us> Terry Reedy wrote: > On 9/11/2011 12:01 AM, Ian Kelly wrote: >> On Sat, Sep 10, 2011 at 1:36 PM, Terry Reedy wrote: >>> The statement containing the explicit next(items) call can optionally be >>> wrapped to explicitly handle the case of an empty iterable in whatever >>> manner is desired. >>> >>> try: >>> >>> except StopIteration: >>> raise ValueError("iterable cannot be empty") >> >> The only time that's optional > > This is an opinion, or rather, a programming philosophy based on > technical facts, rather than a fact itself. You do raise an important > issue. > >> is when you're writing an iterator and >> the try-except would end up looking like this: >> >> try: >> # do stuff with next(items) >> except StopIteration: >> raise StopIteration >> >> And even then, it's probably a good idea to clearly document that >> you're allowing a StopIteration from one iterator to propagate up as a >> StopIteration for another. > > In the yield-pairs example, > > def pairs(iterable): > it = iter(iterable) > for i in it: > yield i, next(it) > > ignoring StopIteration from the get-even explicit next means ignoring an > odd item. If pairs() were in a general purpose library, it should have a > doc string that specifies that, and a test case with an odd number of > items. I would consider a comment in the code itself to be optional, > depending on the intended or expected human audience and the context of > presentation. In this context, the explanation is in the text that > surrounds the code. > >> Apart from that case, whenever you call next() you should always be >> prepared to catch a StopIteration. > > To me, it depends on the contract or specification of the function. If > the behavior for an empty input iterator is not specified, then there is > no basis for writing the body of an except clause. > > While in the past few months I have written examples of all of the three > explicit-next use cases I gave, I was prompted to write them up now by > Tigerstyle's 'Doctest failing' thread. The specification by example > (perhaps given by an instructor) did not include an empty title that > would lead to an empty list of title words. Certainly, the doc for > > def fix_title(title): > small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on') > twords = iter(title.strip().lower().split()) > new_title = [next(twords)] > for word in twords: > if word not in small_words: > word = word.title() > new_title.append(word) > return(' '.join(new_title)) > > should start "Given a title with at least one word, ...". > > The Agile Programming Test-Driven-Development maxim, 'Write the minimum > code needed to pass the test' says that the extra lines needed to catch > and process StopIteration should *not* be written until there is a test > case leading to such. > >> Letting a StopIteration propagate >> up the stack to parts unknown is bad juju because it's a flow control >> exception, not an error-signaling exception. If it happens to >> propagate up to another for loop, then it will break out of the for >> loop, and the exception will simply be swallowed. > > What you are saying is a) that the following code > > for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: > print(fix_title(title)) > > will print 'Amazing', 'A Hell of a Fight', and stop; b) that this is the > worst choice of how to handle the empty title; and c) that in real world > world programming, *someone* should decide whether fix_title('') returns > '' or raises ValueError. > > A counter-argument could be 1. that when a function's contract is > violated, invoking unspecified behavior, anything is allowed; or 2. that > titles are checked for actual content before the case fixup is called, > and the time and mental energy required to define and test behavior for > impossible input is wasted and better spent on something more useful. Having spent hours tracking down errors because somebody did not address a corner case, I find counter-argument 1 unhelpful. Counter-argument 2 I can at least partially agree with; however, in this case where the uncaught exception can mess up flow control elsewhere I do not -- the StopIteration should be caught and changed to something appropriate, such as EmptyTitle (assuming blank titles are errors -- which they probably should be... "Hello, do you have the book '' for sale here?") ~Ethan~ From laurent.payot at gmail.com Sun Sep 11 15:22:26 2011 From: laurent.payot at gmail.com (Laurent) Date: Sun, 11 Sep 2011 12:22:26 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <26428844-acd2-4c7b-bc6a-cf5a8a6259bc@glegroupsg2000goo.googlegroups.com> +1 for PostgreSQL. It's faster than MySQL for years now, and is much more seriously featured. If you don't need ACID properties (transactions stuff) you should also give Document-based databases like MongoDB a try. It changed my code life. From laurent.payot at gmail.com Sun Sep 11 15:22:26 2011 From: laurent.payot at gmail.com (Laurent) Date: Sun, 11 Sep 2011 12:22:26 -0700 (PDT) Subject: using python in web applications In-Reply-To: References: Message-ID: <26428844-acd2-4c7b-bc6a-cf5a8a6259bc@glegroupsg2000goo.googlegroups.com> +1 for PostgreSQL. It's faster than MySQL for years now, and is much more seriously featured. If you don't need ACID properties (transactions stuff) you should also give Document-based databases like MongoDB a try. It changed my code life. From Phillip.M.Feldman at gmail.com Sun Sep 11 15:41:33 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sun, 11 Sep 2011 12:41:33 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32443548.post@talk.nabble.com> Hello Peter, When I run my code, I get the same 14 configurations that your code produces; the only different that I can see in the output is that the configurations are produced in a different order. Note that your code is not creating an iterator, so thus doesn't do what I want. Also, generating the product set and then testing whether the total number of balls is correct will potentially consider a huge number of cases that must be rejected because the sum is wrong; this is too inefficient. Phillip In [2]: list(balls_in_numbered_boxes(10,[4,3,2,1,2])) Out[2]: [(4, 3, 2, 1, 0), (4, 3, 2, 0, 1), (4, 3, 1, 1, 1), (4, 3, 1, 0, 2), (4, 3, 0, 1, 2), (4, 2, 2, 1, 1), (4, 2, 2, 0, 2), (4, 2, 1, 1, 2), (4, 1, 2, 1, 2), (3, 3, 2, 1, 1), (3, 3, 2, 0, 2), (3, 3, 1, 1, 2), (3, 2, 2, 1, 2), (2, 3, 2, 1, 2)] -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443548.html Sent from the Python - python-list mailing list archive at Nabble.com. From Phillip.M.Feldman at gmail.com Sun Sep 11 15:48:07 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sun, 11 Sep 2011 12:48:07 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32443579.post@talk.nabble.com> Chris, Your code is much cleaner than mine. I will have to figure out exactly how it is working. Thanks! Phillip -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32443579.html Sent from the Python - python-list mailing list archive at Nabble.com. From hidura at gmail.com Sun Sep 11 15:53:24 2011 From: hidura at gmail.com (hidura at gmail.com) Date: Sun, 11 Sep 2011 19:53:24 +0000 Subject: using python in web applications In-Reply-To: References: Message-ID: <952711646-1315770807-cardhu_decombobulator_blackberry.rim.net-827506045-@b12.c22.bise6.blackberry> I am agree with postgresql i don' t have any problem, also is better for big applications. And Python is always better language than PHP if you' re going to create a web app. Sent from my BlackBerry? wireless device -----Original Message----- From: Tim Roberts Sender: python-list-bounces+hidura=gmail.com at python.org Date: Sun, 11 Sep 2011 11:48:01 To: Subject: Re: using python in web applications "Littlefield, Tyler" wrote: > >I don't much care for PHP, but the thing that can be said for it is it's >pretty quick. How does Python compare? PHP is quick for development, in that you can slap together some schlock and have it mostly work. The result, however, is usually schlock. The performance of the language itself is almost entirely irrelevant; the execution time is swamped by the network overhead. >I'm also curious what databases are suggested? I've always >done most of my work in MYSql, but from what I understand postgresql is >becoming more popular to. Well, that's a religious argument. Personally, I've always been confused by the draw of MySql. From the very beginning, Postgres has always been more powerful, more reliable, more standard-compliant, and more professional. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Sun Sep 11 16:13:02 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 11 Sep 2011 22:13:02 +0200 Subject: recursive algorithm for balls in numbered boxes References: <32440187.post@talk.nabble.com> <32443548.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > When I run my code, I get the same 14 configurations that your code > produces; I'm sorry, I ran the buggy code from http://old.nabble.com/file/p32439307/balls_in_numbered_boxes.py without realizing it was not http://old.nabble.com/file/p32440187/balls_in_numbered_boxes.py > the only different that I can see in the output is that the > configurations are produced in a different order. Note that your code is > not creating an iterator, so thus doesn't do what I want. The outer loop is in a generator expression and thus evaluates lazily. > Also, > generating the product set and then testing whether the total number of > balls is correct will potentially consider a huge number of cases that > must be rejected because the sum is wrong; this is too inefficient. Indeed; I should have added a disclaimer to make that clear. From robert.kern at gmail.com Sun Sep 11 16:22:28 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 11 Sep 2011 15:22:28 -0500 Subject: optionparse: how to add a line break to the help text In-Reply-To: <4E6C9614.60406@tim.thechases.com> References: <4E6C182D.60905@tim.thechases.com> <4E6C9614.60406@tim.thechases.com> Message-ID: On 9/11/11 6:05 AM, Tim Chase wrote: > As Ben Finney replied, optparse is now deprecated, replaced in part by argparse. > Unfortunately, argparse wasn't backported to the standard library for earlier > 2.x series (I think it became available in 2.7, and may run in earlier versions > if manually added like I had to do on my Debian Py2.6 install). But that makes > it hard for those of us who want to use a built-in option-parsing library across > a wide variety of Python versions. I don't strongly care which I use except that > I want it to be broadly available with minimal fuss. argparse.py can be simply dropped into your codebase, if you want. That's about as minimal of fuss as you can ask for. http://pypi.python.org/pypi/argparse -- 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 rosuav at gmail.com Sun Sep 11 18:41:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 08:41:05 +1000 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy wrote: > What you are saying is a) that the following code > > for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: > ? ?print(fix_title(title)) > At least in Python 3.2, this isn't the case. StopIteration breaks the loop only if it's raised during the assignment, not during the body. >>> x=iter([1,2,3,4,5]) >>> for i in x: print("%d - %d"%(i,next(x))) 1 - 2 3 - 4 Traceback (most recent call last): File "", line 2, in print("%d - %d"%(i,next(x))) StopIteration Compare with: >>> def pair(it): while True: yield next(it),next(it) >>> x=iter([1,2,3,4,5]) >>> for i,j in pair(x): print("%d - %d"%(i,j)) 1 - 2 3 - 4 In this case, the StopIteration bubbles up and quietly terminates the loop. ChrisA From tjreedy at udel.edu Sun Sep 11 20:45:41 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 Sep 2011 20:45:41 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/11/2011 6:41 PM, Chris Angelico wrote: > On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy wrote: >> What you are saying is a) that the following code >> >> for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']: >> print(fix_title(title)) > At least in Python 3.2, this isn't the case. StopIteration breaks the > loop only if it's raised during the assignment, not during the body. It breaks the loop *silently* only if ... >>>> x=iter([1,2,3,4,5]) >>>> for i in x: > print("%d - %d"%(i,next(x))) > > 1 - 2 > 3 - 4 > Traceback (most recent call last): > File "", line 2, in > print("%d - %d"%(i,next(x))) > StopIteration whereas, you are right, it breaks it noisily in the body. So Ian's claim that StopIteration must be caught to avoid silent termination is not true. Thanks for pointing out what I saw but did not cognize the full implication of before. A better exception and an error message with an explaination might still be a good idea, though. -- Terry Jan Reedy From rosuav at gmail.com Sun Sep 11 21:03:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 11:03:24 +1000 Subject: Doctest failing In-Reply-To: <4E6D015A.3070500@stoneleaf.us> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> Message-ID: On Mon, Sep 12, 2011 at 4:43 AM, Ethan Furman wrote: > Chris Angelico wrote: >> >> And I'd do this with a lambda, but that's just me. Of course, if your >> logic is more complicated, it makes more sense to keep it in a named >> function, but a single conditional call can fit nicely into a lambda. > > Lambdas are great when needed, but if don't *need* it, and you have more > than a few, debugging can be a nightmare... "Okay, so this is function > ... and that is function ... and over here we also have > function ... ARGH!" Yeah, they can be like the Bruces sketch at times. A lambda is basically a function defined in an expression. For instance: def add_one(x): return x+1 is (practically) the same as: add_one = lambda x: x+1 In each case, you can call that function and will get back a value. The advantage of lambdas is that, in a list comprehension or map call, the code is right there instead of being elsewhere in a def statement. But as you can see, they quickly become hard to read: [j+2 for i in [[1,2,3],[4,5,6],[7,8,9]] for j in (lambda x: [q+10 for q in x])(i)] Their main advantage isn't in list comps, where you can already use arbitrary expressions, but in calls that require a function as an argument. The map() function is very similar to a generator expression, but it can iterate over multiple iterables at once: >>> list(map(lambda x,y: x+y,[1,2,3],[40,50,60])) [41, 52, 63] Note how the lambda keeps the code right there, whereas a def would separate it out. It's obvious from this one expression that it's adding successive corresponding pairs. Hope that helps! ChrisA From ben+python at benfinney.id.au Sun Sep 11 21:37:10 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 12 Sep 2011 11:37:10 +1000 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> Message-ID: <87sjo2lewp.fsf@benfinney.id.au> Chris Angelico writes: > A lambda is basically a function defined in an expression. For instance: > > def add_one(x): > return x+1 > > is (practically) the same as: > > add_one = lambda x: x+1 Those are only practically the same if you ignore the practical worth of a function knowing the name it was defined with. The latter does not have that, hence I don't see it as practically the same as the former. -- \ ?The Vatican is not a state.? a state must have territory. This | `\ is a palace with gardens, about as big as an average golf | _o__) course.? ?Geoffrey Robertson, 2010-09-18 | Ben Finney From rosuav at gmail.com Sun Sep 11 23:06:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 13:06:54 +1000 Subject: Doctest failing In-Reply-To: <87sjo2lewp.fsf@benfinney.id.au> References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> <87sjo2lewp.fsf@benfinney.id.au> Message-ID: On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney wrote: > Those are only practically the same if you ignore the practical worth of > a function knowing the name it was defined with. The latter does not > have that, hence I don't see it as practically the same as the former. > I know, but in the context of explaining what "lambda" means, it's practically the same. Lambdas can't (afaik) have docstrings either, etc, etc, but in terms of defining lambda, the two are more-or-less equivalent. ChrisA From steve+comp.lang.python at pearwood.info Mon Sep 12 00:29:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 14:29:05 +1000 Subject: Doctest failing References: <678b89fd-82f4-4080-8b36-e4d0ba30cdbf@o9g2000vbo.googlegroups.com> <4E6D015A.3070500@stoneleaf.us> <87sjo2lewp.fsf@benfinney.id.au> Message-ID: <4e6d8a92$0$29972$c3e8da3$5496439d@news.astraweb.com> On Mon, 12 Sep 2011 01:06 pm Chris Angelico wrote: > On Mon, Sep 12, 2011 at 11:37 AM, Ben Finney > wrote: >> Those are only practically the same if you ignore the practical worth of >> a function knowing the name it was defined with. The latter does not >> have that, hence I don't see it as practically the same as the former. >> > > I know, but in the context of explaining what "lambda" means, it's > practically the same. Lambdas can't (afaik) have docstrings either, > etc, etc, but in terms of defining lambda, the two are more-or-less > equivalent. >>> f = lambda x: x+1 >>> f.__name__ '' >>> f.__doc__ = "Return x+1" >>> f.__name__ = "add_one" >>> help(f) Help on function add_one in module __main__: add_one(x) Return x+1 Lambdas are functions, no more, no less. The only difference is that the *syntax* of the lambda statement only allows a single expression rather that the full block of a def, and no name. But because it returns an ordinary function object, you can post-process it just like any other function. Unfortunately, tracebacks ignore the function.__name__ and print the code object name: >>> f >>> f("x") Traceback (most recent call last): File "", line 1, in File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects and the code object name is read-only: >>> f.func_code.co_name '' >>> f.func_code.co_name = "add_one" Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute -- Steven From jpablo.romero at gmail.com Mon Sep 12 00:34:26 2011 From: jpablo.romero at gmail.com (=?ISO-8859-1?Q?Juan_Pablo_Romero_M=E9ndez?=) Date: Sun, 11 Sep 2011 23:34:26 -0500 Subject: What do you guys think about adding a method "to_json" Message-ID: Hello, What do you guys think about adding a method "to_json" to dictionaries and sequence types? Perhaps through a module import? Regards, Juan Pablo From clp2 at rebertia.com Mon Sep 12 00:44:01 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 11 Sep 2011 21:44:01 -0700 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: 2011/9/11 Juan Pablo Romero M?ndez : > Hello, > > What do you guys think about adding a method "to_json" to dictionaries > and sequence types? Perhaps through a module import? Why? We already have json.dumps(); seems to cover the use case. Cheers, Chris From adam.jorgensen.za at gmail.com Mon Sep 12 01:39:52 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Mon, 12 Sep 2011 07:39:52 +0200 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: Perhaps an actual use-case would clarify the need for this? 2011/9/12 Chris Rebert > 2011/9/11 Juan Pablo Romero M?ndez : > > Hello, > > > > What do you guys think about adding a method "to_json" to dictionaries > > and sequence types? Perhaps through a module import? > > Why? We already have json.dumps(); seems to cover the use case. > > Cheers, > Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Mon Sep 12 03:49:31 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 12 Sep 2011 17:49:31 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? Message-ID: Good evening, I have converted ODT to HTML using LibreOffice Writer, because I want to convert from HTML to Creole using python-creole. Unfortunately I get this error: "File "Convert to Creole.py", line 17 SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py on line 18, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details". Unfortunately I can't post my document yet (it's a research paper I'm working on), but I'm sure you'll get the same result if you write up a document in LibreOffice Writer and add some End Notes. How do I automate the removal of all non-ascii characters from my code? Thanks for all suggestions, Alec Taylor From gherron at islandtraining.com Mon Sep 12 04:17:44 2011 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 12 Sep 2011 01:17:44 -0700 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: <4E6DC028.1020101@islandtraining.com> On 09/12/2011 12:49 AM, Alec Taylor wrote: > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? > > Thanks for all suggestions, > > Alec Taylor This question does not quite make sense. The error message is complaining about a python file. What does that file have to do with ODT to HTML conversion and LibreOffice? The error message means the python file (wherever it came from) has a non-ascii character (as you noted), and so it needs something to tell it what such a character means. (That what the encoding is.) A comment like this in line 1 or 2 will specify an encoding: # -*- coding: -*- but, we'll have to know more about the file "Convert to Creole.py" to guess what encoding name should be specified there. You might try utf-8 or latin-1. From alec.taylor6 at gmail.com Mon Sep 12 04:33:14 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 12 Sep 2011 18:33:14 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> Message-ID: from creole import html2creole from BeautifulSoup import BeautifulSoup VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br', 'b', 'i', 'a', 'h1', 'h2'] def sanitize_html(value): ? ?soup = BeautifulSoup(value) ? ?for tag in soup.findAll(True): ? ? ? ?if tag.name not in VALID_TAGS: ? ? ? ? ? ?tag.hidden = True ? ?return soup.renderContents() html2creole(u(sanitize_html('''

Abstract

? ?

[more stuff here] """)) On Mon, Sep 12, 2011 at 6:17 PM, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: >> >> Good evening, >> >> I have converted ODT to HTML using LibreOffice Writer, because I want >> to convert from HTML to Creole using python-creole. Unfortunately I >> get this error: "File "Convert to Creole.py", line 17 >> SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py >> on line 18, but no encoding declared; see >> http://www.python.org/peps/pep-0263.html for details". >> >> Unfortunately I can't post my document yet (it's a research paper I'm >> working on), but I'm sure you'll get the same result if you write up a >> document in LibreOffice Writer and add some End Notes. >> >> How do I automate the removal of all non-ascii characters from my code? >> >> Thanks for all suggestions, >> >> Alec Taylor > > > > This question does not quite make sense. ?The error message is complaining > about a python file. ?What does that file have to do with ODT to HTML > conversion and LibreOffice? > > The error message means the python file (wherever it came from) has a > non-ascii character (as you noted), and so it needs something to tell it > what such a character means. ?(That what the encoding is.) > > A comment like this in line 1 or 2 will specify an encoding: > ?# -*- coding: -*- > but, we'll have to know more about the file "Convert to Creole.py" to guess > what encoding name should be specified there. > > You might try utf-8 or latin-1. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjohn.tedro at gmail.com Mon Sep 12 04:35:44 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Mon, 12 Sep 2011 08:35:44 +0000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: <4E6DC028.1020101@islandtraining.com> References: <4E6DC028.1020101@islandtraining.com> Message-ID: On Mon, Sep 12, 2011 at 8:17 AM, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: > >> Good evening, >> >> I have converted ODT to HTML using LibreOffice Writer, because I want >> to convert from HTML to Creole using python-creole. Unfortunately I >> get this error: "File "Convert to Creole.py", line 17 >> SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py >> on line 18, but no encoding declared; see >> http://www.python.org/peps/**pep-0263.htmlfor details". >> >> Unfortunately I can't post my document yet (it's a research paper I'm >> working on), but I'm sure you'll get the same result if you write up a >> document in LibreOffice Writer and add some End Notes. >> >> How do I automate the removal of all non-ascii characters from my code? >> >> Thanks for all suggestions, >> >> Alec Taylor >> > > > > This question does not quite make sense. The error message is complaining > about a python file. What does that file have to do with ODT to HTML > conversion and LibreOffice? > > The error message means the python file (wherever it came from) has a > non-ascii character (as you noted), and so it needs something to tell it > what such a character means. (That what the encoding is.) > > A comment like this in line 1 or 2 will specify an encoding: > # -*- coding: -*- > but, we'll have to know more about the file "Convert to Creole.py" to guess > what encoding name should be specified there. > > You might try utf-8 or latin-1. > > > > -- > http://mail.python.org/**mailman/listinfo/python-list > If you are having trouble figuring out which encoding your file has, the "file" util is often a quick and dirty solution. #> echo "???" > test.txt #> file test.txt test.txt: UTF-8 Unicode text #> iconv test.txt -f utf-8 -t latin1 > test.l1.txt #> file test.l1.txt test.l1.txt: ISO-8859 text Note: I use latin1 (iso-8859-1) because it can describe the characters '?', '?', '?'. Your encoding might be different depending on what system you are using. The gist is that if you specify the correct encoding as mentioned above with the "coding"-comment, your program will probably (ish) run as intended. -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Sep 12 04:43:51 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 12 Sep 2011 10:43:51 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> Message-ID: Alec Taylor, 12.09.2011 10:33: > from creole import html2creole > > from BeautifulSoup import BeautifulSoup > > VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br', 'b', 'i', 'a', 'h1', 'h2'] > > def sanitize_html(value): > > soup = BeautifulSoup(value) > > for tag in soup.findAll(True): > if tag.name not in VALID_TAGS: > tag.hidden = True > > return soup.renderContents() > html2creole(u(sanitize_html('''

style="margin-left:76.8px;margin-right:0;text-indent:0;">Abstract

>

style="margin-left:76.8px;margin-right:0;text-indent:0;"> > [more stuff here] > """)) Hi, I'm not sure what you are trying to say with the above code, but if it's the code that fails for you with the exception you posted, I would guess that the problem is in the "[more stuff here]" part, which likely contains a non-ASCII character. Note that you didn't declare the source file encoding above. Do as Gary told you. Stefan From steve+comp.lang.python at pearwood.info Mon Sep 12 04:44:29 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 18:44:29 +1000 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> On Wed, 31 Aug 2011 10:33 pm Steven D'Aprano wrote: > Twice in a couple of weeks, I have locked up my PC by running a Python 2.5 > script that tries to create a list that is insanely too big. > > In the first case, I (stupidly) did something like: > > mylist = [0]*12345678901234 [...] > Apart from "Then don't do that!", is there anything I can do to prevent > this sort of thing in the future? Like instruct Python not to request more > memory than my PC has? For anyone who may care, I can report that ulimit under Linux will help with this situation. [steve at wow-wow ~]$ ulimit -v 200000 [steve at wow-wow ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> L = range(100000000) Traceback (most recent call last): File "", line 1, in MemoryError (Of course, I would have eventually got a MemoryError even without the ulimit. *Eventually.* After much thrashing and processes crashing and pain.) Does anyone else think it would be useful for Python's memory manager to enforce user-settable limits? Even just a simple thing like "never try to allocate more than N bytes at once" would probably go a long way to prevent a certain class of accidental (or deliberate) DOSes. -- Steven From steve+comp.lang.python at pearwood.info Mon Sep 12 04:49:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 18:49:56 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> Message-ID: <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > I'm not sure what you are trying to say with the above code, but if it's > the code that fails for you with the exception you posted, I would guess > that the problem is in the "[more stuff here]" part, which likely contains > a non-ASCII character. Note that you didn't declare the source file > encoding above. Do as Gary told you. Even with a source code encoding, you will probably have problems with source files including \xe2 and other "bad" chars. Unless they happen to fall inside a quoted string literal, I would expect to get a SyntaxError. I have come across this myself. While I haven't really investigated in great detail, it appears to happen when copying and pasting code from a document (usually HTML) which uses non-breaking spaces instead of \x20 space characters. All it takes is just one to screw things up. -- Steven From ulrich.eckhardt at dominolaser.com Mon Sep 12 06:00:08 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 12:00:08 +0200 Subject: Terminating an embedded interpreter Message-ID: Hi! I'm trying to provide some scripting capabilities to a program. For that, I'm embedding a Python interpreter, running a script in a separate thread to decouple it from the UI. Now, how should I handle rogue scripts? For example, when a script hangs in an endless loop, how do I signal the Python interpreter to shut down? In other words, I want to trigger something like what Control-C does in a "normal" environment. In case it matters, the OS here is MS Windows. Thanks! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From rmorgan466 at gmail.com Mon Sep 12 06:34:52 2011 From: rmorgan466 at gmail.com (Rita) Date: Mon, 12 Sep 2011 06:34:52 -0400 Subject: working with a large file Message-ID: I have a large file, 18gb uncompressed, and I would like to know what is the preferred method to read this file for random access. I have several processes reading the file which different calculate arguments. My server has 64gb of memory. Not sure what is the preferred way to do this? -- --- Get your facts first, then you can distort them as you please.-- -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Sep 12 06:38:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 20:38:47 +1000 Subject: Terminating an embedded interpreter In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 8:00 PM, Ulrich Eckhardt wrote: > Now, how should I handle rogue scripts? For example, when a script hangs in > an endless loop, how do I signal the Python interpreter to shut down? In > other words, I want to trigger something like what Control-C does in a > "normal" environment. > You can use PyErr_SetInterrupt to raise KeyboardInterrupt, but it can be caught by the script. There's no guaranteed way, short of killing the process. ChrisA From wolfgang at rohdewald.de Mon Sep 12 06:45:00 2011 From: wolfgang at rohdewald.de (Wolfgang Rohdewald) Date: Mon, 12 Sep 2011 12:45:00 +0200 Subject: working with a large file In-Reply-To: References: Message-ID: <201109121245.00224.wolfgang@rohdewald.de> On Montag 12 September 2011, Rita wrote: > I have a large file, 18gb uncompressed, and I would like to > know what is the preferred method to read this file for > random access. I have several processes reading the file > which different calculate arguments. My server has 64gb of > memory. Not sure what is the preferred way to do this? if the data is structured, you could store it in something like sqlite -- Wolfgang From steve+comp.lang.python at pearwood.info Mon Sep 12 07:08:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 12 Sep 2011 21:08:22 +1000 Subject: Terminating an embedded interpreter References: Message-ID: <4e6de828$0$29993$c3e8da3$5496439d@news.astraweb.com> Ulrich Eckhardt wrote: > Hi! > > I'm trying to provide some scripting capabilities to a program. For that, > I'm embedding a Python interpreter, running a script in a separate thread > to decouple it from the UI. > > Now, how should I handle rogue scripts? For example, when a script hangs > in an endless loop, how do I signal the Python interpreter to shut down? If you are using threads, they all run within the same Python process. You can ask a thread to shut down, but you can't force it to from the outside. If the thread runs a script that goes rogue, the script may never return control to the thread long enough for it to respond to your request. The main UI loop can still kill itself, and take all the threads with it, by calling sys.exit. Or if you really need to, os.abort or os._exit can be used for immediate "terminate yourself NOW!!!" commands. (But read the docs for them first.) A better way may be to run the script in a separate process. You can kill the process the same way you would any other rogue process: by sending it a signal. See the os and subprocess modules. But Python's sandboxing abilities are not great. If you really fear rogue, or malicious, scripts, perhaps Python is not the right language for this task. Otherwise, just trust the script to be sane. -- Steven From roy at panix.com Mon Sep 12 07:40:00 2011 From: roy at panix.com (Roy Smith) Date: Mon, 12 Sep 2011 07:40:00 -0400 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e6dc66e$0$29986$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > > mylist = [0]*12345678901234 > [...] > > Apart from "Then don't do that!", is there anything I can do to prevent > > this sort of thing in the future? Like instruct Python not to request more > > memory than my PC has? > > > For anyone who may care, I can report that ulimit under Linux will help with > this situation. > [...] > Does anyone else think it would be useful for Python's memory manager to > enforce user-settable limits? Not me. You've already discovered that ulimit does exactly what you want. Why would be gained by having Python duplicate this functionality? From ulrich.eckhardt at dominolaser.com Mon Sep 12 08:01:47 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 14:01:47 +0200 Subject: Terminating an embedded interpreter References: <4e6de828$0$29993$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Ulrich Eckhardt wrote: >> I'm trying to provide some scripting capabilities to a program. For that, >> I'm embedding a Python interpreter, running a script in a separate thread >> to decouple it from the UI. >> >> Now, how should I handle rogue scripts? For example, when a script hangs >> in an endless loop, how do I signal the Python interpreter to shut down? > > If you are using threads, they all run within the same Python process. You > can ask a thread to shut down, but you can't force it to from the outside. > If the thread runs a script that goes rogue, the script may never return > control to the thread long enough for it to respond to your request. Sorry, I described badly what I was doing. The program itself is written in C++ and I'm running the Python interpreter in a thread separate to the UI, just in order to not hang the UI if anything in the interpreter blocks for extended amounts of time. I know that a Python thread is not a "system" thread but handled and scheduled internally by Python. > The main UI loop can still kill itself, and take all the threads with it, > by calling sys.exit. Or if you really need to, os.abort or os._exit can be > used for immediate "terminate yourself NOW!!!" commands. (But read the > docs for them first.) > A better way may be to run the script in a separate process. You can kill > the process the same way you would any other rogue process: by sending it > a signal. See the os and subprocess modules. Yes, a separate process would be much cleaner, but it would complicate communication back to the parent process. The Python code is supposed to call a few functions I exported. I'd have to tunnel these calls through stdin/stdout/stderr and that is more than what I'm willing to do at the moment. It does sound intriguing though, since that would allow me to embed any scripting language, not just Python. > But Python's sandboxing abilities are not great. If you really fear rogue, > or malicious, scripts, perhaps Python is not the right language for this > task. Otherwise, just trust the script to be sane. I'm not fearing malicious scripts. I'm also not concerned about rare hangs since this in an internal tool. In this case, I'd take a simple 99% solution over a complex 100% solution. Thank you for your thoughts, Steven! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From ulrich.eckhardt at dominolaser.com Mon Sep 12 08:05:04 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 12 Sep 2011 14:05:04 +0200 Subject: Terminating an embedded interpreter References: Message-ID: Chris Angelico wrote: > You can use PyErr_SetInterrupt to raise KeyboardInterrupt This sounds useful. Just to make sure, this would be called from a different thread than the one running the Python script, is that still OK? > , but it can be caught by the script. There's no guaranteed way, > short of killing the process. This will do for my plans, I'm not trying to defend against anything malicious. Thanks you! Uli -- Domino Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From davea at ieee.org Mon Sep 12 08:09:59 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Sep 2011 08:09:59 -0400 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E6DF697.2010208@ieee.org> On 01/-10/-28163 02:59 PM, Steven D'Aprano wrote: > On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > >> I'm not sure what you are trying to say with the above code, but if it's >> the code that fails for you with the exception you posted, I would guess >> that the problem is in the "[more stuff here]" part, which likely contains >> a non-ASCII character. Note that you didn't declare the source file >> encoding above. Do as Gary told you. > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > > I have come across this myself. While I haven't really investigated in great > detail, it appears to happen when copying and pasting code from a document > (usually HTML) which uses non-breaking spaces instead of \x20 space > characters. All it takes is just one to screw things up. > > For me, more common than non-breaking space is the "smart quotes" characters. In that case, one probably doesn't want to delete them, but instead convert them into standard quotes. DaveA From nobody at nowhere.com Mon Sep 12 08:19:25 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 12 Sep 2011 13:19:25 +0100 Subject: PC locks up with list operations References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e5e2d81$0$29991$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, 31 Aug 2011 22:47:59 +1000, Steven D'Aprano wrote: >> Linux seems to fair badly when programs use more memory than physically >> available. Perhaps there's some per-process thing that can be used to >> limit things on Linux? > > As far as I know, ulimit ("user limit") won't help. It can limit the amount > of RAM available to a process, but that just makes the process start using > virtual memory more quickly. It can also limit the amount of virtual memory > used by the shell, but not of other processes. In other words, Linux will > try really, really, really hard to give you the 84 gigabytes you've asked > for on a 2 GB system, even if it means DOSing your system for a month. > > Of course, I would be very happy to learn I'm wrong. Resource limits set by ulimit are inherited by any processes spawned from the shell. They also affect the shell itself, but a shell process shouldn't require a lot of resources. You can use a subshell if you want to impose limits on a specific process. For Python, setting the limit on virtual memory (RAM + swap) to no more than the amount of physical RAM is probably a wise move. Some processes can use swap effectively, but the typical Python program probably can't. There are exceptions, e.g. if most of the memory is accounted for by large NumPy arrays and you're careful about the operations which are performed upon them. But using large amounts of memory for many small objects is almost bound to result in swap-thrashing. One problem with doing this automatically (e.g. in .pythonrc) is the inheritance issue; any processes spawned from the interpreter will also be resource limited. Similarly, any binary libraries loaded into the interpreter will be subject to the process' resource limits. Consequently, there would be some advantages to the Python interpreter having its own resource-limiting mechanism. From ssegvic at zemris.fer.hr Mon Sep 12 08:45:38 2011 From: ssegvic at zemris.fer.hr (=?utf-8?Q?Sini=C5=A1a_=C5=A0egvi=C4=87?=) Date: Mon, 12 Sep 2011 14:45:38 +0200 (CEST) Subject: Portable locale usage In-Reply-To: <4E69DEE8.9050803@shopzeus.com> Message-ID: <1616916126.29418.1315831538309.JavaMail.root@mail.zemris.fer.hr> > From: "Laszlo Nagy" > To: "Sini?a ?egvi?" , python-list at python.org > Sent: Friday, September 9, 2011 11:39:52 AM > Subject: Re: Portable locale usage > > Looks like you have found a bug! :-) Why don't you post a bug report? I just did: http://bugs.python.org/issue12964 Thanks everyone for helping me to sort this out! Sinisa From rosuav at gmail.com Mon Sep 12 08:49:48 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 12 Sep 2011 22:49:48 +1000 Subject: Terminating an embedded interpreter In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:05 PM, Ulrich Eckhardt wrote: > Chris Angelico wrote: >> You can use PyErr_SetInterrupt to raise KeyboardInterrupt > > This sounds useful. Just to make sure, this would be called from a different > thread than the one running the Python script, is that still OK? > >> , but it can be caught by the script. There's no guaranteed way, >> short of killing the process. > > This will do for my plans, I'm not trying to defend against anything > malicious. Yes, that would be what you want then. The main thing to take care of is a blanket 'except' that doesn't specify what it's accepting - it'll snarf the KeyboardInterrupt and carry on its merry way. ChrisA From duncan.booth at invalid.invalid Mon Sep 12 09:06:47 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Sep 2011 13:06:47 GMT Subject: Idioms combining 'next(items)' and 'for item in items:' References: Message-ID: Terry Reedy wrote: > The statement containing the explicit next(items) call can optionally be > wrapped to explicitly handle the case of an empty iterable in whatever > manner is desired. > > try: > > except StopIteration: > raise ValueError("iterable cannot be empty") > > Alternatively, if all you want is for an empty iterable to do nothing, you could write it like this: items = iter(iterable) for first in items: break for item in items: However, the issue I have with any of this pulling the first element out of the loop is that if you want special processing for the first element you are likely to also want it for the last, and if it is a single item you need to process that item with both bits of special code. I don't see how that works unless you have all elements within the single loop and test for first/last. > 2. Process the last item of an iterable differently. As far as I know, > this cannot be done for a generic iterable with a flag. It requires a > look ahead. I think that must be correct, e.g. if reading from an interactive prompt you cannot detect end of input until you fail to read any more. See my answer to http://stackoverflow.com/questions/7365372/is-there-a-pythonic-way-of-knowing-when-the-first-and-last-loop-in-a-for-is-being/7365552#7365552 for a generator that wraps the lookahead. -- Duncan Booth http://kupuguy.blogspot.com From miki.tebeka at gmail.com Mon Sep 12 09:23:09 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 06:23:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: You can add "# coding=UTF8" to the top of your file (see http://www.python.org/dev/peps/pep-0263/). Of you want to remove unicode, there are several options, one of them is passing the file through "iconv --to ascii". From miki.tebeka at gmail.com Mon Sep 12 09:23:09 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 06:23:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: You can add "# coding=UTF8" to the top of your file (see http://www.python.org/dev/peps/pep-0263/). Of you want to remove unicode, there are several options, one of them is passing the file through "iconv --to ascii". From j.reid at mail.cryst.bbk.ac.uk Mon Sep 12 10:03:40 2011 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Mon, 12 Sep 2011 15:03:40 +0100 Subject: Easiest framework to develop simple interactive web site in python? Message-ID: Hi, I need to write a web interface for some computational biology software I've written: http://sysbio.mrc-bsu.cam.ac.uk/johns/STEME/rst/_build/html/index.html I don't have much experience writing web sites or applications. Can anyone recommend a python framework that will allow me to easily write a few pages? I need to accept some user input in the form of some options and download a potentially large file from the user's computer. The job can take some time to run so I'll need to notify them via email when it has finished. I should say our group already uses an Apache web server so I'd like to host the pages from that server. I know there are various python web frameworks but I don't want to learn a complicated one, I really just want the simplest tool for the job. Are any of the following suitable? Zope, Django, Pylons, Grok, Pyramid I see quite a few are listed here: http://wiki.python.org/moin/WebFrameworks Thanks in advance for any help, John. From stefan_ml at behnel.de Mon Sep 12 10:10:44 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 12 Sep 2011 16:10:44 +0200 Subject: working with a large file In-Reply-To: References: Message-ID: Rita, 12.09.2011 12:34: > I have a large file, 18gb uncompressed, and I would like to know what is the > preferred method to read this file for random access. I have several > processes reading the file which different calculate arguments. My server > has 64gb of memory. Not sure what is the preferred way to do this? It depends on the content (and likely also the operating system), but you might want to take a look at the mmap module. Stefan From wxjmfauth at gmail.com Mon Sep 12 10:39:22 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Mon, 12 Sep 2011 07:39:22 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: Message-ID: <55455989-d2bf-44d6-b3cf-ba50f1e87a01@d14g2000yqb.googlegroups.com> On 12 sep, 10:17, Gary Herron wrote: > On 09/12/2011 12:49 AM, Alec Taylor wrote: > > > > > Good evening, > > > I have converted ODT to HTML using LibreOffice Writer, because I want > > to convert from HTML to Creole using python-creole. Unfortunately I > > get this error: "File "Convert to Creole.py", line 17 > > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > > on line 18, but no encoding declared; see > >http://www.python.org/peps/pep-0263.htmlfor details". > > > Unfortunately I can't post my document yet (it's a research paper I'm > > working on), but I'm sure you'll get the same result if you write up a > > document in LibreOffice Writer and add some End Notes. > > > How do I automate the removal of all non-ascii characters from my code? > > > Thanks for all suggestions, > > > Alec Taylor > The coding of the characters is a domain per se. It is independent from any OS's or applications. When working with (plain) text files, you should always be aware about the coding of the text you are working on. If you are using coding directives, you must ensure your coding directive matches the real coding of the text files. A coding directive is only informative, it does not set the coding. I'm pretty sure, you problem comes from this. There is a mismatch somewhere, you are not aware of. Removing ascii chars is certainly not a valuable solution. It must work. If your are working properly, it can not, not work. Frome a linguistic point of view, the web has informed me Creole (*all the Creoles*) can be composed with the iso-8859-1 coding. That means, iso-8859-1, cp1252 and all Unicode coding variants are possible coding directives. jmf From ericsnowcurrently at gmail.com Mon Sep 12 10:44:01 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Mon, 12 Sep 2011 08:44:01 -0600 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 1:49 AM, Alec Taylor wrote: > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? Perhaps try "The Unicode Hammer". http://code.activestate.com/recipes/251871/ -eric > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > From wxjmfauth at gmail.com Mon Sep 12 10:47:00 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Mon, 12 Sep 2011 07:47:00 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> On 12 sep, 10:49, Steven D'Aprano wrote: > > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > This is absurd and a complete non sense. The purpose of a coding directive is to inform the engine, which is processing a text file, about the "language" it has to speak. Can be a html, py or tex file. If you have problem, it's probably a mismatch between your coding directive and the real coding of the file. Typical case: ascii/utf-8 without signature. jmf From bestenborstel at gmail.com Mon Sep 12 10:51:45 2011 From: bestenborstel at gmail.com (G.) Date: Mon, 12 Sep 2011 07:51:45 -0700 (PDT) Subject: Could you please give me some advise on this piece of code? Message-ID: Dear all, I am a python newbie, but I intend to program a python script that communicates with Labview via a UDP socket. I managed to send LabView strings, but the other way around is not working. The code seems to stop working while in the first while loop. I can see the word "test" being print out. When I start LabView UDP_sender.vi it is supposed to send a string back to python, but sometimes it ends with an error saying the port and the ip is already in usage. Do I have to start first LabView or the python scrip when listening to LabView, please? It would be great if you could have a look on my code and could maybe see why it does nothing after "print test", please. Thank you very much. Kind regards, G. # To change this template, choose Tools | Templates # and open the template in the editor. __author__="User" __date__ ="$11.09.2011 19:34:03$" if __name__ == "__main__": print "Das ist ein Test" import socket import time #Define global variables for UDP_IP and UDP_Port, needs to be changed for PETRA-3 #global UDP_IP UDP_IP="127.0.0.1" print "UDP_IP is", UDP_IP #global UDP_PORT UDP_PORT=21312 print "UDP_PORT is", UDP_PORT def openUDPSocket(UDP_IP,UDP_PORT): #UDP_IP="127.0.0.1" #UDP_PORT=5005 print "Creating socket ..." sock=socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM ) # UDP sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #sock.setblocking(0) #sock.bind((UDP_IP,UDP_PORT)) #sock.listen(1) print "Done." return sock def fastPump(sock): # Start pumping and return MESSAGE="pumpfast" # print "UDP target IP:", UDP_IP # print "UDP target port:", UDP_PORT # print "message:", MESSAGE sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) def slowPump(sock): MESSAGE="pumpslow" sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) pumpsocketUDP=openUDPSocket(UDP_IP,UDP_PORT) # Receive messages counter_while_loop=0 print "test" while counter_while_loop < 3: data,addr = pumpsocketUDP.recvfrom(1024) print "test" if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" counter_while_loop=counter_while_loop+1 counter_while_loop=0 while counter_while_loop < 3: fastPump(pumpsocketUDP) time.sleep(5) slowPump(pumpsocketUDP) time.sleep(3) counter_while_loop=counter_while_loop+1 print "Counter_while_loop", counter_while_loop # Close socket pumpsocketUDP.close() From w.brenig at tu-bs.de Mon Sep 12 11:39:35 2011 From: w.brenig at tu-bs.de (Wolfram Brenig) Date: Mon, 12 Sep 2011 17:39:35 +0200 Subject: ipython -wthread vs. ipython -pylab Message-ID: <9d6n9cFs53U1@mid.dfncis.de> Hi, I have a problem with the ipython shell: frequently, within one session I would like to do 2D plotting, using matplotlib, as well as 3D visualization using mayavi The man page for ipython, matplotlib, and mayavi tell me, that I must invoke ipython with ipython -wthread for mayavi and ipython -pylab for matplotlib in order to avoid blocking (which indeed happens if I don't use those options). However, ipython's manpage also states, that only one of -wthread or -pylab can be given? Does that imply I have to get out of the shell each time I want to switch from matplotlib to mayavi usage? Most likely no. But what should I do? Thanks for your help Wolfram From matthias.huening at fu-berlin.de Mon Sep 12 11:42:56 2011 From: matthias.huening at fu-berlin.de (Matthias Huening) Date: Mon, 12 Sep 2011 17:42:56 +0200 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: <9d6nk0FutiU1@mid.uni-berlin.de> Am 12.09.2011 16:03, schrieb John Reid: > > I don't have much experience writing web sites or applications. Can > anyone recommend a python framework that will allow me to easily write a > few pages? You want a simple framework? Try Bottle: http://bottlepy.org/ Matthias From Phillip.M.Feldman at gmail.com Mon Sep 12 11:47:22 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Mon, 12 Sep 2011 08:47:22 -0700 (PDT) Subject: recursive algorithm for balls in numbered boxes In-Reply-To: References: <32440187.post@talk.nabble.com> Message-ID: <32449079.post@talk.nabble.com> Mark Dickinson-2 wrote: > > > This is a well-known trick: to divide 5 (unlabeled) balls amongst 3 > (labeled) boxes, you write down sequences of 5 o's and 2 x's, where > the o's represent the 5 balls and the 'x's represent dividers: > > ooxooxo -> [2, 2, 1] > xoooxoo -> [0, 3, 2] > > And 'combinations(7, 2)' yields successively all the possible > different placements for the 2 dividers in the 7 symbols. > > > This question seems to come up often enough (without the box size > limit twist) that maybe it would be useful to include something like > this recipe in the itertool documentation. > > > For getting this into itertools, I'd suggest opening a feature request > on bugs.python.org and assigning it to Raymond Hettinger. > > -- > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > > You are correct--the case without capacity limits can be handled using the existing machinery in `itertools`. BTW--That trick with the dividers is discussed on page 38 of William Feller's classic text, "An Introduction to Probability Theory and Its Applications". As per your suggestion, I have opened a feature request and assigned it to Raymond. Thanks! -- View this message in context: http://old.nabble.com/recursive-algorithm-for-balls-in-numbered-boxes-tp32440187p32449079.html Sent from the Python - python-list mailing list archive at Nabble.com. From miki.tebeka at gmail.com Mon Sep 12 12:48:42 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 09:48:42 -0700 (PDT) Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: I personally like CherryPy. But it all depends on your needs and style. I suggest you play with some of the packages and select one that you feel best with. From miki.tebeka at gmail.com Mon Sep 12 12:48:42 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 12 Sep 2011 09:48:42 -0700 (PDT) Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: I personally like CherryPy. But it all depends on your needs and style. I suggest you play with some of the packages and select one that you feel best with. From ian.g.kelly at gmail.com Mon Sep 12 12:55:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 10:55:14 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Sun, Sep 11, 2011 at 6:45 PM, Terry Reedy wrote: > whereas, you are right, it breaks it noisily in the body. So Ian's claim > that StopIteration must be caught to avoid silent termination is not true. > Thanks for pointing out what I saw but did not cognize the full implication > of before. A better exception and an error message with an explaination > might still be a good idea, though. But you can't write the function under the assumption that it will only be called from the function body. The following is a slight reorganization of your example that does exhibit the problem: for title in map(fix_title, ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']): print(title) Output: amazing a Hell of a Fight Note that at first glance, my example would appear to be functionally equivalent to yours -- I've merely pulled the fix_title call out of the loop body and into the iterator. But actually they produce different results because fix_title misbehaves by not catching the StopIteration. Cheers, Ian From ian.g.kelly at gmail.com Mon Sep 12 12:58:05 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 10:58:05 -0600 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:55 AM, Ian Kelly wrote: > But you can't write the function under the assumption that it will > only be called from the function body. ?The following is a slight > reorganization of your example that does exhibit the problem: s/function body/for-loop body/ From ian.g.kelly at gmail.com Mon Sep 12 13:41:06 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 12 Sep 2011 11:41:06 -0600 Subject: Could you please give me some advise on this piece of code? In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 8:51 AM, G. wrote: > When I start LabView UDP_sender.vi it is supposed to send a string > back to python, but sometimes it ends with an error saying the port > and the ip is already in usage. Do I have to start first LabView or > the python scrip when listening to LabView, please? If LabView is sending, then the Python script should already be receiving, so start Python first. > def openUDPSocket(UDP_IP,UDP_PORT): > ? ?#UDP_IP="127.0.0.1" > ? ?#UDP_PORT=5005 > ? ?print "Creating socket ..." > ? ?sock=socket.socket( socket.AF_INET, # Internet > ? ? ? ? ? ? ? ? ? ? ? ?socket.SOCK_DGRAM ) # UDP I don't think this is sufficient to create a UDP socket. To be safe, you should specify the protocol as well: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) > ? ?#sock.bind((UDP_IP,UDP_PORT)) Your bind call is commented out, which means that your socket will be bound to an arbitrary port selected by the OS. This will make it hard for LabView to send it messages, since it won't know what port to use. Also, you appear to be using the same address and port for both endpoints. The UDP socket in Python and the UDP socket in LabView should be bound to two separate ports. This is probably why you were getting the "port already in use" error, before you commented this out. > ? ?#sock.listen(1) You don't need this at all. listen() is for TCP sockets. > def fastPump(sock): > ? ?# Start pumping and return > ? ?MESSAGE="pumpfast" > > ? # print "UDP target IP:", UDP_IP > ? # print "UDP target port:", UDP_PORT > ? # print "message:", MESSAGE > > ? ?sock.sendto( MESSAGE, (UDP_IP, UDP_PORT) ) The IP and port here should be that of the destination, i.e. the address of the LabView socket. > counter_while_loop=0 > print "test" > while counter_while_loop < 3: > ? ? ? ?data,addr = pumpsocketUDP.recvfrom(1024) > ? ? ? ?print "test" > ? ? ? ?if not data: > ? ? ? ? ? ? ? ?print "Client has exited!" > ? ? ? ? ? ? ? ?break > ? ? ? ?else: > ? ? ? ? ? ? ? ?print "\nReceived message '", data,"'" > ? ? ? ?counter_while_loop=counter_while_loop+1 You should really use a for loop here: for counter in range(3): data, addr = pumpsocketUPD.recvfrom(1024) print "Received message %r" % data Note that if data is empty, it means that it received an empty message, not that the client has exited. It may be that you're having the LabView client send an empty message when it exits, but this does not happen automatically. HTH, Ian From pruebauno at latinmail.com Mon Sep 12 13:42:35 2011 From: pruebauno at latinmail.com (nn) Date: Mon, 12 Sep 2011 10:42:35 -0700 (PDT) Subject: convert time References: <4e6c4088$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 11, 1:00?am, Steven D'Aprano wrote: > ???? wrote: > > how can i convert "Dec 11" into ?2011-12? > > if my_str == "Dec 11": > ? ? return 1999 ?# 2011 - 12 > > Does that help? > > But seriously... 2011-12 is not a proper date, so the simplest way is > probably something like this: > > def convert(date_str): > ? ? month, short_year = date_str.split() > ? ? if len(short_year) == 4: > ? ? ? ? year = short_year > ? ? else: > ? ? ? ? year = '20' + short_year > ? ? months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split() > ? ? month = months.index(month) + 1 > ? ? return year + '-' + str(month) > > Otherwise see the time and datetime modules: > > http://docs.python.org/library/time.htmlhttp://docs.python.org/library/datetime.html > > -- > Steven Just a small comment that you can get "months" by doing: from calendar import month_abbr months = list(month_abbr) From stefaan.himpe at gmail.com Mon Sep 12 14:37:49 2011 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Mon, 12 Sep 2011 20:37:49 +0200 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: Message-ID: <1ksbq.2549$ex3.1130@newsfe30.ams2> The simplest one to learn is web2py http://www.web2py.com No configuration needed, just unpack and get started. It also has very good documentation and tons of little examples to get things done. The other options you mentioned are good too :) From tjreedy at udel.edu Mon Sep 12 15:24:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 15:24:14 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/12/2011 9:06 AM, Duncan Booth wrote: > Terry Reedy wrote: > >> The statement containing the explicit next(items) call can optionally be >> wrapped to explicitly handle the case of an empty iterable in whatever >> manner is desired. >> >> try: >> >> except StopIteration: >> raise ValueError("iterable cannot be empty") >> >> > Alternatively, if all you want is for an empty iterable to do nothing, To do nothing, just pass above. If the function does nothing, it returns None. In the fix_title function, it should return '', not None. > you could write it like this: > > items = iter(iterable) > for first in items: > > break I could, but I doubt I would ;-). Try...except StopIteration: pass is more explicit and less roundabout. > for item in items: > > > However, the issue I have with any of this pulling the first element out of > the loop is that if you want special processing for the first element you > are likely to also want it for the last, Likely? I would say occasionally. Sentences have first words; file have headers. Special processing for last items is only an issue if it *replaces* the normal processing, rather than following the normal processing. > and if it is a single item you need > to process that item with both bits of special code. I don't see how that works > unless you have all elements within the single loop and test for first/last. Like so, with tests: def first_last_special(iterable): print("\nIterable is",repr(iterable)) items = iter(iterable) try: first = next(items) except StopIteration: print('Nothing'); return print(first, 'is the first item') try: current = next(items) except StopIteration: current = first else: for item in items: print(current, 'is a middle item') current = item print(current, 'is the last item') first_last_special('') first_last_special('1') first_last_special('12') first_last_special('123') first_last_special('12345') -- Terry Jan Reedy From georgeryoung at gmail.com Mon Sep 12 15:49:51 2011 From: georgeryoung at gmail.com (gry) Date: Mon, 12 Sep 2011 12:49:51 -0700 (PDT) Subject: Python: Deleting specific words from a file. References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> Message-ID: <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> On Sep 9, 2:04?am, Terry Reedy wrote: > On 9/8/2011 9:09 PM, papu wrote: > > > > > Hello, I have a data file (un-structed messy file) from which I have > > to scrub specific list of words (delete words). > > > Here is what I am doing but with no result: > > > infile = "messy_data_file.txt" > > outfile = "cleaned_file.txt" > > > delete_list = ["word_1","word_2"....,"word_n"] > > new_file = [] > > fin=open(infile,"") > > fout = open(outfile,"w+") > > for line in fin: > > ? ? ?for word in delete_list: > > ? ? ? ? ?line.replace(word, "") > > ? ? ?fout.write(line) > > fin.close() > > fout.close() > > If you have very many words (and you will need all possible forms of > each word if you do exact matches), The following (untested and > incomplete) should run faster. > > delete_set = {"word_1","word_2"....,"word_n"} > ... > for line in fin: > ? ? ?for word in line.split() > ? ? ? ? ?if word not in delete_set: > ? ? ? ? ? ? ?fout.write(word) # also write space and nl. > > Depending on what your file is like, you might be better with > re.split('(\W+)', line). An example from the manual: > ?>>> re.split('(\W+)', '...words, words...') > ['', '...', 'words', ', ', 'words', '...', ''] > > so all non-word separator sequences are preserved and written back out > (as they will not match delete set). > > -- > Terry Jan Reedy re.sub is handy too: import re delete_list=('the','rain','in','spain') regex = re.compile('\W' + '|'.join(delete_list) + '\W') infile='messy' with open(infile, 'r') as f: for l in f: print regex.sub('', l) From python at mrabarnett.plus.com Mon Sep 12 16:42:21 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 12 Sep 2011 21:42:21 +0100 Subject: Python: Deleting specific words from a file. In-Reply-To: <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> References: <30f9b718-bb3c-4c92-8a03-0f760c993939@a12g2000yqi.googlegroups.com> <22e15921-d543-4604-8996-3bcb2770ef18@et6g2000vbb.googlegroups.com> Message-ID: <4E6E6EAD.5040306@mrabarnett.plus.com> On 12/09/2011 20:49, gry wrote: > On Sep 9, 2:04 am, Terry Reedy wrote: >> On 9/8/2011 9:09 PM, papu wrote: >> >> >> >>> Hello, I have a data file (un-structed messy file) from which I have >>> to scrub specific list of words (delete words). >> >>> Here is what I am doing but with no result: >> >>> infile = "messy_data_file.txt" >>> outfile = "cleaned_file.txt" >> >>> delete_list = ["word_1","word_2"....,"word_n"] >>> new_file = [] >>> fin=open(infile,"") >>> fout = open(outfile,"w+") >>> for line in fin: >>> for word in delete_list: >>> line.replace(word, "") >>> fout.write(line) >>> fin.close() >>> fout.close() >> >> If you have very many words (and you will need all possible forms of >> each word if you do exact matches), The following (untested and >> incomplete) should run faster. >> >> delete_set = {"word_1","word_2"....,"word_n"} >> ... >> for line in fin: >> for word in line.split() >> if word not in delete_set: >> fout.write(word) # also write space and nl. >> >> Depending on what your file is like, you might be better with >> re.split('(\W+)', line). An example from the manual: >> >>> re.split('(\W+)', '...words, words...') >> ['', '...', 'words', ', ', 'words', '...', ''] >> >> so all non-word separator sequences are preserved and written back out >> (as they will not match delete set). >> >> -- >> Terry Jan Reedy > > re.sub is handy too: > import re > delete_list=('the','rain','in','spain') > regex = re.compile('\W' + '|'.join(delete_list) + '\W') You need parentheses around the words (I'm using non-capturing parentheses): regex = re.compile(r'\W(?:' + '|'.join(delete_list) + r')\W') otherwise you'd get: '\Wthe|rain|in|spain\W'. Even better is the word-boundary, in case there's no previous or next character: regex = re.compile(r'\b(?:' + '|'.join(delete_list) + r')\b') Raw string literals are recommended for regexes. > infile='messy' > with open(infile, 'r') as f: > for l in f: > print regex.sub('', l) From tjreedy at udel.edu Mon Sep 12 16:51:01 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 16:51:01 -0400 Subject: Idioms combining 'next(items)' and 'for item in items:' In-Reply-To: References: Message-ID: On 9/12/2011 12:55 PM, Ian Kelly wrote: > On Sun, Sep 11, 2011 at 6:45 PM, Terry Reedy wrote: >> whereas, you are right, it breaks it noisily in the body. So Ian's claim >> that StopIteration must be caught to avoid silent termination is not true. >> Thanks for pointing out what I saw but did not cognize the full implication >> of before. A better exception and an error message with an explaination >> might still be a good idea, though. > > But you can't write the function under the assumption that it will > only be called from the function body. Sigh. You are right. > The following is a slight > reorganization of your example that does exhibit the problem: > > for title in map(fix_title, ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']): > print(title) > > Output: > amazing > a Hell of a Fight > > Note that at first glance, my example would appear to be functionally > equivalent to yours -- I've merely pulled the fix_title call out of > the loop body and into the iterator. But actually they produce > different results because fix_title misbehaves by not catching the > StopIteration. You are right, non-iterators should not raise or pass on StopIteration. There are actually several reasons. 1. The manual defined StopIteration as meaning '[I have] no more values [to give you]'. This is only meaningful coming from an iterator. 2. Your particular point is that StopIteration is (almost) unique in being sometimes, but only sometimes, caught by the interpreter, rather than just by user except clauses. AttributeError is another, which has occasionally caused its own problems. But we cannot stop raising AttributeError while we can always catch StopIteration for explicit next() (and should outside of iterators). 3. In the case of grabbing the first item from an iterator, no first item is a boundary case for the expected, legal type of input. I believe boundary cases should be included in function specifications. While there may be a couple of choices as to response, that is much less than infinity. For fix_title, the choices are ValueError or ''. Any other return would be an error unless explicitly given in the specs. So the boundary case should be included in the test suite to exclude any other random response. 4. StopIteration is an artifact of the choice of implementation. Pulling the first item out before the loop is an alternative to a flag and testing within the loop. Such an implementation detail should not leak into the user's view of the function as an abstraction. If fix_title were a generator function whose instances yielded fixed title words one at a time, then the bare next() would be correct (as you noted). But it is not, and the difference is important, more important than having 'minimal clean code'. Thank you for persisting until I saw that in this context. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 12 16:53:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 16:53:24 -0400 Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4e6dc66e$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/12/2011 7:40 AM, Roy Smith wrote: > In article<4e6dc66e$0$29986$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >>> mylist = [0]*12345678901234 >> [...] >>> Apart from "Then don't do that!", is there anything I can do to prevent >>> this sort of thing in the future? Like instruct Python not to request more >>> memory than my PC has? >> >> >> For anyone who may care, I can report that ulimit under Linux will help with >> this situation. >> [...] >> Does anyone else think it would be useful for Python's memory manager to >> enforce user-settable limits? > > Not me. You've already discovered that ulimit does exactly what you > want. Why would be gained by having Python duplicate this functionality? Having it on Windows. -- Terry Jan Reedy From tjreedy at udel.edu Mon Sep 12 17:04:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 Sep 2011 17:04:50 -0400 Subject: What do you guys think about adding a method "to_json" In-Reply-To: References: Message-ID: On 9/12/2011 12:34 AM, Juan Pablo Romero M?ndez wrote: > Hello, > > What do you guys think about adding a method "to_json" to dictionaries > and sequence types? Perhaps through a module import? Negative. If this were added, why not to_yaml, to_marshal, to_pickle, to_zip, and so on. Better to have each storage or transfer class handle its own instance creation. The one to_x method that every class should have is to_string, which is spelled __str__ and inherited from object. -- Terry Jan Reedy From rhodri at wildebst.demon.co.uk Mon Sep 12 17:39:41 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 12 Sep 2011 22:39:41 +0100 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> Message-ID: On Mon, 12 Sep 2011 15:47:00 +0100, jmfauth wrote: > On 12 sep, 10:49, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> >> Even with a source code encoding, you will probably have problems with >> source files including \xe2 and other "bad" chars. Unless they happen to >> fall inside a quoted string literal, I would expect to get a >> SyntaxError. >> > > This is absurd and a complete non sense. The purpose > of a coding directive is to inform the engine, which > is processing a text file, about the "language" it > has to speak. Can be a html, py or tex file. > If you have problem, it's probably a mismatch between > your coding directive and the real coding of the > file. Typical case: ascii/utf-8 without signature. Now read what Steven wrote again. The issue is that the program contains characters that are syntactically illegal. The "engine" can be perfectly correctly translating a character as a smart quote or a non breaking space or an e-umlaut or whatever, but that doesn't make the character legal! -- Rhodri James *-* Wildebeest Herder to the Masses From rantingrick at gmail.com Mon Sep 12 18:04:15 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 12 Sep 2011 15:04:15 -0700 (PDT) Subject: PyWart: Itertools module needs attention Message-ID: ############################################################ # Quote # ############################################################ # The itertools module is great HOWEVER i believe most # # people are recreating the functionalities due to the # # insanely cryptic and/or missing examples from each # # method # ############################################################ py> print itertools.chain.__doc__ chain(*iterables) --> chain object Return a chain object whose .next() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted. ############################################################ # Quote # ############################################################ # Okay not TOO bad however this simple example would # # suffice: # ############################################################ py> list(itertools.chain([1,2], [3,[4,5],6])) [1, 2, 3, [4, 5], 6] ############################################################ # Quote # ############################################################ # Same for these... # ############################################################ py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " hello word "))) 'hello word ' py> ''.join(list(itertools.takewhile(lambda x:x==" ", " hello word "))) ' ' py> print itertools.compress.__doc__ compress(data, selectors) --> iterator over selected data Return data elements corresponding to true selector elements. Forms a shorter iterator from selected data elements using the selectors to choose the data elements. ############################################################ # Quote # ############################################################ # WTF! Would you like to define a Python "selector". Could # # it be that we should be using "selector function" or # # "predicate function" instead? # ############################################################ From nstinemates at gmail.com Mon Sep 12 18:25:49 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Mon, 12 Sep 2011 22:25:49 +0000 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 10:04 PM, rantingrick wrote: > > ############################################################ > # Quote # > ############################################################ > # The itertools module is great HOWEVER i believe most # > # people are recreating the functionalities due to the # > # insanely cryptic and/or missing examples from each # > # method # > ############################################################ > > py> print itertools.chain.__doc__ > chain(*iterables) --> chain object > Return a chain object whose .next() method returns elements from the > first iterable until it is exhausted, then elements from the next > iterable, until all of the iterables are exhausted. > > ############################################################ > # Quote # > ############################################################ > # Okay not TOO bad however this simple example would # > # suffice: # > ############################################################ > > py> list(itertools.chain([1,2], [3,[4,5],6])) > [1, 2, 3, [4, 5], 6] > > ############################################################ > # Quote # > ############################################################ > # Same for these... # > ############################################################ > > py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " hello > word "))) > 'hello word ' > py> ''.join(list(itertools.takewhile(lambda x:x==" ", " hello > word "))) > ' ' > py> print itertools.compress.__doc__ > compress(data, selectors) --> iterator over selected data > Return data elements corresponding to true selector elements. > Forms a shorter iterator from selected data elements using the > selectors to choose the data elements. > > ############################################################ > # Quote # > ############################################################ > # WTF! Would you like to define a Python "selector". Could # > # it be that we should be using "selector function" or # > # "predicate function" instead? # > ############################################################ > -- > http://mail.python.org/mailman/listinfo/python-list I'm honestly missing the point of this mail. Can you elaborate? -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Mon Sep 12 18:49:49 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 00:49:49 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: Message-ID: 2011/9/12 Alec Taylor : > Good evening, > > I have converted ODT to HTML using LibreOffice Writer, because I want > to convert from HTML to Creole using python-creole. Unfortunately I > get this error: "File "Convert to Creole.py", line 17 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 18, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details". > > Unfortunately I can't post my document yet (it's a research paper I'm > working on), but I'm sure you'll get the same result if you write up a > document in LibreOffice Writer and add some End Notes. > > How do I automate the removal of all non-ascii characters from my code? > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > It would obviously help to see the content of the line mentioned in the traceback (and probably its context); however, that value seems to correspond with ? in some European encodings, in which case it would probably be part of some quoted unicode/string literal. (at least in python 2, in python3 it could also be a name of an object in python code, the traceback seems to be the same for both cases.) cf. >>> print '\xe2'.decode("iso-8859-1") ? # and likewise for iso-8859-... 1,2,3,4; 9, 10, 14, 15, 16, some windows- encodings etc. Possibly (as previouslz suggested) adding the encoding information like iso-8859-1 or windows-1252 or others depending on other data etc. at the top of the source file might fix the error. Which would be certainly preferable to throwing all non ascii data away. Zou would add e.g. # -*- coding: iso-8859-1 -*- as the first or second line of the file. hth, vbr From ethan at stoneleaf.us Mon Sep 12 19:29:07 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 12 Sep 2011 16:29:07 -0700 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: <4E6E95C3.7010708@stoneleaf.us> Nick Stinemates wrote: > I'm honestly missing the point of this mail. rantingrick is a well-known troll, and doesn't need to have a point. Please do not feed the troll. ~Ethan~ From 1248283536 at qq.com Mon Sep 12 23:08:57 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 11:08:57 +0800 Subject: =?gbk?B?u9i4tKO6IHN0cmFuZyB0aGluZzo=?= Message-ID: i change open into open1,it's ok now import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open1,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] but i want "open" to be my data field,not open1 to be my field , how can i do? ------------------ ???? ------------------ ???: "Chris Angelico"; ????: 2011?9?6?(???) ??4:22 ???: "python-list"; ??: Re: strang thing: 2011/9/6 ???? <1248283536 at qq.com>: > file = open(filename,'r') > when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Mon Sep 12 23:12:03 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 11:12:03 +0800 Subject: =?gbk?B?u9i4tKO6IHN0cmFuZyB0aGluZzo=?= Message-ID: i change open into open1,it's ok now import os import csv for name in os.listdir('/tmp/quote/'): filename='/tmp/quote/'+name file = open(filename,'r') file.readline() for row in csv.reader(file): (date,open1,high,low,close,vol,adjclose) = (row[0], row[1], row[2], row[3],row[4], row[5], row[6]) print row[0], row[1], row[2], row[3],row[4], row[5], row[6] but i want "open" to be my data field,not open1 to be my field , how can i do? ------------------ ???? ------------------ ???: "Chris Angelico"; ????: 2011?9?6?(???) ??4:22 ???: "python-list"; ??: Re: strang thing: 2011/9/6 ???? <1248283536 at qq.com>: > file = open(filename,'r') > when i add (date,open,high,low,close,vol,adjclose) = (row[0], row[1], You're assigning to the name "open", which is shadowing the built-in of the same name. The second time through the loop, you're not calling the usual open() function, you're trying to call your string. That's what your error is telling you. Hope that helps! ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From chunuan723 at gmail.com Mon Sep 12 23:15:10 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 12 Sep 2011 20:15:10 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <14aa0131-2040-456d-9218-0200c968d166@u17g2000prc.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on. From steve+comp.lang.python at pearwood.info Mon Sep 12 23:28:33 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 13 Sep 2011 13:28:33 +1000 Subject: strang thing: References: Message-ID: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> (I sent this reply a week ago, but it seems to have disappeared. So trying again.) On Tue, 6 Sep 2011 06:18 pm ???? wrote: > when i ?add ? ?(date,open,high,low,close,vol,adjclose) = (row[0], row[1], > row[2], row[3],row[4], row[5], row[6]) change the code into Here you define a new variable called "open", which has the value of row[1]. This shadows (hides) the built-in function also called "open", so later when you do this: > ? ? file = open(filename,'r') > TypeError: 'str' object is not callable Python uses your string variable "open" instead of the built-in function. The best solution is to avoid using the name "open", instead call it "open_" (underscore at the end is the usual convention to avoid shadowing built-ins). Or "open_value" or any other appropriate name. Another solution is to save a reference to the open built-in first: my_open = open open = "something" file = my_open("filename", "r") -- Steven From rosuav at gmail.com Mon Sep 12 23:42:56 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 13 Sep 2011 13:42:56 +1000 Subject: strang thing: In-Reply-To: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e6ecde2$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Sep 13, 2011 at 1:28 PM, Steven D'Aprano wrote: > The best solution is to avoid using the name "open", instead call it "open_" > (underscore at the end is the usual convention to avoid shadowing > built-ins). Or "open_value" or any other appropriate name. > This is why every good programmer keeps a thesaurus handy. I just now had a "concept collision" on the word 'cancel', and did a quick search to come up with 'annul' as an alternative. Although in this case I didn't search my thesaurus, I actually looked for Magic: The Gathering cards... yeah, I'm a nerd, aren't you? :) There's lots of synonyms for open, and it's entirely possible that one will work. Otherwise, Steven's other solution works just fine too, and you can go humorous with that too: sesame = open open = "something" file = sesame("filename", "r") ChrisA From anbumani923 at gmail.com Tue Sep 13 00:12:39 2011 From: anbumani923 at gmail.com (anbu) Date: Mon, 12 Sep 2011 21:12:39 -0700 (PDT) Subject: WANTED FRESHER IT,CSC,CIVIL,MECH Message-ID: http://123maza.com/65/cute540/ From sillyousu at gmail.com Tue Sep 13 00:20:54 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 12 Sep 2011 21:20:54 -0700 (PDT) Subject: =?UTF-8?Q?Should_a_beginner_do_some_coding_excises=3F_How_can_I_?= =?UTF-8?Q?find_the_sources=EF=BC=9F?= Message-ID: I'm reading "Learning Python"? Chinese version?. Before I go through the whole book, I want to do some excises matching each charter. Any tips? Any better advice? From amitatgroups at gmail.com Tue Sep 13 00:26:48 2011 From: amitatgroups at gmail.com (Amit Jain) Date: Mon, 12 Sep 2011 21:26:48 -0700 (PDT) Subject: Default Admin user on weblogic domain deleted after executing create command using WLST Message-ID: Hello All, we observed that user exactly deleted when 'create' cmd is executed: filestore = create("wlstProperties.getProperty(fileStoreName)", "FileStore") jmsServer = create("AUAJMSServer", "JMSServer") ... .. etc. http://groups.google.com/group/comp.lang.java.programmer/browse_thread/thread/1927322accdb6e6e/223e1c7cd208a86c Please suggestion... regards, Amit J. From jabba.laci at gmail.com Tue Sep 13 00:33:22 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Tue, 13 Sep 2011 00:33:22 -0400 Subject: update all python packages on Debian/Ubuntu Message-ID: Hi, I use Ubuntu and the Python packages on my system were either installed with (1) apt-get, or with (2) pip. Since the number of python packages in the Ubuntu repositories is limited, I had to install several packages with pip. Now I want to upgrade the packages that were installed with pip (and only those packages). I can collect the list of python packages: (pip freeze | cut -d = -f 1 | grep -v FIXME | xargs echo | tr ' ' '\n' >list.txt) 2>/dev/null However, if I update every package in list.txt with "pip install -U", it will also update the ones that were installed with apt-get. Since apt-get builds a database with the installed files, I'm sure it won't like that pip replaces those files. I didn't try it yet but I'm afraid it would mess up the system. So, how to upgrade the python packages correctly? Thanks, Laszlo From memilanuk at gmail.com Tue Sep 13 01:14:02 2011 From: memilanuk at gmail.com (memilanuk) Date: Mon, 12 Sep 2011 22:14:02 -0700 Subject: =?UTF-8?B?UmU6IFNob3VsZCBhIGJlZ2lubmVyIGRvIHNvbWUgY29kaW5nIGV4Y2k=?= =?UTF-8?B?c2VzPyBIb3cgY2FuIEkgZmluZCB0aGUgc291cmNlc++8nw==?= In-Reply-To: References: Message-ID: On 09/12/2011 09:20 PM, sillyou su wrote: > I'm reading "Learning Python"? Chinese version?. Before I go through > the whole book, I want to do some excises matching each charter. > Any tips? Any better advice? > For the code examples, have you tried looking up the home page for the book? Google for 'oreilly learning python' and find the correct edition that you have. If its the 4th ed (current), you should end up on a page like this: http://shop.oreilly.com/product/9780596158071.do Down in the right hand side-bar, there should be a menu 'Essential Links' and one of the options is 'Download code' or something along those lines. The link should take you to a zip file with all the code examples in the book. As far as practice exercises... maybe something like codingbat.com/python would be helpful. Its not related to the book at all, and doesn't go nearly as in depth... but its kind of neat to play with and see how your code works when someone else is grading it! (at least for me). HTH, Monte From data.2 at rediff.com Tue Sep 13 01:24:49 2011 From: data.2 at rediff.com (gaurav) Date: Mon, 12 Sep 2011 22:24:49 -0700 (PDT) Subject: Get careers in Management work. Message-ID: <5fd4f6a9-8404-4bda-a484-12bba1aefdc2@z26g2000pre.googlegroups.com> Wide ranges of careers opportunity. Management careers. http://rojgars1.webs.com/hrm.htm http://topcareer.webs.com/qualitymanagement.htm HRM, PM, marketing manager jobs and accounts jobs move to your next career start earning with manager level. http://todayvacancy.blogspot.com/2011/07/account-assistant.html http://freshersemployment.blogspot.com/2011/07/finance-management.html High-quality careers. All types of Management careers. http://sites.google.com/site/jobinmanagement/operation-management-jobs From wuwei23 at gmail.com Tue Sep 13 02:56:30 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 12 Sep 2011 23:56:30 -0700 (PDT) Subject: using python in web applications References: Message-ID: <775ad552-1452-4b32-bf93-024c6d3761ea@u6g2000prc.googlegroups.com> On Sep 10, 1:54 pm, "Littlefield, Tyler" wrote: > I'm not feeling particularly masochistic, so I do not want to develop > this project in PHP; essentially I'm looking to build a web-based MMO. Google have been promoting the use of appengine along with HTML5 & JS to produce games. One advantage of using GAE to host the server is it takes care of the scaling for you. I found these presentations fascinating: http://cc-2011-html5-games.appspot.com/#1 http://io-2011-html5-games-hr.appspot.com/#1 This article covers the process in a little more depth: http://clouddbs.blogspot.com/2011/02/how-to-write-html5-game-in-30-days-with.html Google are also aggregating platform-specific info here: http://code.google.com/games Hope this helps (and let us know when you have something to show off!) From j.reid at mail.cryst.bbk.ac.uk Tue Sep 13 03:30:42 2011 From: j.reid at mail.cryst.bbk.ac.uk (John Reid) Date: Tue, 13 Sep 2011 08:30:42 +0100 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: <1ksbq.2549$ex3.1130@newsfe30.ams2> References: <1ksbq.2549$ex3.1130@newsfe30.ams2> Message-ID: On 12/09/11 19:37, Stefaan Himpe wrote: > The simplest one to learn is web2py http://www.web2py.com > No configuration needed, just unpack and get started. > It also has very good documentation and tons of little examples to get > things done. > > The other options you mentioned are good too :) > OK I've had a look at bottle, cherrypy and web2py and they look fairly straightforward. I'll check out some more and see where I get to. Thanks for the tips, John. From limodou at gmail.com Tue Sep 13 03:45:35 2011 From: limodou at gmail.com (limodou) Date: Tue, 13 Sep 2011 15:45:35 +0800 Subject: Easiest framework to develop simple interactive web site in python? In-Reply-To: References: <1ksbq.2549$ex3.1130@newsfe30.ams2> Message-ID: On Tue, Sep 13, 2011 at 3:30 PM, John Reid wrote: > On 12/09/11 19:37, Stefaan Himpe wrote: >> >> The simplest one to learn is web2py http://www.web2py.com >> No configuration needed, just unpack and get started. >> It also has very good documentation and tons of little examples to get >> things done. >> >> The other options you mentioned are good too :) >> > > OK I've had a look at bottle, cherrypy and web2py and they look fairly > straightforward. I'll check out some more and see where I get to. Thanks for > the tips, > John. > maybe you can also try out uliweb. -- I like python! UliPad <>: http://code.google.com/p/ulipad/ UliWeb <>: http://code.google.com/p/uliweb/ My Blog: http://hi.baidu.com/limodou From wxjmfauth at gmail.com Tue Sep 13 03:49:17 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 13 Sep 2011 00:49:17 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> Message-ID: <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> On 12 sep, 23:39, "Rhodri James" wrote: > Now read what Steven wrote again. ?The issue is that the program contains ? > characters that are syntactically illegal. ?The "engine" can be perfectly ? > correctly translating a character as a smart quote or a non breaking space ? > or an e-umlaut or whatever, but that doesn't make the character legal! > Yes, you are right. I did not understand in that way. However, a small correction/precision. Illegal character do not exit. One can "only" have an ill-formed encoded code points or an illegal encoded code point representing a character/glyph. Basically, in the present case. The issue is most probably a mismatch between the coding directive and the real coding, with "no coding directive" == 'ascii'. jmf From yongyingwen at yahoo.com.cn Tue Sep 13 04:13:01 2011 From: yongyingwen at yahoo.com.cn (fashion t shirts seller) Date: Tue, 13 Sep 2011 01:13:01 -0700 (PDT) Subject: Michael Jordan 23. Message-ID: <829dc097-43c4-4192-a631-0e949715499b@x32g2000prf.googlegroups.com> In addition to the expression of this athletes foot propulsion technology that they run very fast from the other major areas, including Air Jordan 2009, satin sheets and the rear panel of nba basketball shoes, said middle layer blown-glass is a unique movement in each shoes. The silk is inspired by the belief that People Michael Jordan in basketball is very similar to the art of personal http://www.cheap-nbabasketballshoes.com/defense to defend themselves in a sport of fencing. Sheets are used to remind the importance of the defensive players wore light clothing fencers irony. Hologram of a diamond shape to be included in the ankle support and insurance, leather, also used in the nba players http://www.cheap-nbabasketballshoes.com/shoes, so that it is not only a function of the courts, but Ye Hao looked at the court. Jordan brand sports shoes, which add an additional buffer to keep athletes safe and comfortable ankle. In order to fully understand this work into the design of http://www.cheap-nbabasketballshoes.com/sports shoes, a person must do a careful observation and analysis of every part of the shoes. For example, the end including the full range of models, which helps to increase the grip, the needle in the upper two rows and deliberately sewn three rows below it in order to reflect the famous Michael Jordan 23. http://www.cheap-nbabasketballshoes.com/ From steve+comp.lang.python at pearwood.info Tue Sep 13 04:15:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 13 Sep 2011 18:15:39 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> Message-ID: <4e6f112c$0$29997$c3e8da3$5496439d@news.astraweb.com> On Tue, 13 Sep 2011 05:49 pm jmfauth wrote: > On 12 sep, 23:39, "Rhodri James" wrote: > > >> Now read what Steven wrote again. ?The issue is that the program contains >> characters that are syntactically illegal. ?The "engine" can be perfectly >> correctly translating a character as a smart quote or a non breaking >> space or an e-umlaut or whatever, but that doesn't make the character >> legal! >> > > Yes, you are right. I did not understand in that way. > > However, a small correction/precision. Illegal character > do not exit. One can "only" have an ill-formed encoded code > points or an illegal encoded code point representing a > character/glyph. You are wrong there. There are many ASCII characters which are illegal in Python source code, at least outside of comments and string literals, and possibly even there. >>> code = "x = 1 + \b 2" # all ASCII characters >>> print(code) x = 1 + 2 >>> exec(code) Traceback (most recent call last): File "", line 1, in File "", line 1 x = 1 + 2 ^ SyntaxError: invalid syntax Now, imagine that somehow a \b ASCII backspace character somehow gets introduced into your source file. When you go to run the file, or import it, you will get a SyntaxError. Changing the encoding will not help. -- Steven From wxjmfauth at gmail.com Tue Sep 13 05:04:09 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Tue, 13 Sep 2011 02:04:09 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> <98d81fe1-79df-4e37-87aa-399a78b52353@bi2g2000vbb.googlegroups.com> <44bd982b-e740-4c77-974e-aa8c9eb47d6e@y4g2000vbx.googlegroups.com> <4e6f112c$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4a674dba-078b-4353-a6ae-01c205460e91@w12g2000yqa.googlegroups.com> On 13 sep, 10:15, Steven D'Aprano wrote: The intrinsic coding of the characters is one thing, The usage of bytes stream supposed to represent a text is one another thing, jmf From sillyousu at gmail.com Tue Sep 13 06:31:06 2011 From: sillyousu at gmail.com (sillyou su) Date: Tue, 13 Sep 2011 03:31:06 -0700 (PDT) Subject: =?UTF-8?Q?Re=3A_Should_a_beginner_do_some_coding_excises=3F_How_ca?= =?UTF-8?Q?n_I_find_the_sources=EF=BC=9F?= References: Message-ID: <1ef0994b-e274-420d-8889-e26556cc7b84@h32g2000prl.googlegroups.com> On Sep 13, 1:14?pm, memilanuk wrote: > On 09/12/2011 09:20 PM, sillyou su wrote: > > > I'm reading "Learning Python"? Chinese version?. Before I go through > > the whole book, I want to do some excises matching each charter. > > Any tips? Any better advice? > > For the code examples, have you tried looking up the home page for the > book? ?Google for 'oreilly learning python' and find the correct edition > that you have. > > If its the 4th ed (current), you should end up on a page like this: > > http://shop.oreilly.com/product/9780596158071.do > > Down in the right hand side-bar, there should be a menu 'Essential > Links' and one of the options is 'Download code' or something along > those lines. ?The link should take you to a zip file with all the code > examples in the book. > > As far as practice exercises... maybe something like > codingbat.com/python would be helpful. ?Its not related to the book at > all, and doesn't go nearly as in depth... but its kind of neat to play > with and see how your code works when someone else is grading it! (at > least for me). > > HTH, > > Monte codingbat.com/python! The website is really interesting. Thank you! From 1248283536 at qq.com Tue Sep 13 07:14:15 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Tue, 13 Sep 2011 19:14:15 +0800 Subject: problem:import csv data Message-ID: import sqlite3 con = sqlite3.connect('/home/stock.db') cur = con.cursor() cur.execute('''CREATE TABLE quote (ticker TEXT,date TEXT, popen TEXT, high TEXT, low TEXT,vol TEXT,adjclose TEXT);''') i=/tmp/data.csv cur.execute('.separator "," ') cur.execute('.import %s quote' % i) con.commit() cur.close() con.close() the output is : cur.execute('.separator"," ') sqlite3.OperationalError: near ".": syntax error how to fix it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexander_naumov at opensuse.org Tue Sep 13 08:21:03 2011 From: alexander_naumov at opensuse.org (Alex Naumov) Date: Tue, 13 Sep 2011 14:21:03 +0200 Subject: send string to input of another process Message-ID: Hello everybody, I'm looking for some solution, maybe someone of you can help me. I call another process via os.system("process") and it waits for some input. I have to write a comment (for example, like using svn or git), and after that to close input (for example, like ":wq" using vim). How can I give/write this comment and put it in the input for next process (which start after)? Thanks a lot for your time and help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mimohammedimran41 at gmail.com Tue Sep 13 08:29:37 2011 From: mimohammedimran41 at gmail.com (mohammed imran) Date: Tue, 13 Sep 2011 05:29:37 -0700 (PDT) Subject: mohammedimran Message-ID: http://123maza.com/65/fun564/ From vacorama at gmail.com Tue Sep 13 08:31:59 2011 From: vacorama at gmail.com (ron) Date: Tue, 13 Sep 2011 05:31:59 -0700 (PDT) Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 12, 4:49?am, Steven D'Aprano wrote: > On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote: > > > I'm not sure what you are trying to say with the above code, but if it's > > the code that fails for you with the exception you posted, I would guess > > that the problem is in the "[more stuff here]" part, which likely contains > > a non-ASCII character. Note that you didn't declare the source file > > encoding above. Do as Gary told you. > > Even with a source code encoding, you will probably have problems with > source files including \xe2 and other "bad" chars. Unless they happen to > fall inside a quoted string literal, I would expect to get a SyntaxError. > > I have come across this myself. While I haven't really investigated in great > detail, it appears to happen when copying and pasting code from a document > (usually HTML) which uses non-breaking spaces instead of \x20 space > characters. All it takes is just one to screw things up. > > -- > Steven Depending on the load, you can do something like: "".join([x for x in string if ord(x) < 128]) It's worked great for me in cleaning input on webapps where there's a lot of copy/paste from varied sources. From miki.tebeka at gmail.com Tue Sep 13 09:09:59 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 13 Sep 2011 06:09:59 -0700 (PDT) Subject: problem:import csv data In-Reply-To: References: Message-ID: <40eaa387-16b1-4100-8998-38e90a9f615e@glegroupsg2000goo.googlegroups.com> .separator (and .import) are not SQL commands but "sqlite3" commands. You can get the same effect with the following code: with open('/tmp/data.csv') as fo: reader = csv.reader(fo) cur.executemany('INSERT INTO quote VALUES (?, ?, ?, ?, ?, ?, ?)'), reader) HTH -- Miki Tebeka http://pythonwise.blogspot.com From miki.tebeka at gmail.com Tue Sep 13 09:09:59 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 13 Sep 2011 06:09:59 -0700 (PDT) Subject: problem:import csv data In-Reply-To: References: Message-ID: <40eaa387-16b1-4100-8998-38e90a9f615e@glegroupsg2000goo.googlegroups.com> .separator (and .import) are not SQL commands but "sqlite3" commands. You can get the same effect with the following code: with open('/tmp/data.csv') as fo: reader = csv.reader(fo) cur.executemany('INSERT INTO quote VALUES (?, ?, ?, ?, ?, ?, ?)'), reader) HTH -- Miki Tebeka http://pythonwise.blogspot.com From manodec25 at gmail.com Tue Sep 13 09:22:16 2011 From: manodec25 at gmail.com (mano mano) Date: Tue, 13 Sep 2011 06:22:16 -0700 (PDT) Subject: The Usenet newsgroup news:comp.lang.python ... Message-ID: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Mikael Lyngvig accurately summarizes comp.lang.python discussion of the technical merits of Tkinter, wxPython, and Python-bound JPI. Malcolm Tredinnick ............... http://123maza.com/48/doll789/ From pavlovevidence at gmail.com Tue Sep 13 09:31:52 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 Sep 2011 06:31:52 -0700 (PDT) Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> <4E5E2BCB.5090903@simplistix.co.uk> Message-ID: <7ae217be-3069-404a-8fcc-e45f4187f30c@glegroupsg2000goo.googlegroups.com> On Wednesday, August 31, 2011 5:49:24 AM UTC-7, Benjamin Kaplan wrote: > 32-bit or 64-bit Python? A 32-bit program will crash once memory hits > 2GB. A 64-bit program will just keep consuming RAM until your computer > starts thrashing. The problem isn't your program using more RAM than > you have, just more RAM than you have free. Last time I faced a > situation like this, I just decided it was better to stick to the > 32-bit program and let it crash if it got too big. On my 64-bit Linux system, I got a memory error in under a second, no thrashing. I have no swap. It's overrated. Carl Banks From vlastimil.brom at gmail.com Tue Sep 13 09:33:00 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 15:33:00 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/13 ron : > > Depending on the load, you can do something like: > > "".join([x for x in string if ord(x) < 128]) > > It's worked great for me in cleaning input on webapps where there's a > lot of copy/paste from varied sources. > -- > http://mail.python.org/mailman/listinfo/python-list > Well, for this kind of dirty "data cleaning" you may as well use e.g. >>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") u'text with non ASCII in between ...' >>> vbr From jon at jaggersoft.com Tue Sep 13 09:34:56 2011 From: jon at jaggersoft.com (Jon Jagger) Date: Tue, 13 Sep 2011 06:34:56 -0700 (PDT) Subject: ACCU conference call for proposals Message-ID: ACCU is a non-profit organisation run by software enthusiasts for software enthusiasts. ACCU warmly invites you to propose a session for this leading software development conference. Call for Proposals - ACCU 2012 April 24-28, 2012. Barcelo Oxford Hotel, Oxford, UK Submission website: https://www.conftool.pro/accu2012/ Submission deadline: 16th of October 2011 twitter: @accu2012 #accu2012 More details can be found here http://accu.org/index.php/conferences/accu_conference_2012/accu2012_Call_for_Papers The conference has always benefited from the strength of its programme. Please help us make 2012 another successful event. Jon Jagger Conference Chair From kushal.kumaran+python at gmail.com Tue Sep 13 10:01:41 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 13 Sep 2011 19:31:41 +0530 Subject: send string to input of another process In-Reply-To: References: Message-ID: On 13 Sep 2011 17:53, "Alex Naumov" wrote: > > Hello everybody, > > I'm looking for some solution, maybe someone of you can help me. > > I call another process via os.system("process") and it waits for some input. I have to write a comment (for example, like using svn or git), and after that to close input (for example, like ":wq" using vim). > How can I give/write this comment and put it in the input for next process (which start after)? > > Take a look at the subprocess module, especially the communicate method. Note that you will not be able to script screen-oriented programs like vim using this, unless it has some mode where you can drive it by piping commands on stdin. If you want to provide commit messages, I'm sure your vc system accepts those on the command line instead. -- regards, kushal -------------- next part -------------- An HTML attachment was scrubbed... URL: From saranyamathaiyan at gmail.com Tue Sep 13 10:52:13 2011 From: saranyamathaiyan at gmail.com (saranya saran) Date: Tue, 13 Sep 2011 07:52:13 -0700 (PDT) Subject: HI YOU WILL GET EARN MORE MONEY Message-ID: open this webpage you will get more ideas Webpages: http://123maza.com/65/tiger205/ From alec.taylor6 at gmail.com Tue Sep 13 11:02:05 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 14 Sep 2011 01:02:05 +1000 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: Hmm, nothing mentioned so far works for me... Here's a very small test case: >>> python -u "Convert to Creole.py" File "Convert to Creole.py", line 1 SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details >>> Exit Code: 1 Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") On Tue, Sep 13, 2011 at 11:33 PM, Vlastimil Brom wrote: > 2011/9/13 ron : >> >> Depending on the load, you can do something like: >> >> "".join([x for x in string if ord(x) < 128]) >> >> It's worked great for me in cleaning input on webapps where there's a >> lot of copy/paste from varied sources. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Well, for this kind of dirty "data cleaning" you may as well use e.g. > >>>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") > u'text ?with non ASCII in between ...' >>>> > > vbr > -- > http://mail.python.org/mailman/listinfo/python-list > From jpiitula at ling.helsinki.fi Tue Sep 13 11:29:03 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 13 Sep 2011 18:29:03 +0300 Subject: How do I automate the removal of all non-ascii characters from my code? References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: Alec Taylor writes: > Hmm, nothing mentioned so far works for me... > > Here's a very small test case: > > >>> python -u "Convert to Creole.py" > File "Convert to Creole.py", line 1 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 1, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details > >>> Exit Code: 1 > > Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") The people who told you to declare the source code encoding in the source file would like to see Line 0. See . [1001] ruuvi$ cat ctc.py # coding=utf-8 print u'''x ? 1'''.encode("ascii", "ignore").decode("ascii") [1002] ruuvi$ python ctc.py x 1 [1003] ruuvi$ From ian.g.kelly at gmail.com Tue Sep 13 11:45:03 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 13 Sep 2011 09:45:03 -0600 Subject: PyWart: Itertools module needs attention In-Reply-To: References: Message-ID: On Mon, Sep 12, 2011 at 4:04 PM, rantingrick wrote: > > ############################################################ > # ? ? ? ? ? ? ? ? ? ? ? ? ?Quote ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ > # The itertools module is great HOWEVER i believe most ? ? # > # people are recreating the functionalities due to the ? ? # > # insanely cryptic and/or missing examples from each ? ? ? # > # method ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ Have you looked at the online itertools documentation at all? http://docs.python.org/library/itertools.html > py> ''.join(list(itertools.dropwhile(lambda x:x==" ", " ? ?hello > word ? ?"))) > 'hello word ? ?' > py> ''.join(list(itertools.takewhile(lambda x:x==" ", " ? ?hello > word ? ?"))) > ' ? ?' These are too complex to be good examples. Drop the lambda and replace it with a built-in. Also, str.join is perfectly capable of taking an iterator as its argument. There is no reason at all to construct a list first. > py> print itertools.compress.__doc__ > compress(data, selectors) --> iterator over selected data > Return data elements corresponding to true selector elements. > Forms a shorter iterator from selected data elements using the > selectors to choose the data elements. > > ############################################################ > # ? ? ? ? ? ? ? ? ? ? ? ? ?Quote ? ? ? ? ? ? ? ? ? ? ? ? ? # > ############################################################ > # WTF! Would you like to define a Python "selector". Could # > # it be that we should be using "selector function" or ? ? # > # "predicate function" instead? ? ? ? ? ? ? ? ? ? ? ? ? ? ?# > ############################################################ Notice that it says "selector elements", not "selector functions". You have misconstrued what this function does. Hint: it does not use predicates at all. I can agree though that this could probably use a simple example in the doc string. From ramit.prasad at jpmorgan.com Tue Sep 13 12:24:10 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 12:24:10 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> Written by Kayode Odeyemi Well, I did try using super(), but I got this: >>> class B(A): ... def __init__(self, module): ... super(A, self).log('system') ... >>> c = B('module') ================================================= You should be passed super the current class you want the super class of, not the type of the super class. So it should be: super(B, self).log('system') # Notice that it passed class B Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Sep 13 12:37:11 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Sep 2011 12:37:11 -0400 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Message-ID: <4E6F86B7.8080601@ieee.org> On 01/-10/-28163 02:59 PM, mano mano wrote: > Mikael Lyngvig accurately summarizes comp.lang.python discussion of > the technical merits of Tkinter, wxPython, and Python-bound JPI. > Malcolm Tredinnick ............... > > http://12......89/ > SPAM ALERT From ramit.prasad at jpmorgan.com Tue Sep 13 12:46:08 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 12:46:08 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> >You should be passed super the current class you want the super class of, not the type of the super class. So it should be: >super(B, self).log('system') # Notice that it passed class B Ugh, apologies for the poor English; my tea has not kicked in. That first line would be more understandable as: 'You should pass the current class (B) you want the super class of, not the type of the super class (A) itself. So it should be:' To clarify, by passing A to super it retrieves the definition for the base class (object) which does not have the function you are trying to access. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Tue Sep 13 12:56:55 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 13 Sep 2011 17:56:55 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Sep 13, 2011 at 5:46 PM, Prasad, Ramit wrote: > >You should be passed super the current class you want the super class of, > not the type of the super class. So it should be:**** > > >super(*B*, self).log('system') # Notice that it passed class B**** > > ** ** > > Ugh, apologies for the poor English; my tea has not kicked in.**** > > ** ** > > That first line would be more understandable as: ?You should pass the > current class (B) you want the super class of, not the type of the super > class (A) itself. So it should be:?**** > > ** ** > > To clarify, by passing A to super it retrieves the definition for the base > class (object) which does not have the function you are trying to access.* > *** > > ** ** > > Ramit > Thanks for helping me clarify on how to use super() in Py2+. That really worked! >>> class B(A): ... def __init__(self, module): ... self.module = A.log(self, module) ... print self.module # printing here is completely unnecessary in a good OOP language ... >>> c = B('system') logged >>> class B(A): ... def __init__(self, module): ... print super(B, self).log('system') # printing here is completely unnecessary in a good OOP language ... >>> c = B('system') logged >>> When an instance of a class is created, all codes within that instance block should be executed. That's my understanding of OOP. Thanks everyone! > **** > > ** ** > > ** ** > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology**** > > 712 Main Street | Houston, TX 77002**** > > work phone: 713 - 216 - 5423**** > > **** > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of securities, > accuracy and completeness of information, viruses, confidentiality, legal > privilege, and legal entity disclaimers, available at > http://www.jpmorgan.com/pages/disclosures/email. > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Sep 13 13:24:34 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 13 Sep 2011 11:24:34 -0600 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Sep 13, 2011 at 10:56 AM, Kayode Odeyemi wrote: >>>> class B(A): > ... ? ? def __init__(self, module): > ... ? ? ? ? ? ? self.module = A.log(self, module) > ... ? ? ? ? ? ? print self.module # printing here is completely unnecessary > in a good OOP language > ... >>>> c = B('system') > logged >>>> class B(A): > ... ? ? def __init__(self, module): > ... ? ? ? ? ? ? print super(B, self).log('system')?# printing here is > completely unnecessary in a good OOP language > ... >>>> c = B('system') > logged >>>> > When an instance of a class is created, all codes within that instance block > should be executed. That's my understanding of OOP. The initializer should be executed, which is what Python does. Your initializer then calls A.log, which does nothing interesting at all. My question is, what exactly is it that you intend A.log to do? As written, it does not do any logging. It merely constructs a string and then returns it. Neither constructing a string, nor returning a string, imply logging it or printing it. From vlastimil.brom at gmail.com Tue Sep 13 14:13:44 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 13 Sep 2011 20:13:44 +0200 Subject: How do I automate the removal of all non-ascii characters from my code? In-Reply-To: References: <4E6DC028.1020101@islandtraining.com> <4e6dc7b4$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/13 Alec Taylor : > Hmm, nothing mentioned so far works for me... > > Here's a very small test case: > >>>> python -u "Convert to Creole.py" > ?File "Convert to Creole.py", line 1 > SyntaxError: Non-ASCII character '\xe2' in file Convert to Creole.py > on line 1, but no encoding declared; see > http://www.python.org/peps/pep-0263.html for details >>>> Exit Code: 1 > > Line 1: a=u'''?'''.encode("ascii", "ignore").decode("ascii") > > On Tue, Sep 13, 2011 at 11:33 PM, Vlastimil Brom > wrote: >> 2011/9/13 ron : >>> >>> Depending on the load, you can do something like: >>> >>> "".join([x for x in string if ord(x) < 128]) >>> >>> It's worked great for me in cleaning input on webapps where there's a >>> lot of copy/paste from varied sources. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> Well, for this kind of dirty "data cleaning" you may as well use e.g. >> >>>>> u"?te?xt ??? wi????th??? ??no????n AS???C?????I?????I?? i???n ??bet????wee???n .??..?".encode("ascii", "ignore").decode("ascii") >> u'text ?with non ASCII in between ...' >>>>> >> >> vbr >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Ok, in that case the encoding probably would be utf-8; \xe2 is just the first part of the encoded data >>> u'?'.encode("utf-8") '\xe2\x89\xa4' >>> Setting this encoding at the beginning of the file, as mentioned before, might solve the problem while retaining the symbol in question (or you could move from syntax error to some unicode related error depending on other circumstances...). vbr From davea at ieee.org Tue Sep 13 15:31:08 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Sep 2011 15:31:08 -0400 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E6FAF7C.40406@ieee.org> On 01/-10/-28163 02:59 PM, Kayode Odeyemi wrote: > > When an instance of a class is created, all codes within that instance block > should be executed. That's my understanding of OOP. > I don't understand this phrasing at all. Could you show a specific example of something that does not execute code you think should be executed? I suspect you're just confused by things the interactive session is printing out, which are not part of the language, and work a bit differently. DaveA From dreyemi at gmail.com Tue Sep 13 15:53:18 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 13 Sep 2011 20:53:18 +0100 Subject: Invoke a superclass method from a subclass constructor In-Reply-To: <4E6FAF7C.40406@ieee.org> References: <4E6C9044.5060302@jollybox.de> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B197E2@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16B1987A@EMARC112VS01.exchad.jpmchase.net> <4E6FAF7C.40406@ieee.org> Message-ID: On Tue, Sep 13, 2011 at 8:31 PM, Dave Angel wrote: > I suspect you're just confused by things the interactive session is > printing out, which are not part of the language, and work a bit > differently. You are right. This is where I missed it. The command interface requires a print command, as against using a return statement. My apologies. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Sep 13 16:20:16 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 13 Sep 2011 21:20:16 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 Message-ID: Hi all, Unpyc3 can recreate Python3 source code from code objects, function source code from function objects, and module source code from .pyc files. The current version is able to decompile itself successfully :). It has been tested with Python3.2 only. It currently reconstructs most of Python 3 (see TODO below) constructs but probably needs to be tested more thoroughly. All feedback welcome. Unpyc3 is a single file and is available at http://code.google.com/p/unpyc3/ Example: >>> from unpyc3 import decompile >>> def foo(x, y, z=3, *args): ... global g ... for i, j in zip(x, y): ... if z == i + j or args[i] == j: ... g = i, j ... return ... >>> print(decompile(foo)) def foo(x, y, z=3, *args): global g for i, j in zip(x, y): if z == i + j or args[i] == j: g = i, j return TODO: * Support for keyword-only arguments * Handle assert statements * Show docstrings for functions and modules * Nice spacing between function/class declarations Have fun! Note: unpyc3 is totally unrelated to another project called "unpyc" which I discovered when I tried to register the same project name on google code. -- Arnaud From tjhanson at yahoo.com Tue Sep 13 16:25:06 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 13:25:06 -0700 Subject: Need some experience Message-ID: <201109131325.06524.tjhanson@yahoo.com> I have been a desktop Linux user for better than eleven years, as a hobby. Back when we still did most of our computing on desktops I even set up a rudimentary server setup in my home. Nothing fancy or anything, but I was proud of it and of the fact that it was built Microsoft free. I have no formal education in IT nor programming. Retired now, my career was finance; I was an IRS field agent. Since retiring two years ago, I have renewed my interest in software. I know some C and lately decided to learn Python. I have worked through a couple of the introductory texts and have a feeling for the OOP model, although I won't be able to call myself an experienced practitioner anytime soon. I am looking for an open source project that will allow me to develop my skills further. Financially, I'm set; I'm not looking for a job. I'm looking for some drudge work, where I can look at other peoples' code and make a contribution. Naturally I do not want to do this forever; I'm hoping to get up to speed with my skill set so I can work to more complexity later. Does anyone have some ideas that would help me? From t at jollybox.de Tue Sep 13 16:37:05 2011 From: t at jollybox.de (Thomas Jollans) Date: Tue, 13 Sep 2011 22:37:05 +0200 Subject: Need some experience In-Reply-To: <201109131325.06524.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> Message-ID: <4E6FBEF1.5020404@jollybox.de> On 13/09/11 22:25, Tim Hanson wrote: > I have been a desktop Linux user for better than eleven years, as a hobby. > Back when we still did most of our computing on desktops I even set up a > rudimentary server setup in my home. Nothing fancy or anything, but I was > proud of it and of the fact that it was built Microsoft free. I have no > formal education in IT nor programming. Retired now, my career was finance; I > was an IRS field agent. > > Since retiring two years ago, I have renewed my interest in software. I know > some C and lately decided to learn Python. I have worked through a couple of > the introductory texts and have a feeling for the OOP model, although I won't > be able to call myself an experienced practitioner anytime soon. > > I am looking for an open source project that will allow me to develop my > skills further. > > Financially, I'm set; I'm not looking for a job. I'm looking for some drudge > work, where I can look at other peoples' code and make a contribution. > Naturally I do not want to do this forever; I'm hoping to get up to speed with > my skill set so I can work to more complexity later. > > Does anyone have some ideas that would help me? This is becoming something of an FAQ - I don't suppose there's a canned response link somewhere ? ;-) I like to recommend CPython itself ? which is a bit hypocritical, as I haven't touched it in quite a while. It has a constantly overflowing bug tracker where I'm sure you can find a lot of fascinating problems that need solving. The community, I have found, is welcoming and friendly. Much of the standard library is written in Python, but if you know C, you can have a go at the C code as well. Thomas From tjhanson at yahoo.com Tue Sep 13 16:52:24 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 13:52:24 -0700 Subject: Need some experience In-Reply-To: <4E6FBEF1.5020404@jollybox.de> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> Message-ID: <201109131352.25059.tjhanson@yahoo.com> On Tuesday, September 13, 2011 01:37:05 pm Thomas Jollans wrote: > On 13/09/11 22:25, Tim Hanson wrote: > > I have been a desktop Linux user for better than eleven years, as a > > hobby. Back when we still did most of our computing on desktops I even > > set up a rudimentary server setup in my home. Nothing fancy or > > anything, but I was proud of it and of the fact that it was built > > Microsoft free. I have no formal education in IT nor programming. > > Retired now, my career was finance; I was an IRS field agent. > > > > Since retiring two years ago, I have renewed my interest in software. I > > know some C and lately decided to learn Python. I have worked through a > > couple of the introductory texts and have a feeling for the OOP model, > > although I won't be able to call myself an experienced practitioner > > anytime soon. > > > > I am looking for an open source project that will allow me to develop my > > skills further. > > > > Financially, I'm set; I'm not looking for a job. I'm looking for some > > drudge work, where I can look at other peoples' code and make a > > contribution. Naturally I do not want to do this forever; I'm hoping to > > get up to speed with my skill set so I can work to more complexity > > later. > > > > Does anyone have some ideas that would help me? > > This is becoming something of an FAQ - I don't suppose there's a canned > response link somewhere ? ;-) > > I like to recommend CPython itself ? which is a bit hypocritical, as I > haven't touched it in quite a while. It has a constantly overflowing bug > tracker where I'm sure you can find a lot of fascinating problems that > need solving. The community, I have found, is welcoming and friendly. > Much of the standard library is written in Python, but if you know C, > you can have a go at the C code as well. > > Thomas That's not a bad idea. From the past I know that bug fixing is a great way to learn a language. If you know a specific site to key in on, feel free to send me there. Otherwise I'll poke around the Python site and find it. From tjhanson at yahoo.com Tue Sep 13 17:14:45 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 14:14:45 -0700 Subject: Need some experience In-Reply-To: <4E6FBEF1.5020404@jollybox.de> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> Message-ID: <201109131414.45610.tjhanson@yahoo.com> On Tuesday, September 13, 2011 01:37:05 pm Thomas Jollans wrote: > On 13/09/11 22:25, Tim Hanson wrote: > > I have been a desktop Linux user for better than eleven years, as a > > hobby. Back when we still did most of our computing on desktops I even > > set up a rudimentary server setup in my home. Nothing fancy or > > anything, but I was proud of it and of the fact that it was built > > Microsoft free. I have no formal education in IT nor programming. > > Retired now, my career was finance; I was an IRS field agent. > > > > Since retiring two years ago, I have renewed my interest in software. I > > know some C and lately decided to learn Python. I have worked through a > > couple of the introductory texts and have a feeling for the OOP model, > > although I won't be able to call myself an experienced practitioner > > anytime soon. > > > > I am looking for an open source project that will allow me to develop my > > skills further. > > > > Financially, I'm set; I'm not looking for a job. I'm looking for some > > drudge work, where I can look at other peoples' code and make a > > contribution. Naturally I do not want to do this forever; I'm hoping to > > get up to speed with my skill set so I can work to more complexity > > later. > > > > Does anyone have some ideas that would help me? > > This is becoming something of an FAQ - I don't suppose there's a canned > response link somewhere ? ;-) > > I like to recommend CPython itself ? which is a bit hypocritical, as I > haven't touched it in quite a while. It has a constantly overflowing bug > tracker where I'm sure you can find a lot of fascinating problems that > need solving. The community, I have found, is welcoming and friendly. > Much of the standard library is written in Python, but if you know C, > you can have a go at the C code as well. > > Thomas Never mind. I found it. From lists at cheimes.de Tue Sep 13 17:36:52 2011 From: lists at cheimes.de (Christian Heimes) Date: Tue, 13 Sep 2011 23:36:52 +0200 Subject: Need some experience In-Reply-To: <201109131352.25059.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> <4E6FBEF1.5020404@jollybox.de> <201109131352.25059.tjhanson@yahoo.com> Message-ID: Am 13.09.2011 22:52, schrieb Tim Hanson: > That's not a bad idea. From the past I know that bug fixing is a great way to > learn a language. If you know a specific site to key in on, feel free to send > me there. Otherwise I'll poke around the Python site and find it. It's a great idea. We are always looking for volunteers that help the community to reduce the amount of open bugs. The bug tracker at http://bugs.python.org/ even has a category for beginners. You just have to search for keyword -> easy and you'll get a bunch of low hanging fruits to pick from. From tjhanson at yahoo.com Tue Sep 13 18:09:42 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 15:09:42 -0700 Subject: Need some experience In-Reply-To: References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> Message-ID: <201109131509.42974.tjhanson@yahoo.com> On Tuesday, September 13, 2011 02:36:52 pm Christian Heimes wrote: > Am 13.09.2011 22:52, schrieb Tim Hanson: > > That's not a bad idea. From the past I know that bug fixing is a great > > way to learn a language. If you know a specific site to key in on, feel > > free to send me there. Otherwise I'll poke around the Python site and > > find it. > > It's a great idea. We are always looking for volunteers that help the > community to reduce the amount of open bugs. The bug tracker at > http://bugs.python.org/ even has a category for beginners. You just have > to search for keyword -> easy and you'll get a bunch of low hanging > fruits to pick from. This is exactly what I'm looking for. I don't know who is the "volunteer" here, me for obvious reasons, or the Python community for doing some free hand-holding. Now I know how I'll spend the next year. Thank you! From jack.bates at gmail.com Tue Sep 13 18:27:32 2011 From: jack.bates at gmail.com (Jack Bates) Date: Tue, 13 Sep 2011 15:27:32 -0700 Subject: ImportError: cannot import name dns Message-ID: Why is the following ImportError raised? $ ./test Traceback (most recent call last): File "./test", line 3, in from foo import dns File "/home/jablko/foo/dns.py", line 1, in from foo import udp File "/home/jablko/foo/udp.py", line 1, in from foo import dns ImportError: cannot import name dns $ I reproduce this error with the following four files and five lines: == foo/dns.py == from foo import udp == foo/udp.py == from foo import dns == foo/__init__.py == (empty) == test == #!/usr/bin/env python from foo import dns From ben+python at benfinney.id.au Tue Sep 13 18:37:02 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 14 Sep 2011 08:37:02 +1000 Subject: Need some experience References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> Message-ID: <87y5xsjchd.fsf@benfinney.id.au> Tim Hanson writes: > On Tuesday, September 13, 2011 02:36:52 pm Christian Heimes wrote: > > We are always looking for volunteers that help the community to > > reduce the amount of open bugs. The bug tracker at > > http://bugs.python.org/ even has a category for beginners. You just > > have to search for keyword -> easy and you'll get a bunch of low > > hanging fruits to pick from. > > This is exactly what I'm looking for. I don't know who is the "volunteer" > here, me for obvious reasons, or the Python community for doing some free > hand-holding. Now I know how I'll spend the next year. Thank you! Excellent attitude. Thank you in advance for contributing to the Python community. -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From ben+python at benfinney.id.au Tue Sep 13 18:40:35 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 14 Sep 2011 08:40:35 +1000 Subject: The Usenet newsgroup news:comp.lang.python ... References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> Message-ID: <87ty8gjcbg.fsf@benfinney.id.au> mano mano writes: > Mikael Lyngvig accurately summarizes comp.lang.python discussion No, you're posting spam links. Go away and spend the rest of your miserable life in a deep hole. -- \ ?If society were bound to invent technologies which could only | `\ be used entirely within the law, then we would still be sitting | _o__) in caves sucking our feet.? ?Gene Kan, creator of Gnutella | Ben Finney From ramit.prasad at jpmorgan.com Tue Sep 13 18:53:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 18:53:49 -0400 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <87ty8gjcbg.fsf@benfinney.id.au> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> <87ty8gjcbg.fsf@benfinney.id.au> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> >> Mikael Lyngvig accurately summarizes comp.lang.python discussion >No, you're posting spam links. Go away and spend the rest of your >miserable life in a deep hole. I was wondering since the text seemed like plausible non-spam (to me). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Tue Sep 13 18:58:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 14 Sep 2011 08:58:13 +1000 Subject: The Usenet newsgroup news:comp.lang.python ... In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> References: <89dd8a94-98ec-4809-884f-688038861edc@a10g2000prn.googlegroups.com> <87ty8gjcbg.fsf@benfinney.id.au> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB46E8@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, Sep 14, 2011 at 8:53 AM, Prasad, Ramit wrote: > I was wondering since the text seemed like plausible non-spam (to me). > I suspect it was autogenerated from subject lines of recent emails. It'd not be hard to design a template that covers comp.lang.* or even comp.*. ChrisA From ramit.prasad at jpmorgan.com Tue Sep 13 19:09:50 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 19:09:50 -0400 Subject: ImportError: cannot import name dns In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Jack Bates Sent: Tuesday, September 13, 2011 5:28 PM To: python-list at python.org Subject: ImportError: cannot import name dns Why is the following ImportError raised? $ ./test Traceback (most recent call last): File "./test", line 3, in from foo import dns File "/home/jablko/foo/dns.py", line 1, in from foo import udp File "/home/jablko/foo/udp.py", line 1, in from foo import dns ImportError: cannot import name dns $ I reproduce this error with the following four files and five lines: == foo/dns.py == from foo import udp == foo/udp.py == from foo import dns == foo/__init__.py == (empty) == test == #!/usr/bin/env python from foo import dns =========================================================================== It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. Circular dependency is a Bad Thing. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tjreedy at udel.edu Tue Sep 13 21:12:27 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 Sep 2011 21:12:27 -0400 Subject: Need some experience In-Reply-To: <201109131509.42974.tjhanson@yahoo.com> References: <201109131325.06524.tjhanson@yahoo.com> <201109131352.25059.tjhanson@yahoo.com> <201109131509.42974.tjhanson@yahoo.com> Message-ID: >> It's a great idea. We are always looking for volunteers that help the >> community to reduce the amount of open bugs. The bug tracker at >> http://bugs.python.org/ even has a category for beginners. You just have >> to search for keyword -> easy and you'll get a bunch of low hanging >> fruits to pick from. > > This is exactly what I'm looking for. I don't know who is the "volunteer" > here, me for obvious reasons, or the Python community for doing some free > hand-holding. Now I know how I'll spend the next year. Thank you! Also consider the core-mentorship mailing list and the dev guide at http://docs.python.org/devguide -- Terry Jan Reedy From elven199208 at gmail.com Tue Sep 13 21:19:37 2011 From: elven199208 at gmail.com (zhenzhen zhang) Date: Tue, 13 Sep 2011 18:19:37 -0700 (PDT) Subject: Offer various hats including Red Bull Hats on http://www.mlbhatshop.com/ Message-ID: Defending MX2 champion Ken is currently leading the MX2 championship while Max Nagl heads to his favourite track of the season looking for points to close the gap on fellow Red Bull Teka KTM Factory Racing team http://www.mlbhatshop.com/ rider Tony Cairoli. by red bull hats. From tjhanson at yahoo.com Tue Sep 13 21:44:41 2011 From: tjhanson at yahoo.com (Tim Hanson) Date: Tue, 13 Sep 2011 18:44:41 -0700 Subject: Need some experience In-Reply-To: References: <201109131325.06524.tjhanson@yahoo.com> <201109131509.42974.tjhanson@yahoo.com> Message-ID: <201109131844.41562.tjhanson@yahoo.com> On Tuesday, September 13, 2011 06:12:27 pm Terry Reedy wrote: > >> It's a great idea. We are always looking for volunteers that help the > >> community to reduce the amount of open bugs. The bug tracker at > >> http://bugs.python.org/ even has a category for beginners. You just have > >> to search for keyword -> easy and you'll get a bunch of low hanging > >> fruits to pick from. > > > > This is exactly what I'm looking for. I don't know who is the "volunteer" > > here, me for obvious reasons, or the Python community for doing some free > > hand-holding. Now I know how I'll spend the next year. Thank you! > > Also consider the core-mentorship mailing list and the dev guide at > http://docs.python.org/devguide This is equally helpful. Thanks! From rantingrick at gmail.com Tue Sep 13 22:08:34 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 13 Sep 2011 19:08:34 -0700 (PDT) Subject: PyWart: Itertools module needs attention References: Message-ID: <9e8eaa71-6044-422b-ac8f-d3e28ae5751f@b10g2000vbz.googlegroups.com> On Sep 13, 10:45?am, Ian Kelly wrote: > Have you looked at the online itertools documentation at all? > > http://docs.python.org/library/itertools.html Yes the online docs are much better. I really like the source code showing the inner workings of the methods. However i always get upset when i see poorly thought out doc-strings. My philosophy is that we should use the built in help function first and only visit the documentation if more instruction is needed. I may need to create another PyWart on the topic of doc-strings and how the author of these strings needs to forget everything he knows and imagine he is a complete python neophyte. I remember my initial frustrations learning about functions (in another life it seems) and my inability to grasp the concept was due to poor examples. I believe the author use the Fibonacci sequence as an example (Python docs use this example also). What an idiot! What does conditionals, linear assignment, loops, the print function, in-place addition, logic, blah, blah, have to do with understanding a function... NOTHING! The most basic and by far the best first example for functions (in any language) is this... def add(x, y): return x + y Followed by this... def sub(x,y): return x - y Simple and to the point. It simply reeks of "ah ha"! I dare anyone to create a better introductory function example. Dear Tutorial Writer: When writing tutorials please check your ego at the door. Thank you. From anacrolix at gmail.com Tue Sep 13 22:23:52 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Wed, 14 Sep 2011 12:23:52 +1000 Subject: GIL switch interval Message-ID: i'm curious as to what can be done with (and handled better) by adjusting sys.setswitchinterval i've opened a question on SO for this, that people might find of interest: http://stackoverflow.com/questions/7376776/sys-setswitchinterval-in-python-3-2-and-beyond From 1248283536 at qq.com Tue Sep 13 22:39:36 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 14 Sep 2011 10:39:36 +0800 Subject: Connection reset by peer Message-ID: there is a multi-threads program dowloading data from yahoo,the main structure is as the following(omit something unimportant ) class webdata(object): def __init__(self,name): self.jobs = Queue.Queue() if x in name: self.jobs.put(x) def download(self): try: weburl=self.jobs.get() url = weburl hx = httplib2.Http() resp, content = hx.request(url, headers=headers) print self.jobs.task_done() except: print url,"wrong" self.jobs.task_done() def run(self): for i in range(30): threading.Thread(target=self.download).start() self.jobs.join() if __name__=="__main__": webdata('quote').run() quote is a list which i want to download,i was confused ,this program can download something, can't download something, when i cancel try,except , i get the output: File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1436, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1188, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1171, in _conn_request content = response.read() File "/usr/lib/python2.7/httplib.py", line 541, in read return self._read_chunked(amt) File "/usr/lib/python2.7/httplib.py", line 590, in _read_chunked value.append(self._safe_read(chunk_left)) File "/usr/lib/python2.7/httplib.py", line 647, in _safe_read chunk = self.fp.read(min(amt, MAXAMOUNT)) File "/usr/lib/python2.7/socket.py", line 380, in read data = self._sock.recv(left) error: [Errno 104] Connection reset by peer i want to know, my computer(client) reset it ,or the yahoo (server) reset it ,what is the peer?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed Sep 14 00:12:53 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 14 Sep 2011 06:12:53 +0200 Subject: stackoverflow and c.l.py (was: GIL switch interval) In-Reply-To: References: Message-ID: Matt Joiner, 14.09.2011 04:23: > i'm curious as to what can be done with (and handled better) by > adjusting sys.setswitchinterval > i've opened a question on SO for this, that people might find of > interest: http://stackoverflow.com[...] I wonder why people ask this kind of question on stackoverflow, and then come here asking people to go over there, read the question, and (potentially) provide an answer. IMHO, c.l.py is a much better place to ask Python(-related) questions than stackoverflow. It's also a much better place to search for an answer that is already available in the archives. Stefan From steve+comp.lang.python at pearwood.info Wed Sep 14 01:35:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 15:35:37 +1000 Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> On Wed, 14 Sep 2011 02:12 pm Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. You should post that question on stackoverflow, and ask them to reply here. -- Steven From vincent.vandevyvre at swing.be Wed Sep 14 01:53:50 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 07:53:50 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: Message-ID: <4E70416E.5090208@swing.be> An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Wed Sep 14 02:08:00 2011 From: questions.anon at gmail.com (questions anon) Date: Wed, 14 Sep 2011 16:08:00 +1000 Subject: memory error Message-ID: Hello All, I keep coming across a memory error when processing many netcdf files. I assume it has something to do with how I loop things and maybe need to close things off properly. In the code below I am looping through a bunch of netcdf files (each file is hourly data for one month) and within each netcdf file I am outputting a *png file every three hours. This works for one netcdf file but when it begins to process the next netcdf file I receive this memory error: *Traceback (most recent call last): File "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", line 44, in TSFC=ncfile.variables['T_SFC'][:] File "netCDF4.pyx", line 2473, in netCDF4.Variable.__getitem__ (netCDF4.c:23094) MemoryError* To reduce processing requirements I have tried making the LAT and LON to only use [0] but I also receive an error: *Traceback (most recent call last): File "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", line 75, in x,y=map(*N.meshgrid(LON,LAT)) File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line 3256, in meshgrid numRows, numCols = len(y), len(x) # yes, reversed TypeError: len() of unsized object* finally I have added gc.collect() in a couple of places but that doesn't seem to do anything to help. I am using :*Python 2.7.2 |EPD 7.1-2 (32-bit)| (default, Jul 3 2011, 15:13:59) [MSC v.1500 32 bit (Intel)] on win32* Any feedback will be greatly appreciated! from netCDF4 import Dataset import numpy import numpy as N import matplotlib.pyplot as plt from numpy import ma as MA from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os import gc print "start processing...." inputpath=r'E:/GriddedData/Input/' outputpath=r'E:/GriddedData/Validation/' shapefile1="E:/test_GIS/DSE_REGIONS" for (path, dirs, files) in os.walk(inputpath): for dir in dirs: print dir sourcepath=os.path.join(path,dir) relativepath=os.path.relpath(sourcepath,inputpath) newdir=os.path.join(outputpath,relativepath) if not os.path.exists(newdir): os.makedirs(newdir) for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", ncfile ncfile=os.path.join(sourcepath,ncfile) #print ncfile ncfile=Dataset(ncfile, 'r+', 'NETCDF4') TSFC=ncfile.variables['T_SFC'][:,:,:] TIME=ncfile.variables['time'][:] LAT=ncfile.variables['latitude'][:] LON=ncfile.variables['longitude'][:] fillvalue=ncfile.variables['T_SFC']._FillValue TSFC=MA.masked_values(TSFC, fillvalue) ncfile.close() gc.collect() print "garbage collected" for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): print TSFC, TIME #convert time from numbers to date and prepare it to have no symbols for saving to filename cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') # compute map projection coordinates for lat/lon grid. x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title('Surface temperature at %s UTC'%ncfiletime) ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) plt.close() gc.collect() print "garbage collected again" print "end of processing" -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Wed Sep 14 02:20:04 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 07:20:04 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E70416E.5090208@swing.be> References: <4E70416E.5090208@swing.be> Message-ID: On 14 September 2011 06:53, Vincent Vande Vyvre wrote: > > Hi, trying your code, I have had numbers of errors: Hi Vincent, thanks for trying it. > ? File "unpyc3.py", line 55, in > ??? SETUP_WITH, > NameError: name 'SETUP_WITH' is not defined > > commented it > > ? File "unpyc3.py", line 58, in > ??? STORE_DEREF, DELETE_DEREF, > NameError: name 'DELETE_DEREF' is not defined > > commented it What version of Python are you running this on? This is module is written for Python 3. It looks like you're using an old version of Python (before the with statement was introduced - 2.5?) > ? File "unpyc3.py", line 96, in dec_module > ??? stream = open(pyc_path, "rb") > UnboundLocalError: local variable 'pyc_path' referenced before assignment > > change pyc_path to path Thanks, I've fixed that. -- Arnaud From ethan at stoneleaf.us Wed Sep 14 02:47:10 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 13 Sep 2011 23:47:10 -0700 Subject: stackoverflow and c.l.py In-Reply-To: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e703d2b$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E704DEE.6070603@stoneleaf.us> Steven D'Aprano wrote: > On Wed, 14 Sep 2011 02:12 pm Stefan Behnel wrote: > >> Matt Joiner, 14.09.2011 04:23: >>> i'm curious as to what can be done with (and handled better) by >>> adjusting sys.setswitchinterval >>> i've opened a question on SO for this, that people might find of >>> interest: http://stackoverflow.com[...] >> I wonder why people ask this kind of question on stackoverflow, and then >> come here asking people to go over there, read the question, and >> (potentially) provide an answer. > > You should post that question on stackoverflow, and ask them to reply here. +10! From vincent.vandevyvre at swing.be Wed Sep 14 04:13:15 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 10:13:15 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: <4E70416E.5090208@swing.be> Message-ID: <4E70621B.2000408@swing.be> An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Wed Sep 14 04:24:31 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2011 08:24:31 GMT Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and > then come here asking people to go over there, read the question, and > (potentially) provide an answer. > > IMHO, c.l.py is a much better place to ask Python(-related) questions > than stackoverflow. It's also a much better place to search for an > answer that is already available in the archives. > If you want an answer to how to get a specific bit of code to work then Stackoverflow is better if only because people can see who has already answered so don't need to waste time re-answering every trivial little question about syntax. Also there's a theory that people can search for existing answers so only one person in the class has to ask how to do their homework. I've never actually asked a question on Stackoverflow but I have found the answers to a lot of problems I've had. If you want an open-ended discussion then c.l.py is the place to go. On Stackoverflow you would likely just have the question closed pdq. -- Duncan Booth http://kupuguy.blogspot.com From t at jollybox.de Wed Sep 14 04:37:13 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 14 Sep 2011 10:37:13 +0200 Subject: Connection reset by peer In-Reply-To: References: Message-ID: <4E7067B9.2070102@jollybox.de> On 14/09/11 04:39, ???? wrote: > i want to know, my computer(client) reset it ,or the yahoo > (server) reset it ,what is the peer?? This refers to your program's peer, as in the entity it's communicating with. When you're the client, the other party (which, once the connection is established, is considered to be of equal rank - a peer) is the server. tl;dr: yahoo. From ars.rithika at gmail.com Wed Sep 14 04:42:31 2011 From: ars.rithika at gmail.com (Selvi Arul) Date: Wed, 14 Sep 2011 01:42:31 -0700 (PDT) Subject: www.brunningonline.net/simon/blog/archives/001919.html Message-ID: <4198c5fe-0444-4006-a9df-6239d56214fd@r8g2000prd.googlegroups.com> http://123maza.com/65/orange458/ From vincent.vandevyvre at swing.be Wed Sep 14 04:44:02 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 10:44:02 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E70621B.2000408@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> Message-ID: <4E706952.8000201@swing.be> An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Wed Sep 14 04:44:40 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 14 Sep 2011 18:44:40 +1000 Subject: Replace pip installed package with latest git version? Message-ID: Good evening, I've installed a version of python-creole from pip. How do I upgrade it to the latest git version? (Windows 7 x64 SP1) Thanks for all suggestions, Alec Taylor From ars.rithika at gmail.com Wed Sep 14 04:48:48 2011 From: ars.rithika at gmail.com (Selvi Arul) Date: Wed, 14 Sep 2011 01:48:48 -0700 (PDT) Subject: Python Shutdown hook comp.lang.python. My comp.lang.python post..... Message-ID: <0b5094ac-764c-4374-b58a-b53775b3e521@f24g2000prb.googlegroups.com> http://123maza.com/65/orange458/ From arnodel at gmail.com Wed Sep 14 05:31:50 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 10:31:50 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E706952.8000201@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> Message-ID: On 14 September 2011 09:44, Vincent Vande Vyvre wrote: > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' Could you show me what you do to get this error? Thank you, Arnaud PS: I've checked; DELETE_DEREF was introduced in Python3.2 From vincent.vandevyvre at swing.be Wed Sep 14 06:03:49 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Wed, 14 Sep 2011 12:03:49 +0200 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> Message-ID: <4E707C05.70103@swing.be> An HTML attachment was scrubbed... URL: From memilanuk at gmail.com Wed Sep 14 08:33:54 2011 From: memilanuk at gmail.com (memilanuk) Date: Wed, 14 Sep 2011 05:33:54 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On 09/13/2011 09:12 PM, Stefan Behnel wrote: > Matt Joiner, 14.09.2011 04:23: >> i'm curious as to what can be done with (and handled better) by >> adjusting sys.setswitchinterval >> i've opened a question on SO for this, that people might find of >> interest: http://stackoverflow.com[...] > > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. > > IMHO, c.l.py is a much better place to ask Python(-related) questions > than stackoverflow. It's also a much better place to search for an > answer that is already available in the archives. > > Stefan > Just an opinion from the unwashed masses... but I don't see the p0rn spam over on SO that I do on c.l.py, for one. I also seem to generally get better results from the search engine there, for two. Not saying one is necessarily better than the other, but just subscribing to the feed for the [python] tag on SO has a pretty good SNR... From rosuav at gmail.com Wed Sep 14 08:47:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 14 Sep 2011 22:47:15 +1000 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 10:33 PM, memilanuk wrote: > Not saying one is necessarily better than the other, but just subscribing to > the feed for the [python] tag on SO has a pretty good SNR... The SNR here isn't bad either. Most of the spam gets filtered out, and even stuff like Ranting Rick posts can be of some amusement when it's a slow day... ChrisA From memilanuk at gmail.com Wed Sep 14 09:05:23 2011 From: memilanuk at gmail.com (memilanuk) Date: Wed, 14 Sep 2011 06:05:23 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: On 09/14/2011 05:47 AM, Chris Angelico wrote: > The SNR here isn't bad either. Most of the spam gets filtered out, and > even stuff like Ranting Rick posts can be of some amusement when it's > a slow day... I subscribe to the list via Gmane, and if 'most of the spam' gets filtered out, I'd hate to see how much gets submitted as I still see 2-5 minimum blatant spam per day on here. Rick & Xang Li are two examples of what you *don't* see (or at least I don't) @ SO From anddimario at gmail.com Wed Sep 14 09:06:39 2011 From: anddimario at gmail.com (Andrea Di Mario) Date: Wed, 14 Sep 2011 15:06:39 +0200 Subject: Twisted Perspective Broker: get client ip Message-ID: Hi, i'm writing a perspective broker server. Now, i should get the client IP, that perspective broker writes well in the log. I've tried to get it from MyRealm with: mind.broker.transport.getPeer(), without success. I've tried self.transport.getPeer() to, with this result: exceptions.AttributeError: Listner instance has no attribute 'transport' It's strange, because PB wrote the client IP, infact in log i've line with: 2011-09-11 16:41:58+0200 [Broker,0,127.0.0.1] ............ Could you suggest me something? Thanks. Here the code: from OpenSSL import SSL from twisted.internet import reactor, ssl from ConfigParser import SafeConfigParser from twisted.python import log from twisted.spread import pb from twisted.cred import checkers, portal from zope.interface import implements import hashlib class Listner(pb.Avatar): def __init__(self, name): self.name = name def perspective_getDictionary(self, dictionary): print dictionary def perspective_simplyAccess(self, access): print access def verifyCallback(connection, x509, errnum, errdepth, ok): if not ok: log.msg("Certificato non valido: %s" % x509.get_subject()) return False else: log.msg("Connessione stabilita, vertificato valido: %s" % x509.get_subject()) return True class MyRealm: implements(portal.IRealm) def requestAvatar(self, avatarId, mind, *interfaces): if pb.IPerspective not in interfaces: raise NotImplementedError return pb.IPerspective, Listner(avatarId), lambda:None if __name__ == "__main__": CONFIGURATION = SafeConfigParser() CONFIGURATION.read('server.conf') PORT = CONFIGURATION.get('general', 'port') LOGFILE = CONFIGURATION.get('general', 'log') log.startLogging(open(LOGFILE,'a')) myContextFactory = ssl.DefaultOpenSSLContextFactory(CONFIGURATION.get('general', 'keypath'), CONFIGURATION.get('general', 'certpath')) ctx = myContextFactory.getContext() ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback) ctx.load_verify_locations(CONFIGURATION.get('general', 'cacert')) p = portal.Portal(MyRealm()) c = checkers.FilePasswordDB('passwords.txt', caseSensitive=True, cache=True) p.registerChecker(c) factory = pb.PBServerFactory(p) reactor.listenSSL(int(PORT), factory, myContextFactory) reactor.run() -- Andrea Di Mario From gandalf at shopzeus.com Wed Sep 14 09:08:50 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 14 Sep 2011 15:08:50 +0200 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <4E70A762.1050701@shopzeus.com> On 2011-09-14 15:05, memilanuk wrote: > > Rick & Xang Li are two examples of what you *don't* see (or at least I > don't) @ SO I knew Xang's name would come up. :-) Epic. From roy at panix.com Wed Sep 14 09:42:55 2011 From: roy at panix.com (Roy Smith) Date: Wed, 14 Sep 2011 09:42:55 -0400 Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: In article , Duncan Booth wrote: > If you want an answer to how to get a specific bit of code to work then > Stackoverflow is better if only because people can see who has already > answered so don't need to waste time re-answering every trivial little > question about syntax. Any halfway decent newsreader application will follow threading and put all the responses to a given question in one place. Of course, this is a relatively new feature. If your newsreader is any older than about the mid 1980's, it may not be able to do this. In article , Stefan Behnel wrote: > I wonder why people ask this kind of question on stackoverflow, and then > come here asking people to go over there, read the question, and > (potentially) provide an answer. If you ask here you will probably get the correct answer to your question (along with some deep dives into related topics, which are often more valuable than the original answer). If you ask on SO, you may also get the correct answer, but in addition you will earn SO karma points. Maybe even some neat badge. I guess it all depends on what your goal is. Obligatory GIL comment -- I wrote some code the other day that used 4 threads to perform 4 I/O bound operations (fetching 4 jpegs in parallel over http). I figured the fact that they were I/O bound would avoid any GIL problems. I was shocked and dismayed, however, to find that the 4 operations all got serialized. I guess I really didn't understand how the GIL worked after all. So, I rewrote it to use the multiprocessing module. Egads, still serialized! To make a long story short, it turns out we were using some crappy consumer-grade Linksys box as our DNS server, and *it* was single threaded. My 4 threads were blocking on name resolution! We moved to using a real nameserver, and I converted the code back to using threading. Works like a charm now. From alec.taylor6 at gmail.com Wed Sep 14 10:26:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 15 Sep 2011 00:26:48 +1000 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: --editable=git+https://github.com/jedie/python-creole.git is not the right forma t; it must have #egg=Package On Wed, Sep 14, 2011 at 10:54 PM, One Murithi wrote: > pip install -e > On Wed, Sep 14, 2011 at 11:44 AM, Alec Taylor > wrote: >> >> Good evening, >> >> I've installed a version of python-creole from pip. How do I upgrade >> it to the latest git version? >> >> (Windows 7 x64 SP1) >> >> Thanks for all suggestions, >> >> Alec Taylor >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From jack.bates at gmail.com Wed Sep 14 12:22:29 2011 From: jack.bates at gmail.com (Jack Bates) Date: Wed, 14 Sep 2011 09:22:29 -0700 Subject: ImportError: cannot import name dns In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> Message-ID: > It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. > > Circular dependency is a Bad Thing. According to this documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-import_stmt http://effbot.org/zone/import-confusion.htm - I thought Python would do something like: 1. check for "dns" in sys.modules (initially not found) 2. create new empty module, add it to sys.modules as "dns" 3. execute dns.py in new module namespace (executes "from foo import udp") 4. check for "udp" in sys.modules (not found) 5. create new empty module, add it to sys.modules as "udp" 6. execute udp.py in new module namespace (executes "from foo import dns") 7. check for "dns" in sys.modules (found!) 8. done executing udp.py 9. done executing dns.py So I'd expect attempting to access symbols from "dns" while executing udp.py to fail, because dns.py isn't done executing at this point. However I don't attempt to access any symbols from "dns" - so I don't expect this ImportError What is my mistake? From mickyhulse.lists at gmail.com Wed Sep 14 12:58:55 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Wed, 14 Sep 2011 09:58:55 -0700 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: Hello, On Wed, Sep 14, 2011 at 1:44 AM, Alec Taylor wrote: > I've installed a version of python-creole from pip. How do I upgrade > it to the latest git version? Not sure if you got an answer yet, but this is how I would do it: sudo pip install --upgrade git+git://github.com/jedie/python-creole.git#egg=python-creole The "sudo" may or may not be required. Hths. Cheers, Micky From mickyhulse.lists at gmail.com Wed Sep 14 13:06:35 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Wed, 14 Sep 2011 10:06:35 -0700 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 9:58 AM, Micky Hulse wrote: > Not sure if you got an answer yet, but this is how I would do it: > sudo pip install --upgrade > git+git://github.com/jedie/python-creole.git#egg=python-creole Having read your message more closely, it sounds like you did not install the package originally form github? If that's the case, I don't think using --upgrade will be of any help. Sorry 'bout that. I suppose you would have to uninstall the original PIP version: sudo pip uninstall egg-name.egg (or just the package name) ... and then: sudo pip install -e git+git://github.com/jedie/python-creole.git#egg=python-creole Although, I am not sure if that is the best way to do it. Crawling back into my hole now. :) Micky From alec.taylor6 at gmail.com Wed Sep 14 13:11:40 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 15 Sep 2011 03:11:40 +1000 Subject: Replace pip installed package with latest git version? In-Reply-To: References: Message-ID: Thanks, uninstalling first worked. :D On Thu, Sep 15, 2011 at 3:06 AM, Micky Hulse wrote: > On Wed, Sep 14, 2011 at 9:58 AM, Micky Hulse wrote: >> Not sure if you got an answer yet, but this is how I would do it: >> sudo pip install --upgrade >> git+git://github.com/jedie/python-creole.git#egg=python-creole > > Having read your message more closely, it sounds like you did not > install the package originally form github? If that's the case, I > don't think using --upgrade will be of any help. Sorry 'bout that. > > I suppose you would have to uninstall the original PIP version: > > sudo pip uninstall egg-name.egg (or just the package name) > > ... and then: > > sudo pip install -e > git+git://github.com/jedie/python-creole.git#egg=python-creole > > Although, I am not sure if that is the best way to do it. > > Crawling back into my hole now. :) > > Micky > -- > http://mail.python.org/mailman/listinfo/python-list > From janssen at parc.com Wed Sep 14 14:47:18 2011 From: janssen at parc.com (Bill Janssen) Date: Wed, 14 Sep 2011 11:47:18 PDT Subject: ANN: PyGUI 2.5 In-Reply-To: <962t3eFgd1U1@mid.individual.net> References: <962t3eFgd1U1@mid.individual.net> Message-ID: <17012.1316026038@parc.com> Gregory Ewing wrote: > Terry Reedy wrote: > > > Greg left out the most important to me: > > "Now works with Python 3 on MacOSX and Windows!" > > I'm not making too much of that at the moment, because it > *doesn't* work on Linux yet, and I've no idea how long > it will be before it does. > > The issue is that there will apparently not be any > Python 3 version of pygtk, on the grounds that gobject > introspection can be used instead. Unfortunately, > Gtk 3 and related libraries don't quite handle gobject > introspection well enough to support PyGUI at the moment. One possibility would be to develop a PyGUI branch on top of Tk, so that it would work with Python anywhere. Bill From duncan.booth at invalid.invalid Wed Sep 14 15:00:50 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Sep 2011 19:00:50 GMT Subject: stackoverflow and c.l.py (was: GIL switch interval) References: Message-ID: Roy Smith wrote: > In article , > Duncan Booth wrote: > >> If you want an answer to how to get a specific bit of code to work then >> Stackoverflow is better if only because people can see who has already >> answered so don't need to waste time re-answering every trivial little >> question about syntax. > > Any halfway decent newsreader application will follow threading and put > all the responses to a given question in one place. Of course, this is > a relatively new feature. If your newsreader is any older than about > the mid 1980's, it may not be able to do this. > Sorry, I evidently didn't make myself clear. On Usenet it could be hours before your local server updates with other posts on the thread, on Stackoverflow the answers will update live as they are posted. -- Duncan Booth http://kupuguy.blogspot.com From t at jollybox.de Wed Sep 14 15:34:38 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 14 Sep 2011 21:34:38 +0200 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <4E7101CE.7060103@jollybox.de> On 14/09/11 21:00, Duncan Booth wrote: > Roy Smith wrote: > >> In article , >> Duncan Booth wrote: >> >>> If you want an answer to how to get a specific bit of code to work then >>> Stackoverflow is better if only because people can see who has already >>> answered so don't need to waste time re-answering every trivial little >>> question about syntax. >> >> Any halfway decent newsreader application will follow threading and put >> all the responses to a given question in one place. Of course, this is >> a relatively new feature. If your newsreader is any older than about >> the mid 1980's, it may not be able to do this. >> > Sorry, I evidently didn't make myself clear. On Usenet it could be hours > before your local server updates with other posts on the thread, on > Stackoverflow the answers will update live as they are posted. The mailing list python-list, however, doesn't have this problem. (unless when people post from slow USENET servers of course...) From tim at akwebsoft.com Wed Sep 14 15:50:44 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 14 Sep 2011 11:50:44 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') Message-ID: <20110914195044.GK4331@johnsons-web.com> I have written a class that uses ftplib.FTP as the parent. I need to reconcile the modified time of a workstation file with that same filename on a remote server. Let's say we have a file called '400.shtml'. I get the mtime on my workstation by >> os.path.getmtime('400.shtml') 1311648420.0 And I use >> ftp.sendcmd('MDTM 400.shtml') ## for the remote server '213 20110726004703' My question is how to compare the two outputs? Pointers to documentation and other resources are invited. thanks -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From arnodel at gmail.com Wed Sep 14 15:51:37 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 14 Sep 2011 20:51:37 +0100 Subject: ANN: unpyc3 - a python bytecode decompiler for Python3 In-Reply-To: <4E707C05.70103@swing.be> References: <4E70416E.5090208@swing.be> <4E70621B.2000408@swing.be> <4E706952.8000201@swing.be> <4E707C05.70103@swing.be> Message-ID: On 14 September 2011 11:03, Vincent Vande Vyvre wrote: > Le 14/09/11 11:31, Arnaud Delobelle a ?crit?: [...] > Could you show me what you do to get this error? Thank you, > [vincent at myhost unpyc3]$ python > Python 3.2.1 (default, Jul 11 2011, 12:37:47) > [GCC 4.6.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from unpyc3 import decompile >>>> print (decompile("shredder.pyc")) > Traceback (most recent call last): > ? File "", line 1, in > ? File "unpyc3.py", line 110, in decompile > ??? return dec_module(obj) > ? File "unpyc3.py", line 99, in dec_module > ??? code = Code(code_obj) > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' >>>> print (decompile("unpyc3.pyc")) > Traceback (most recent call last): > ? File "", line 1, in > ? File "unpyc3.py", line 110, in decompile > ??? return dec_module(obj) > ? File "unpyc3.py", line 99, in dec_module > ??? code = Code(code_obj) > ? File "unpyc3.py", line 211, in __init__ > ??? for v in code_obj.co_cellvars + code_obj.co_freevars] > AttributeError: 'NoneType' object has no attribute 'co_cellvars' >>>> import os >>>> os.path.isfile("shredder.pyc") > True >>>> os.path.isfile("unpyc3.pyc") > True >>>> > > it seems the return of marshal.load(stream) is None I think the reason may be that your unpyc3.pyc and shredder.pyc files were compiled with a different version of python and the read_code function returns None because the magic number in the .pyc file is incorrect because of these two lines: if magic != imp.get_magic(): return None I have now changed this so that it loads the file anyway but prints a warning. I guess this may break badly though. In Python 3.2, .pyc files are "hidden" in a __pycache__ directory. So the Python 3.2 specific unpyc3.pyc file for example is probably located at .../unpyc3/__pycache__/unpyc3-cpython-32.pyc The easiest way to find the path of the .pyc file if you know the path of the .py file is probably as follows: >>> import imp >>> imp.cache_from_source("unpyc3.py") '__pycache__/unpyc3.cpython-32.pyc' Here's an example decompiling the dis module from the standard library: >>> import dis >>> dis.__file__ '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/dis.py' >>> imp.cache_from_source(dis.__file__) '/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/__pycache__/dis.cpython-32.pyc' >>> print(decompile(_)) __doc__ = 'Disassembler of Python byte code into mnemonics.' import sys import types from opcode import * from opcode import __all__ as _opcodes_all __all__ = ['code_info', 'dis', 'disassemble', 'distb', 'disco', 'findlinestarts', 'findlabels', 'show_code'] + _opcodes_all del _opcodes_all _have_code = types.MethodType, types.FunctionType, types.CodeType, type def _try_compile(source, name): try: c = compile(source, name, 'eval') except SyntaxError: c = compile(source, name, 'exec') return c [... many more lines ...] I hope this will work for you, -- Arnaud PS: I've also added support for the IMPORT_STAR opcode which I had overlooked. From badouglas at gmail.com Wed Sep 14 16:16:41 2011 From: badouglas at gmail.com (bruce) Date: Wed, 14 Sep 2011 13:16:41 -0700 Subject: libxml2dom quesiton Message-ID: Hi. Test question. Trying to see how to insert a test node into an existing dom tree. For the test, it has a TR/TD with a td[@class="foo"] that has an associated TR.. Trying to figure out how out how to insert a "

" around the tr/td in question... Curious as to how to accomplish this. Thoughts/pointers. thanks -------------------------- sample code/html chunk follows: import libxml2dom text is below tt = libxml2dom.parseString(text, html=1) t1path_=tt.xpath(t1path) aa=tt.createElement("
") print len(t1path_) for a in t1path_: tt.insertBefore(aa,None) print a.nodeName print a.toString() sys.exit() -------------------------------------------- s3== trying to get::
From ladasky at my-deja.com Wed Sep 14 16:47:50 2011 From: ladasky at my-deja.com (John Ladasky) Date: Wed, 14 Sep 2011 13:47:50 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? Message-ID: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Hi folks, Apologies if this is a bit off-topic, but there must be another Pythoneer out there who can help me navigate my current problem. I'm working with matplotlib, the Python graphing package. I need to ask some questions about it, and the place to ask those questions would appear to be the matplotlib-users discussion group. Matplotlib- users appears to be hosted on sourceforge.net (and is not mirrored anywhere else?), so I tried to sign up for an account (at https://sourceforge.net/user/registration). Yesterday, after filling out the registration page, Sourceforge rejected my registration, without any notice that I observed. Today, I tried that registration again. This time, on the upper right corner of the rejection page, I saw the following message: "your registration violated our anti-spam filter." WTF? I tried searching Sourceforge for information on what their anti-spam filter is, and how my registration could possibly have violated it. I found nothing. If anyone out there can tell me how 1) I can actually register with Sourceforge, or 2) how I might post to matplotlib-users without bothering with Sourceforge, I would be most grateful! From anikom15 at gmail.com Wed Sep 14 18:26:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 15:26:40 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <20110914222640.GA4942@Smoke> On Wed, Sep 14, 2011 at 10:47:15PM +1000, Chris Angelico wrote: > On Wed, Sep 14, 2011 at 10:33 PM, memilanuk wrote: > > Not saying one is necessarily better than the other, but just subscribing to > > the feed for the [python] tag on SO has a pretty good SNR... > > The SNR here isn't bad either. Most of the spam gets filtered out, and > even stuff like Ranting Rick posts can be of some amusement when it's > a slow day... > > ChrisA And IMO the quality of [Python] code here is better than at SO. From anikom15 at gmail.com Wed Sep 14 18:27:58 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 15:27:58 -0700 Subject: stackoverflow and c.l.py In-Reply-To: References: Message-ID: <20110914222757.GB4942@Smoke> On Wed, Sep 14, 2011 at 06:05:23AM -0700, memilanuk wrote: > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >The SNR here isn't bad either. Most of the spam gets filtered out, and > >even stuff like Ranting Rick posts can be of some amusement when it's > >a slow day... > > I subscribe to the list via Gmane, and if 'most of the spam' gets > filtered out, I'd hate to see how much gets submitted as I still see > 2-5 minimum blatant spam per day on here. > > Rick & Xang Li are two examples of what you *don't* see (or at least > I don't) @ SO > I don't understand the matter of spam and trolls. You can just delete it if you don't want it. It's not like we're getting thousands per day. From rhodri at wildebst.demon.co.uk Wed Sep 14 19:26:06 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 15 Sep 2011 00:26:06 +0100 Subject: stackoverflow and c.l.py References: Message-ID: On Wed, 14 Sep 2011 14:05:23 +0100, memilanuk wrote: > Rick & Xang Li are two examples of what you *don't* see (or at least I > don't) @ SO Then you haven't been looking hard enough ;-) -- Rhodri James *-* Wildebeest Herder to the Masses From steve+comp.lang.python at pearwood.info Wed Sep 14 19:58:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 15 Sep 2011 09:58:32 +1000 Subject: stackoverflow and c.l.py References: Message-ID: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> memilanuk wrote: > On 09/14/2011 05:47 AM, Chris Angelico wrote: >> The SNR here isn't bad either. Most of the spam gets filtered out, and >> even stuff like Ranting Rick posts can be of some amusement when it's >> a slow day... > > I subscribe to the list via Gmane, and if 'most of the spam' gets > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > minimum blatant spam per day on here. 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but still.) Since nearly all of it is obvious, it's easy to filter out of your mail client, news client, or if all else fails, your attention. The hard ones to ignore are the ones that look like they might be legitimate, but fortunately most spammers are too lazy or stupid to bother with even the most feeble disguise. Either way, I don't consider half a dozen spam posts a day to be anything more than a minor distraction. Commercial spam is annoying, but otherwise harmless because it is so easy to filter. What's really the problem is crackpots, trollers and griefers, because there is a terrible temptation to engage them in debate: "someone is wrong on the Internet!". If you want to see a news group gone bad, go to something like sci.math. You can't move for the cranks "disproving" Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 is the One True Actual Infinity (I'm not making that last one up!). -- Steven From clp2 at rebertia.com Wed Sep 14 20:41:51 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 17:41:51 -0700 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: <20110914195044.GK4331@johnsons-web.com> References: <20110914195044.GK4331@johnsons-web.com> Message-ID: On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > I have written a class that uses ftplib.FTP as the parent. > I need to reconcile the modified time of a workstation file with > that same filename on a remote server. > Let's say we have a file called '400.shtml'. I get the mtime on > my workstation by >>> os.path.getmtime('400.shtml') > 1311648420.0 http://docs.python.org/library/os.path.html#os.path.getmtime Your sample seems to be a typical Unix timestamp: http://en.wikipedia.org/wiki/Unix_time > And I use >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > '213 20110726004703' RFC 3659 - Extensions to FTP Sec 3. File Modification Time (MDTM) http://tools.ietf.org/html/rfc3659#section-3 (Note: Code 213 = File status response) > My question is how to compare the two outputs? > Pointers to documentation and other resources are invited. Cheers, Chris From du at baow.com Wed Sep 14 21:23:46 2011 From: du at baow.com (=?UTF-8?B?5paH5bGxIOadnA==?=) Date: Wed, 14 Sep 2011 18:23:46 -0700 (PDT) Subject: A documents editor in Firefox with Python Sphinx tool Message-ID: <5b7cd4f0-f3ff-49a1-af00-e899ecb1e93d@z7g2000vbp.googlegroups.com> Baow is a tool that makes it easy to organize your internet resources and create intelligent and beautiful web pages within Firefox web browser. Highlights : * Tree based outline, help you organize internet resources and documents. * Save or bookmark web images, files or pages. * Multi level project management. * Full text search. * Generate web pages by Python Sphinx tools, http://sphinx.pocoo.org . Lots of quick menus help you write and preview Python Sphinx and reStructuredText markup documents. * Multi platform support, Windows, Linux, Mac, etc. Home page: https://addons.mozilla.org/en-US/firefox/addon/baow/ From nevesagar at gmail.com Wed Sep 14 21:41:43 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 07:11:43 +0530 Subject: help regarding re.search Message-ID: Hi, I have a small program where I want to do just a small regex operation. I want to see if value of a variable 'A' is present in an another variable 'B'. The below code works fine but as soon as the variable 'A' has some string including a dot it fails. for example say: B="xxxxyyyydpkg.ipazzzzz The code works fine when A="dpkg" however the code does not work when A="dpkg.ipa" if re.search(A,B): # do something. Can somebody please help me ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nevesagar at gmail.com Wed Sep 14 21:46:06 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 07:16:06 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hi, I have a small program where I want to do just a small regex operation. I want to see if value of a variable 'A' is present in an another variable 'B'. The below code works fine but as soon as the variable 'A' has some string including a dot it fails. for example say: B="xxxxyyyydpkg.ipazzzzz The code works fine when A="dpkg" however the code does not work when A="dpkg.ipa" if re.search(A,B): # do something. Can somebody please help me ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Sep 14 21:55:12 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 18:55:12 -0700 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 6:41 PM, Sagar Neve wrote: > Hi, > I have a small program where I want to do just a small regex operation. > I want to see if value of a variable 'A' is present in an another variable > 'B'.? The below code works fine but as soon as the variable 'A' has some > string including a dot it fails. There's no need to use regexes at all! Just do: if A in B: # do something > for example say: > B="xxxxyyyydpkg.ipazzzzz > The code works fine? when A="dpkg" > however the code does not work when A="dpkg.ipa" Right, because period is a regex metacharacter. To have it treated as a literal character to match, escape it: http://docs.python.org/library/re.html#re.escape Cheers, Chris -- http://rebertia.com From chris at rebertia.com Wed Sep 14 21:57:54 2011 From: chris at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 18:57:54 -0700 Subject: Problem with Dos command by python script In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 1:13 PM, Jonatas Emidio wrote: > Here i come!! > > I have the following problem... > I need run by python script a string with some "DOS commands - Windows > prompt"!! > For exemple: > print 'cd temp' > print 'mkdir temp_app' > > How can i run this string in the python, but as a DOS interpreter? Use the `subprocess` module, and pass shell=True. http://docs.python.org/library/subprocess.html Cheers, Chris From tim at akwebsoft.com Wed Sep 14 22:02:42 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 14 Sep 2011 18:02:42 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: References: <20110914195044.GK4331@johnsons-web.com> Message-ID: <20110915020242.GL4331@johnsons-web.com> * Chris Rebert [110914 16:46]: > On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > > I have written a class that uses ftplib.FTP as the parent. > > I need to reconcile the modified time of a workstation file with > > that same filename on a remote server. > > Let's say we have a file called '400.shtml'. I get the mtime on > > my workstation by > >>> os.path.getmtime('400.shtml') > > 1311648420.0 > > http://docs.python.org/library/os.path.html#os.path.getmtime > Your sample seems to be a typical Unix timestamp: Yup. Needs to be converted to a timedate stamp, methinks. > http://en.wikipedia.org/wiki/Unix_time I'll look at that tomorrow. Late here. > > And I use > >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > > '213 20110726004703' > RFC 3659 - Extensions to FTP > Sec 3. File Modification Time (MDTM) > http://tools.ietf.org/html/rfc3659#section-3 > > (Note: Code 213 = File status response) and '213 20110726004703'[4:] should give me the string representation of the timedate stamp on the remote file. Thanks. I will look at the unix_time entry soon. -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From elven199208 at gmail.com Wed Sep 14 22:26:35 2011 From: elven199208 at gmail.com (zhenzhen zhang) Date: Wed, 14 Sep 2011 19:26:35 -0700 (PDT) Subject: Offer Red Bull Hats superior in quality and price is favourable on http://www.mlbhatshop.com/ Message-ID: <3cc9671e-37d2-4a40-9800-fac7f7a5fdd6@a7g2000yqb.googlegroups.com> MLBHatShop with Original Red Bull Hats, New Era Hats, Monster Energy Hats, Red Bull Beanies, DC Hats, Red Bull New Era Hats, Monster Beanies Sales Promotion. Door to Door Free Shipping. http://www.mlbhatshop.com/ From anikom15 at gmail.com Wed Sep 14 23:05:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 14 Sep 2011 20:05:40 -0700 Subject: stackoverflow and c.l.py In-Reply-To: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110915030540.GA5695@Smoke> On Thu, Sep 15, 2011 at 09:58:32AM +1000, Steven D'Aprano wrote: > memilanuk wrote: > > > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >> The SNR here isn't bad either. Most of the spam gets filtered out, and > >> even stuff like Ranting Rick posts can be of some amusement when it's > >> a slow day... > > > > I subscribe to the list via Gmane, and if 'most of the spam' gets > > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > > minimum blatant spam per day on here. > > 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but > still.) Since nearly all of it is obvious, it's easy to filter out of your > mail client, news client, or if all else fails, your attention. The hard > ones to ignore are the ones that look like they might be legitimate, but > fortunately most spammers are too lazy or stupid to bother with even the > most feeble disguise. > > Either way, I don't consider half a dozen spam posts a day to be anything > more than a minor distraction. > > Commercial spam is annoying, but otherwise harmless because it is so easy to > filter. What's really the problem is crackpots, trollers and griefers, > because there is a terrible temptation to engage them in debate: "someone > is wrong on the Internet!". If you want to see a news group gone bad, go to > something like sci.math. You can't move for the cranks "disproving" > Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 > is the One True Actual Infinity (I'm not making that last one up!). > > > This is really what I love and hate about the internet. It's full of people who argue for the sake of venting their internal frustrations. How many discussions comparing declarative and imperative programming languages have you seen on the web? They are everywhere. Really, there's no point to these discussions, just use what you like, but it's still fun to read and think. This goes into all kinds of subjects. That said, this post is somewhat of a rant and may spur debate. It is what it is, no matter where you are, the internet is just a natural breeder of this kind of thing. From nevesagar at gmail.com Wed Sep 14 23:33:59 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 09:03:59 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: If A in B: does nt seem to be working. Am I missing something here. -$agar On Sep 15, 2011 7:25 AM, "Chris Rebert" wrote: > On Wed, Sep 14, 2011 at 6:41 PM, Sagar Neve wrote: >> Hi, >> I have a small program where I want to do just a small regex operation. >> I want to see if value of a variable 'A' is present in an another variable >> 'B'. The below code works fine but as soon as the variable 'A' has some >> string including a dot it fails. > > There's no need to use regexes at all! Just do: > if A in B: > # do something > >> for example say: >> B="xxxxyyyydpkg.ipazzzzz >> The code works fine when A="dpkg" >> however the code does not work when A="dpkg.ipa" > > Right, because period is a regex metacharacter. To have it treated as > a literal character to match, escape it: > http://docs.python.org/library/re.html#re.escape > > Cheers, > Chris > -- > http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Sep 14 23:35:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 20:35:23 -0700 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: > If A in B: > does nt seem to be working. > Am I missing something here. Please provide a snippet of the code in question, and be specific about how it's not working. Cheers, Chris -- http://rebertia.com From greg.ewing at canterbury.ac.nz Thu Sep 15 00:28:49 2011 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 15 Sep 2011 16:28:49 +1200 Subject: ANN: PyGUI 2.5 In-Reply-To: <17012.1316026038@parc.com> References: <962t3eFgd1U1@mid.individual.net> <17012.1316026038@parc.com> Message-ID: <4E717F01.5090806@canterbury.ac.nz> On 15/09/11 06:47, Bill Janssen wrote: > One possibility would be to develop a PyGUI branch on top of Tk, so that > it would work with Python anywhere. Unfortunately, I doubt whether Tk would be up to the task of supporting PyGUI efficiently. The philosophies of model-view separation and allowing more than one view of a model are at odds with the way Tk works. Anyone who wants to have a go at it is welcome to try, though. -- Greg From nevesagar at gmail.com Thu Sep 15 00:41:53 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:11:53 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Here is the code url="http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa " Man_Param="/us/r1000" Opt_Param1="Purple" Opt_Param2="dpkg.ipa" if (Opt_Param2 in url): print "hello." else: print "bye." It gives me: ./sample.py: line 9: syntax error near unexpected token `:' ./sample.py: line 9: `if (Opt_Param2 in url): ' Help. On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: > On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: > > If A in B: > > does nt seem to be working. > > Am I missing something here. > > Please provide a snippet of the code in question, and be specific > about how it's not working. > > Cheers, > Chris > -- > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Sep 15 00:49:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 14:49:31 +1000 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 2:41 PM, Sagar Neve wrote: > ./sample.py: line 9: syntax error near unexpected token `:' > ./sample.py: line 9: `if (Opt_Param2 in url):??? ' > It worked for me in Python 3.2. What version of Python are you using? ChrisA From nevesagar at gmail.com Thu Sep 15 00:54:13 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:24:13 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: I figured it out with the sample program I gave you. It was my mistake; However, the same thing with same values is not working in my main program. Here is what I am trying: The program traverses with correct values upto the if condition we just discussed; but fails to quality that if condition; instead it should qualify. for key in dictionary: m=re.search(key, url) if m !=None: values=dictionary[key] for v in values: v_array=v.split(',') Man_Param=v_array[4] Opt_Param1=v_array[5] Opt_Param2=v_array[6] Cat=v_array[1] Man_Param=re.sub(r'"(?P.*?)"','\g', Man_Param) Opt_Param1=re.sub(r'"(?P.*?)"','\g', Opt_Param1) Opt_Param2=re.sub(r'"(?P.*?)"','\g', Opt_Param2) Cat=re.sub(r'"(?P.*?)"','\g', Cat) Cat=re.sub(r':','_', Cat) Cat=re.sub(r' ','_', Cat) print "hello..Man_Param=%s,Opt_Param1=%s, Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) #sys.exit(1) if len(Opt_Param1): if len(Opt_Param2): #if (re.search(Man_Param,url) and re.search(Opt_Param1,url) and re.search(Opt_Param2,url) ): print url * if (Man_Param in url):#and (Opt_Param1 in url) and (Opt_Param2 in url): * print "all are found..\n" sys.exit(1) if((int(cl) < 5000 or int(rc) == 206) and re.match(r"AS_D",Cat) ): Cat= Cat + "_cont" foutname = "output" + "/" + Cat +"." + str(cnt) fout =open(foutname, "a") fout.write(line) fout.close else: print "here\n"; sys.exit(1) On Thu, Sep 15, 2011 at 10:19 AM, Chris Angelico wrote: > On Thu, Sep 15, 2011 at 2:41 PM, Sagar Neve wrote: > > ./sample.py: line 9: syntax error near unexpected token `:' > > ./sample.py: line 9: `if (Opt_Param2 in url): ' > > > > It worked for me in Python 3.2. What version of Python are you using? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Thu Sep 15 00:55:19 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 15 Sep 2011 10:25:19 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 10:11 AM, Sagar Neve wrote: > Here is the code > > > url="http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa" > > Man_Param="/us/r1000" > Opt_Param1="Purple" > Opt_Param2="dpkg.ipa" > > if (Opt_Param2 in url): > ??? print "hello." > else: > ??? print "bye." > > It? gives me: > > ./sample.py: line 9: syntax error near unexpected token `:' > ./sample.py: line 9: `if (Opt_Param2 in url):??? ' > > That looks like a bash error message. Syntax errors in python show up with a stack trace. Run your program using the python interpreter like this: python file.py OR python3 file.py whatever is applicable in your environment. > > > On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: >> >> On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve wrote: >> > If A in B: >> > does nt seem to be working. >> > Am I missing something here. >> >> Please provide a snippet of the code in question, and be specific >> about how it's not working. >> -- regards, kushal From nevesagar at gmail.com Thu Sep 15 00:58:21 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 10:28:21 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Yes. It is been resolved now for the sample program. however, as mentioned in other post. It is not working in the main program On Thu, Sep 15, 2011 at 10:25 AM, Kushal Kumaran < kushal.kumaran+python at gmail.com> wrote: > On Thu, Sep 15, 2011 at 10:11 AM, Sagar Neve wrote: > > Here is the code > > > > > > url=" > http://xy.yz.com/us/r1000/012/Purple/b1/c6/e2/mzm.dxkjsfbl..d2.dpkg.ipa" > > > > Man_Param="/us/r1000" > > Opt_Param1="Purple" > > Opt_Param2="dpkg.ipa" > > > > if (Opt_Param2 in url): > > print "hello." > > else: > > print "bye." > > > > It gives me: > > > > ./sample.py: line 9: syntax error near unexpected token `:' > > ./sample.py: line 9: `if (Opt_Param2 in url): ' > > > > > > That looks like a bash error message. Syntax errors in python show up > with a stack trace. Run your program using the python interpreter > like this: > > python file.py > OR > python3 file.py > > whatever is applicable in your environment. > > > > > > > On Thu, Sep 15, 2011 at 9:05 AM, Chris Rebert wrote: > >> > >> On Wed, Sep 14, 2011 at 8:33 PM, Sagar Neve > wrote: > >> > If A in B: > >> > does nt seem to be working. > >> > Am I missing something here. > >> > >> Please provide a snippet of the code in question, and be specific > >> about how it's not working. > >> > > -- > regards, > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Sep 15 01:01:52 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 15:01:52 +1000 Subject: help regarding re.search In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 2:55 PM, Kushal Kumaran wrote: > That looks like a bash error message. ?Syntax errors in python show up > with a stack trace. ?Run your program using the python interpreter > like this: > > python file.py > OR > python3 file.py > > whatever is applicable in your environment. > Or add a shebang to the top of your script. ChrisA From python at bdurham.com Thu Sep 15 01:19:20 2011 From: python at bdurham.com (python at bdurham.com) Date: Thu, 15 Sep 2011 01:19:20 -0400 Subject: Cancel or timeout a long running regular expression Message-ID: <1316063960.26516.140258141338017@webmail.messagingengine.com> Is there a way to cancel or timeout a long running regular expression? I have a program that accepts regular expressions from users and I'm concerned about how to handle worst case regular expressions that seem to run forever. Ideally I'm looking for a way to evaluate a regular expression and timeout after a specified time period if the regular expression hasn't completed yet. Or a way for a user to cancel a long running regular expression. I was thinking there might be a technique I could use to evaluate regular expressions in a thread or another process launched via multiprocessing module and then kill the thread/process after a specified timeout period. My concern about the multiprocessing module technique is that launching a process for every regex evaluation sounds pretty inefficient. And I don't think the threading module supports the ability to kill threads from outside a thread itself. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt.pounsett at gmail.com Thu Sep 15 01:20:19 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Wed, 14 Sep 2011 22:20:19 -0700 (PDT) Subject: cause __init__ to return a different class? Message-ID: I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. I've tried both returning the subclass (as I would when overloading an operator) but I get the complaint that __init__ wants to return None instead of a type. The other thing I tried was overwriting 'self' while inside __init__ but that doesn't seem to work either. class Parent(object): def __init__(self, foo): if foo == True: self = Child(foo) class Child(Parent): def __init__(self, foo): pass Is there a way to do this? From GadgetSteve at live.co.uk Thu Sep 15 01:31:06 2011 From: GadgetSteve at live.co.uk (Gadget/Steve) Date: Thu, 15 Sep 2011 06:31:06 +0100 Subject: Problem with Dos command by python script In-Reply-To: References: Message-ID: On 14/09/2011 9:13 PM, Jonatas Emidio wrote: > Here i come!! > > I have the following problem... > I need run by python script a string with some "DOS commands - Windows > prompt"!! > For exemple: > print 'cd temp' > print 'mkdir temp_app' > > How can i run this string in the python, but as a DOS interpreter? The direct answer to your question is to tell you to take a look at the subprocess module documentation but if the above is what you would like to do then take a look as os.chdir(), os.mkdir(), os.mkdirs() and then do the above in python. I would also suggest that you should raise this sort of question at Gadget/Steve From clp2 at rebertia.com Thu Sep 15 01:35:26 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 14 Sep 2011 22:35:26 -0700 Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett wrote: > I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. ?My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. > Is there a way to do this? Override __new__() instead: http://docs.python.org/reference/datamodel.html#object.__new__ Cheers, Chris From ryan at rfk.id.au Thu Sep 15 01:54:06 2011 From: ryan at rfk.id.au (Ryan Kelly) Date: Thu, 15 Sep 2011 15:54:06 +1000 Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: <4E7192FE.7050904@rfk.id.au> On 15/09/11 15:35, Chris Rebert wrote: > On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett > wrote: >> I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified. My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass. > >> Is there a way to do this? > > Override __new__() instead: > http://docs.python.org/reference/datamodel.html#object.__new__ The above will do exactly what you want, but it's generally bad style unless you have a very specific use-case. Is there a particular reason you need to "magically" return a subclass, rather than making this explicit in the code? To be friendlier to others reading your code, I would consider using a classmethod to create an alternative constructor: class MyBaseClass(object): @classmethod def get_random_subclass(cls, *args, **kwds) subcls = random.choice(cls.__subclasses__()) return subcls(*args, **kwds) To me, this reads pretty cleanly and makes it obvious that something unusual is going on: obj = MyBaseClass.get_random_subclass() While this hides the intention of the code and would require additional documentation or comments: obj = MyBaseClass() # note: actually returns a subclass! Just a thought :-) Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From steve+comp.lang.python at pearwood.info Thu Sep 15 02:00:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 15 Sep 2011 16:00:26 +1000 Subject: cause __init__ to return a different class? References: Message-ID: <4e71947b$0$29998$c3e8da3$5496439d@news.astraweb.com> On Thu, 15 Sep 2011 03:20 pm Matthew Pounsett wrote: > I'm wondering if there's a way in python to cause __init__ to return a > class other than the one initially specified. My use case is that I'd > like to have a superclass that's capable of generating an instance of a > random subclass. You need to override the constructor, not the initializer. By the time __init__ is called, the instance has already been created. > I've tried both returning the subclass (as I would when overloading an > operator) but I get the complaint that __init__ wants to return None > instead of a type. > > The other thing I tried was overwriting 'self' while inside __init__ but > that doesn't seem to work either. No, because self is just an ordinary local variable. Overwriting self just changes the local variable, not the instance. However, you can sometimes modify the instance's class. One sometimes useful trick is something like this: class Test(object): def __init__(self): if condition(): self.__class__ = AnotherClass which will work, and is supported, so long as Test class and AnotherClass are compatible. (If they're not compatible, you'll get an exception.) -- Steven From see.my.homepage at gmail.com Thu Sep 15 02:46:09 2011 From: see.my.homepage at gmail.com (Maciej Sobczak) Date: Wed, 14 Sep 2011 23:46:09 -0700 (PDT) Subject: YAMI4 1.4.0 released Message-ID: <48755301-61d9-4a0e-8baf-52094a719b06@bl1g2000vbb.googlegroups.com> I am pleased to announce that the 1.4.0 version of YAMI4 is available for download: http://www.inspirel.com/yami4 YAMI4 is a messaging solution for distributed systems that supports Ada, C++, Java, .NET and Python. An important improvement in the Python module (both for 2.x and 3.x variants) is that the wrapping interface layer in a natively compiled module was changed so that previously known bugs in the Python standard library (ctypes) were bypassed and now the YAMI4 module should work also on 64-bit platforms. Apart from this strictly Python-related improvement, this new release bring a GUI management console that allows to browse and manage name servers, message brokers and individual agents in a bigger distributed system. -- Maciej Sobczak * http://www.msobczak.com * http://www.inspirel.com From sajuptpm at gmail.com Thu Sep 15 03:44:55 2011 From: sajuptpm at gmail.com (sajuptpm) Date: Thu, 15 Sep 2011 00:44:55 -0700 (PDT) Subject: Change Location in the google search page Message-ID: <2fb9a504-eeca-4b95-b844-cc695e63161d@l7g2000vbz.googlegroups.com> Hi, I want to open Google search page and Change the Location link in the left hand nav of Google) from the users current location to a different location, then return the results of the updated search. I tried to change google search location through http://www.google.co.in/preferences?hl=en#loc , but getting error mechanize._response.httperror_seek_wrapper: HTTP Error 404: Not Found Here is the code i tried ========================================= 1 import re import cookielib from mechanize import Browser import mechanize br1= Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br1.set_cookiejar(cj) br1.set_handle_robots(False) br1.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en- US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] P_URL = "http://www.google.co.in/preferences?hl=en#loc" s_page = br1.open(P_URL) loc_form = br1.select_form(name="langform") br1.form['luul'] = u'bangaluru' # <------ New location resp = br1.submit() print "---------resp---------",resp.read() Output ======= $ python a11.py Traceback (most recent call last): File "a11.py", line 94, in ? resp = br1.submit() File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 541, in submit File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 203, in open File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 255, in _mech_open mechanize._response.httperror_seek_wrapper: HTTP Error 404: Not Found ========================================= 2 Tried this also, but getting blank google search page. import re from mechanize import Browser LOGIN_URL = "http://www.google.co.in/search?q=new+york +locksmith&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en- US:official&client=firefox-a" br = Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] s_page = br.open(LOGIN_URL) loc_form = br.select_form(nr=1) loc_text_fld = br.form.find_control(id='lc-input') loc_text_fld.__dict__['_value'] = 'kerala' #Change the Location resp = br.submit() print "\n\n----------resp----------", resp.read() #Returning blank google search page. From gnujohn at gmail.com Thu Sep 15 04:01:37 2011 From: gnujohn at gmail.com (john) Date: Thu, 15 Sep 2011 01:01:37 -0700 (PDT) Subject: stackoverflow and c.l.py References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87120dfa-6b7d-4e03-8ff1-6926cc247cbc@bl1g2000vbb.googlegroups.com> On Sep 14, 4:58?pm, Steven D'Aprano wrote: > memilanuk wrote: > > On 09/14/2011 05:47 AM, Chris Angelico wrote: > >> The SNR here isn't bad either. Most of the spam gets filtered out, and > >> even stuff like Ranting Rick posts can be of some amusement when it's > >> a slow day... > > > I subscribe to the list via Gmane, and if 'most of the spam' gets > > filtered out, I'd hate to see how much gets submitted as I still see 2-5 > > minimum blatant spam per day on here. > > 2-5 spam posts is nothing. (Well, I know any spam is too much spam, but > still.) Since nearly all of it is obvious, it's easy to filter out of your > mail client, news client, or if all else fails, your attention. The hard > ones to ignore are the ones that look like they might be legitimate, but > fortunately most spammers are too lazy or stupid to bother with even the > most feeble disguise. > > Either way, I don't consider half a dozen spam posts a day to be anything > more than a minor distraction. > > Commercial spam is annoying, but otherwise harmless because it is so easy to > filter. What's really the problem is crackpots, trollers and griefers, > because there is a terrible temptation to engage them in debate: "someone > is wrong on the Internet!". If you want to see a news group gone bad, go to > something like sci.math. You can't move for the cranks "disproving" > Cantor's Diagonal Theorem and Special Relativity and proving that 10**603 > is the One True Actual Infinity (I'm not making that last one up!). > > -- > Steven And, all this time, I'd thought it was ((10**603) - 1) that was the highest. Oh, well. From 1248283536 at qq.com Thu Sep 15 04:28:51 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Thu, 15 Sep 2011 16:28:51 +0800 Subject: method:wrong structure Message-ID: there are three programs,all of them left main structure, code0 is ok,i don't know why code2 and code3 can't run,how to fix them? code0 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): #loadstatus={'equity':self.loadequity(),'option':self,loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() s.loadequity() code1 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): loadstatus={'equity':self.loadequity(),'option':self,loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() loadstatus['equity'] wrong output is name 'self' is not defined code2 class webdata(object): def __init__(self,arg): def loadequity(self): def loadoption(self): loadstatus={'equity':loadequity(),'option':loadoption()} def run(self): if __name__=="__main__": s=webdata('equity').run() s.loadequity() wrong output is : TypeError: loadequity() takes exactly 1 argument (0 given) -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Sep 15 04:39:48 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 15 Sep 2011 01:39:48 -0700 Subject: method:wrong structure In-Reply-To: References: Message-ID: 2011/9/15 ???? <1248283536 at qq.com>: > there are? three? programs,all of them? left? main? structure, > code0 is ok,i don't know why code2 and code3 can't run,how to fix them? > code0 > class?? webdata(object): > ??? def? __init__(self,arg): > > ??? def? loadequity(self): > > ??? def? loadoption(self): > > ??? #loadstatus={'equity':self.loadequity(),'option':self,loadoption()} > > ??? def? run(self): > > if? __name__=="__main__": > ???? s=webdata('equity').run() > ???? s.loadequity() > > code1 > class?? webdata(object): > ??? def? __init__(self,arg): > > ??? def? loadequity(self): > > ??? def? loadoption(self): > > ??? loadstatus={'equity':self.loadequity(),'option':self,loadoption()} Class definitions are executable code. So the assignment to loadstatus happens *while the class webdata is still being defined*. There is therefore no class instance object or `self` at this point, hence the error when you try and do self.loadequity(): you're trying to call an instance method before it's even possible for there to be instances of the class. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Thu Sep 15 04:39:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 15 Sep 2011 18:39:53 +1000 Subject: stackoverflow and c.l.py In-Reply-To: <20110915030540.GA5695@Smoke> References: <4e713fa9$0$29990$c3e8da3$5496439d@news.astraweb.com> <20110915030540.GA5695@Smoke> Message-ID: On Thu, Sep 15, 2011 at 1:05 PM, Westley Mart?nez wrote: > This is really what I love and hate about the internet. ?It's full of > people who argue for the sake of venting their internal frustrations. > How many discussions comparing declarative and imperative programming > languages have you seen on the web? Yes, it's both normal and useful on the internet to break off conversation to argue about a minor technicality. But it's completely inappropriate in other contexts, to the point that it can be used for comedy. Two characters, in the middle of a rather heated debate, stop to discuss grammar: "Listen - I've come to pinch her!" "Mercy! Whom?" "You mean who." "Nay! It is the accusative after the verb!" ChrisA From gelonida at gmail.com Thu Sep 15 05:05:53 2011 From: gelonida at gmail.com (Gelonida N) Date: Thu, 15 Sep 2011 11:05:53 +0200 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hi Sagar, In order to be able to help you I propose following: On 09/15/2011 06:54 AM, Sagar Neve wrote: . . . > print "hello..Man_Param=%s,Opt_Param1=%s, > Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) Change above line into > print "hello..Man_Param=%r,Opt_Param1=%r, > Opt_Param2=%r\n" %(Man_Param,Opt_Param1,Opt_Param2) and show us the output of an example which is NOT working. printing with '%r" might help to show some 'hidden special characters' From nizamov.shawkat at gmail.com Thu Sep 15 05:08:50 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Thu, 15 Sep 2011 11:08:50 +0200 Subject: method:wrong structure In-Reply-To: References: Message-ID: > > ??? loadstatus={'equity':self.loadequity(),'option':self,loadoption()} > comma instead of dot after self. From nevesagar at gmail.com Thu Sep 15 05:38:12 2011 From: nevesagar at gmail.com (Sagar Neve) Date: Thu, 15 Sep 2011 15:08:12 +0530 Subject: help regarding re.search In-Reply-To: References: Message-ID: Hey Thanks. I just resolved it and yes you are right there was a (hidden) new-line to it. I found it in a crude way of putting dots before and after. I was to post about it here and saw your message. I was not knowing about %r. Thanks for that. Thats a good addition to my knowledge. Thanks a bunch of all. My day is saved. Best Regards, Sagar Neve. On Thu, Sep 15, 2011 at 2:35 PM, Gelonida N wrote: > Hi Sagar, > > In order to be able to help you I propose following: > > On 09/15/2011 06:54 AM, Sagar Neve wrote: > . . . > > print "hello..Man_Param=%s,Opt_Param1=%s, > > Opt_Param2=%s\n" %(Man_Param,Opt_Param1,Opt_Param2) > > Change above line into > > > print "hello..Man_Param=%r,Opt_Param1=%r, > > Opt_Param2=%r\n" %(Man_Param,Opt_Param1,Opt_Param2) > > > and show us the output of an example which is NOT working. > > printing with '%r" might help to show some 'hidden special characters' > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From k.sahithi2862 at gmail.com Thu Sep 15 06:06:43 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Thu, 15 Sep 2011 03:06:43 -0700 (PDT) Subject: DEEPIKA PADUKONE IN DUM MARO DUM MOVIE Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR HOT PHOTO&VIDEOS KATRINA KAIF RARE PHOTOS http://southactresstou.blogspot.com/2011/07/katrina-kaif-wallpapers.html AISHWARYA RAI DIFFERENT PICS http://southactresstou.blogspot.com/2011/05/aishwarya-rai.html DEEPIKA PADUKONE NEW STILLS http://southactresstou.blogspot.com/2011/05/deepika-padukone_22.html SAMANTHA HOT EXCLUSIVE PHOTOS http://southactresstou.blogspot.com/2011/09/south-actress-samantha.html FOR EXCLUSIVE HOT ASIN PICS http://southactresstou.blogspot.com/2011/09/asin.html HOT SOUTH ACTRESS IN DIFFERENT DRESSES http://southactresstou.blogspot.com/2011/08/south-actress.html DOOKUDU LATEST MOVIE STILLS http://southactresstou.blogspot.com/2011/08/dookudu-movie-stills.html KAJAL LATEST ROMANTIC STILLS http://southactresstou.blogspot.com/2011/07/kajal-agarwal-in-naperu-shiva.html TAMANNA HOT PHOTOS & VIDEOS http://southactresstou.blogspot.com/2011/07/tamanna-wallpapers.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html From tartley at tartley.com Thu Sep 15 06:31:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 15 Sep 2011 03:31:16 -0700 (PDT) Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: <73c4a919-555b-453c-8cf7-eec3e645e419@glegroupsg2000goo.googlegroups.com> Perhaps a more idiomatic way of achieving the same thing is to use a factory function, which returns instances of different classes: def PersonFactory(foo): if foo: return Person() else: return Child() Apologies if the code is messed up, I'm posting from Google groups web UI. From arnodel at gmail.com Thu Sep 15 07:10:58 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 12:10:58 +0100 Subject: How does a function know the docstring of its code object? Message-ID: Hi all, You can do: def foo(): "foodoc" pass function = type(lambda:0) foo2 = function(foo.__code__, globals()) assert foo2.__doc__ == "foodoc" I am wondering how the function constructor knows that foo.__code__ has a docstring. I can see that foo.__code__.co_consts == ('foodoc',) But I can't find where in foo.__code__ is stored the information that the first constant in foo.__code__ is actually a docstring. -- Arnaud From keymint1498 at gmail.com Thu Sep 15 08:51:45 2011 From: keymint1498 at gmail.com (superhappyfuntime) Date: 15 Sep 2011 12:51:45 GMT Subject: What is wrong with this code? Message-ID: it's not running. here it is: #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. #this is defines what means what. you can just read howto.pdf instead of this part. here it is: = '\begin{document}' it's an article = '\documentclass article' it's a book = '\documentclass{book}' it's a letter = '\documentclass{letter}' it's a report = '\documentclass{report}' it's called = '\title{' it's over! = '\end{document}' #this is where you come in: type what you want below using the terms explained in howto.pdf print ('it's an article it's called test} here it is: Hello World! it's over!') -- I'm trying a new usenet client for Mac, Nemo OS X, since 0 days. You can download it at http://www.malcom-mac.com/nemo From python at mrabarnett.plus.com Thu Sep 15 09:02:27 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 15 Sep 2011 14:02:27 +0100 Subject: Turkic I and re Message-ID: <4E71F763.2010109@mrabarnett.plus.com> I'm interested to know the opinion of Turkish users of the re or regex module. When the re module performs a case-insensitive match, it matches 'I' with 'i'. In Turkish, however, it should match 'I' with '?' and '?' with 'i'. The regex module at http://pypi.python.org/pypi/regex currently uses a compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' with 'i'. I was wondering if it would be preferable to have a TURKIC flag instead ("(?T)" or "(?T:...)" in the pattern). Without the Turkic flag it would match 'I' with 'i'; with Turkic flag it would match 'I' with '?' and '?' with 'i'. From me at alanplum.com Thu Sep 15 09:16:15 2011 From: me at alanplum.com (Alan Plum) Date: Thu, 15 Sep 2011 15:16:15 +0200 Subject: Turkic I and re In-Reply-To: <4E71F763.2010109@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4E71FA9F.8090702@alanplum.com> On 2011-09-15 15:02, MRAB wrote: > The regex module at http://pypi.python.org/pypi/regex currently uses a > compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' > with 'i'. > > I was wondering if it would be preferable to have a TURKIC flag instead > ("(?T)" or "(?T:...)" in the pattern). I think the problem many people ignore when coming up with solutions like this is that while this behaviour is pretty much unique for Turkish script, there is no guarantee that Turkish substrings won't appear in other language strings (or vice versa). For example, foreign names in Turkish are often given as spelled in their native (non-Turkish) script variants. Likewise, Turkish names in other languages are often given as spelled in Turkish. The Turkish 'I' is a peculiarity that will probably haunt us programmers until hell freezes over. Unless Turkey abandons its traditional orthography or people start speaking only a single language at a time (including names), there's no easy way to deal with this. In other words: the only way to make use of your proposed flag is if you have a fully language-tagged input (e.g. an XML document making extensive use of xml:lang) and only ever apply regular expressions to substrings containing one culture at a time. From me at alanplum.com Thu Sep 15 09:24:45 2011 From: me at alanplum.com (Alan Plum) Date: Thu, 15 Sep 2011 15:24:45 +0200 Subject: using python in web applications In-Reply-To: <4E6C05CD.3010905@tysdomain.com> References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> <4E6C05CD.3010905@tysdomain.com> Message-ID: <4E71FC9D.1080603@alanplum.com> On 2011-09-11 02:50, Littlefield, Tyler wrote: > I replied to that one off list I guess, but I figured Django was way > more overhead than I wanted, doesn't really fit with solving the speed > issue. Depending on your needs, you may find something like bottle or Flask a better choice then. Django can be scaled down a lot, but it's a full-featured framework at its heart. Bottle is pretty minimal (IIRC it doesn't even come with any templating). Flask is somewhere in between as it bundles Werkzeug (a pure WSGI framework) with Jinja (a template library) with some glue code. I have used Flask in the past but often found myself implementing half of Django anyway, which is why I eventually switched. When I only need a bare API with no database and without templates, I usually go for Bottle these days. If you feel like coding closer to the metal and care more about performance than readability, you might also find Twisted useful. From roy at panix.com Thu Sep 15 09:42:33 2011 From: roy at panix.com (Roy Smith) Date: Thu, 15 Sep 2011 09:42:33 -0400 Subject: using python in web applications References: <53b67f0d-509a-46c4-83c8-7b9783ff1b5c@glegroupsg2000goo.googlegroups.com> <4E6C05CD.3010905@tysdomain.com> Message-ID: In article , Alan Plum wrote: > Django can be scaled down a lot, but it's a full-featured framework at > its heart. You can pick and chose which parts of django you want to use. You don't need to use any of the Django model stuff. You don't need to use any of the template system. You can tear out all or most of the default middleware. At that point, about all that's left is the route parser and dispatch code. The nice thing about this is that as you incrementally discover which pieces of it you really do need, it's easy to pull them in. That being said, we've made a lot of use of Tornado for small stand-alone web services with just a couple of routes. In retrospect, it's unclear if there's any justifiable argument for why we use both Tornado and Django, other than hysterical raisins. From johnjohn.tedro at gmail.com Thu Sep 15 09:44:54 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Thu, 15 Sep 2011 13:44:54 +0000 Subject: Turkic I and re In-Reply-To: <4E71FA9F.8090702@alanplum.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> Message-ID: On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum wrote: > On 2011-09-15 15:02, MRAB wrote: > >> The regex module at http://pypi.python.org/pypi/**regexcurrently uses a >> compromise, where it matches 'I' with 'i' and also 'I' with '?' and '?' >> with 'i'. >> >> I was wondering if it would be preferable to have a TURKIC flag instead >> ("(?T)" or "(?T:...)" in the pattern). >> > > I think the problem many people ignore when coming up with solutions like > this is that while this behaviour is pretty much unique for Turkish script, > there is no guarantee that Turkish substrings won't appear in other language > strings (or vice versa). > > For example, foreign names in Turkish are often given as spelled in their > native (non-Turkish) script variants. Likewise, Turkish names in other > languages are often given as spelled in Turkish. > > The Turkish 'I' is a peculiarity that will probably haunt us programmers > until hell freezes over. Unless Turkey abandons its traditional orthography > or people start speaking only a single language at a time (including names), > there's no easy way to deal with this. > > In other words: the only way to make use of your proposed flag is if you > have a fully language-tagged input (e.g. an XML document making extensive > use of xml:lang) and only ever apply regular expressions to substrings > containing one culture at a time. > > -- > http://mail.python.org/**mailman/listinfo/python-list > Python does not appear to support special cases mapping, in effect, it is not 100% compliant with the unicode standard. The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case Mappings) of the unicode standard. http://www.unicode.org/versions/Unicode6.0.0/ch05.pdf#G21180 AFAIK, the case methods of python strings seems to be built around the assumption that len("string") == len("string".upper()), but some of these casing rules require that the string grow. Like uppercasing of the german sharp s "?" which should be translated to the expanded string "SS". These special cases should be triggered on specific locales, but I have not been able to verify that the Turkic uppercasing of "i" works on either python 2.6, 2.7 or 3.1: locale.setlocale(locale.LC_ALL, "tr_TR.utf8") # warning, requires turkish locale on your system. ord("i".upper()) == 0x130 # is False for me, but should be True I wouldn't be surprised if these issues are translated into the 're' module. The only support appears to be 'L' switch, but it only makes "\w, \W, \b, \B, \s and \S dependent on the current locale". Which probably does not yield to the special rules mentioned above, but I could be wrong. Make sure that your locale is correct and test again. If you are unsuccessful, I don't see a 'Turkic flag' being introduced into re module any time soon, given the following from PEP 20 "Special cases aren't special enough to break the rules" Cheers, -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Sep 15 10:06:08 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 15 Sep 2011 15:06:08 +0100 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> Message-ID: <4E720650.8010101@mrabarnett.plus.com> On 15/09/2011 14:44, John-John Tedro wrote: > On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum > wrote: > > On 2011-09-15 15:02, MRAB wrote: > > The regex module at http://pypi.python.org/pypi/__regex > currently uses a > compromise, where it matches 'I' with 'i' and also 'I' with '?' > and '?' > with 'i'. > > I was wondering if it would be preferable to have a TURKIC flag > instead > ("(?T)" or "(?T:...)" in the pattern). > > > I think the problem many people ignore when coming up with solutions > like this is that while this behaviour is pretty much unique for > Turkish script, there is no guarantee that Turkish substrings won't > appear in other language strings (or vice versa). > > For example, foreign names in Turkish are often given as spelled in > their native (non-Turkish) script variants. Likewise, Turkish names > in other languages are often given as spelled in Turkish. > > The Turkish 'I' is a peculiarity that will probably haunt us > programmers until hell freezes over. Unless Turkey abandons its > traditional orthography or people start speaking only a single > language at a time (including names), there's no easy way to deal > with this. > > In other words: the only way to make use of your proposed flag is if > you have a fully language-tagged input (e.g. an XML document making > extensive use of xml:lang) and only ever apply regular expressions > to substrings containing one culture at a time. > > -- > http://mail.python.org/__mailman/listinfo/python-list > > > > Python does not appear to support special cases mapping, in effect, it > is not 100% compliant with the unicode standard. > > The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case > Mappings ) > of the unicode standard. > http://www.unicode.org/versions/Unicode6.0.0/ch05.pdf#G21180 > > AFAIK, the case methods of python strings seems to be built around the > assumption that len("string") == len("string".upper()), but some of > these casing rules require that the string grow. Like uppercasing of the > german sharp s "?" which should be translated to the expanded string "SS". > These special cases should be triggered on specific locales, but I have > not been able to verify that the Turkic uppercasing of "i" works on > either python 2.6, 2.7 or 3.1: > > locale.setlocale(locale.LC_ALL, "tr_TR.utf8") # warning, requires > turkish locale on your system. > ord("i".upper()) == 0x130 # is False for me, but should be True > > I wouldn't be surprised if these issues are translated into the 're' module. > There has been some discussion on the Python-dev list about improving Unicode support in Python 3. It's somewhat unlikely that Unicode will become locale-dependent in Python because it would cause problems; you don't want: "i".upper() == "I" to be maybe true, maybe false. An option would be to specify whether it should be locale-dependent. > The only support appears to be 'L' switch, but it only makes "\w, \W, > \b, \B, \s and \S dependent on the current locale". That flag is for locale-dependent 8-bit encodings. The ASCII (Python 3), LOCALE and UNICODE flags are mutually exclusive. > Which probably does not yield to the special rules mentioned above, but > I could be wrong. Make sure that your locale is correct and test again. > > If you are unsuccessful, I don't see a 'Turkic flag' being introduced > into re module any time soon, given the following from PEP 20 > "Special cases aren't special enough to break the rules" > That's why I'm interested in the view of Turkish users. The rest of us will probably never have to worry about it! :-) (There's a report in the Python bug tracker about this issue, which is why the regex module has the compromise.) From ulrich.eckhardt at dominolaser.com Thu Sep 15 10:17:18 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Thu, 15 Sep 2011 16:17:18 +0200 Subject: What is wrong with this code? References: Message-ID: <38d9k8-u8t.ln1@satorlaser.homedns.org> superhappyfuntime wrote: > #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. It's LaTeX, not Python. Uli From gordon at panix.com Thu Sep 15 10:21:41 2011 From: gordon at panix.com (John Gordon) Date: Thu, 15 Sep 2011 14:21:41 +0000 (UTC) Subject: What is wrong with this code? References: Message-ID: In superhappyfuntime writes: > it's not running. here it is: > #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > #this is defines what means what. you can just read howto.pdf instead > of this part. > here it is: = '\begin{document}' > it's an article = '\documentclass article' > it's a book = '\documentclass{book}' > it's a letter = '\documentclass{letter}' > it's a report = '\documentclass{report}' > it's called = '\title{' > it's over! = '\end{document}' > #this is where you come in: type what you want below using the terms > explained in howto.pdf > print ('it's an article it's called test} here it is: Hello World! > it's over!') You cannot use words like it's inside a single-quoted string. Either escape the word like this: it\'s or enclose the entire string in double quotes. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From matt.pounsett at gmail.com Thu Sep 15 10:41:29 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Thu, 15 Sep 2011 07:41:29 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> On Sep 15, 1:35?am, Chris Rebert wrote: > Override __new__() instead: > http://docs.python.org/reference/datamodel.html#object.__new__ Aha.. thanks! The reference book I'm working from neglects to mention __new__, so I'd assumed __init__ was the constructor. It hadn't occurred to me that python would separate the functions (I still don't see exactly why it would be useful to do that, but perhaps insight will come with time). From matt.pounsett at gmail.com Thu Sep 15 10:45:12 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Thu, 15 Sep 2011 07:45:12 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <028d3cb7-3724-42e8-b347-31eedf9ef149@i5g2000vbw.googlegroups.com> On Sep 15, 1:54?am, Ryan Kelly wrote: > The above will do exactly what you want, but it's generally bad style > unless you have a very specific use-case. ?Is there a particular reason > you need to "magically" return a subclass, rather than making this > explicit in the code? > > To be friendlier to others reading your code, I would consider using a > classmethod to create an alternative constructor: Yeah, I was considering doing this as well, particularly if I couldn't have made the other work. The reason I'm not too concerned about anyone misinterpreting what's going on is that in this case the base class is actually named for being a constructor, and any rare case where I want a specific subclass the subclass will be created directly. Thanks very much for your help! From python.list at tim.thechases.com Thu Sep 15 11:00:09 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 15 Sep 2011 10:00:09 -0500 Subject: Turkic I and re In-Reply-To: <4E720650.8010101@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> <4E720650.8010101@mrabarnett.plus.com> Message-ID: <4E7212F9.4040804@tim.thechases.com> On 09/15/11 09:06, MRAB wrote: > It's somewhat unlikely that Unicode will become locale-dependent in > Python because it would cause problems; you don't want: > > "i".upper() == "I" > > to be maybe true, maybe false. > > An option would be to specify whether it should be locale-dependent. There have been several times when I've wished that unicode strings would grow something like .locale_aware_insensitive_cmp(other[, locale=locale.getdefaultlocale()] ) to return -1/0/1 like cmp(), or in case sort-order is nonsensical/arbitrary (such as for things like Mandarin glyphs) .insensitive_locale_equal(other,[, locale=locale.getdefaultlocale()] ) so you could do something like if "i".locale_aware_insensitive_cmp("I"): not_equal() else: equal() or if "i".insensitive_locale_equal("I"): equal() else: not_equal() because while I know that .upper() or .lower() doesn't work in a lot of cases, I don't really care about the upper/lower'ness of the result, I want to do an insensitive compare (and most of teh time it's just for equality, not for sorting). It's my understanding[1] that the same goes for the German where "?".upper() is traditionally written as "SS" but "SS".lower() is traditionally just "ss" instead of "?". So if these language-dependent comparisons were relegated to a well-tested core method of a unicode string, it may simplify the work/issue for you. -tkc [1] http://en.wikipedia.org/wiki/Letter_case#Special_cases From yasar11732 at gmail.com Thu Sep 15 11:04:27 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 15 Sep 2011 18:04:27 +0300 Subject: Turkic I and re In-Reply-To: <4E720650.8010101@mrabarnett.plus.com> References: <4E71F763.2010109@mrabarnett.plus.com> <4E71FA9F.8090702@alanplum.com> <4E720650.8010101@mrabarnett.plus.com> Message-ID: Hi, I am a Turkish self-taught python user. Personally, I don't think I am in a position to discuss a issue in this scale. But in my opinion, I think pardus* developers should be invited to join to this discussion. As they are using python heavily on most of their projects** I think they would have something valueable to say about this subject. Here is the pardus-developers mailing list : http://liste.pardus.org.tr/mailman/listinfo/pardus-devel And as for me, I always expect Turkish locale might cause problems, and use some workarounds if neccessary. For example, If I needed to match lower-case or upper-case Turkish "i", I would probably go with [i?] with unicode flag. *) a linux distro developed by Scientific & Technological Research Council of Turkey **) http://developer.pardus.org.tr/projects/index.html 2011/9/15 MRAB > On 15/09/2011 14:44, John-John Tedro wrote: > >> On Thu, Sep 15, 2011 at 1:16 PM, Alan Plum > > wrote: >> >> On 2011-09-15 15:02, MRAB wrote: >> >> The regex module at http://pypi.python.org/pypi/__**regex >> > >> currently uses a >> compromise, where it matches 'I' with 'i' and also 'I' with '?' >> and '?' >> with 'i'. >> >> I was wondering if it would be preferable to have a TURKIC flag >> instead >> ("(?T)" or "(?T:...)" in the pattern). >> >> >> I think the problem many people ignore when coming up with solutions >> like this is that while this behaviour is pretty much unique for >> Turkish script, there is no guarantee that Turkish substrings won't >> appear in other language strings (or vice versa). >> >> For example, foreign names in Turkish are often given as spelled in >> their native (non-Turkish) script variants. Likewise, Turkish names >> in other languages are often given as spelled in Turkish. >> >> The Turkish 'I' is a peculiarity that will probably haunt us >> programmers until hell freezes over. Unless Turkey abandons its >> traditional orthography or people start speaking only a single >> language at a time (including names), there's no easy way to deal >> with this. >> >> In other words: the only way to make use of your proposed flag is if >> you have a fully language-tagged input (e.g. an XML document making >> extensive use of xml:lang) and only ever apply regular expressions >> to substrings containing one culture at a time. >> >> -- >> http://mail.python.org/__**mailman/listinfo/python-list >> >> > >> >> >> Python does not appear to support special cases mapping, in effect, it >> is not 100% compliant with the unicode standard. >> >> The locale specific 'i' casing in Turkic is mentioned in 5.18 (Case >> Mappings > pdf#G21180 >> >) >> >> of the unicode standard. >> http://www.unicode.org/**versions/Unicode6.0.0/ch05.**pdf#G21180 >> >> AFAIK, the case methods of python strings seems to be built around the >> assumption that len("string") == len("string".upper()), but some of >> these casing rules require that the string grow. Like uppercasing of the >> german sharp s "?" which should be translated to the expanded string "SS". >> These special cases should be triggered on specific locales, but I have >> not been able to verify that the Turkic uppercasing of "i" works on >> either python 2.6, 2.7 or 3.1: >> >> locale.setlocale(locale.LC_**ALL, "tr_TR.utf8") # warning, requires >> turkish locale on your system. >> ord("i".upper()) == 0x130 # is False for me, but should be True >> >> I wouldn't be surprised if these issues are translated into the 're' >> module. >> >> There has been some discussion on the Python-dev list about improving > Unicode support in Python 3. > > It's somewhat unlikely that Unicode will become locale-dependent in > Python because it would cause problems; you don't want: > > "i".upper() == "I" > > to be maybe true, maybe false. > > An option would be to specify whether it should be locale-dependent. > > > The only support appears to be 'L' switch, but it only makes "\w, \W, >> \b, \B, \s and \S dependent on the current locale". >> > > That flag is for locale-dependent 8-bit encodings. The ASCII (Python > 3), LOCALE and UNICODE flags are mutually exclusive. > > > Which probably does not yield to the special rules mentioned above, but >> I could be wrong. Make sure that your locale is correct and test again. >> >> If you are unsuccessful, I don't see a 'Turkic flag' being introduced >> into re module any time soon, given the following from PEP 20 >> "Special cases aren't special enough to break the rules" >> >> That's why I'm interested in the view of Turkish users. The rest of us > will probably never have to worry about it! :-) > > (There's a report in the Python bug tracker about this issue, which is > why the regex module has the compromise.) > > -- > http://mail.python.org/**mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Thu Sep 15 11:17:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 15 Sep 2011 09:17:53 -0600 Subject: How does a function know the docstring of its code object? In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 5:10 AM, Arnaud Delobelle wrote: > Hi all, > > You can do: > > def foo(): > ? ?"foodoc" > ? ?pass > > function = type(lambda:0) > foo2 = function(foo.__code__, globals()) > assert foo2.__doc__ == "foodoc" > > I am wondering how the function constructor knows that foo.__code__ > has a docstring. ?I can see that > > ? ?foo.__code__.co_consts == ('foodoc',) > > But I can't find where in foo.__code__ is stored the information that > the first constant in foo.__code__ is actually a docstring. >From what I'm seeing, it appears that if there is no docstring, the first constant will always be None. So if the first constant is a string, then it's a docstring. From Genevieve.Diagorn at open-groupe.com Thu Sep 15 11:30:11 2011 From: Genevieve.Diagorn at open-groupe.com (=?iso-8859-1?Q?Genevi=E8ve_Diagorn?=) Date: Thu, 15 Sep 2011 17:30:11 +0200 Subject: From Python on Solaris to Python on LINUX Message-ID: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Hi, I work on projects developed in Python 2.3 on Solaris. The customer asks us to pass on LINUX in a recent version of Python. Is it someone has already realized this modification? What are the traps to be avoided? Is it a long and difficult phase? What is the most recent version on LINUX? Thanks. Genevi?ve -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Thu Sep 15 11:44:46 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 16:44:46 +0100 Subject: How does a function know the docstring of its code object? In-Reply-To: References: Message-ID: On 15 September 2011 16:17, Ian Kelly wrote: > On Thu, Sep 15, 2011 at 5:10 AM, Arnaud Delobelle wrote: >> Hi all, >> >> You can do: >> >> def foo(): >> ? ?"foodoc" >> ? ?pass >> >> function = type(lambda:0) >> foo2 = function(foo.__code__, globals()) >> assert foo2.__doc__ == "foodoc" >> >> I am wondering how the function constructor knows that foo.__code__ >> has a docstring. [...] > > From what I'm seeing, it appears that if there is no docstring, the > first constant will always be None. ?So if the first constant is a > string, then it's a docstring. > Yes it seems to be the case. Even if None is not used in the function, it appears in co_consts. Good thinking! Thanks, -- Arnaud From fulvio.valente at strath.ac.uk Thu Sep 15 11:55:13 2011 From: fulvio.valente at strath.ac.uk (Fulvio Valente) Date: Thu, 15 Sep 2011 16:55:13 +0100 Subject: Request for research feedback Message-ID: <4296A2DFD9C6B4499A22AA3E585D715902D6AF01B7F1@E2K7-MS3.ds.strath.ac.uk> Hi, I am a research intern at the University of Strathclyde who has been doing a summer research internship. I hope that this is not an inappropriate place to ask, but I am looking for participants willing to use and evaluate an application that was written as part of this internship. If you choose to participate, this should only take no more than an hour or two of your time at the very most, unless you wish to not use the analysis files provided. My project is to experiment with ways of inferring and displaying socio-technical information about a software project from a version control repository by creating a prototype application. The application infers authorship information in the form of "closeness scores" between authors and the files they have worked on by traversing the history of a Mercurial repository. This is then displayed as a map of socio-technical dependencies between files and the authors that worked on them and between authors and the files they have worked on, which should allow for easy visual comparisons of closeness. Some potential applications and use cases I can envision in the program's current form include discovering who the key figures are (i.e. who to talk to about a problem) or what the bus factor (how many people need to be "hit by a bus" before a project is in trouble because there's nobody left who understands it) is for a project or a subsystem within it. Perhaps a little more depressingly, this also maybe be used to highlight potential cases of poor productivity to be investigated. The program itself, Jimmy (for lack of a better name), has a binary distribution which can be found at http://geeksoc.org/~fvalente/jimmy/jimmy_r1.zip and only requires Java 7 and Mercurial (other libraries are included), getting you started quickly. The source is available at https://bitbucket.org/fvalente/jimmy and if you wish to build it yourself, it depends on Guava r09 and JUNG 2.0.1 (api, algorithms, graph-impl, visualization) which itself depends on Apache Commons collections-generic 4.0.1. To perform a basic analysis of a project, you can open a directory that's a Mercurial repository and it will just look at the list of commits and the files that changed, adding 1 to a score each time an author touches a file, which should only take a minute or two, even for large projects. If you have more time, you can do the more expensive diff stats analysis which compares the size of each diff with the average diff size of the project, excluding empty diffs and binary changes. Unfortunately, the diff stats analysis is very slow due to retrieving each diff requiring the spawning of a hg subprocess (for reference, my 4 year old quad-core machine can do only ~10,000 commits per hour). I don't have a progress UI yet, but progress status is sent to stdout when doing a diff stats analysis. Once analysis is complete, you can save the results to review later by using the open analysis results option. To navigate the results you can switch to viewing a particular file or author of interest from the file and author lists on the left. For files, this will display that file as a node in the centre with the authors that have been involved with it as orbiting nodes, with the connecting lines' length, thickness and colour shortening, thickening and approaching red respectively as the closeness score between that author and the file increases. For authors, it is the same except the files they have worked on will be the orbiting nodes. You can also directly navigate to having a display based on an orbiting node by clicking it in the display rather than searching through the file or author lists. The display can be zoomed by using the scroll wheel and can be translated with the scroll bars or by dragging on an area not occupied by a node. What I would like is for you to please run Jimmy on one or more Mercurial repositories of your choice and to give some feedback on it. Some questions I'd particularly like answered are: * Do the closeness scores it produces match with your perception of the relationships between people and code in the project? (e.g. if you're looking at a particular file and some authors involved in it are shown as closer than others, is this the result you would have expected from a perfect version of Jimmy?) * Does the visualisation of the scores substantially improve your ability to draw conclusions from the data compared to just reading a saved analysis (which is just plaintext)? * If, hypothetically, you had no prior knowledge about the project, would using it help you to discover the key figures (e.g. maintainer, BDFL) behind the project or any of its subsystems? (Alternatively, do such people correctly show up as having touched a wider variety of files and with closer relations to them than other people?) * If you were a manager would you be able to use it to discover potential productivity issues that you would then investigate further? To help save you time from having to do a full analysis of a project, I have supplied analysis files from 3 open-source projects which you can open with the "Open analysis results" option: * cpython: http://geeksoc.org/~fvalente/jimmy/cpython.txt * libSDL: http://geeksoc.org/~fvalente/jimmy/libsdl.txt * Go: http://geeksoc.org/~fvalente/jimmy/golang.txt Some general suggestions on whether and why the current ways of inferring closeness scores and visualising that data are flawed would also be greatly appreciated, as well as potential avenues to explore for improving them. Suggestions I've already received include: * Being able to collapse files into folders or subsystem groups to make larger projects more navigable, perhaps with autoexpansion when zooming the display. In its current form, Jimmy produces disappointing/funny results when you want to see a diagram for, say, a large project's maintainer. * Being able to mine data from a subset of the repository (time range, revision range, include/exclude files/directories, etc.) * Reducing the closeness score contributions of multiple commits made in quick succession, or another method of mitigating the bias in favour of fine-grained committers * Reducing the closeness score contributions of older commits * Interfacing with Mercurial via the recently introduced command server API, which should hopefully make performance non-abysmal * Support for more version control systems. Git would top this list * Perhaps the ability to see a timeline for the project and how closeness changes over time Responses can be made privately to me, if you wish. For the purposes of my report, I will also anonymise all responses received in line with ethical best practices. Thank you for reading. From dmitrey15 at gmail.com Thu Sep 15 12:24:58 2011 From: dmitrey15 at gmail.com (dmitrey) Date: Thu, 15 Sep 2011 09:24:58 -0700 (PDT) Subject: [ANN} OpenOpt, FuncDesigner, DerApproximator, SpaceFuncs release 0.36 Options Message-ID: Hi all, new release of our free scientific soft (OpenOpt, FuncDesigner, DerApproximator, SpaceFuncs) v. 0.36 is out: OpenOpt: Now solver interalg can handle all types of constraints and integration problems Some minor improvements and code cleanup FuncDesigner: Interval analysis now can involve min, max and 1-d monotone splines R -> R of 1st and 3rd order Some bugfixes and improvements SpaceFuncs: Some minor changes DerApproximator: Some improvements for obtaining derivatives in points from R^n where left or right derivative for a variable is absent, especially for stencil > 1 See http://openopt.org for more details. Regards, D. From phihag at phihag.de Thu Sep 15 12:26:04 2011 From: phihag at phihag.de (Philipp Hagemeister) Date: Thu, 15 Sep 2011 18:26:04 +0200 Subject: From Python on Solaris to Python on LINUX In-Reply-To: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> References: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Message-ID: <4E72271C.1020502@phihag.de> > What are the traps to be avoided? Assuming you're not using any OS features (scan the code for "/dev" and "/proc"), the transition from Solaris to Linux will be seamless. Your main problem will be the transition from the archaic Python 2.3 to a modern one. Luckily, all 2.x Pythons should be backwards-compatible. In summary, your application should work just fine (although being written in 2.3, it's probably not as maintainable as a modern application would). > What is the most recent version on LINUX? There are multiple Linux distributions which can differ quite a lot. debian, Ubuntu, and CentOS are popular ones. As you can see on http://www.debian.org/CD/ , the current debian version is 6.0. As you can't see at the moment on http://kernel.org/ , the current Linux kernel version is 3.0 (although most distribution will want to test the kernel and therefore include a slightly older one). -- Philipp -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature URL: From miki.tebeka at gmail.com Thu Sep 15 12:37:44 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 15 Sep 2011 09:37:44 -0700 (PDT) Subject: cause __init__ to return a different class? In-Reply-To: References: Message-ID: I'd go for a factory function (http://en.wikipedia.org/wiki/Factory_method_pattern): def create(foo): return Child(foo) if foo else Parent() From neuroniru at gmail.com Thu Sep 15 12:40:01 2011 From: neuroniru at gmail.com (neeru K) Date: Thu, 15 Sep 2011 22:10:01 +0530 Subject: help regarding extracting a smaller list from larger one Message-ID: Dear Python Users, I am trying to write a code for visualization (raster plots and peri-event time histogram) of time series electrophysiological data using numpy, scipy and matlplotlib in python. I am importing the data into list using loadtext command. I was curious if anyone is aware of a function in numpy that can *extract a smaller list containing numbers from a larger list* given the upper and lower limit of the values between which the smaller list lies. Thank you in advance. Sincerely, niranjan -- Niranjan Kambi Senior Research Fellow, Neeraj Lab, National Brain Research Centre, Manesar, Gurgaon-122050 Haryana, INDIA Ph:+919818654846 website:- http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html email:- neuro.niru at nbrc.res.in, neuroniru at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Thu Sep 15 12:57:24 2011 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 15 Sep 2011 18:57:24 +0200 Subject: how to make a nested list Message-ID: <4E722E74.7030908@gmail.com> hello, I need a nested list, like this >>> A= [ [None,None], [None,None], [None, None] ] >>> A[2][0] =77 >>> A [[None, None], [None, None], [77, None]] Because the list is much larger, I need a shortcut (ok I can use a for loop) So I tried >>> B = 3 * [ [ None, None ]] >>> B[2][0] = 77 >>> B [[77, None], [77, None], [77, None]] which doesn't work as expected. any suggestions ? thanks, Stef From ramit.prasad at jpmorgan.com Thu Sep 15 13:09:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 13:09:07 -0400 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFACA@EMARC112VS01.exchad.jpmchase.net> >>> B = 3 * [ [ None, None ]] That makes a list of the exact same list object: [ a, a, a ] where a = [ None, None ]. Instead I would do something like (untested python2.x): B = [ [ None, None ] for x in xrange(3) ] Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ppearson at nowhere.invalid Thu Sep 15 13:17:42 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 15 Sep 2011 17:17:42 GMT Subject: how to make a nested list References: Message-ID: <9deq9lFpo7U1@mid.individual.net> On Thu, 15 Sep 2011 18:57:24 +0200, Stef Mientki wrote: [snip] > Because the list is much larger, I need a shortcut (ok I can use a for loop) > So I tried > >>> B = 3 * [ [ None, None ]] > >>> B[2][0] = 77 > >>> B > [[77, None], [77, None], [77, None]] > > which doesn't work as expected. > > any suggestions ? >>> b = [[None, None] for i in range(3)] >>> b[2][0] = 77 >>> b [[None, None], [None, None], [77, None]] If you don't understand why the other approach resulted in [[77, None], [77, None], [77, None]], feel free to ask. It's a mistake that I think everybody makes at least once. -- To email me, substitute nowhere->spamcop, invalid->net. From gherron at digipen.edu Thu Sep 15 13:24:15 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 10:24:15 -0700 Subject: help regarding extracting a smaller list from larger one In-Reply-To: References: Message-ID: <4E7234BF.5030101@digipen.edu> On 09/15/2011 09:40 AM, neeru K wrote: > Dear Python Users, > I am trying to write a code for visualization (raster plots and > peri-event time histogram) of time series electrophysiological data > using numpy, scipy and matlplotlib in python. I am importing the data > into list using loadtext command. > I was curious if anyone is aware of a function in numpy that can > *extract a smaller list containing numbers from a larger list* given > the upper and lower limit of the values between which the smaller list > lies. > Thank you in advance. > Sincerely, > niranjan > > -- > Niranjan Kambi > Senior Research Fellow, > Neeraj Lab, > National Brain Research Centre, > Manesar, Gurgaon-122050 > Haryana, INDIA > Ph:+919818654846 > website:- > http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html > email:- neuro.niru at nbrc.res.in , > neuroniru at gmail.com > Do mean to extract a sub-list from a list based on lower and upper indexes into the list? Python has a standard notation for indicating sub-lists, and numpy implements them: >>> a = numpy.array(range(10)) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a[3:6] array([3, 4, 5]) If you mean something else, please be more specific, and we'll try again. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From howe.steven at gmail.com Thu Sep 15 13:27:53 2011 From: howe.steven at gmail.com (GrayShark) Date: Thu, 15 Sep 2011 12:27:53 -0500 Subject: From Python on Solaris to Python on LINUX References: Message-ID: I think that was more of a version question the Kernel questin 1) you can install any and all versions python on a linux computer. You just need you app to select the correct path, correct python interpret. Likely there many be some some drivers in /dev that are not the same as in Solaris. But that shouldn't daunt you. So start by installing python2.3, then test and fix version by version through python2.7. python3.0 might be a pretty be rewrite. 2) Try to pick a version of linux supported locally; likely SuSE, even though Novell/Attachmate owns it. SuSE seems popular in Europe. On Thu, 15 Sep 2011 18:26:04 +0200, Philipp Hagemeister wrote: >> What are the traps to be avoided? > > Assuming you're not using any OS features (scan the code for "/dev" and > "/proc"), the transition from Solaris to Linux will be seamless. > > Your main problem will be the transition from the archaic Python 2.3 to > a modern one. Luckily, all 2.x Pythons should be backwards-compatible. > > In summary, your application should work just fine (although being > written in 2.3, it's probably not as maintainable as a modern > application would). > >> What is the most recent version on LINUX? > There are multiple Linux distributions which can differ quite a lot. > debian, Ubuntu, and CentOS are popular ones. As you can see on > http://www.debian.org/CD/ , the current debian version is 6.0. As you > can't see at the moment on http://kernel.org/ , the current Linux kernel > version is 3.0 (although most distribution will want to test the kernel > and therefore include a slightly older one). > > -- Philipp From gherron at digipen.edu Thu Sep 15 13:28:23 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 10:28:23 -0700 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: <4E7235B7.4030207@digipen.edu> On 09/15/2011 09:57 AM, Stef Mientki wrote: > hello, > > I need a nested list, like this > > >>> A= [ [None,None], [None,None], [None, None] ] > >>> A[2][0] =77 > >>> A > [[None, None], [None, None], [77, None]] > > > Because the list is much larger, I need a shortcut (ok I can use a for > loop) > So I tried > >>> B = 3 * [ [ None, None ]] > >>> B[2][0] = 77 > >>> B > [[77, None], [77, None], [77, None]] > > which doesn't work as expected. > > any suggestions ? > > thanks, > Stef A for loop to fill in the array would work, but list comprehension (which is really just an internal loop for filling an array) is probably more efficient, certainly less code, and arguably more Pythonic. A = [ [None,None] for i in range(1000) ] Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From tim at akwebsoft.com Thu Sep 15 13:38:16 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 15 Sep 2011 09:38:16 -0800 Subject: Reconciling os.path.getmtime vs ftp.sendcmd('MDTM filename') In-Reply-To: <20110915020242.GL4331@johnsons-web.com> References: <20110914195044.GK4331@johnsons-web.com> <20110915020242.GL4331@johnsons-web.com> Message-ID: <20110915173816.GM4331@johnsons-web.com> * Tim Johnson [110914 18:18]: > * Chris Rebert [110914 16:46]: > > On Wed, Sep 14, 2011 at 12:50 PM, Tim Johnson wrote: > > > I have written a class that uses ftplib.FTP as the parent. > > > I need to reconcile the modified time of a workstation file with > > > that same filename on a remote server. > > > Let's say we have a file called '400.shtml'. I get the mtime on > > > my workstation by > > >>> os.path.getmtime('400.shtml') > > > 1311648420.0 > > > > http://docs.python.org/library/os.path.html#os.path.getmtime > > Your sample seems to be a typical Unix timestamp: > Yup. Needs to be converted to a timedate stamp, methinks. > > http://en.wikipedia.org/wiki/Unix_time > I'll look at that tomorrow. Late here. > > > And I use > > >>> ftp.sendcmd('MDTM 400.shtml') ## for the remote server > > > '213 20110726004703' > > > RFC 3659 - Extensions to FTP > > Sec 3. File Modification Time (MDTM) > > http://tools.ietf.org/html/rfc3659#section-3 > > > > (Note: Code 213 = File status response) > and '213 20110726004703'[4:] should give me > the string representation of the timedate stamp on the > remote file. FYI: datetime.datetime.fromtimestamp(mod_time) Is probably what I was looking for. However, for my purposes - I'm going to take another approach. Every uploaded file is defined in an object stored on my workstationr: I will store the MDTM string after upload and then on the next upload, compare the stored string with the return value from ftp.sendcmd('MDTM ' + filename) Thanks for the input. -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From arnodel at gmail.com Thu Sep 15 13:39:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 15 Sep 2011 18:39:34 +0100 Subject: cause __init__ to return a different class? In-Reply-To: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> References: <45466810-5082-45bd-82d0-ba58a16c4289@t29g2000vby.googlegroups.com> Message-ID: On 15 September 2011 15:41, Matthew Pounsett wrote: > On Sep 15, 1:35?am, Chris Rebert wrote: >> Override __new__() instead: >> http://docs.python.org/reference/datamodel.html#object.__new__ > > Aha.. thanks! ?The reference book I'm working from neglects to mention > __new__, so I'd assumed __init__ was the constructor. ?It hadn't > occurred to me that python would separate the functions (I still don't > see exactly why it would be useful to do that, but perhaps insight > will come with time). If you're interested in the reason, I suggest you read Guido's essay on "new style classes" which were introduced in Python 2.2 (and are now a good 10 years old I think): http://www.python.org/download/releases/2.2.3/descrintro -- Arnaud From ladasky at my-deja.com Thu Sep 15 14:43:33 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 11:43:33 -0700 (PDT) Subject: how to make a nested list References: Message-ID: Stef, Are your bottom-level lists always of length 2? If so, then you could use an array, instead of a list of lists. Python ships with a module called array, but it doesn't allow you to put non-numeric types into arrays, and it looks like you want the NoneType. I use the popular numpy module, which does allow non- numeric types. You might also like the slice notation that numpy uses for referencing items in the array. The indices go inside a single set of square brackets, and are separated by commas. >>> from numpy import empty >>> B = empty((3,2), object) >>> B array([[None, None], [None, None], [None, None]], dtype=object) >>> B[2,0] = 77 >>> B array([[None, None], [None, None], [77, None]], dtype=object) From tjreedy at udel.edu Thu Sep 15 14:54:57 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Sep 2011 14:54:57 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: <1316063960.26516.140258141338017@webmail.messagingengine.com> References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On 9/15/2011 1:19 AM, python at bdurham.com wrote: > Is there a way to cancel or timeout a long running regular expression? > I have a program that accepts regular expressions from users and I'm > concerned about how to handle worst case regular expressions that seem > to run forever. Ideally I'm looking for a way to evaluate a regular > expression and timeout after a specified time period if the regular > expression hasn't completed yet. Or a way for a user to cancel a long > running regular expression. This is a general problem when evaluating *any* expression from the outside. [0]*10000*10000 will eat space as well as time. At least, as far as I know, an re cannot cause a disk reformat ;-). There have been previous discussions on this generally topic. > I was thinking there might be a technique I could use to evaluate > regular expressions in a thread or another process launched via > multiprocessing module and then kill the thread/process after a > specified timeout period. Only solution I remember ever seen posted. I wonder if there are any heuristics for detecting exponential time re's. > My concern about the multiprocessing module > technique is that launching a process for every regex evaluation sounds > pretty inefficient. And I don't think the threading module supports the > ability to kill threads from outside a thread itself. -- Terry Jan Reedy From neuroniru at gmail.com Thu Sep 15 14:55:08 2011 From: neuroniru at gmail.com (neeru K) Date: Fri, 16 Sep 2011 00:25:08 +0530 Subject: help regarding extracting a smaller list from larger one In-Reply-To: <4E7234BF.5030101@digipen.edu> References: <4E7234BF.5030101@digipen.edu> Message-ID: Dear Gary, thank you for the reply. I will be more specific and take the same example that you have given and tell you what is my problem - array([0.0, 1.3, 2.45, 3.87, 4.54, 5.11, 6.90, 7.78, 8.23, 9.01]) from this array I want to a sub-list with lower and upper indexes that are not present in the above array for example - sub-list[3, 8] Is there a function for this? thank you niranjan On Thu, Sep 15, 2011 at 10:54 PM, Gary Herron wrote: > On 09/15/2011 09:40 AM, neeru K wrote: > >> Dear Python Users, >> I am trying to write a code for visualization (raster plots and peri-event >> time histogram) of time series electrophysiological data using numpy, scipy >> and matlplotlib in python. I am importing the data into list using loadtext >> command. >> I was curious if anyone is aware of a function in numpy that can *extract >> a smaller list containing numbers from a larger list* given the upper and >> lower limit of the values between which the smaller list lies. >> Thank you in advance. >> Sincerely, >> niranjan >> >> -- >> Niranjan Kambi >> Senior Research Fellow, >> Neeraj Lab, >> National Brain Research Centre, >> Manesar, Gurgaon-122050 >> Haryana, INDIA >> Ph:+919818654846 >> website:- http://www.nbrc.ac.in/faculty/**neeraj/Lab_webpage/Niranjan_** >> Kambi.html >> email:- neuro.niru at nbrc.res.in , >> neuroniru at gmail.com >> >> Do mean to extract a sub-list from a list based on lower and upper > indexes into the list? Python has a standard notation for indicating > sub-lists, and numpy implements them: > > >>> a = numpy.array(range(10)) > >>> a > array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >>> a[3:6] > array([3, 4, 5]) > > If you mean something else, please be more specific, and we'll try again. > > Gary Herron > > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wm at localhost.localdomain Thu Sep 15 15:14:11 2011 From: wm at localhost.localdomain (Waldek M.) Date: Thu, 15 Sep 2011 21:14:11 +0200 Subject: Request for research feedback References: Message-ID: <1oxwvsczcdfj4$.dlg@localhost.localdomain> On Thu, 15 Sep 2011 16:55:13 +0100, Fulvio Valente wrote: > Hi, I am a research intern at the University of Strathclyde > who has been doing a summer research internship. I don't want to be rude, but please: could you rather first research how to use a newsreader before you use it? These long lines (a few times the limit of 78 characters per line) make your post unreadable. Thanks, Waldek From nagle at animats.com Thu Sep 15 15:27:58 2011 From: nagle at animats.com (John Nagle) Date: Thu, 15 Sep 2011 12:27:58 -0700 Subject: PC locks up with list operations In-Reply-To: References: <4e5e2a0c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7251c1$0$1673$742ec2ed@news.sonic.net> On 8/31/2011 5:40 AM, Chris Withers wrote: > On 31/08/2011 13:33, Steven D'Aprano wrote: >> I am using Linux desktops; both incidents were with Python 2.5. Do newer >> versions of Python respond to this sort of situation more gracefully? > > Ironically, Windows does better here and dumps you out with a > MemoryError before slowly recovering. > > Linux seems to fair badly when programs use more memory than physically > available. Linux virtual memory has some known design problems. For example, you can crash many Linux systems with a program which opens large files and accesses them randomly, combined with another program which is spawning processes that need a fair amount of memory. The disk caching system tries to use all unused memory, and when process startup is consuming pages, it's possible to get into a situation where a page is needed, the task requesting it can't block, and a lock preventing freeing a file cache page is set. Arguably, paging to disk is obsolete. RAM is too cheap and disk is too slow. John Nagle From ramit.prasad at jpmorgan.com Thu Sep 15 16:11:13 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 16:11:13 -0400 Subject: Request for research feedback In-Reply-To: <1oxwvsczcdfj4$.dlg@localhost.localdomain> References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFF05@EMARC112VS01.exchad.jpmchase.net> I don't want to be rude but... Rude: >I don't want to be rude, but please: could you rather first research >how to use a newsreader before you use it? >These long lines (a few times the limit of 78 characters per line) >make your post unreadable. Not rude: >These long lines (a few times the limit of 78 characters per line) >make your post unreadable. Sincerely, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From fulvio.valente at strath.ac.uk Thu Sep 15 16:19:46 2011 From: fulvio.valente at strath.ac.uk (Fulvio Valente) Date: Thu, 15 Sep 2011 21:19:46 +0100 Subject: Request for research feedback In-Reply-To: <1oxwvsczcdfj4$.dlg@localhost.localdomain> References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <4E725DE2.7050704@strath.ac.uk> Whoops, I thought the rather iffy Exchange web client at my institution would've wrapped outgoing messages automatically. I'm now using a proper client for that account which should prevent such issues in the future. Thanks for the heads up. For anyone who couldn't stand to read the original message, a fixed version is at http://geeksoc.org/~fvalente/jimmy/request.txt (figured it'd be rude to repost it directly in this message). On 15/09/2011 20:14, Waldek M. wrote: > On Thu, 15 Sep 2011 16:55:13 +0100, Fulvio Valente wrote: > >> Hi, I am a research intern at the University of Strathclyde >> who has been doing a summer research internship. > > I don't want to be rude, but please: could you rather first research > how to use a newsreader before you use it? > These long lines (a few times the limit of 78 characters per line) > make your post unreadable. > > Thanks, > Waldek -- Regards, - Fulvio From ladasky at my-deja.com Thu Sep 15 16:52:45 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 13:52:45 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption Message-ID: Suppose that I have a multi-core computer with N CPU's, and I create a multiprocessing.Pool in Python 2.6 with N-1 Processes. (My rationale for choosing N-1 Processes was discussed here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/65ba3ccd4be8228c) Then I use Pool.map_async() to break up a long-running task T1 into M chunks, where M > 2N. Suppose that I have a second, parallelizable, long-running task T2 that I want to address in REAL TIME when the need arises. Using Pool, is there a way for me to insert the chunks of T2 at the HEAD of the task queue, instead of at its TAIL? I've been snooping around inside Pool, and I would guess that what I want to do is to manipulate Pool._inqueue, which is a multiprocessing.queues.SimpleQueue object. I haven't found any documentation for SimpleQueue. It appears to have only the most rudimentary of public methods -- put, get, and empty. Reading further, I can see that multiprocessing.Queue (not the same as SimpleQueue) has put_nowait(), which looks like what I need. Assuming that I had access to put_nowait(), then I would need an option in map_async() which would invoke put_nowait() rather than just plain put(). Does anyone know of an efficient way to accomplish this? I'm thinking that a subclass of Pool which replaces the SimpleQueue with a full- fledged Queue, and which overrides map_async() allowing for a no-wait task, would be very useful... but maybe I'm re-inventing the wheel. Thanks for your advice! From ladasky at my-deja.com Thu Sep 15 17:49:53 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 14:49:53 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Message-ID: Hate to bump this, but... I found Sourceforge's IRC, and tried to ask for help there, and it doesn't look like I can get any help until business hours tomorrow. Anyone? From vlastimil.brom at gmail.com Thu Sep 15 18:02:10 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 16 Sep 2011 00:02:10 +0200 Subject: how to make a nested list In-Reply-To: <4E722E74.7030908@gmail.com> References: <4E722E74.7030908@gmail.com> Message-ID: 2011/9/15 Stef Mientki : > hello, > > I need a nested list, like this > >>>> A= [ [None,None], [None,None], [None, None] ] >>>> A[2][0] =77 >>>> A > [[None, None], [None, None], [77, None]] > ... > > thanks, > Stef > -- > http://mail.python.org/mailman/listinfo/python-list > Besides the above sugestions to correct the nested list approach, if you need to set and access the data at the given "coordinates" you could also use a nested defaultdict, which doesn't need to be pre-filled before setting, e.g.: >>> from collections import defaultdict as dd >>> def dd_dd(): ... return dd(dd) ... >>> dd_matrix = dd(dd_dd) >>> >>> dd_matrix[2][0] = 77 >>> dd_matrix[2][0] 77 >>> dd_matrix defaultdict(, {2: defaultdict(, {0: 77})}) >>> However, the nested list are concise enough, I guess. Regards, vbr From rosuav at gmail.com Thu Sep 15 18:14:00 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:14:00 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: References: Message-ID: On Fri, Sep 16, 2011 at 6:52 AM, John Ladasky wrote: > Suppose that I have a second, parallelizable, long-running task T2 > that I want to address in REAL TIME when the need arises. ?Using Pool, > is there a way for me to insert the chunks of T2 at the HEAD of the > task queue, instead of at its TAIL? > That's a self-contradiction there. Even if you insert a task into the head of the queue, it won't be addressed in real time; the only way to do that would be to have a dedicated process, always ready to handle the real-time events, or else some kind of interrupt system. But if you just want them handled when there's a worker available, what you're after is a priority queue system. I don't know if one exists in Python already or not, but if not, it'd be a worthwhile addition. ChrisA From rosuav at gmail.com Thu Sep 15 18:22:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:22:42 +1000 Subject: how to make a nested list In-Reply-To: References: <4E722E74.7030908@gmail.com> Message-ID: On Fri, Sep 16, 2011 at 8:02 AM, Vlastimil Brom wrote: > Besides the above sugestions to correct the nested list approach, > if you need to set and access the data at the given "coordinates" you > could also use a nested defaultdict... The defaultdict is efficient for a sparse matrix, but I suspect that it'd be rather worse if you use all the elements. ChrisA From gherron at digipen.edu Thu Sep 15 18:25:18 2011 From: gherron at digipen.edu (Gary Herron) Date: Thu, 15 Sep 2011 15:25:18 -0700 Subject: help regarding extracting a smaller list from larger one In-Reply-To: References: <4E7234BF.5030101@digipen.edu> Message-ID: <4E727B4E.4000400@digipen.edu> On 09/15/2011 11:55 AM, neeru K wrote: > Dear Gary, > thank you for the reply. > I will be more specific and take the same example that you have given > and tell you what is my problem - > array([0.0, 1.3, 2.45, 3.87, 4.54, 5.11, 6.90, 7.78, 8.23, 9.01]) > from this array I want to a sub-list with lower and upper indexes that > are not present in the above array for example - sub-list[3, 8] > Is there a function for this? > thank you > niranjan You say "index", but I think that is not what you mean. An index is in integer referring to an element's position in the array. The "value" at an index is what I believe you are referring to. Nevertheless, I think list comprehension is what you want: [ x for x in A if 3.0 <= x <= 8.0 ] will extract all the values between 3 and 8 from the array A and create a new list containing them. If you want the new list to be a numpy array then numpy.array([ x for x in A if 3.0 <= x <= 8.0 ]) > > > On Thu, Sep 15, 2011 at 10:54 PM, Gary Herron > wrote: > > On 09/15/2011 09:40 AM, neeru K wrote: > > Dear Python Users, > I am trying to write a code for visualization (raster plots > and peri-event time histogram) of time series > electrophysiological data using numpy, scipy and matlplotlib > in python. I am importing the data into list using loadtext > command. > I was curious if anyone is aware of a function in numpy that > can *extract a smaller list containing numbers from a larger > list* given the upper and lower limit of the values between > which the smaller list lies. > Thank you in advance. > Sincerely, > niranjan > > -- > Niranjan Kambi > Senior Research Fellow, > Neeraj Lab, > National Brain Research Centre, > Manesar, Gurgaon-122050 > Haryana, INDIA > Ph:+919818654846 > website:- > http://www.nbrc.ac.in/faculty/neeraj/Lab_webpage/Niranjan_Kambi.html > email:- neuro.niru at nbrc.res.in > >, neuroniru at gmail.com > > > > Do mean to extract a sub-list from a list based on lower and upper > indexes into the list? Python has a standard notation for > indicating sub-lists, and numpy implements them: > > >>> a = numpy.array(range(10)) > >>> a > array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > >>> a[3:6] > array([3, 4, 5]) > > If you mean something else, please be more specific, and we'll try > again. > > Gary Herron > > > -- > Gary Herron, PhD. > Department of Computer Science > DigiPen Institute of Technology > (425) 895-4418 > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From ladasky at my-deja.com Thu Sep 15 18:25:49 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 15:25:49 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> On Sep 15, 3:14?pm, Chris Angelico wrote: > On Fri, Sep 16, 2011 at 6:52 AM, John Ladasky wrote: > > Suppose that I have a second, parallelizable, long-running task T2 > > that I want to address in REAL TIME when the need arises. ?Using Pool, > > is there a way for me to insert the chunks of T2 at the HEAD of the > > task queue, instead of at its TAIL? > > That's a self-contradiction there. Even if you insert a task into the > head of the queue, it won't be addressed in real time; the only way to > do that would be to have a dedicated process, always ready to handle > the real-time events, or else some kind of interrupt system. > > But if you just want them handled when there's a worker available, > what you're after is a priority queue system. I don't know if one > exists in Python already or not, but if not, it'd be a worthwhile > addition. > > ChrisA Hi, Chris, Sorry if I'm not quite familiar with the proper terminology for queues. Let me try to define what I need as precisely as I can. 1) I aim to keep all five child Processes as busy as possible at all times, crunching numbers. 2) I break my data for the low-priority task, T1, into large enough chunks to benefit from multiprocessing, but small enough so that any given Process should become available fairly frequently -- say, every 50 milliseconds. Starting 50 milliseconds late would be close enough to "real time" for my purposes. 3) But let's say that T1 still has twenty chunks in the Process queue when T2 comes along. I could be waiting 300 milliseconds for the queue to empty. If I could just ensure that T2 gets the next available Processes, I would be happy. Since T2 is also parallelizable and I am using five child Processes, I would divide T2 into exactly five chunks. These chunks should get inserted at positions 0-4 in the queue rather than at 20-24. T2 would briefly commandeer all five Processes and then clear out. If that's not putting T2 at the head of the queue, I guess I don't know a better way to describe it. From ladasky at my-deja.com Thu Sep 15 18:32:43 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 15:32:43 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> Ah. Now, see? Having the right vocabulary helps. Searching for "priority queue" brings up this discussion from back in January: http://groups.google.com/group/comp.lang.python/browse_frm/thread/b69aeced28634898 Now, this discussion refers to a PriorityPool class which doesn't appear to be a standard part of Python (2.6, anyway). But I'm not the first one to ask the question, and there's code out there. From rosuav at gmail.com Thu Sep 15 18:32:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:32:53 +1000 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Fri, Sep 16, 2011 at 4:54 AM, Terry Reedy wrote: > On 9/15/2011 1:19 AM, python at bdurham.com wrote: >> I was thinking there might be a technique I could use to evaluate >> regular expressions in a thread or another process launched via >> multiprocessing module and then kill the thread/process after a >> specified timeout period. > > Only solution I remember ever seen posted. Then here's a minor refinement. Since long-running RE is the exceptional case, optimize for the other. Keep the process around and feed it all the jobs you get, and on problem, kill and respawn. That way, you pay most of the overhead cost only when you make use of the separation. (There's still some IPC overhead of course. Can't escape that.) ChrisA From rosuav at gmail.com Thu Sep 15 18:35:20 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:35:20 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> References: <80a631d9-9f5b-40bc-91a1-7657d5fc271a@w21g2000yql.googlegroups.com> Message-ID: On Fri, Sep 16, 2011 at 8:25 AM, John Ladasky wrote: > Starting 50 milliseconds late would be close enough > to "real time" for my purposes. > ... > > If that's not putting T2 at the head of the queue, I guess I don't > know a better way to describe it. Yep, your terms are correct, with that caveat ("immediate" or "urgent" without being "real-time"). So you're definitely looking for a priority queue. It may be possible to patch a different queue object straight into Pool, but I've never done anything like that. It's probably best to dig in the code and add an option somewhere to pass in a queue object - that'd be a very useful feature imho. ChrisA From rosuav at gmail.com Thu Sep 15 18:52:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 16 Sep 2011 08:52:46 +1000 Subject: multiprocessing.Pool, its queue, and pre-emption In-Reply-To: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> References: <500f0c1f-fa8d-4f54-b1be-f0310ae347b3@1g2000vbu.googlegroups.com> Message-ID: On Fri, Sep 16, 2011 at 8:32 AM, John Ladasky wrote: > Ah. Now, see? ?Having the right vocabulary helps. ?Searching for > "priority queue" brings up this discussion from back in January: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/b69aeced28634898 > > Now, this discussion refers to a PriorityPool class which doesn't > appear to be a standard part of Python (2.6, anyway). ?But I'm not the > first one to ask the question, and there's code out there. Awesome! I wasn't aware of that (although considering the volume of traffic on this list, I doubt there's any human who knows everything that's been discussed). Previously-solved problems save everyone a lot of trouble. ChrisA From cs at zip.com.au Thu Sep 15 18:54:40 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 16 Sep 2011 08:54:40 +1000 Subject: From Python on Solaris to Python on LINUX In-Reply-To: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> References: <02dc01cc73bc$5bee1fc0$13ca5f40$@Diagorn@open-groupe.com> Message-ID: <20110915225440.GA26026@cskk.homeip.net> On 15Sep2011 17:30, Genevi?ve Diagorn wrote: | I work on projects developed in Python 2.3 on Solaris. The customer asks us | to pass on LINUX in a recent version of Python. | | Is it someone has already realized this modification? What are the traps to | be avoided? | | Is it a long and difficult phase? Aside from the very minor things mentioned by others, only two things occur to me: - if you use the struct module and you're moving from SPARC to Intel the endianness of some things may change - if you call external shell commands, there are (usually minor) differences between the Solaris and GNU toolsets Neither seems likely to be a big problem and of course both are "outside Python" in a sense. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Do not taunt Happy Fun Coder. From ramit.prasad at jpmorgan.com Thu Sep 15 19:16:05 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 19:16:05 -0400 Subject: help regarding extracting a smaller list from larger one In-Reply-To: <4E727B4E.4000400@digipen.edu> References: <4E7234BF.5030101@digipen.edu> <4E727B4E.4000400@digipen.edu> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CF01B7@EMARC112VS01.exchad.jpmchase.net> >Nevertheless, I think list comprehension is what you want: > [ x for x in A if 3.0 <= x <= 8.0 ] >will extract all the values between 3 and 8 from the array A and create >a new list containing them. >If you want the new list to be a numpy array then > numpy.array([ x for x in A if 3.0 <= x <= 8.0 ]) I have been told that the following is much faster than list generation for filtering if you are using numpy arrays. I have not looked to see if this claim is accurate, but since it was one of the SciPy creators....I trust him :) YMMV foo = numpy.array([ [1.2,2.3,1.3], [4.3,2.1,6.2], [3.2,1.2,6.5], [1.4,2.1,4.3]]) #if we want 2nd element > 2 and 3rd element < 6 mask = (foo[:,2]>2)&(foo[:,2]<6) v = foo[mask] #this is a view and if you want a new list, you will have to wrap it # I assume np.array(v) will create new array (untested). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From sohel807 at gmail.com Fri Sep 16 00:48:30 2011 From: sohel807 at gmail.com (Akand Islam) Date: Thu, 15 Sep 2011 21:48:30 -0700 (PDT) Subject: Comparisons of computation timing Message-ID: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> I have run my codes (written in Python) in my Notebook (3 GB Ram, Dual- core CPU T4500 @ 2.3 GHz) and in my lab machine (11.57 GB Ram, i7-920 CPU @ 2.67 GHz). However, I have found execution time in Notebook 250.3 seconds, and in Lab machine 333.2 seconds. How is it possible? Good configuration machine performs slower??? I reran the codes, same finding whatsoever. I run Windows 7 in my laptop, and Ubuntu 11.04 in lab machine. Both are 64 bit. When I ran my simulation in Notebook, I also did some other stuffs; however for the case of lab machine I did nothing other than running simulation only. About the codes: Basically it simply solves some non-linear equations using "fsolve" along with some other calculations. I will appreciate if some one discusses about possible reasons? For fair comparisons, in both machines I ran exactly the same codes. My codes are not parallelized, is this the main reason i7 processes show slower performance? Thanks in advance, Akand From wm at localhost.localdomain Fri Sep 16 01:46:52 2011 From: wm at localhost.localdomain (Waldek M.) Date: Fri, 16 Sep 2011 07:46:52 +0200 Subject: Request for research feedback References: <1oxwvsczcdfj4$.dlg@localhost.localdomain> Message-ID: <1drj37uduixks$.dlg@localhost.localdomain> On Thu, 15 Sep 2011 16:11:13 -0400, Prasad, Ramit wrote: > I don't want to be rude but... > Not rude: > Rude: You're right. I must have gotten a few bad habits I didn't even realize. Thanks. Waldek From ladasky at my-deja.com Fri Sep 16 02:31:49 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 15 Sep 2011 23:31:49 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: On Sep 15, 1:52?pm, John Ladasky wrote: > I've been snooping around inside Pool, and I would guess that what I > want to do is to manipulate Pool._inqueue, which is a > multiprocessing.queues.SimpleQueue object. ?I haven't found any > documentation for SimpleQueue. ?It appears to have only the most > rudimentary of public methods -- put, get, and empty. Reading more deeply, I think that my first guess was incorrect. There's also Pool._taskqueue, and it's a full-fledged Queue. It appears that map.async() puts pending jobs there, not in Pool._inqueue. If this is true, then all that should have to be done is to override a few methods. I'm going to try it. From chunuan723 at gmail.com Fri Sep 16 02:39:23 2011 From: chunuan723 at gmail.com (he sharon) Date: Thu, 15 Sep 2011 23:39:23 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <43895317-a79b-44ef-b85e-9adccd37309a@i5g2000vbw.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on. on our site: www.popbaseballhats.com From 1248283536 at qq.com Fri Sep 16 02:39:28 2011 From: 1248283536 at qq.com (=?utf-8?B?YWxpYXM=?=) Date: Fri, 16 Sep 2011 14:39:28 +0800 Subject: parse html:what is the meaning of "//"? Message-ID: code1: import lxml.html import urllib down='http://finance.yahoo.com/q/op?s=C+Options' content=urllib.urlopen(down).read() root=lxml.html.document_fromstring(content) table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] tds=table.xpath("tr[@valign='top']//td") for td in tds: print td.text_content() what i get is : Call Options Expire at close Friday, September 16, 2011 these are waht i want. code2 import lxml.html import urllib down='http://finance.yahoo.com/q/op?s=C+Options' content=urllib.urlopen(down).read() root=lxml.html.document_fromstring(content) table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] tds=table.xpath("//tr[@valign='top']//td") for td in tds: print td.text_content() what i get is : N/A N/A 2 114 48.00 C110917P00048000 16.75 0.00 N/A N/A 0 23 50.00 C110917P00050000 23.16 0.00 N/A N/A 115 2,411 Highlighted options are in-the-money. (omit something) there is only one difference between code1 and code2 : in code1 is : tds=table.xpath("tr[@valign='top']//td") in code2 is: tds=table.xpath("//tr[@valign='top']//td") i want to know why the "//" make output different? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Fri Sep 16 03:01:39 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Fri, 16 Sep 2011 09:01:39 +0200 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: Am 15.09.2011 15:16 schrieb Alan Plum: > The Turkish 'I' is a peculiarity that will probably haunt us programmers > until hell freezes over. That's why it would have been nice if the Unicode guys had defined "both Turkish i-s" at separate codepoints. Then one could have the three pairs I, i ("normal") I (other one), ? and ?, i (the other one). But alas, they haven't. Thomas From steve+comp.lang.python at pearwood.info Fri Sep 16 03:19:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 17:19:05 +1000 Subject: Comparisons of computation timing References: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> Message-ID: <4e72f86a$0$29976$c3e8da3$5496439d@news.astraweb.com> Akand Islam wrote: > I have run my codes (written in Python) in my Notebook (3 GB Ram, Dual- > core CPU T4500 @ 2.3 GHz) and in my lab machine (11.57 GB Ram, i7-920 > CPU @ 2.67 GHz). However, I have found execution time in Notebook > 250.3 seconds, and in Lab machine 333.2 seconds. How is it possible? > Good configuration machine performs slower??? I reran the codes, same > finding whatsoever. I run Windows 7 in my laptop, and Ubuntu 11.04 in > lab machine. Both are 64 bit. When I ran my simulation in Notebook, I > also did some other stuffs; however for the case of lab machine I did > nothing other than running simulation only. In a modern, multi-processing operating system like Windows, Mac OS or Linux, you can *never* run only the simulation. There are always other processes running. Even if you have no other applications running, the system itself could have dozens or hundreds of processes running in the background. On one of my Linux systems, a desktop running about four applications, I have over two hundred processes: [steve at orac ~]$ ps aux | wc -l 218 Without knowing more about the two systems, and the code you ran, it is impossible to say why one is faster than the other. Your question is like this: "I drove from home to work with an old Toyota, and it took twenty minutes. Then the next day, I borrowed my cousin's brand new Ferrari, and the same journey took thirty minutes. How is this possible?" On the Ubuntu machine, what does "ulimit -a" report? How does that compare to the Window machine? Where there any cron jobs running at the time? Did your Ubuntu system decide that this was a good time to download a whole lot of system updates? Can you use the "nice" command to run at a higher priority? Is your code limited by CPU, memory or disk I/O? Which desktop environment is your Ubuntu system running, Gnome, Unity, KDE, Ratpoison, or something else? There could be dozens of factors that make a difference to speed. > About the codes: Basically it simply solves some non-linear equations > using "fsolve" along with some other calculations. What is "fsolve"? > I will appreciate if some one discusses about possible reasons? For > fair comparisons, in both machines I ran exactly the same codes. My > codes are not parallelized, is this the main reason i7 processes show > slower performance? Don't believe hardware manufacturer's advertising. These days, chip speed is not so important. Cache misses are MUCH more critical: a slow chip with a big cache will out-perform a fast chip with a small cache nearly always. -- Steven From steve+comp.lang.python at pearwood.info Fri Sep 16 03:25:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 17:25:39 +1000 Subject: Turkic I and re References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4e72f9f4$0$30003$c3e8da3$5496439d@news.astraweb.com> Thomas Rachel wrote: > Am 15.09.2011 15:16 schrieb Alan Plum: > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers >> until hell freezes over. Meh, I don't think it's much more peculiar that any other diacritic issue. If I'm German or English, I probably want ? and O to match during case-insensitive comparisons, so that Z?e and ZOE match. If I'm Icelandic, I don't. I don't really see why Turkic gets singled out. > That's why it would have been nice if the Unicode guys had defined "both > Turkish i-s" at separate codepoints. > > Then one could have the three pairs > I, i ("normal") > I (other one), ? > > and > > ?, i (the other one). And then people will say, "How can I match both sorts of dotless uppercase I but not dotted I when I'm doing comparisons?" -- Steven From nizamov.shawkat at gmail.com Fri Sep 16 03:30:01 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Fri, 16 Sep 2011 09:30:01 +0200 Subject: Comparisons of computation timing In-Reply-To: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> References: <55375986-1841-4b6c-b921-089e649a4fa8@w21g2000yql.googlegroups.com> Message-ID: > About the codes: Basically it simply solves some non-linear equations > using "fsolve" along with some other calculations. > Looks like you are using some third party libraries like numpy/scipy. Do these libraries have the same version on both platforms? What about python interpreter versions - are they the same? Best regards, Shavkat Nizamov From johnjohn.tedro at gmail.com Fri Sep 16 04:00:16 2011 From: johnjohn.tedro at gmail.com (John-John Tedro) Date: Fri, 16 Sep 2011 08:00:16 +0000 Subject: Fwd: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> <4e72f9f4$0$30003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 16, 2011 at 7:25 AM, Steven D'Aprano < steve+comp.lang.python at pearwood.info> wrote: > Thomas Rachel wrote: > > > Am 15.09.2011 15:16 schrieb Alan Plum: > > > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers > >> until hell freezes over. > > > Meh, I don't think it's much more peculiar that any other diacritic issue. > If I'm German or English, I probably want ? and O to match during > case-insensitive comparisons, so that Z?e and ZOE match. If I'm Icelandic, > I don't. I don't really see why Turkic gets singled out. > > > > That's why it would have been nice if the Unicode guys had defined "both > > Turkish i-s" at separate codepoints. > > > > Then one could have the three pairs > > I, i ("normal") > > I (other one), ? > > > > and > > > > ?, i (the other one). > > And then people will say, "How can I match both sorts of dotless uppercase > I > but not dotted I when I'm doing comparisons?" > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > Yeah, it's more probable that language conventions and functions grow around characters that look right. No one except developers care what specific codepoint they have, so soon you would have a mish-mash of special rules converting between each special case. P.S. Sorry Steven, i missed clicking "reply to all". -- John-John Tedro -------------- next part -------------- An HTML attachment was scrubbed... URL: From keobox at gmail.com Fri Sep 16 05:30:08 2011 From: keobox at gmail.com (keobox) Date: Fri, 16 Sep 2011 02:30:08 -0700 (PDT) Subject: why ps/fname of a python interpreter changes across platforms? Message-ID: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Hello, I'm writing a little supervisor of some python scripts. To check if the scrips are running I'm using the ps -o pid,fname command on both RH Linux and solaris 10. All the scripts are launched using "python script.py" command, they are not launched with exec permissions. I don't know why the fname of the python interpreter changes across platforms. I saw a "isapytho" in some solaris 10 platforms. I saw "python2." in some Linux platforms. On most platforms the value is "python". Why? Ok, I know that I can easily work around the problem by not using "fname" and parse the ps output in another way, but I don't understand how is possible that the combination of ps and python behaves so badly. Any idea? Regards, Cesare From kevin.p.dwyer at gmail.com Fri Sep 16 07:01:14 2011 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Fri, 16 Sep 2011 12:01:14 +0100 Subject: parse html:what is the meaning of "//"? References: Message-ID: alias wrote: > > > > Highlighted options are in-the-money. > (omit something) > there is only one difference between code1 and code2 : > in code1 is : tds=table.xpath("tr[@valign='top']//td") > in code2 is: tds=table.xpath("//tr[@valign='top']//td") > > i want to know why the "//" make output different? This is an XPATH question, not really Python-related. See http://www.w3schools.com/xpath/xpath_syntax.asp Cheers, Kev From stefan_ml at behnel.de Fri Sep 16 07:02:06 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 16 Sep 2011 13:02:06 +0200 Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: alias, 16.09.2011 08:39: > code1: > import lxml.html > import urllib > down='http://finance.yahoo.com/q/op?s=C+Options' > content=urllib.urlopen(down).read() > root=lxml.html.document_fromstring(content) I see this quite often, but many people don't know that this can be simplified to import lxml.html url = 'http://finance.yahoo.com/q/op?s=C+Options' root = lxml.html.parse(url).getroot() which is less code, but substantially more efficient. > table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] > tds=table.xpath("tr[@valign='top']//td") > for td in tds: > print td.text_content() > > what i get is : > Call Options > Expire at close Friday, September 16, 2011 > these are waht i want. > > code2 > import lxml.html > import urllib > down='http://finance.yahoo.com/q/op?s=C+Options' > content=urllib.urlopen(down).read() > root=lxml.html.document_fromstring(content) > table = root.xpath("//table[@class='yfnc_mod_table_title1']")[0] > tds=table.xpath("//tr[@valign='top']//td") Here, you are looking for all "tr" tags in the table recursively, instead of taking just the ones that are direct children of the "table" tag. That's what "//" is there for, it's a recursive subtree selector. You might want to read up on XPath expressions. > what i get is : > N/A > N/A > 2 > 114 > 48.00 > C110917P00048000 > 16.75 > 0.00 > N/A > N/A > 0 > 23 > 50.00 > C110917P00050000 > 23.16 > 0.00 > N/A > N/A > 115 > 2,411 > > > Highlighted options are in-the-money. I don't see any highlighting in your text above, and I don't know what you mean by "in-the-money". Stefan From andrea.crotti.0 at gmail.com Fri Sep 16 07:13:15 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 16 Sep 2011 12:13:15 +0100 Subject: create a directory structure Message-ID: <4E732F4B.3090409@gmail.com> I would like to write a program which creates a directory structure and fills in a few templated fields some values passed in as arguments. So for example create_struct.py might create base_dir: |_ sub_dir1: |_ sub_file1 ... It's quite simple in theory, but I would also like to make it very easily maintanable, for example with a nice representation of the structure (an INI file maybe). Any ideas/advise on how to make it easy to write and to maintain? From steve+comp.lang.python at pearwood.info Fri Sep 16 07:13:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 21:13:43 +1000 Subject: why ps/fname of a python interpreter changes across platforms? References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Message-ID: <4e732f68$0$29997$c3e8da3$5496439d@news.astraweb.com> keobox wrote: > Hello, > I'm writing a little supervisor of some python scripts. > To check if the scrips are running I'm using the ps -o pid,fname > command on both RH Linux and solaris 10. > All the scripts are launched using "python script.py" command, they > are not launched with exec permissions. > > I don't know why the fname of the python interpreter changes across > platforms. Ask the person who built the system, or the people who made the distribution. They are free to name the Python executable anything they like. -- Steven From yasar11732 at gmail.com Fri Sep 16 07:34:37 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Fri, 16 Sep 2011 14:34:37 +0300 Subject: Fwd: why ps/fname of a python interpreter changes across platforms? In-Reply-To: References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> <4e732f68$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: ---------- Y?nlendirilmi? ileti ---------- Kimden: Ya?ar Arabac? Tarih: 16 Eyl?l 2011 14:33 Konu: Re: why ps/fname of a python interpreter changes across platforms? Kime: Steven D'Aprano For example, in arch linux, I had 3 different interpreters named python, python26 and python27 because some of the applications needed one, and some needed others. That might be the reason. 2011/9/16 Steven D'Aprano > keobox wrote: > > > Hello, > > I'm writing a little supervisor of some python scripts. > > To check if the scrips are running I'm using the ps -o pid,fname > > command on both RH Linux and solaris 10. > > All the scripts are launched using "python script.py" command, they > > are not launched with exec permissions. > > > > I don't know why the fname of the python interpreter changes across > > platforms. > > Ask the person who built the system, or the people who made the > distribution. They are free to name the Python executable anything they > like. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From oktaysafak at superonline.com Fri Sep 16 08:12:50 2011 From: oktaysafak at superonline.com (Oktay Safak) Date: Fri, 16 Sep 2011 15:12:50 +0300 Subject: Turkic I and re In-Reply-To: References: <4E71F763.2010109@mrabarnett.plus.com> Message-ID: <4E733D42.90400@superonline.com> Well, I'm a self taught Turkish python coder. I was bitten by this first in Python 2.3 and asked the group about it then. You can find the correspondence by googling "unicode bug in turkish characters? " There are a couple of posts with that topic line but they don't come out in one thread. So check them all. Anyway, to summarize, Martin v.L?wis answered my question back then and suggested some locale settings but the problem seems to be with Windows actually. His method worked on Linux, but not on windows. He said that Python delegates uppercasing of strings to the operating system on Windows, and Windows is broken there. What he said was: "Python delegates the toupper call to the operating system. It does not, in itself, include a database of lower/upper case conversions for all locales. So there is nothing we can do about that; ask Microsoft." So I ended up not asking Microsoft of course, but using [i?] in re and writing a couple of utility functions upper_tr(), lower_tr() and title_tr() etc to use in my own projects. But of course when foreign language names etc. are mixed in a text it blows but I can't see a way to avoid it when that's the case. I hope this helps, Oktay Safak Thomas Rachel wrote: > Am 15.09.2011 15:16 schrieb Alan Plum: > >> The Turkish 'I' is a peculiarity that will probably haunt us programmers >> until hell freezes over. > > That's why it would have been nice if the Unicode guys had defined > "both Turkish i-s" at separate codepoints. > > Then one could have the three pairs > I, i ("normal") > I (other one), ? > > and > > ?, i (the other one). > > But alas, they haven't. > > > Thomas -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Fri Sep 16 09:08:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 06:08:54 -0700 (PDT) Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) From miki.tebeka at gmail.com Fri Sep 16 09:08:54 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 06:08:54 -0700 (PDT) Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) From JKPeck at gmail.com Fri Sep 16 09:09:30 2011 From: JKPeck at gmail.com (JKPeck) Date: Fri, 16 Sep 2011 06:09:30 -0700 (PDT) Subject: Strange Python internal error Message-ID: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> We have a user on Windows with Python 2.6 who gets this error message when executing an import statement. from extension import Template, Syntax, processcmd SystemError: ..\Objects\listobject.c:169: bad argument to internal function The module can be imported directly via import extension with no problem. And large numbers of other users execute this same code with no problem. Does anybody have a clue as to how this might arise? TIA, Jon Peck From 1248283536 at qq.com Fri Sep 16 09:26:28 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 16 Sep 2011 21:26:28 +0800 Subject: parse html:what is the meaning of "//"? Message-ID: through the following code,i get the content of webpage, import lxml.html url = 'http://finance.yahoo.com/q/op?s=C+Options' root = lxml.html.parse(url).getroot() with your method ,how can i get the content of webpage in my python program? ------------------ Original ------------------ From: "Miki Tebeka"; Date: Fri, Sep 16, 2011 09:08 PM To: "python-list"; Cc: "python-list"; Subject: Re: parse html:what is the meaning of "//"? As a side note, it's way easier to get this data using YQL. See for example: http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=SELECT%20*%20FROM%20yahoo.finance.options%20WHERE%20symbol%3D%27C%27%20AND%20expiration%3D%272011-09%27 Which gives you the data in JSON format. (See link at bottom for API URL) -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Fri Sep 16 09:52:16 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Fri, 16 Sep 2011 15:52:16 +0200 Subject: Different class 'str' between v3. In-Reply-To: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> Message-ID: <4E735490.4060509@swing.be> An HTML attachment was scrubbed... URL: From nobody at nowhere.com Fri Sep 16 09:57:06 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 16 Sep 2011 14:57:06 +0100 Subject: Cancel or timeout a long running regular expression References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Thu, 15 Sep 2011 14:54:57 -0400, Terry Reedy wrote: >> I was thinking there might be a technique I could use to evaluate >> regular expressions in a thread or another process launched via >> multiprocessing module and then kill the thread/process after a >> specified timeout period. > > Only solution I remember ever seen posted. I wonder if there are any > heuristics for detecting exponential time re's. Exponential growth results from non-determinism, i.e. if there are multiple transitions for a given character from a given state. Common patterns include: ...(a...)?a... ...(a...)*a... ...(a...)+a... with a choice between matching the "a" at the start of the bracketed pattern or the "a" following it. (xxxa...|xxxb...|xxxc...) with a choice between branches which cannot be resolved until more data has been read. For re.search (as opposed to re.match): axxxa... When axxx has been read, a following "a" gives a choice between continuing the existing match with the second "a", or aborting and matching against the first "a". For patterns which contain many copies of the initial character, each copy creates another branch. Also, using back-references in a regexp [sic] can be a significant performance killer, as it rules out the use of a DFA (which, IIRC, Python doesn't do anyhow) and can require brute-forcing many combinations. A particularly bad case is: (a*)\1 matching against "aaaaaaaa...". If the performance issue is with re.match/re.search rather than with re.compile, one option is to use ctypes to access libc's regexp functions. Those are likely to provide better searching throughput at the expense of potentially increased compilation time. From andrea.crotti.0 at gmail.com Fri Sep 16 10:00:10 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 16 Sep 2011 15:00:10 +0100 Subject: create a directory structure In-Reply-To: <4E732F4B.3090409@gmail.com> References: <4E732F4B.3090409@gmail.com> Message-ID: <4E73566A.1010808@gmail.com> After some research, I think that paste-script is the best choice in this case. I can define templates and I'll get my directory structure nicely populated for me. From duncan.booth at invalid.invalid Fri Sep 16 10:44:12 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2011 14:44:12 GMT Subject: why ps/fname of a python interpreter changes across platforms? References: <014688d5-e917-4f58-80fc-0670e47f71d9@19g2000vbx.googlegroups.com> Message-ID: keobox wrote: > I don't know why the fname of the python interpreter changes across > platforms. > > I saw a "isapytho" in some solaris 10 platforms. > I saw "python2." in some Linux platforms. > On most platforms the value is "python". > Why? > It shows you part of the name of the program that is running. On a typical Linux system you could run python using the default interpreter 'python', or you could be explicit about the version you want to run and use 'python2.4', 'python2.5', 'python2.6', 'python2.7', 'python3.2' (all of these are available on the system in from of me). Of course 4 of those will be truncated to 'python2.' if you only look at the first 8 characters (which is what your command does) but you also get 'python' and 'python3.' That's why there's a lot of variation. I have no idea why it has a strange name on Solaris, maybe someone compiled their own private version. -- Duncan Booth http://kupuguy.blogspot.com From aspineux at gmail.com Fri Sep 16 11:42:25 2011 From: aspineux at gmail.com (aspineux) Date: Fri, 16 Sep 2011 08:42:25 -0700 (PDT) Subject: pyzmail-0.9.9 mail library to read, compose and send emails easily, support for py3k Message-ID: Now pyzmail include support for python 3.2 and above pyzmail is a high level mail library for Python. It provides functions and classes that help to read, compose and send emails. pyzmail exists because their is no reasons that handling mails with Python would be more difficult than with popular mail clients like Outlook or Thunderbird. pyzmail hide the difficulties of the MIME structure and MIME encoding/decoding. It also hide the problem of the internationalized header encoding/decoding. The library contains lot of sample and is very well documented. http://www.magiksys.net/pyzmail/ Alain Spineux From miki.tebeka at gmail.com Fri Sep 16 12:13:14 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 16 Sep 2011 09:13:14 -0700 (PDT) Subject: Strange Python internal error In-Reply-To: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> Message-ID: <1e1f841b-dc17-42d3-bf88-86a27a92752e@glegroupsg2000goo.googlegroups.com> Try to narrow it down: from extension import Template from extension import Syntax from extension import processcmd Which one fails? What is this "extension" package? From martin.schoon at gmail.com Fri Sep 16 13:29:53 2011 From: martin.schoon at gmail.com (Martin =?UTF-8?Q?Sch=C3=B6=C3=B6n?=) Date: 16 Sep 2011 17:29:53 GMT Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> Message-ID: <9dhfchFvt2U1@mid.individual.net> On 2011-09-15, John Ladasky wrote: > Hate to bump this, but... I found Sourceforge's IRC, and tried to ask > for help there, and it doesn't look like I can get any help until > business hours tomorrow. Anyone? No help really but I 'joined' Sourceforge about a year ago and had no problems whatsoever. Could it be some anti-robot filter that's gotten overly picky? /Martin From ramit.prasad at jpmorgan.com Fri Sep 16 13:52:33 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 13:52:33 -0400 Subject: ImportError: cannot import name dns In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4719@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB5052@EMARC112VS01.exchad.jpmchase.net> NOTE: This is all speculation on my part. I am hoping someone on the list will give us more concrete details. 1. check for "dns" in sys.modules (initially not found) 2. create new empty module, add it to sys.modules as "dns" 3. execute dns.py in new module namespace (executes "from foo import udp") It has not yet added anything defined in dns because it is still on import statement 4. check for "udp" in sys.modules (not found) 5. create new empty module, add it to sys.modules as "udp" 6. execute udp.py in new module namespace (executes "from foo import dns") Cannot do this because dns is still not defined even though it the name is in sys.modules and since we are still in the middle of the first statement defining dns, it raises an error. 7. check for "dns" in sys.modules (found!) 8. done executing udp.py 9. done executing dns.py Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: Jack Bates [mailto:jack.bates at gmail.com] Sent: Wednesday, September 14, 2011 11:22 AM To: Prasad, Ramit Cc: python-list at python.org Subject: Re: ImportError: cannot import name dns > It is a circular dependency. Dns will try to import udp which will in turn import dns (again) in an endless cycle; instead an ImportError is raised. > > Circular dependency is a Bad Thing. According to this documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-import_stmt http://effbot.org/zone/import-confusion.htm - I thought Python would do something like: So I'd expect attempting to access symbols from "dns" while executing udp.py to fail, because dns.py isn't done executing at this point. However I don't attempt to access any symbols from "dns" - so I don't expect this ImportError What is my mistake? This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From brandonfigura at gmail.com Fri Sep 16 14:12:21 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:12:21 -0700 (PDT) Subject: strange results Message-ID: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> I am having a problem with a graphics program that I created. Actually, I don't know if it is the program or a bug in Python. The code for the program is as follows; from gasp import * begin_graphics(width=640, height=480, title='Houses at Night', background=color.BLACK) def draw_house(x, y): a = (x, y + 100) b = (x +50, y +140) c = (x +100, y + 100) Box((x, y), 100, 100, filled=True, color=color.BLUE) # the house Box((x + 35, y), 30, 50, filled=True, color=color.GREEN) # the door Circle((x + 62, y + 16), 1, filled=True, color=color.GOLD) # the door knob Box((x + 20, y + 60), 20, 20, filled=True, color=color.YELLOW) # the left window Line((x + 20, y + 71), (x + 40, y + 71), color=color.ORANGE) # horizontal line (left window) Line((x + 29, y + 60), (x + 29, y + 80), color=color.ORANGE) # vertical line (left window) Box((x + 60, y + 60), 20, 20, filled=True, color=color.YELLOW) # the right window Line((x + 60, y + 71), (x + 80, y + 71), color=color.ORANGE) # horizontal line (right window) Line((x + 69, y + 60), (x + 69, y + 80), color=color.ORANGE) # vertical line (right window) Polygon([a, b, c], filled=True, color=color.RED) # the roof draw_house(20, 20) draw_house(270, 20) draw_house(520, 20) draw_house(145, 180) draw_house(395, 180) draw_house(270, 340) update_when('key_pressed') end_graphics() ends here, but it When I run the program, I do not get any error messages but there are parts of the 'draw_house' function missing on the canvas. Each call to 'draw_house has different things missing, they are not all the exact same. There are some parts that show in one call to 'draw_house' that do not show in others and visa versa. Does anyone have any idea what may be going on? From brandonfigura at gmail.com Fri Sep 16 14:35:12 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:35:12 -0700 (PDT) Subject: unexpected results Message-ID: <13f31aba-e7e3-4697-96fa-74ab26bfc18a@s20g2000yql.googlegroups.com> I am having a problem when I run a graphics program that I created. I do not get an error when I run the program, there are just some weird things going on. I do not know if it is the program causing the problem or a bug in Python. Here is the code for the program: from gasp import * begin_graphics(width=640, height=480, title='Houses at Night', background=color.BLACK) def draw_house(x, y): # function for drawing a house a = (x, y + 100) # 'a' coordinate for Polygon b = (x +50, y +140) # 'b' coordinate for Polygon c = (x +100, y + 100) # 'c' coordinate for Polygon Box((x, y), 100, 100, filled=True, color=color.BLUE) # the house Box((x + 35, y), 30, 50, filled=True, color=color.GREEN) # the door Circle((x + 62, y + 16), 1, filled=True, color=color.GOLD) # the door knob Box((x + 20, y + 60), 20, 20, filled=True, color=color.YELLOW) # the left window Line((x + 20, y + 71), (x + 40, y + 71), color=color.ORANGE) # horizontal line (left window) Line((x + 29, y + 60), (x + 29, y + 80), color=color.ORANGE) # vertical line (left window) Box((x + 60, y + 60), 20, 20, filled=True, color=color.YELLOW) # the right window Line((x + 60, y + 71), (x + 80, y + 71), color=color.ORANGE) # horizontal line (right window) Line((x + 69, y + 60), (x + 69, y + 80), color=color.ORANGE) # vertical line (right window) Polygon([a, b, c], filled=True, color=color.RED) # the roof draw_house(20, 20) draw_house(270, 20) draw_house(520, 20) draw_house(145, 180) draw_house(395, 180) draw_house(270, 340) update_when('key_pressed') end_graphics() The program launches just fine, bringing up the gasp window like it should. The problem is that almost all of the calls to 'draw_house' are different. Some features will show up in one house but not in another and visa versa. Does anyone have any idea what the problem may be? From brandonfigura at gmail.com Fri Sep 16 14:39:54 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 11:39:54 -0700 (PDT) Subject: unexpected results References: <13f31aba-e7e3-4697-96fa-74ab26bfc18a@s20g2000yql.googlegroups.com> Message-ID: Sorry, Everyone. I got an error when posting the first post and did'nt come in to see if it had actually posted before I tried another post. From ben.r.shepherd at gmail.com Fri Sep 16 14:47:43 2011 From: ben.r.shepherd at gmail.com (Benshep) Date: Fri, 16 Sep 2011 11:47:43 -0700 (PDT) Subject: Using tuples to eliminate multiple dict values Message-ID: I need a dictionary that returns the same value for multiple keys. i.e. (1) >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } (2) >>>dict[1] (3) 'text' I cant figure out what i need on line 2 to make this scenario work. Is there a simple way to check if the a number is present in the key and then return the value? Thanks From thatiparthysreenivas at gmail.com Fri Sep 16 15:21:06 2011 From: thatiparthysreenivas at gmail.com (zombie) Date: Fri, 16 Sep 2011 12:21:06 -0700 (PDT) Subject: way to calculate 2**1000 without expanding it? Message-ID: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Hi guys, i am writing a program to sum up the digits of a number 2**1000? Is there a way/formula to do it without expanding it? From ramit.prasad at jpmorgan.com Fri Sep 16 15:28:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 15:28:07 -0400 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB52AB@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Benshep Sent: Friday, September 16, 2011 1:48 PM To: python-list at python.org Subject: Using tuples to eliminate multiple dict values I need a dictionary that returns the same value for multiple keys. i.e. (1) >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } (2) >>>dict[1] (3) 'text' I cant figure out what i need on line 2 to make this scenario work. Is there a simple way to check if the a number is present in the key and then return the value? Thanks ---------------------------------------------------------------- I think I must be missing something. Can you not do the following? >>> d = { 1:'text', 2:'text', 3:'text', 5:'other text', 6:'other text', 7:'other text' } >>> d[1] 'text' If you are they need to share the same value you can also do something like this. >>> t1 = [ 'text' ] >>> t2 = [ 'other text' ] >>> d = { 1:t1, 2:t1, 3:t1, 5:t2, 6:t2, 7:t2 } >>> d[1] ['text'] >>> d[1][0]='new text' >>> d[2][0] 'new text' >>> d {1: ['new text'], 2: ['new text'], 3: ['new text'], 5: ['other text'], 6: ['other text'], 7: ['other text']} Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python at mrabarnett.plus.com Fri Sep 16 15:29:41 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 16 Sep 2011 20:29:41 +0100 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <4E73A3A5.3090209@mrabarnett.plus.com> On 16/09/2011 19:47, Benshep wrote: > I need a dictionary that returns the same value for multiple keys. > > i.e. > > (1)>>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } That will create a dict with 2 keys, both of which are tuples. > (2)>>>dict[1] > (3) 'text' > > I cant figure out what i need on line 2 to make this scenario work. Is > there a simple way to check if the a number is present in the key and > then return the value? > If you want multiple keys, then you must provide them separately: my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other text', 7: 'other text'} or use 'for' to iterate through the keys for each value: my_dict = dict([(k, 'text') for k in (1, 2, 3)] + [(k, 'other text') for k in (5, 6, 7)]) or something similar. From ben.r.shepherd at gmail.com Fri Sep 16 15:47:14 2011 From: ben.r.shepherd at gmail.com (Benshep) Date: Fri, 16 Sep 2011 12:47:14 -0700 (PDT) Subject: Using tuples to eliminate multiple dict values References: Message-ID: <3827f27a-8a37-4609-a9b1-62f06635c76d@hg2g2000vbb.googlegroups.com> thanks, I had a feeling that may be the way to go and my data just changed so it will work better that way. Thanks for the quick reply From arnodel at gmail.com Fri Sep 16 16:00:24 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:00:24 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 20:21, zombie wrote: > Hi guys, > ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? > Is there a way/formula to do it without expanding it? > > -- > http://mail.python.org/mailman/listinfo/python-list > In base 2, the answer is 1 :) Hopefully-helpfully-but-not-so-sure'ly yours, -- Arnaud From ian.g.kelly at gmail.com Fri Sep 16 16:06:34 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 14:06:34 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: > Hi guys, > ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? > Is there a way/formula to do it without expanding it? Possibly, but why worry about it? It's only around 300 digits. Since this sounds like homework, I won't post the one-liner I used to do it the brute-force way, but I will note that it takes about 200 microseconds to run on my laptop. Cheers, Ian From ramit.prasad at jpmorgan.com Fri Sep 16 16:16:03 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 16:16:03 -0400 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB53D3@EMARC112VS01.exchad.jpmchase.net> >> Hi guys, >> i am writing a program to sum up the digits of a number 2**1000? >> Is there a way/formula to do it without expanding it? >Since this sounds like homework, I won't post the one-liner I used to >do it the brute-force way, but I will note that it takes about 200 >microseconds to run on my laptop. If you happen to be new to Python, I will say I used these functions to create a one liner (in alphabetical order). Int Lambda Map Reduce Str Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From arnodel at gmail.com Fri Sep 16 16:17:45 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:17:45 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 21:06, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >> Hi guys, >> ? ? ? ? i am writing a program to sum up the digits of a number 2**1000? >> Is there a way/formula to do it without expanding it? > > Possibly, but why worry about it? ?It's only around 300 digits. > > Since this sounds like homework, I won't post the one-liner I used to > do it the brute-force way, but I will note that it takes about 200 > microseconds to run on my laptop. Ah go on, let's make a codegolf contest out of it. My entry: >>> sum(map(int,str(2**1000))) 1366 -- Arnaud From ian.g.kelly at gmail.com Fri Sep 16 16:20:46 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 14:20:46 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 2:17 PM, Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 That is exactly what mine was. From nagle at animats.com Fri Sep 16 16:50:45 2011 From: nagle at animats.com (John Nagle) Date: Fri, 16 Sep 2011 13:50:45 -0700 Subject: Why do closures do this? In-Reply-To: References: <20110828134505.795cd32b8fc5ccc472f85ae3@johnohagan.com> Message-ID: <4e73b6a7$0$1667$742ec2ed@news.sonic.net> On 8/27/2011 9:19 PM, Terry Reedy wrote: > On 8/27/2011 11:45 PM, John O'Hagan wrote: >> Somewhat apropos of the recent "function principle" thread, I was >> recently surprised by this: >> >> funcs=[] >> for n in range(3): >> def f(): >> return n >> funcs.append(f) >> >> >> >> The last expression, IMO surprisingly, is [2,2,2], not [0,1,2]. That's correct behavior, because a closure captures the binding of a nonlocal variable, not its value. There is only one "n" for all iterations. If you create a local variable within the closed function: def f() localn = n return(localn) there's a copy of "localn" for each iteration, and you're returning it. Try this in PyPy, which tries not to box numbers, and see what happens there. This is one of those Python features which complicates optimization. For performance, an implementation should handle numbers as machine numbers, not objects. (Creating an object to hold a machine primitive like an int, float, or bool is called "boxing' the number.) CPython always carries around a full CObject for ordinary numbers, which is why CPython numeric performance is so bad. PyPy tries not to do that, although there are rare cases when it has to, like this one. John Nagle From gherron at digipen.edu Fri Sep 16 16:53:10 2011 From: gherron at digipen.edu (Gary Herron) Date: Fri, 16 Sep 2011 13:53:10 -0700 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4E73B736.7060401@digipen.edu> On 09/16/2011 01:17 PM, Arnaud Delobelle wrote: > On 16 September 2011 21:06, Ian Kelly wrote: >> On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >>> Hi guys, >>> i am writing a program to sum up the digits of a number 2**1000? >>> Is there a way/formula to do it without expanding it? >> Possibly, but why worry about it? It's only around 300 digits. >> >> Since this sounds like homework, I won't post the one-liner I used to >> do it the brute-force way, but I will note that it takes about 200 >> microseconds to run on my laptop. > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 > Here's another one-liner using a generator instead of map: sum(int(c) for c in str(2**1000)) Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From arnodel at gmail.com Fri Sep 16 16:57:12 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 16 Sep 2011 21:57:12 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 16 September 2011 21:20, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 2:17 PM, Arnaud Delobelle wrote: >> Ah go on, let's make a codegolf contest out of it. >> My entry: >> >>>>> sum(map(int,str(2**1000))) >> 1366 > > That is exactly what mine was. > Slightly longer: >>> eval("+".join(str(2**1000))) 1366 This looks like a winner but I cheated (the result depends on the state of the interpreter): >>> eval("+".join(`2**1000`)) 1366 -- Arnaud From stefan-usenet at bytereef.org Fri Sep 16 17:07:31 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Fri, 16 Sep 2011 23:07:31 +0200 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <4E73B736.7060401@digipen.edu> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> <4E73B736.7060401@digipen.edu> Message-ID: <20110916210731.GA20553@sleipnir.bytereef.org> Gary Herron wrote: >>>> i am writing a program to sum up the digits of a number 2**1000? >>>> Is there a way/formula to do it without expanding it? > > Here's another one-liner using a generator instead of map: > > sum(int(c) for c in str(2**1000)) The OP did not specify the base: >>> bin(2**1000).count('1') 1 Or just: >>> print(1) 1 Stefan Krah From ramit.prasad at jpmorgan.com Fri Sep 16 17:13:38 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Sep 2011 17:13:38 -0400 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16DB54F7@EMARC112VS01.exchad.jpmchase.net> >>> sum(map(int,str(2**1000))) *smacks face* Gah, forgot about sum. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tjreedy at udel.edu Fri Sep 16 18:01:27 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:01:27 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On 9/16/2011 9:57 AM, Nobody wrote: >>I wonder if there are any >> heuristics for detecting exponential time re's. > > Exponential growth results from non-determinism, i.e. if there are > multiple transitions for a given character from a given state. > > Common patterns include: > > ...(a...)?a... > ...(a...)*a... > ...(a...)+a... > > with a choice between matching the "a" at the start of the bracketed > pattern or the "a" following it. > > (xxxa...|xxxb...|xxxc...) > > with a choice between branches which cannot be resolved until more data > has been read. > > For re.search (as opposed to re.match): > > axxxa... > > When axxx has been read, a following "a" gives a choice between > continuing the existing match with the second "a", or aborting and > matching against the first "a". For patterns which contain many copies of > the initial character, each copy creates another branch. > > Also, using back-references in a regexp [sic] can be a significant > performance killer, as it rules out the use of a DFA (which, IIRC, Python > doesn't do anyhow) and can require brute-forcing many combinations. A > particularly bad case is: > > (a*)\1 > > matching against "aaaaaaaa...". > > If the performance issue is with re.match/re.search rather than with > re.compile, one option is to use ctypes to access libc's regexp functions. > Those are likely to provide better searching throughput at the expense of > potentially increased compilation time. Now, can you write that as a heuristic *algorithm* def dangerous_re(some_re):? -- Terry Jan Reedy From tjreedy at udel.edu Fri Sep 16 18:16:43 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:16:43 -0400 Subject: parse html:what is the meaning of "//"? In-Reply-To: References: Message-ID: On 9/16/2011 7:02 AM, Stefan Behnel wrote: >> 0.00 >> N/A >> N/A >> 115 >> 2,411 >> >> >> Highlighted options are in-the-money. > > I don't see any highlighting in your text above, Gone with the ascii conversion. > and I don't know what you mean by "in-the-money". If a stock sells now for $20, an option to buy it for $19 is in-the-money and has definite value while an option to buy it for $21 is not, but is out-of-the-money and only has value according to one's subjective estimate of the likelihood of a rise above $21 before the option expires. -- Terry Jan Reedy From emekamicro at gmail.com Fri Sep 16 18:19:05 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 00:19:05 +0200 Subject: Code Review Message-ID: Hello All, While learning Python I put together another Text Twist. I would want somebody to go through it and comment. https://github.com/janus/Text-Twist -- Regards, Emeka * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 16 18:30:03 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 Sep 2011 18:30:03 -0400 Subject: Different class 'str' between v3. In-Reply-To: <4E735490.4060509@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: On 9/16/2011 9:52 AM, Vincent Vande Vyvre wrote: > Testing the following code, I've differend return with python 3.1.2 and > 3.2.2 running on two different machines with two different versions of Linux. I get > # -*- coding: utf-8 -*- > > import os > import sys > import platform > > print('\nPython version: ', sys.version.split()[0]) > print(platform.platform()) > > paths = ['/home/vincent/image.jpg', '/home/vincent/?????.jpg'] > > for path in paths: > print('\nPath: {0}, Type: {1}'.format(path, type(path))) > if not os.path.exists(path) or not os.path.isfile(path): > print('File not found: {0}'.format(path)) > else: > print('File exists') I get Python version: 3.2.2rc1 Windows-7-6.1.7601-SP1 Path: /home/vincent/image.jpg, Type: File not found: /home/vincent/image.jpg Path: /home/vincent/?????.jpg, Type: File not found: /home/vincent/?????.jpg so > [vincent at myhost ~]$ python string_2.py > > Python version: 3.2.2 > Linux-3.0-ARCH-x86_64-Pentium-R-_Dual-Core_CPU_T4500_ at _2.30GHz-with-glibc2.2.5 > > Path: /home/vincent/image.jpg, Type: > File exists > Traceback (most recent call last): > File "string_2.py", line 13, in > print('\nPath: {0}, Type: {1}'.format(path, type(path))) > UnicodeEncodeError: 'ascii' codec can't encode characters in position > 21-25: ordinal not in range(128) is not specific to 3.2.2 in general. Try the two Python versions on the same machine. Or try the test suite on each. See the test module doc for how. -- Terry Jan Reedy From brandonfigura at gmail.com Fri Sep 16 19:09:33 2011 From: brandonfigura at gmail.com (Fig) Date: Fri, 16 Sep 2011 16:09:33 -0700 (PDT) Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: I took out all of the color commands that were in the shape functions and all of the features to the 'draw_house' function showed showed up. I started putting the color commands back into the shape functions and have no problems with some of them but when I put the color command back into others, some of the features start to disappear. As far as I can see, all of the code is right but I'm just a beginner so I am not for sure. Can anyone tell me why this is doing what it is. From rosuav at gmail.com Fri Sep 16 19:19:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 17 Sep 2011 09:19:53 +1000 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 4:47 AM, Benshep wrote: > (1) ? >>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } > As I understand it, you're looking for a simple syntax for what MRAB posted: > my_dict = {1: 'text', 2: 'text', 3: 'text', 5: 'other text', 6 : 'other text', 7: 'other text'} Since your first line of code is syntactically legal, you could do a simple check afterwards to translate it: my_dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } for k in list(my_dict.keys()): if isinstance(k,tuple): val=my_dict.pop(k) for i in k: my_dict[i]=val Tested in Python 3.2; in Python 2, the list() call is superfluous, everything else should work fine. Chris Angelico From ian.g.kelly at gmail.com Fri Sep 16 19:28:39 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 17:28:39 -0600 Subject: Different class 'str' between v3. In-Reply-To: <4E735490.4060509@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: On Fri, Sep 16, 2011 at 7:52 AM, Vincent Vande Vyvre wrote: > [vincent at myhost ~]$ python string_2.py > > Python version:? 3.2.2 > Linux-3.0-ARCH-x86_64-Pentium-R-_Dual-Core_CPU_T4500_ at _2.30GHz-with-glibc2.2.5 > > Path: /home/vincent/image.jpg, Type: > File exists > Traceback (most recent call last): > ? File "string_2.py", line 13, in > ??? print('\nPath: {0}, Type: {1}'.format(path, type(path))) > UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-25: > ordinal not in range(128) This looks like a terminal encoding issue on the second PC. Your terminal is probably not using a unicode encoding, and so it is unable to print a unicode string. Cheers, Ian From ppaterson at gmail.com Fri Sep 16 19:48:08 2011 From: ppaterson at gmail.com (Paul Paterson) Date: Fri, 16 Sep 2011 16:48:08 -0700 (PDT) Subject: setuptools: getting data files to be installed Message-ID: <9476205.3046.1316216888277.JavaMail.geo-discussion-forums@prdy8> I'm having a problem using setuptools to create a distribution for a project that includes data files. I can get the data files to be included in the zipped package file (*.tar.gz) but when I easy_install the package the data files are not installed. (Ubuntu 11.04, Python2.7). I'm trying to use easy_install because the project is a game with dependencies and so it would be nice for easy_install to handle all that for people. My setup.py file is below at the end of the post. I create the zip with, > python setup.py egg_info ... > python setup.py sdist Then the dist/tacman-0.1.tar.gz includes my data files as identified in the MANIFEST.in file. But when I do, > sudo easy_install dist/tacman-0.1.tar.gz ... the python modules appear in /usr/local/lib/python27/dist-packages/tacman-0.1-py2.7.egg but the data files are nowhere to be seen. I tried locating them using pkg_resources but that didn't help. Some Googling suggested /usr/share as a location but they weren't there either. Am I looking in the right place or did they just not get installed? The whole distribution file is at http://perpetualpyramid.com/tacman-0.1.tar.gz in case that helps. The file is bit large because it is a game and the zip includes the music and graphics. Thanks for any help and pointers. Paul --- setup.py --- from setuptools import setup, find_packages import game.common setup(name='tacman', version=game.common.version, scripts=['tacman.py'], entry_points = { 'console_scripts' : [ 'tacman = tacman.tacman', ] }, description='A tactical, turn-based clone on PACMAN', author='Paul Paterson', author_email='ppaterson at gmail.com', url='http://www.perpetualpyramid/tacman.html', download_url=('http://perpetualpyramid.com/tacman-%s.tar.gz' % game.common.version), include_package_data=True, zip_safe=False, packages=[ 'serge', 'serge.blocks', 'serge.tools', 'serge.tools.template', 'game', ], package_dir={'':'.'}, classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Games/Entertainment", "Topic :: Games/Entertainment :: Puzzle Games", ], install_requires=[ 'pygame', 'networkx', ], long_description='''\ TACMAN ------ A turn-based, tactical version of PACMAN. Play a PACMAN clone where the action is turn based. You move and then the ghosts move. The turn-based action adds additional tactical elements to the game and allows you to plan ahead and outwit the ghosts! Requires: Python 2.6+, pygame 1.9+, networkx ''', ) From python.list at tim.thechases.com Fri Sep 16 19:48:40 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 16 Sep 2011 18:48:40 -0500 Subject: Using tuples to eliminate multiple dict values In-Reply-To: References: Message-ID: <4E73E058.6010303@tim.thechases.com> On 09/16/11 13:47, Benshep wrote: > I need a dictionary that returns the same value for multiple keys. > > i.e. > > (1)>>> dict = { (1,2,3) : 'text' , (5,6,7) : 'other text' } > (2)>>>dict[1] > (3) 'text' > > I cant figure out what i need on line 2 to make this scenario work. Is > there a simple way to check if the a number is present in the key and > then return the value? You could use something like d = dict( (k,v) for keys in ( ((1,2,3), 'text'), ((5,6,7), 'other text'), ) for k in keys ) which seems to do what you want with minimal redundancy of declarations. - From steve+comp.lang.python at pearwood.info Fri Sep 16 22:17:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 17 Sep 2011 12:17:05 +1000 Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4e740322$0$29983$c3e8da3$5496439d@news.astraweb.com> Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > >>>> sum(map(int,str(2**1000))) > 1366 Time for some obfuscated Python! b = (16,13624) for i in range(23, 42, 3): b = (b[0]*b[0], b[1]+1024) for j in range(12345, 8929, -7): b = (b[0]+b[0], b[1]-3) while b > (0,9876): b = tuple((lambda a,b: map(lambda a,b:a+b, a,b)) ((lambda a,b: map(lambda a,b:a*b, a,b)) (b,(0,1)), (lambda a,b: map(lambda a,b:a-b, a,b)) (divmod(b[0],10),(0,64)))) print b[1] -- Steven From invalid at invalid.invalid Fri Sep 16 22:19:12 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 17 Sep 2011 02:19:12 +0000 (UTC) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 2011-09-16, Gary Herron wrote: > On 09/16/2011 01:17 PM, Arnaud Delobelle wrote: >> On 16 September 2011 21:06, Ian Kelly wrote: >>> On Fri, Sep 16, 2011 at 1:21 PM, zombie wrote: >>>> Hi guys, >>>> i am writing a program to sum up the digits of a number 2**1000? >>>> Is there a way/formula to do it without expanding it? >>> Possibly, but why worry about it? It's only around 300 digits. >>> >>> Since this sounds like homework, I won't post the one-liner I used to >>> do it the brute-force way, but I will note that it takes about 200 >>> microseconds to run on my laptop. >> Ah go on, let's make a codegolf contest out of it. >> My entry: >> >>>>> sum(map(int,str(2**1000))) >> 1366 >> > > Here's another one-liner using a generator instead of map: > > sum(int(c) for c in str(2**1000)) Just in case you can't spare the 3KB required for the list of integers that map creates. :) In this case it doesn't matter, but it's not hard to find problems where the difference between the memory requirements for a generator and a map/list-comprehension are significant enough to worry about. -- Grant From chunuan723 at gmail.com Fri Sep 16 22:56:41 2011 From: chunuan723 at gmail.com (he sharon) Date: Fri, 16 Sep 2011 19:56:41 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <18e9f5c3-055e-4515-a7dc-517f46e90ec5@s2g2000vby.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From chunuan723 at gmail.com Fri Sep 16 22:58:59 2011 From: chunuan723 at gmail.com (he sharon) Date: Fri, 16 Sep 2011 19:58:59 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From ian.g.kelly at gmail.com Fri Sep 16 23:11:44 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 16 Sep 2011 21:11:44 -0600 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On Fri, Sep 16, 2011 at 8:19 PM, Grant Edwards wrote: >> Here's another one-liner using a generator instead of map: >> >> ? ? ?sum(int(c) for c in str(2**1000)) > > Just in case you can't spare the 3KB required for the list of integers > that map creates. :) > > In this case it doesn't matter, but it's not hard to find problems > where the difference between the memory requirements for a generator > and a map/list-comprehension are significant enough to worry about. Unless otherwise specified, I generally assume that code on this list is for Python 3, and map in Python 3 returns an iterator. Cheers, Ian From vincent.vandevyvre at swing.be Fri Sep 16 23:28:25 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sat, 17 Sep 2011 05:28:25 +0200 Subject: Different class 'str' between v3. In-Reply-To: References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> Message-ID: <4E7413D9.4000706@swing.be> An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Sat Sep 17 00:55:41 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sat, 17 Sep 2011 06:55:41 +0200 Subject: Different class 'str' between v3. In-Reply-To: <4E7413D9.4000706@swing.be> References: <10b34bf7-ecd0-472d-8c69-634d7e6ed77f@glegroupsg2000goo.googlegroups.com> <4E735490.4060509@swing.be> <4E7413D9.4000706@swing.be> Message-ID: <4E74284D.7090900@swing.be> An HTML attachment was scrubbed... URL: From alex.kapps at web.de Sat Sep 17 02:59:10 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 17 Sep 2011 08:59:10 +0200 Subject: strange results In-Reply-To: References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: <4E74453E.2020908@web.de> On 17.09.2011 01:09, Fig wrote: > I took out all of the color commands that were in the shape functions > and all of the features to the 'draw_house' function showed showed up. > I started putting the color commands back into the shape functions and > have no problems with some of them but when I put the color command > back into others, some of the features start to disappear. As far as I > can see, all of the code is right but I'm just a beginner so I am not > for sure. Can anyone tell me why this is doing what it is. > Just tried your program on Ubuntu 10.04 with Python 2.6.5 and GASP 0.3.3 and it worked fine. What OS, Python version and GASP version are you using? If you don't get an answer here, try asking on the Launchpad project site: https://launchpad.net/gasp From ladasky at my-deja.com Sat Sep 17 03:26:19 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 00:26:19 -0700 (PDT) Subject: Accessing matplotlib-users discussion group? References: <4a923fa6-47ad-4083-8770-a2b23446dadf@br5g2000vbb.googlegroups.com> <9dhfchFvt2U1@mid.individual.net> Message-ID: <03b8d48e-4fdf-4aaf-8249-367ac618d4f1@s3g2000vbx.googlegroups.com> On Sep 16, 10:29?am, Martin Sch??n wrote: > On 2011-09-15, John Ladasky wrote: > > > Hate to bump this, but... I found Sourceforge's IRC, and tried to ask > > for help there, and it doesn't look like I can get any help until > > business hours tomorrow. ?Anyone? > > No help really but I 'joined' Sourceforge about a year ago and > had no problems whatsoever. > > Could it be some anti-robot filter that's gotten overly picky? > > /Martin Well, I got through to Sourceforge today, and succeeded in subscribing. A support person said that their site's registration web page has compatibility issues with certain web browsers and/or their extensions. I was using Chrome. They asked me to try another browser, I tried Firefox, and it worked. Personally, I find that to be pretty bizarre -- but it worked. From ladasky at my-deja.com Sat Sep 17 04:34:18 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 01:34:18 -0700 (PDT) Subject: multiprocessing.Pool, its queue, and pre-emption References: Message-ID: Hey, this pretty easy hack appears to work! [code] from multiprocessing.pool import Pool, RUN, MapResult, mapstar class PriorityPool(Pool): def map_async_nowait(self, func, iterable, chunksize=None, \ callback=None): """ Same as map_async(), except uses put_nowait() and thus posts tasks to the head of the task queue rather than its tail. """ assert self._state == RUN if not hasattr(iterable, '__len__'): iterable = list(iterable) if chunksize is None: chunksize, extra = divmod(len(iterable), len(self._pool) * 4) if extra: chunksize += 1 task_batches = Pool._get_tasks(func, iterable, chunksize) result = MapResult(self._cache, chunksize, len(iterable), \ callback) self._taskqueue.put_nowait((((result._job, i, mapstar, (x,), {}) \ for i, x in enumerate(task_batches)), None)) return result def size(self): """ This is not an essential function, but I use it in the demo to ensure that I initially create enough tasks to occupy every Process. """ return len(self._pool) ##================================================================## if __name__ == "__main__": from time import sleep def demo_task(args): num, time = args sleep(time) print num, time pool = PriorityPool() size = pool.size() print "\nConstructed a pool which contains", size, "Processes." print "Queueing", 2*size, "normal-priority tasks." normal = enumerate([3.0 + t for t in range(2*size)]) pool.map_async(demo_task, normal, chunksize = 1) print "Queueing", size, "high-priority tasks." high = [(2*size + t, 0.2 + 0.1*t) for t in range(size)] pool.map_async_nowait(demo_task, high, chunksize = 1) sleep(30) # Give all tasks on the queue time to complete. print "Complete." [/code] Below is a typical output from my six-core CPU system. The output differs slightly from run to run -- that's multiprocessing for you, it's asynchronous. The tasks are given numbers which correspond to the order that they are added to the queue. The high-priority tasks are added last and are thus numbered 12-17 (I place asterisks next to these in the output, below). Each task prints its number and its time when it completes. I expect the normal-priority tasks 0-5 to finish before any high-priority tasks, and they always do. Tasks 6 and 7 are then interleaved among the high-priority tasks -- not quite what I expect, but that may have something to do with my rather arbitrary choices of sleep times. But tasks 8-11 always get pushed to the back, and complete last. [output] Constructed a pool which contains 6 Processes. Queueing 12 normal-priority tasks. Queueing 6 high-priority tasks. 0 3.0 1 4.0 2 5.0 3 6.0 4 7.0 5 8.0 6 9.0 12 0.2 * 13 0.3 * 14 0.4 * 15 0.5 * 7 10.0 16 0.6 * 17 0.7 * 8 11.0 9 12.0 10 13.0 11 14.0 [/output] Please feel free to use this, though I would appreciate an acknowledgment in your code if you do. :^) From phihag at phihag.de Sat Sep 17 07:19:01 2011 From: phihag at phihag.de (Philipp Hagemeister) Date: Sat, 17 Sep 2011 13:19:01 +0200 Subject: Code Review In-Reply-To: References: Message-ID: <4E748225.8020602@phihag.de> Instead of comments, you can often use docstrings (http://www.python.org/dev/peps/pep-0257/ ): This is hard to read due to the indentation, and cannot be accessed programmatically: #Update the GUI def update_gui(self, new_word): Instead, use this: def update_gui(self, new_word): "Update the GUI." Now, you can use help(Message) to get information about the method. You'll notice "Update the GUI." is not helpfull at all for a method called update_gui. Comments (and docstrings) that reproduce the method name are not useful. A couple of minor things: * If you delete code, delete it, don't comment it out. * Use newlines between two methods. Compare def a(self): pass def b(self): pass def c(self): pass with def a(self): pass def b(self): pass def c(self): pass The latter looks neat and not nearly as crammed as the former. * Don't use newlines where they shouldn't be, for example in if val == 0: label.unbind('') * Even if it's just the comments, typos make a very bad impression of a coder and the code. I'd automatically assume lots of bugs and untested code when I see more than the occasional typo. * GUI programming is fun, but does not lend itself to structured programming and good practices. You should never use global. Instead, have an object encapsulating the state and pass that object to the method itself or its object. * Don't commit .pyc files, they're totally useless. Since python 2.6, you can add the following in your .bashrc to make python not create them: export "PYTHONDONTWRITEBYTECODE=dont" In git, you can add the following in your project's .gitignore or ~/.gitignore_global: *.pyc [More on .gitignore: http://help.github.com/ignore-files/ ] * Otherwise, the code looks pretty good for a beginner. You may, however, want to replace def word_not_found(word): if word in searchedwordset: return 0 else: return 1 with just: def word_not_found(word): return word not in searchedwordset (or just skip this method and write word not in searchedwordset). Cheers, Philipp Emeka wrote: > Hello All, > > While learning Python I put together another Text Twist. I would want > somebody to go through it and comment. > https://github.com/janus/Text-Twist > > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: OpenPGP digital signature URL: From rafadurancastaneda at gmail.com Sat Sep 17 07:56:25 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sat, 17 Sep 2011 13:56:25 +0200 Subject: create a directory structure In-Reply-To: <4E73566A.1010808@gmail.com> References: <4E732F4B.3090409@gmail.com> <4E73566A.1010808@gmail.com> Message-ID: 2011/9/16 Andrea Crotti > After some research, I think that paste-script is the best choice in this > case. > > I can define templates and I'll get my directory structure nicely populated > for me. > > -- > http://mail.python.org/**mailman/listinfo/python-list > I think you might want to look at Fabricor vagrant -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Sat Sep 17 09:26:23 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 14:26:23 +0100 Subject: Code Review In-Reply-To: <4E748225.8020602@phihag.de> References: <4E748225.8020602@phihag.de> Message-ID: Philipp, Thanks so much for your time and comment. I will re-work my code accordingly. Regards, Emeka On Sat, Sep 17, 2011 at 12:19 PM, Philipp Hagemeister wrote: > Instead of comments, you can often use docstrings > (http://www.python.org/dev/peps/pep-0257/ ): > > This is hard to read due to the indentation, and cannot be accessed > programmatically: > > #Update the GUI > def update_gui(self, new_word): > > Instead, use this: > > def update_gui(self, new_word): > "Update the GUI." > > Now, you can use help(Message) to get information about the method. > You'll notice "Update the GUI." is not helpfull at all for a method > called update_gui. Comments (and docstrings) that reproduce the method > name are not useful. > > A couple of minor things: > > * If you delete code, delete it, don't comment it out. > * Use newlines between two methods. Compare > def a(self): > pass > def b(self): > pass > def c(self): > pass > > with > > def a(self): > pass > > def b(self): > pass > > def c(self): > pass > > The latter looks neat and not nearly as crammed as the former. > * Don't use newlines where they shouldn't be, for example in > if val == 0: > > label.unbind('') > * Even if it's just the comments, typos make a very bad impression of a > coder and the code. I'd automatically assume lots of bugs and untested > code when I see more than the occasional typo. > * GUI programming is fun, but does not lend itself to structured > programming and good practices. You should never use global. Instead, > have an object encapsulating the state and pass that object to the > method itself or its object. > * Don't commit .pyc files, they're totally useless. Since python 2.6, > you can add the following in your .bashrc to make python not create them: > > export "PYTHONDONTWRITEBYTECODE=dont" > > In git, you can add the following in your project's .gitignore or > ~/.gitignore_global: > > *.pyc > > [More on .gitignore: http://help.github.com/ignore-files/ ] > * Otherwise, the code looks pretty good for a beginner. You may, > however, want to replace > > def word_not_found(word): > if word in searchedwordset: > return 0 > else: > return 1 > > with just: > > def word_not_found(word): > return word not in searchedwordset > > (or just skip this method and write word not in searchedwordset). > > Cheers, > > Philipp > > > > Emeka wrote: > > Hello All, > > > > While learning Python I put together another Text Twist. I would want > > somebody to go through it and comment. > > https://github.com/janus/Text-Twist > > > > > > > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From brandonfigura at gmail.com Sat Sep 17 09:58:27 2011 From: brandonfigura at gmail.com (Fig) Date: Sat, 17 Sep 2011 06:58:27 -0700 (PDT) Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: On Sep 17, 1:59?am, Alexander Kapps wrote: > On 17.09.2011 01:09, Fig wrote: > > > I took out all of the color commands that were in the shape functions > > and all of the features to the 'draw_house' function showed showed up. > > I started putting the color commands back into the shape functions and > > have no problems with some of them but when I put the color command > > back into others, some of the features start to disappear. As far as I > > can see, all of the code is right but I'm just a beginner so I am not > > for sure. Can anyone tell me why this is doing what it is. > > Just tried your program on Ubuntu 10.04 with Python 2.6.5 and GASP > 0.3.3 and it worked fine. What OS, Python version and GASP version > are you using? > > If you don't get an answer here, try asking on the Launchpad project > site: > > https://launchpad.net/gasp My OS is Windows 7, Python 2.7.2, I downloaded and installed the python-gasp-0.2.0beta1.win32.exe file, and I also have these installed: Python 2.7 pygame-1.9.2a0 and Python 2.7 pywin32-216 From yasar11732 at gmail.com Sat Sep 17 11:10:31 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sat, 17 Sep 2011 18:10:31 +0300 Subject: Modifiying __getattribute__ of an instance Message-ID: I am trying to modify __getattribute__() method for an instance, as you may already know,__getattirbute__ is read-only attribute in Python. What I have in mind is, create a new object like this: def create_new_instace(old_instance): class temp(old_instance.__class__): def __init__(self,*args,**kwargs): "Since we will copy an already inited instance" pass def __getattribute__(self,attr): # do stuff new_instance = temp() # magically copy all attrs of old_instance to new_instance return new_instance Is this kind of thing possible? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From as at sci.fi Sat Sep 17 11:25:11 2011 From: as at sci.fi (Anssi Saari) Date: Sat, 17 Sep 2011 18:25:11 +0300 Subject: strange results References: <5bf9fb8e-6c46-4342-8eb3-a0b71fcb0205@k28g2000yqh.googlegroups.com> Message-ID: Fig writes: > My OS is Windows 7, Python 2.7.2, I downloaded and installed the > python-gasp-0.2.0beta1.win32.exe file, and I also have these > installed: Python 2.7 pygame-1.9.2a0 and Python 2.7 pywin32-216 Then maybe that old beta version is your problem? For the record, your code works for me too in Linux and python-gasp 0.3.3. Looks like there's no Windows installer for newer python-gasp. Maybe you could install with easy_install as they describe on the site? From missive at hotmail.com Sat Sep 17 11:58:32 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 17 Sep 2011 20:28:32 +0430 Subject: os independent rename Message-ID: I just got a bug report the heart of which is the difference between unix and windows in using os.rename (ie, "On Windows, if dst already exists, OSError will be raised") Hmm, I thought, maybe I'm supposed to use shutil here. That is the "high-level" operations. Unfortunately, shutil.move says it depends on os.rename So, what is the best way to do this that will behave the same across operating systems? From ian.g.kelly at gmail.com Sat Sep 17 12:41:18 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 17 Sep 2011 10:41:18 -0600 Subject: os independent rename In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 9:58 AM, Lee Harr wrote: > > I just got a bug report the heart of which is the > difference between unix and windows in using > os.rename > > (ie, "On Windows, if dst already exists, OSError will be raised") > > Hmm, I thought, maybe I'm supposed to use > shutil here. That is the "high-level" operations. > Unfortunately, shutil.move says it depends on > os.rename > > So, what is the best way to do this that will > behave the same across operating systems? shutil.move works for me, at least in Python 2.7. The docstring doesn't seem to match the code here: try: os.rename(src, real_dst) except OSError: if os.path.isdir(src): if _destinsrc(src, dst): raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst) copytree(src, real_dst, symlinks=True) rmtree(src) else: copy2(src, real_dst) os.unlink(src) From invalid at invalid.invalid Sat Sep 17 12:42:18 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 17 Sep 2011 16:42:18 +0000 (UTC) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: On 2011-09-17, Ian Kelly wrote: > On Fri, Sep 16, 2011 at 8:19 PM, Grant Edwards wrote: >>> Here's another one-liner using a generator instead of map: >>> >>> ? ? ?sum(int(c) for c in str(2**1000)) >> >> Just in case you can't spare the 3KB required for the list of integers >> that map creates. :) >> >> In this case it doesn't matter, but it's not hard to find problems >> where the difference between the memory requirements for a generator >> and a map/list-comprehension are significant enough to worry about. > > Unless otherwise specified, I generally assume that code on this list > is for Python 3, and map in Python 3 returns an iterator. Indeed, I forgot about that (I'm still using Python 2 since I use some libraries that haven't been ported). -- Grant From kw at codebykevin.com Sat Sep 17 14:01:47 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 17 Sep 2011 14:01:47 -0400 Subject: Python bug in Windows 8--report now, or later? Message-ID: I have been testing my Python application on the just-released developer preview of Windows 8 and have noted an error: the application does not create an app folder in the user's "application data" directory. This causes the app to crash on startup. Manually creating the directory solves the problem. Since the app uses an os.mkdir() call to create the directory, and since the app runs fine on Windows 7, my guess is that the bug lies somewhere in the interaction between Python (I'm using ActivePython 2.7) and Windows. Here's the relevant code: #make preferences directory if it does not exist def makePrefsDir(self): self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], 'MyApp')) if not os.path.exists(self.appdir): os.mkdir(self.appdir) I realize that this developer preview of Windows is still at somewhere between alpha- and beta-level, and it's possible things will get better. Should I wait to report this as a bug until Windows 8 is released, or do the Python developers test Python on pre-release versions of Windows? From missive at hotmail.com Sat Sep 17 14:40:02 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 17 Sep 2011 23:10:02 +0430 Subject: os independent rename Message-ID: > shutil.move works for me, at least in Python 2.7. The docstring> doesn't seem to match the code Thanks for checking that. Looks like there is a closed report about the misleading docs:http://bugs.python.org/issue12577 Closed a couple of months ago, but the docs have not madeit to the web yet.... -------------- next part -------------- An HTML attachment was scrubbed... URL: From shajiashish at gmail.com Sat Sep 17 14:41:18 2011 From: shajiashish at gmail.com (Indian Entertainment) Date: Sat, 17 Sep 2011 11:41:18 -0700 (PDT) Subject: All Posters Com Message-ID: With more than 1,000,000 images, AllPosters is your one-stop-shop for wall art, providing a huge assortment of posters, art prints and other items to suit all interests, decorating styles and budgets. Browse the latest posters in music, movies, sports, and more. Find your favorite art prints from the classic masters. Discover up-and-coming artists. Explore our special collections. Then choose from a wide array of custom-framing, canvas, wood-mounting and other service options to truly make it your own ? all high quality and at amazing prices. Start searching now and see for yourself how AllPosters is transforming the way the world discovers and personalizes art. Check out the art we're digging right now and what's on our gotta-hang-it list. We've narrowed down the 1,000,000 options (and counting) on AllPosters.com to our select favorites, including vintage posters, retro comics, Warhol masterpieces and a samurai. http://tinyurl.com/44skelw From nobody at nowhere.com Sat Sep 17 15:00:53 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 17 Sep 2011 20:00:53 +0100 Subject: Cancel or timeout a long running regular expression References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: On Fri, 16 Sep 2011 18:01:27 -0400, Terry Reedy wrote: > Now, can you write that as a heuristic *algorithm* > def dangerous_re(some_re):? return re.search(r'\\\d', some_re) is not None That will handle the most extreme case ;) If the OP is serious about analysing regexps, sre_parse.parse() will decompose a regexp to a more convenient form. However, I wouldn't rely upon being able to catch every possible bad case. The only robust solution is to use a separate process (threads won't suffice, as they don't have a .kill() method). From nobody at nowhere.com Sat Sep 17 15:18:19 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 17 Sep 2011 20:18:19 +0100 Subject: os independent rename References: Message-ID: On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: > So, what is the best way to do this that will > behave the same across operating systems? Delete the destination first, but after checking that it isn't the same as the source. On Windows, that last bit is harder than it seems. A string-based comparison won't work. Even if you ignore case, there's the issue of 8.3 filenames, and some other odd cases. From tjreedy at udel.edu Sat Sep 17 17:19:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Sep 2011 17:19:26 -0400 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On 9/17/2011 2:01 PM, Kevin Walzer wrote: > I have been testing my Python application on the just-released developer > preview of Windows 8 and have noted an error: the application does not > create an app folder in the user's "application data" directory. This > causes the app to crash on startup. Manually creating the directory > solves the problem. Since the app uses an os.mkdir() call to create the > directory, and since the app runs fine on Windows 7, my guess is that > the bug lies somewhere in the interaction between Python (I'm using > ActivePython 2.7) and Windows. We need more that guesses to act. I think is premature to call this a 'Python bug'. > Here's the relevant code: > > #make preferences directory if it does not exist > def makePrefsDir(self): > self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], 'MyApp')) > if not os.path.exists(self.appdir): > os.mkdir(self.appdir) > > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do > the Python developers test Python on pre-release versions of Windows? 3 days ago (Sept 14) someone asked about 'Windows 8 support' on pydev list. The answers were 1) 2.7 and 3.2 appear to run fine on the Dev release (but there was no report of test suite results); 2) Python directly uses so little of the Win interface that problems are not anticipated; 3) applications might have to make Win 8 specific adjustments and should test before the release. Of course, if MS accidentally changes thinly wrapped system calls such as os.environ, .exists, and .makedir, there will be a problem but that is their bug. My impression is that they are not intentionally breaking such things. I anticipate 3.3 and some future 2.7.z will be officially supported (and tested) on Win 8. -- Terry Jan Reedy From rosuav at gmail.com Sat Sep 17 17:20:26 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 07:20:26 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 4:01 AM, Kevin Walzer wrote: > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do the > Python developers test Python on pre-release versions of Windows? I would consider reporting it as a bug in Windows 8, not a bug in Python. Chris Angelico From rosuav at gmail.com Sat Sep 17 17:35:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 07:35:01 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) Message-ID: On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: > The only robust solution is to use a separate process (threads won't > suffice, as they don't have a .kill() method). > Forking a thread to discuss threads.... ahem. Why is it that threads can't be killed? Do Python threads correspond to OS-provided threads (eg POSIX threads on Linux)? Every OS threading library I've seen has some way of killing threads, although I've not looked in detail into POSIX threads there (there seem to be two options, pthread_kill and pthread_cancel, that could be used, but I've not used either). If nothing else, it ought to be possible to implement a high level kill simply by setting a flag that the interpreter will inspect every few commands, the same way that KeyboardInterrupt is checked for. Is it just that nobody's implemented it, or is there a good reason for avoiding offering this sort of thing? Chris Angelico From clp2 at rebertia.com Sat Sep 17 18:27:45 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 17 Sep 2011 15:27:45 -0700 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 2:35 PM, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: >> The only robust solution is to use a separate process (threads won't >> suffice, as they don't have a .kill() method). > > Forking a thread to discuss threads.... ahem. > > Why is it that threads can't be killed? Do Python threads correspond > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading > library I've seen has some way of killing threads, although I've not > looked in detail into POSIX threads there (there seem to be two > options, pthread_kill and pthread_cancel, that could be used, but I've > not used either). If nothing else, it ought to be possible to > implement a high level kill simply by setting a flag that the > interpreter will inspect every few commands, the same way that > KeyboardInterrupt is checked for. > > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? It's possible that the reason is analogous to why Java has deprecated its equivalent, Thread.stop(): http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Cheers, Chris From rosuav at gmail.com Sat Sep 17 19:19:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 09:19:46 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 8:27 AM, Chris Rebert wrote: > It's possible that the reason is analogous to why Java has deprecated > its equivalent, Thread.stop(): > http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Interesting. The main argument against having a way to raise an arbitrary exception in a different thread is that it gets around Java's requirement to declare all exceptions that a routine might throw - a requirement that Python doesn't have. So does that mean it'd be reasonable to have a way to trigger a "TerminateThread" exception (like SystemExit but for one thread) remotely? The above article recommends polling a variable, but that's the exact sort of thing that exceptions are meant to save you from doing. ChrisA From cs at zip.com.au Sat Sep 17 19:23:38 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 18 Sep 2011 09:23:38 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <20110917232338.GA22838@cskk.homeip.net> On 17Sep2011 15:27, Chris Rebert wrote: | On Sat, Sep 17, 2011 at 2:35 PM, Chris Angelico wrote: | > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: | >> The only robust solution is to use a separate process (threads won't | >> suffice, as they don't have a .kill() method). | > | > Forking a thread to discuss threads.... ahem. | > | > Why is it that threads can't be killed? Do Python threads correspond | > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading | > library I've seen has some way of killing threads, although I've not | > looked in detail into POSIX threads there (there seem to be two | > options, pthread_kill and pthread_cancel, that could be used, but I've | > not used either). If nothing else, it ought to be possible to | > implement a high level kill simply by setting a flag that the | > interpreter will inspect every few commands, the same way that | > KeyboardInterrupt is checked for. | > | > Is it just that nobody's implemented it, or is there a good reason for | > avoiding offering this sort of thing? | | It's possible that the reason is analogous to why Java has deprecated | its equivalent, Thread.stop(): | http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html Interesting. A lot of that discussion concerns exceptions that the Java app is unprepared for. Java's strong typing includes the throwable exceptions, so that's a quite legitimate concern. The aborting mutex regions thing is also very real. Conversely, Python can have unexpected exceptions anywhere, anytime because it is not strongly typed in this way. That doesn't make it magicly robust against this, but does mean this is _already_ an issue in Python programs, threaded or otherwise. Context managers can help a lot here, in that they offer a reliable exception handler in a less ad hoc fashion than try/except because it is tied to the locking object; but they won't magicly step in save your basic: with my_lock: stuff... Personally I'm of the view that thread stopping should be part of the overt program logic, not a low level facility (such as causing a ThreadDeath exception asynchronously). The latter has all the troubles in the cited URL. Doing it overtly would go like this: ... outside ... that_thread.stop() # sets the "stopping" flag on the thread object that_thread.join() # and now maybe we wait for it... ... thread code ... ... do stuff, eg: with my_lock: muck about ... if thread.stopping: abort now, _outside_ the mutex ... This avoids the issue of aborting in the middle of supposedly mutex-safe code. It still requires scattering checks on thread.stopping through library code such as the OP's rogue regexp evaluator. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ One measure of `programming complexity' is the number of mental objects you have to keep in mind simultaneously in order to understand a program. The mental juggling act is one of the most difficult aspects of programming and is the reason programming requires more concentration than other activities. It is the reason programmers get upset about `quick interruptions' -- such interruptions are tantamount to asking a juggler to keep three balls in the air and hold your groceries at the same time. - Steve McConnell, _Code Complete_ From cs at zip.com.au Sat Sep 17 19:27:54 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 18 Sep 2011 09:27:54 +1000 Subject: os independent rename In-Reply-To: References: Message-ID: <20110917232754.GA24525@cskk.homeip.net> On 17Sep2011 20:18, Nobody wrote: | On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: | > So, what is the best way to do this that will | > behave the same across operating systems? | | Delete the destination first, but after checking that it isn't the same as | the source. This is usually a step that the UNIX os.rename is designed to avoid. By deleting first, there is a window where the destination doesn't exist at all. Also, if the subsequent rename fails, the destination is missing long term. os.rename() on UNIX specifies that after the call either the new items is at destination (success) or the old item is (failure). Either way you still have a valid destination object. So you're breaking the model that os.rename() strives explicitly to provide. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Q: How many user support people does it take to change a light bulb? A: We have an exact copy of the light bulb here and it seems to be working fine. Can you tell me what kind of system you have? From tjreedy at udel.edu Sat Sep 17 19:30:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 Sep 2011 19:30:31 -0400 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On 9/17/2011 7:19 PM, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 8:27 AM, Chris Rebert wrote: >> It's possible that the reason is analogous to why Java has deprecated >> its equivalent, Thread.stop(): >> http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html > > Interesting. The main argument against having a way to raise an > arbitrary exception in a different thread is that it gets around > Java's requirement to declare all exceptions that a routine might > throw - a requirement that Python doesn't have. I saw the main argument as being that stopping a thread at an arbitrary point can have an arbitrary, unpredictable effect on all other threads. And more so that shutting down an independent process. -- Terry Jan Reedy From rosuav at gmail.com Sat Sep 17 19:38:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 18 Sep 2011 09:38:05 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sun, Sep 18, 2011 at 9:26 AM, Dennis Lee Bieber wrote: > def threadWork(lock, a1, a2, rate): > ? ? ? ?while True: > ? ? ? ? ? ? ? ?time.sleep(rate) > ? ? ? ? ? ? ? ?lock.lock() > ? ? ? ? ? ? ? ?t = a2.balance / 2 > ? ? ? ? ? ? ? ?a1.balance += t > ? ? ? ? ? ? ? ?#say a thread.kill kills at this point > ? ? ? ? ? ? ? ?a2.balance -= t > ? ? ? ? ? ? ? ?lock.release() > It's obviously going to be an issue with killing processes too, which is why database engines have so much code specifically to protect against this. But if it's done as an exception, all you need is to catch that exception and reraise it: def threadWork(lock, a1, a2, rate): try: while True: time.sleep(rate) lock.lock() t = a2.balance / 2 a1.balance += t #say a thread.kill kills at this point a2.balance -= t lock.release() except: # roll back the transaction in some way lock.release() raise It'd require some care in coding, but it could be done. And if the lock/transaction object can be coded for it, it could even be done automatically: def threadWork(lock, a1, a2, rate): while True: time.sleep(rate) transaction.begin() t = a2.balance / 2 transaction.apply(a1.balance,t) #say a thread.kill kills at this point transaction.apply(a2.balance,-t) transaction.commit() If the transaction object doesn't get its commit() called, it does no actions at all, thus eliminating all issues of locks. Obviously there won't be any problem with the Python interpreter itself (refcounts etc) if the kill is done by exception - that would be a potential risk if using OS-level kills. ChrisA From python at mrabarnett.plus.com Sat Sep 17 19:52:15 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 18 Sep 2011 00:52:15 +0100 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <4E7532AF.8000707@mrabarnett.plus.com> On 18/09/2011 00:26, Dennis Lee Bieber wrote: > On Sun, 18 Sep 2011 07:35:01 +1000, Chris Angelico > declaimed the following in gmane.comp.python.general: > >> Is it just that nobody's implemented it, or is there a good reason for >> avoiding offering this sort of thing? >> > Any asynchronous "kill" runs the risk of leaving shared data > structures in a corrupt state. {Stupid example, but, in pseudo-Python: > > import time > > class Account(object): > def __init__(self, initial=0.0) > self.balance = initial > > myAccount = Account(100.0) > yourAccount = Account(100.0) > > accountLock = threading.Lock() > > def threadWork(lock, a1, a2, rate): > while True: > time.sleep(rate) > lock.lock() > t = a2.balance / 2 > a1.balance += t > #say a thread.kill kills at this point > a2.balance -= t > lock.release() > > # create/start thread1 passing (accountLock, myAccount, yourAccount, 60) > # create/start thread2 passing (accountLock, yourAccount, myAccount, > 120) > > time.sleep(300) > thread1.kill() > > So... Thread1 may be killed after one account gets incremented but > before the other is decremented... And what happens to the lock? If it > doesn't get released as part of the .kill() processing, they program is > dead-locked (and the magically appearing money will never be seen). If > it does get released, then the sum total of "money" in the system will > have increased. > [snip] The lock won't be released if an exception is raised, for example, if 'a1' isn't an Account instance and has no 'balance' attribute. Using a context manager would help in that case. From davea at ieee.org Sat Sep 17 20:04:42 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 17 Sep 2011 20:04:42 -0400 Subject: os independent rename In-Reply-To: References: Message-ID: <4E75359A.6060907@ieee.org> On 01/-10/-28163 02:59 PM, Nobody wrote: > On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote: > >> So, what is the best way to do this that will >> behave the same across operating systems? > Delete the destination first, but after checking that it isn't the same as > the source. > > On Windows, that last bit is harder than it seems. A string-based > comparison won't work. Even if you ignore case, there's the issue of 8.3 > filenames, and some other odd cases. > > Or rename it twice, with the intermediate file being something that does not exist. For example, generate a random name, and if it exists, repeat till you come up with one that does not. Once the first rename has succeeded, you can safely delete the destination. Even this approach can have problems in the face of symlinks or multiple partitions. DaveA From missive at hotmail.com Sat Sep 17 20:41:33 2011 From: missive at hotmail.com (Lee Harr) Date: Sun, 18 Sep 2011 05:11:33 +0430 Subject: tool to point out os dependence problems? Message-ID: One thing that I've always liked about python is that itmakes it?pretty easy to write programs that run acrossoperating?systems. After running in to a problem today with os.renameI am wondering if there is a tool out there that canpoint out any known os dependence issues. A quick trip to google shows nothing obvious. From ladasky at my-deja.com Sat Sep 17 23:06:27 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 17 Sep 2011 20:06:27 -0700 (PDT) Subject: Python bug in Windows 8--report now, or later? References: Message-ID: <49c99fa3-d0e0-4acb-b6fa-68959bbca52f@o9g2000vbo.googlegroups.com> On Sep 17, 2:20?pm, Chris Angelico wrote: > I would consider reporting it as a bug in Windows 8, not a bug in Python. > > Chris Angelico +1, beat me to it. :^) From invalid at invalid.invalid Sun Sep 18 00:15:57 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 18 Sep 2011 04:15:57 +0000 (UTC) Subject: Python bug in Windows 8--report now, or later? References: Message-ID: On 2011-09-17, Chris Angelico wrote: > I would consider reporting it as a bug in Windows 8, not a bug in Good luck with that plan. ;) [I don't know anything about this particular issue, but I do know that when there is a bug in Windows, it's usually everyboyd else that has to change to work around it.] From anikom15 at gmail.com Sun Sep 18 00:40:32 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Sat, 17 Sep 2011 21:40:32 -0700 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: <20110918044032.GA17257@Smoke> On Sun, Sep 18, 2011 at 04:15:57AM +0000, Grant Edwards wrote: > On 2011-09-17, Chris Angelico wrote: > > > I would consider reporting it as a bug in Windows 8, not a bug in > > Good luck with that plan. ;) > > [I don't know anything about this particular issue, but I do know that > when there is a bug in Windows, it's usually everyboyd else that has > to change to work around it.] > > Actually Microsoft usually goes out of its way to ensure backwards- compatibily, even when the app developer is DOING IT WRONG. From alec.taylor6 at gmail.com Sun Sep 18 01:42:00 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sun, 18 Sep 2011 15:42:00 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: <20110918044032.GA17257@Smoke> References: <20110918044032.GA17257@Smoke> Message-ID: On Sun, Sep 18, 2011 at 2:40 PM, Westley Mart?nez wrote: > On Sun, Sep 18, 2011 at 04:15:57AM +0000, Grant Edwards wrote: >> On 2011-09-17, Chris Angelico wrote: >> >> > I would consider reporting it as a bug in Windows 8, not a bug in >> >> Good luck with that plan. ?;) >> >> [I don't know anything about this particular issue, but I do know that >> when there is a bug in Windows, it's usually everyboyd else that has >> to change to work around it.] >> >> > > Actually Microsoft usually goes out of its way to ensure backwards- > compatibily, even when the app developer is DOING IT WRONG. > -- > http://mail.python.org/mailman/listinfo/python-list > For those interested, Windows 8 is available here: http://msdn.microsoft.com/windows/apps/br229516/ From dreyemi at gmail.com Sun Sep 18 05:39:03 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 10:39:03 +0100 Subject: Getting a list value from key/value pair Message-ID: Hi all, If I have a list with key/value pair, how do I get the value of the key? I'm working with this code snippet: >>> items = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status', 'pending'), ('timeout','120')]} >>> print [items[i] for i in items.keys()] [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), ('timeout' , 60)]] >>> -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From r32813 at freescale.com Sun Sep 18 05:41:30 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Sun, 18 Sep 2011 09:41:30 +0000 Subject: Python 2.7.1 64-bit Build on HP-UX11.31 ia64 with aCC - Many modules failed to build In-Reply-To: References: Message-ID: <02EA6D704E30CE499C5071776509A925F52AAB@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I have posted this in Compiler SIG and re-post here in case anyone who knows about this issue is not subscribed to that group. I am working on python build on my server using HP-UX ANSI C Compiler. I want to be consistent using aCC throughout instead of gcc for my python and cx_Oracle build as Oracle is not supporting gcc build much. Here is my aCC version. # swlist -l product | grep Compiler ACXX C.06.26.EVAL HP C/aC++ Compiler C-ANSI-C C.06.26.EVAL HP C/aC++ Compiler COMPLIBS B.11.31 Compiler Support Libraries Anyhow, my issue now is when I am building my python in 64-bit, I am encountering many modules failed to build issue, despite the python executable is successfully built. There are just so many modules that failed, that I would conclude my build failed. :P I followed through the instruction in README file for 64-bit build using HP-UX compiler (--without-gcc option is used in configure). I exported and unexported the environment variables before configure and make is run, respectively. I also removed -O option in the Makefile before running make. I have a few questions. 1.) Why Makefile is re-generated after python executable is created? I noticed the removal of optimization flag in Makefile is gone/restored after python binary is generated. 2.) 64-bit option. It seems that this is a bad flag that linker doesn't recognize? Many important modules failed to build, and I believe its due to this error. When I manually execute ld without passing in +DD64 flag, the module is generated successfull. ld -b +DD64 -lxnet build/temp.hp-ux-B.11.31-ia64-2.7/home/r32813/Build/2.7.1/Python-2.7.1/Modules/mathmodule.o build/temp.hp-ux-B.11.31-ia64-2.7/home/r32813/Build/2.7.1/Python-2.7.1/Modules/_math.o -L/usr/local/lib -lm -o build/lib.hp-ux-B.11.31-ia64-2.7/math.so ld: Unrecognized argument: +DD64 Fatal error. Above is just showing one of the modules that failed to build. 3.) Built in modules, I see the compiler cannot find the bit of information required to build _tkinter module. How do I make the configure able to locate my tcl/tk source code or binary which I have already installed and built separately (and successfully)? So, where do I place the source code if I need to put it so that the compiler can find? To end my question, here is the outcome of my build. For build in modules, I just need my _tkinter running. For shared libraries, I think need most of them, those are the basic functions that my application calls. Thanks in advance for your reply. Python build finished, but the necessary bits to build these modules were not found: _bsddb _curses _curses_panel _sqlite3 _ssl _tkinter bsddb185 bz2 dl gdbm imageop linuxaudiodev ossaudiodev readline spwd sunaudiodev zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _bisect _codecs_cn _codecs_hk _codecs_iso2022 _codecs_jp _codecs_kr _codecs_tw _collections _csv _ctypes _ctypes_test _elementtree _functools _heapq _hotshot _io _json _locale _lsprof _md5 _multibytecodec _multiprocessing _random _sha _socket _struct _testcapi array audioop binascii cmath cPickle crypt cStringIO datetime dbm fcntl future_builtins grp itertools math mmap nis operator parser pyexpat resource select strop syslog termios time unicodedata From t at jollybox.de Sun Sep 18 06:16:09 2011 From: t at jollybox.de (Thomas Jollans) Date: Sun, 18 Sep 2011 12:16:09 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C4E9.60209@jollybox.de> On 18/09/11 11:39, Kayode Odeyemi wrote: > Hi all, > > If I have a list with key/value pair, how do I get the value of the key? > > I'm working with this code snippet: Python 3.2.2 (default, Sep 5 2011, 04:33:58) [GCC 4.6.1 20110819 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> lst = [ ('key1', 'value1'), ('key2', 'value2') ] >>> d = dict (lst) >>> d['key1'] 'value1' >>> > >>>> items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} >>>> print [items[i] for i in items.keys()] > [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), > ('timeout' > , 60)]] >>>> > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > > From vincent.vandevyvre at swing.be Sun Sep 18 06:22:00 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sun, 18 Sep 2011 12:22:00 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C648.7070000@swing.be> An HTML attachment was scrubbed... URL: From vincent.vandevyvre at swing.be Sun Sep 18 06:25:41 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Sun, 18 Sep 2011 12:25:41 +0200 Subject: Getting a list value from key/value pair In-Reply-To: References: Message-ID: <4E75C725.2050903@swing.be> An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sun Sep 18 06:30:06 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 11:30:06 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C648.7070000@swing.be> References: <4E75C648.7070000@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:22 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > Like that: > > # -*- coding: utf-8 -*- > > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in items.iteritems(): > print "\n {0}".format(key) > for val in value: > print "\t{0}: {1}".format(val[0], val[1]) > > for python 2.x > Thank you very much :) -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.crotti.0 at gmail.com Sun Sep 18 06:44:59 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 18 Sep 2011 11:44:59 +0100 Subject: create a directory structure In-Reply-To: References: <4E732F4B.3090409@gmail.com> <4E73566A.1010808@gmail.com> Message-ID: <4E75CBAB.6060204@gmail.com> On 09/17/2011 12:56 PM, Rafael Dur?n Casta?eda wrote: > I think you might want to look at Fabric > or vagrant > > > Thanks, but I don't understand how these two project would help me... I don't need to deploy on many machines via ssh, I only need that each machine is able to create an initial infrastructure. Paste-script allows me to do that, and in plus is ready to do many other things. Doing it in a hand-made fashion might also work well, but I think using paste-script is better for future extensions/improvements. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Sun Sep 18 06:50:53 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 11:50:53 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C725.2050903@swing.be> References: <4E75C725.2050903@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:25 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > Hi all, > > > If I have a list with key/value pair, how do I get the value of the key? > > > I'm working with this code snippet: > > >>> items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > >>> print [items[i] for i in items.keys()] > [[('status', 'pending'), ('timeout', '120')], [('status', 'pending'), > ('timeout' > , 60)]] > >>> > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > Sorry, for python3.x > > # -*- coding: utf-8 -*- > > > d = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in d.items(): > > print("\n {0}".format(key)) > for val in value: > print("\t{0}: {1}".format(val[0], val[1])) > > Very helpful! I gave your karma at http://stackoverflow.com/questions/7460675/getting-a-list-value-from-key-value-pair -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Sun Sep 18 08:13:03 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 18 Sep 2011 05:13:03 -0700 (PDT) Subject: way to calculate 2**1000 without expanding it? References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> Message-ID: <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> On Sep 16, 9:17?pm, Arnaud Delobelle wrote: > Ah go on, let's make a codegolf contest out of it. > My entry: > > >>> sum(map(int,str(2**1000))) You could save another character by replacing "2**1000" with "2<<999" -- Mark From dreyemi at gmail.com Sun Sep 18 08:44:50 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sun, 18 Sep 2011 13:44:50 +0100 Subject: Getting a list value from key/value pair In-Reply-To: <4E75C648.7070000@swing.be> References: <4E75C648.7070000@swing.be> Message-ID: On Sun, Sep 18, 2011 at 11:22 AM, Vincent Vande Vyvre < vincent.vandevyvre at swing.be> wrote: > ** > Le 18/09/11 11:39, Kayode Odeyemi a ?crit : > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > Like that: > > # -*- coding: utf-8 -*- > > > items = {'fees':[('status','pending'), ('timeout',60)], > 'hostel':[('status', > 'pending'), ('timeout','120')]} > > for key, value in items.iteritems(): > print "\n {0}".format(key) > for val in value: > print "\t{0}: {1}".format(val[0], val[1]) > > for python 2.x > Vincent, with: values = ('status', 'pending') ('timeout', '120') ('status', 'pending') ('timeout', 60) How do I comma separate it and put each each item in a dict? >>> for key, value in items.iteritems(): ... for val in value: ... md = {} ... for q in val: ... md.update(q) ... print md ... Traceback (most recent call last): File "", line 5, in ValueError: dictionary update sequence element #0 has length 1; 2 is required Thank you -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sun Sep 18 09:50:40 2011 From: python at bdurham.com (python at bdurham.com) Date: Sun, 18 Sep 2011 09:50:40 -0400 Subject: Cancel or timeout a long running regular expression In-Reply-To: References: <1316063960.26516.140258141338017@webmail.messagingengine.com> Message-ID: <1316353840.13565.140258142485365@webmail.messagingengine.com> Thanks for everyone's comments - much appreciated! Malcolm (the OP) From arnodel at gmail.com Sun Sep 18 10:10:10 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 18 Sep 2011 15:10:10 +0100 Subject: way to calculate 2**1000 without expanding it? In-Reply-To: <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> References: <33160283.436.1316200866800.JavaMail.geo-discussion-forums@prgd31> <4be23f78-5eea-44db-b659-6bd8f7ab3752@15g2000vbb.googlegroups.com> Message-ID: On Sep 18, 2011 1:20 PM, "Mark Dickinson" wrote: > > On Sep 16, 9:17 pm, Arnaud Delobelle wrote: > > Ah go on, let's make a codegolf contest out of it. > > My entry: > > > > >>> sum(map(int,str(2**1000))) > > You could save another character by replacing "2**1000" with "2<<999" > Excellent! -- Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From anbumani923 at gmail.com Sun Sep 18 10:30:34 2011 From: anbumani923 at gmail.com (anbu) Date: Sun, 18 Sep 2011 07:30:34 -0700 (PDT) Subject: 2011 NEW MODAL GIRLS SEX VIDEO AND PICTURES FREE DOWNLOAD Message-ID: http://123maza.com/65/cute540/ From zdoor at xs4all.nl Sun Sep 18 11:55:08 2011 From: zdoor at xs4all.nl (Alex van der Spek) Date: Sun, 18 Sep 2011 17:55:08 +0200 Subject: Numpy.array with dtype works on list of tuples not on list of lists? Message-ID: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Why does this not work? >>> dat=[[1,2,3],[4,5,6]] >>> col=[('a','f4'),('b','f4'),('c','f4')] >>> arr=numpy.array(dat,dtype=col) Traceback (most recent call last): File "", line 1, in arr=numpy.array(dat,dtype=col) TypeError: expected a readable buffer object >>> But this does: >>> dat=[(1,2,3),(4,5,6)] >>> arr=numpy.array(dat,dtype=col) >>> arr array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', '>> The only difference that the object is a list of tuples now? Thanks for clarification, Alex van der Spek From rosuav at gmail.com Sun Sep 18 13:55:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 19 Sep 2011 03:55:16 +1000 Subject: GTK2.TextView examples In-Reply-To: <1316367199.2789.YahooMailRC@web83811.mail.sp1.yahoo.com> References: <1316367199.2789.YahooMailRC@web83811.mail.sp1.yahoo.com> Message-ID: On Mon, Sep 19, 2011 at 3:33 AM, Lance Dillon wrote: > Here are some examples that use GTK2.TextTag. Interestingly, neither runs on my Windows system - I don't have GDK2 or Pango. Much appreciate the examples though - can some of them go into the official docs? It may well be that I'm using completely the wrong tools here. What I want to do is write a console in Pike, more or less a telnet/MUD client. Is it better to use TextView, or to use a GdkDisplay or somesuch and draw the text myself? ChrisA From philip at semanchuk.com Sun Sep 18 13:57:10 2011 From: philip at semanchuk.com (Philip Semanchuk) Date: Sun, 18 Sep 2011 13:57:10 -0400 Subject: Numpy.array with dtype works on list of tuples not on list of lists? In-Reply-To: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> References: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Message-ID: <119665A7-EF5F-49D4-9B59-83C8D21EEA8A@semanchuk.com> On Sep 18, 2011, at 11:55 AM, Alex van der Spek wrote: > Why does this not work? > >>>> dat=[[1,2,3],[4,5,6]] >>>> col=[('a','f4'),('b','f4'),('c','f4')] >>>> arr=numpy.array(dat,dtype=col) > > Traceback (most recent call last): > File "", line 1, in > arr=numpy.array(dat,dtype=col) > TypeError: expected a readable buffer object > > But this does: > >>>> dat=[(1,2,3),(4,5,6)] >>>> arr=numpy.array(dat,dtype=col) >>>> arr > array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', ' > The only difference that the object is a list of tuples now? I don't know why you're seeing what you're seeing, but if you don't get answer here you could try asking on the numpy list. Good luck Philip From matt.pounsett at gmail.com Sun Sep 18 16:19:24 2011 From: matt.pounsett at gmail.com (Matthew Pounsett) Date: Sun, 18 Sep 2011 13:19:24 -0700 (PDT) Subject: cause __init__ to return a different class? References: Message-ID: <731ee8c8-3f8d-49ad-91a9-4e247f66d252@bl1g2000vbb.googlegroups.com> On Sep 15, 1:54?am, Ryan Kelly wrote: > To be friendlier to others reading your code, I would consider using a > classmethod to create an alternative constructor: I finally got back to looking at this today. As it turns out, un- overriding __new__ in the child class is more complicated than I first expected, and isn't worth the extra effort. So, I ended up using a constructor class method as you suggested. Thanks again! From robert.kern at gmail.com Sun Sep 18 16:31:58 2011 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 18 Sep 2011 15:31:58 -0500 Subject: Numpy.array with dtype works on list of tuples not on list of lists? In-Reply-To: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> References: <4e761461$0$2418$e4fe514c@news2.news.xs4all.nl> Message-ID: On 9/18/11 10:55 AM, Alex van der Spek wrote: > Why does this not work? > >>>> dat=[[1,2,3],[4,5,6]] >>>> col=[('a','f4'),('b','f4'),('c','f4')] >>>> arr=numpy.array(dat,dtype=col) > > Traceback (most recent call last): > File "", line 1, in > arr=numpy.array(dat,dtype=col) > TypeError: expected a readable buffer object >>>> > > But this does: > >>>> dat=[(1,2,3),(4,5,6)] >>>> arr=numpy.array(dat,dtype=col) >>>> arr > array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)], dtype=[('a', ' ('c', '>>> > > The only difference that the object is a list of tuples now? numpy questions are best asked on the numpy mailing list: http://www.scipy.org/Mailing_Lists To answer your question, though, numpy.array() needs to figure out a lot of different things about the input data simultaneously, in particular its shape. Structured arrays (i.e. with elements that have individual fields as above) pose a new problem in that its individual elements are sequences themselves. In order to help it decide whether it should recurse down into a sequence to find its elements or decide that the sequence *is* an element in its own right, we settled on the convention that tuples are to be considered elements and that lists are sequences of elements. -- 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 keymint1498 at gmail.com Sun Sep 18 17:07:22 2011 From: keymint1498 at gmail.com (superhappyfuntime) Date: 18 Sep 2011 21:07:22 GMT Subject: What is wrong with this code? References: <38d9k8-u8t.ln1@satorlaser.homedns.org> Message-ID: On 09-15-2011, Ulrich Eckhardt wrote: > superhappyfuntime wrote: >> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > It's LaTeX, not Python. > Uli no, it's a cap for LaTeX written in python -- I'm trying a new usenet client for Mac, Nemo OS X, since 0 days. You can download it at http://www.malcom-mac.com/nemo From resourts137 at gmail.com Sun Sep 18 17:54:25 2011 From: resourts137 at gmail.com (iqbal iqbal) Date: Sun, 18 Sep 2011 14:54:25 -0700 (PDT) Subject: Booking cheapest airlines Tickets Pakistan world wide Message-ID: Booking cheapest airlines Tickets Pakistan world wide http://karachi-guest-house-5star-hotels.blogspot.com/ From steve+comp.lang.python at pearwood.info Sun Sep 18 18:00:51 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Sep 2011 22:00:51 GMT Subject: What is wrong with this code? References: <38d9k8-u8t.ln1@satorlaser.homedns.org> Message-ID: <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> On Sun, 18 Sep 2011 21:07:22 +0000, superhappyfuntime wrote: > On 09-15-2011, Ulrich Eckhardt wrote: > >> superhappyfuntime wrote: >>> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > >> It's LaTeX, not Python. > >> Uli > > no, it's a cap for LaTeX written in python If it's Python, it's no Python syntax I've ever seen before. >>> here it is: = '\begin{document}' File "", line 1 here it is: = '\begin{document}' ^ SyntaxError: invalid syntax How about if you start off by explaining what you think "a cap for LaTeX" means, or provide a link to something that will explain it? This is a Python list, and we don't necessarily know much about LaTeX. -- Steven From irmen.NOSPAM at xs4all.nl Sun Sep 18 19:05:20 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 19 Sep 2011 01:05:20 +0200 Subject: ANN: Pyro 4.9 released Message-ID: <4e767930$0$2480$e4fe514c@news2.news.xs4all.nl> Hello, Pyro 4.9 has just been released! Get it from Pypi: http://pypi.python.org/pypi/Pyro4/ Documentation: http://packages.python.org/Pyro4/index.html Changes include: * the documentation has finally been completed * changed asyncresult a little in non-compatible ways. * added more examples: gui_eventloop, deadlock, itunes * serialized data is released a bit faster to improve garbage collection * fixed setting several socket options such as SO_REUSEADDR. (See the change log in the documentation for a more detailed list) Pyro = Python Remote Objects. It is a library that enables you to build applications in which objects can talk to each other over the network, with minimal programming effort. You can just use normal Python method calls, with almost every possible parameter and return value type, and Pyro takes care of locating the right object on the right computer to execute the method. It is designed to be very easy to use, and to generally stay out of your way. But it also provides a set of powerful features that enables you to build distributed applications rapidly and effortlessly. Pyro is written in 100% pure Python and therefore runs on many platforms and Python versions, including Python 3.x. Enjoy, Irmen de Jong From ian.g.kelly at gmail.com Mon Sep 19 01:41:29 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 18 Sep 2011 23:41:29 -0600 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 5:38 PM, Chris Angelico wrote: > But if it's done as an exception, all you need is to > catch that exception and reraise it: > > def threadWork(lock, a1, a2, rate): > ? try: > ? ? ? while True: > ? ? ? ? ? ? ? time.sleep(rate) > ? ? ? ? ? ? ? lock.lock() > ? ? ? ? ? ? ? t = a2.balance / 2 > ? ? ? ? ? ? ? a1.balance += t > ? ? ? ? ? ? ? #say a thread.kill kills at this point > ? ? ? ? ? ? ? a2.balance -= t > ? ? ? ? ? ? ? lock.release() > ?except: > ? ? ?# roll back the transaction in some way > ? ? ?lock.release() > ? ? ?raise And what if the thread gets killed a second time while it's in the except block? > It'd require some care in coding, but it could be done. And if the > lock/transaction object can be coded for it, it could even be done > automatically: > > def threadWork(lock, a1, a2, rate): > ? ? ? while True: > ? ? ? ? ? ? ? time.sleep(rate) > ? ? ? ? ? ? ? transaction.begin() > ? ? ? ? ? ? ? t = a2.balance / 2 > ? ? ? ? ? ? ? transaction.apply(a1.balance,t) > ? ? ? ? ? ? ? #say a thread.kill kills at this point > ? ? ? ? ? ? ? transaction.apply(a2.balance,-t) > ? ? ? ? ? ? ? transaction.commit() > > If the transaction object doesn't get its commit() called, it does no > actions at all, thus eliminating all issues of locks. And what if the thread gets killed in the middle of the commit? Getting the code right is going to be a lot more complicated than just adding a couple of try/excepts. Cheers, Ian From greg.ewing at canterbury.ac.nz Mon Sep 19 01:56:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 19 Sep 2011 17:56:42 +1200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <9do3stFtq8U1@mid.individual.net> Ian Kelly wrote: > And what if the thread gets killed a second time while it's in the except block? > And what if the thread gets killed in the middle of the commit? For these kinds of reasons, any feature for raising asynchronous exceptions in another thread would need to come with some related facilites: * A way of blocking asynchronous exceptions around a critical section would be needed. * Once an asynchronous exception has been raised, further asynchronous exceptions should be blocked until explicitly re-enabled. * Asynchronous exceptions should probably be disabled initially in a new thread until it explicitly enables them. Some care would still be required to write code that is robust in the presence of asynchronous exceptions, but given these facilities, it ought to be possible. -- Greg From adam.jorgensen.za at gmail.com Mon Sep 19 02:03:08 2011 From: adam.jorgensen.za at gmail.com (Adam Jorgensen) Date: Mon, 19 Sep 2011 08:03:08 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: The point of the Java thread.stop() being deprecated seems to have very little to do with undeclared exceptions being raised and a lot to do with objects being left in a potentially damaged state. As Ian said, it's a lot more complex than just adding try/catches. Killing a thread in the middle of some non-atomic operation with side-effects that propagate beyond the thread is a recipe for trouble. In fact, while a a lot can be written about Java being a poor language the specific article linked to about why Java deprecated thread.stop() gives a pretty damn good explanation as to why Thread.stop() and the like are a bad idea and what a better idea might be (Signalling that a graceful halt should be attempted) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Sep 19 02:25:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 19 Sep 2011 16:25:59 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Mon, Sep 19, 2011 at 3:41 PM, Ian Kelly wrote: > And what if the thread gets killed in the middle of the commit? > Database managers solved this problem years ago. It's not done by preventing death until you're done - death can come from someone brutally pulling out your power cord. There's no "except PowerCordRemoved" to protect you from that! There are various ways, and I'm sure one of them will work for whatever situation is needed. ChrisA From geek.swarup at gmail.com Mon Sep 19 02:38:53 2011 From: geek.swarup at gmail.com (swarupchandra kamerkar) Date: Mon, 19 Sep 2011 12:08:53 +0530 Subject: Need help on using the USB module Message-ID: Hi, I am trying to use Pythoin on windows. I wanted to use the uSB module. I downloaded it and installed it. Still I get the following message. >>> import usb Traceback (most recent call last): File "", line 1, in import usb ImportError: DLL load failed: The specified module could not be found. What is it that I am missing? Regards Swarup -------------- next part -------------- An HTML attachment was scrubbed... URL: From Shambhu.Rajak at kpitcummins.com Mon Sep 19 03:03:10 2011 From: Shambhu.Rajak at kpitcummins.com (Shambhu Rajak) Date: Mon, 19 Sep 2011 07:03:10 +0000 Subject: What is wrong with this code? In-Reply-To: <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> References: <38d9k8-u8t.ln1@satorlaser.homedns.org> <4e766a13$0$29995$c3e8da3$5496439d@news.astraweb.com> Message-ID: <408F64D89899604FB24015E64E10490C0329A3@KCHJEXMB02.kpit.com> I think you cannnot use "\" as normal string ,it?s a metacharacter, u can use it like this: '\\begin{document}' -Shambhu -----Original Message----- From: Steven D'Aprano [mailto:steve+comp.lang.python at pearwood.info] Sent: Monday, September 19, 2011 3:31 AM To: python-list at python.org Subject: Re: What is wrong with this code? On Sun, 18 Sep 2011 21:07:22 +0000, superhappyfuntime wrote: > On 09-15-2011, Ulrich Eckhardt wrote: > >> superhappyfuntime wrote: >>> #this is antiWYSIWYG, an easy to learn cap for begginners to LaTeX. > >> It's LaTeX, not Python. > >> Uli > > no, it's a cap for LaTeX written in python If it's Python, it's no Python syntax I've ever seen before. >>> here it is: = '\begin{document}' File "", line 1 here it is: = '\begin{document}' ^ SyntaxError: invalid syntax How about if you start off by explaining what you think "a cap for LaTeX" means, or provide a link to something that will explain it? This is a Python list, and we don't necessarily know much about LaTeX. -- Steven From chunuan723 at gmail.com Mon Sep 19 05:15:16 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 19 Sep 2011 02:15:16 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <3138b9b7-7b69-411a-a63f-f0c12cfbe56a@1g2000yqm.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From Antoon.Pardon at rece.vub.ac.be Mon Sep 19 06:04:01 2011 From: Antoon.Pardon at rece.vub.ac.be (Antoon Pardon) Date: Mon, 19 Sep 2011 12:04:01 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <20110919100401.GD3410@trout.vub.ac.be> On Sun, Sep 18, 2011 at 07:35:01AM +1000, Chris Angelico wrote: > On Sun, Sep 18, 2011 at 5:00 AM, Nobody wrote: > Forking a thread to discuss threads.... ahem. > > Why is it that threads can't be killed? Do Python threads correspond > to OS-provided threads (eg POSIX threads on Linux)? Every OS threading > library I've seen has some way of killing threads, although I've not > looked in detail into POSIX threads there (there seem to be two > options, pthread_kill and pthread_cancel, that could be used, but I've > not used either). If nothing else, it ought to be possible to > implement a high level kill simply by setting a flag that the > interpreter will inspect every few commands, the same way that > KeyboardInterrupt is checked for. > > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? Python has a half baked solution to this. If you go to http://docs.python.org/release/3.2.2/c-api/init.html You will find the following: int PyThreadState_SetAsyncExc(long id, PyObject *exc) Asynchronously raise an exception in a thread. The id argument is the thread id of the target thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn?t found. If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions. Some recipes can be found at: http://www.google.com/search?ie=UTF-8&oe=utf-8&q=python+recipe+PyThreadState_SetAsyncExc However it this doesn't work 100% correctly. Last time I tried using this, it didn't work with an exception instance but only with an execption class as parameter. There was a discussion at http://mail.python.org/pipermail/python-dev/2006-August/068158.html about this. I don't know how it was finaly resolved. -- Antoon Pardon From hfaber at invalid.net Mon Sep 19 07:11:51 2011 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 19 Sep 2011 13:11:51 +0200 Subject: Operator commutativity Message-ID: Hi there, when I have a python class X which overloads an operator, I can use that operator to do any operation for example with an integer y = X() + 123 however, say I want the "+" operator to be commutative. Then y = 123 + X() should have the same result. However, since it does not call __add__ on an instance of X, but on the int 123, this fails: TypeError: unsupported operand type(s) for +: 'int' and 'X' How can I make this commutative? Best regards, Henrik From arnodel at gmail.com Mon Sep 19 07:17:22 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Mon, 19 Sep 2011 12:17:22 +0100 Subject: Operator commutativity In-Reply-To: References: Message-ID: On 19 September 2011 12:11, Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? Overload X.__radd__() as well HTH -- Arnaud From paul.nospam at rudin.co.uk Mon Sep 19 07:23:48 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 19 Sep 2011 12:23:48 +0100 Subject: Operator commutativity References: Message-ID: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Henrik Faber writes: > How can I make this commutative? Incidentally - this isn't really about commutativity at all - the question is how can you define both left and right versions of add, irrespective of whether they yield the same result. I think __radd__ is what you're after. From duncan.booth at invalid.invalid Mon Sep 19 07:26:08 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Sep 2011 11:26:08 GMT Subject: Operator commutativity References: Message-ID: Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? > By defining __radd__ >>> class X: def __add__(self, other): return "%r + %r" % (self, other) def __radd__(self, other): return "%r + %r" % (other, self) >>> X() + 123 '<__main__.X object at 0x029C45B0> + 123' >>> 123 + X() '123 + <__main__.X object at 0x02101910>' -- Duncan Booth http://kupuguy.blogspot.com From hfaber at invalid.net Mon Sep 19 07:32:00 2011 From: hfaber at invalid.net (Henrik Faber) Date: Mon, 19 Sep 2011 13:32:00 +0200 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: On 19.09.2011 13:23, Paul Rudin wrote: > Henrik Faber writes: > >> How can I make this commutative? > > Incidentally - this isn't really about commutativity at all - the > question is how can you define both left and right versions of add, > irrespective of whether they yield the same result. Right. The operator+ in my case just happens to be commutative and I wanted a language way to express this. > I think __radd__ is what you're after. It is, thank you very much - I knew there was some way to get this done nicely. Perfect! :-) Best regards, Henrik From stars9820 at gmail.com Mon Sep 19 08:09:55 2011 From: stars9820 at gmail.com (star ship) Date: Mon, 19 Sep 2011 05:09:55 -0700 (PDT) Subject: AMAZING WORK AT HOME Message-ID: <2863194c-8fb4-4809-9d50-302ef3e5bbc7@z41g2000yqb.googlegroups.com> Hi this is most power ful earning site. part time job for you refer friends and other people and earn more money. http://www.pswtracker.com/index.php?refid=26536 thanks From roy at panix.com Mon Sep 19 08:10:27 2011 From: roy at panix.com (Roy Smith) Date: Mon, 19 Sep 2011 08:10:27 -0400 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: In article , Henrik Faber wrote: > On 19.09.2011 13:23, Paul Rudin wrote: > > Henrik Faber writes: > > > >> How can I make this commutative? > > > > Incidentally - this isn't really about commutativity at all - the > > question is how can you define both left and right versions of add, > > irrespective of whether they yield the same result. > > Right. The operator+ in my case just happens to be commutative and I > wanted a language way to express this. > > > I think __radd__ is what you're after. > > It is, thank you very much - I knew there was some way to get this done > nicely. Perfect! :-) __radd__() only solves the problem if the left-hand operand has no __add__() method itself. class C1: def __add__(self, other): print "C1.__add__()" def __radd__(self, other): print "C1.__radd__()" class C2: def __add__(self, other): print "C2.__add__()" def __radd__(self, other): print "C2.__radd__()" c1 = C1() c2 = C2() c1 + c2 c2 + c1 $ python radd.py C1.__add__() C2.__add__() From robin at reportlab.com Mon Sep 19 08:42:30 2011 From: robin at reportlab.com (Robin Becker) Date: Mon, 19 Sep 2011 13:42:30 +0100 Subject: help needed on decimal formatting issue Message-ID: <4E7738B6.2080000@chamonix.reportlab.co.uk> I'm not really very used to the decimal module so I'm asking here if any one can help me with a problem in a well known third party web framework The code in question is def format_number(value, max_digits, decimal_places): """ Formats a number into a string with the requisite number of digits and decimal places. """ if isinstance(value, decimal.Decimal): context = decimal.getcontext().copy() context.prec = max_digits return u'%s' % str( value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) else: return u"%.*f" % (decimal_places, value) we have set up decimal fields with max_digits=7 decimal_places=2 and max_digits=10, decimal_places=4. We are getting issues with quantize failing with the message 'quantize result has too many digits for current context'. Anyhow, I believe that we need to adjust the above code so that the precision is actually set to context.prec = max_digits+decimal_places but I'm not certain that is right. Presumably the author thought that the fields could have large values of both max_digits and decimal_places. Initially I thought precision must be to do with decimal_places only, but changing context.prec = decimal_places did not fix the issue. Can someone enlighten me? The failing case for the original code was format_number(Decimal('914146.80'),7,2) with context.prec = decimal_places we failed differently with format_number(Decimal('42.7571'),10,4) so I adopted context.prec = max_digits+decimal_places and that seems to work. If this is indeed a proper fix I will send a bug report to the well known jazz based framework. -- Robin Becker From ethan at stoneleaf.us Mon Sep 19 08:48:07 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 19 Sep 2011 05:48:07 -0700 Subject: Operator commutativity In-Reply-To: References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <4E773A07.6090505@stoneleaf.us> Roy Smith wrote: > In article , > Henrik Faber wrote: > >> On 19.09.2011 13:23, Paul Rudin wrote: >>> Henrik Faber writes: >>> >>>> How can I make this commutative? >>> Incidentally - this isn't really about commutativity at all - the >>> question is how can you define both left and right versions of add, >>> irrespective of whether they yield the same result. >> Right. The operator+ in my case just happens to be commutative and I >> wanted a language way to express this. >> >>> I think __radd__ is what you're after. >> It is, thank you very much - I knew there was some way to get this done >> nicely. Perfect! :-) > > __radd__() only solves the problem if the left-hand operand has no > __add__() method itself. Only true if the left-hand operand is so ill-behaved it doesn't check to see if it makes sense to add itself to the right-hand operand. If it doesn't know how, it should `return NotImplemented` -- Python will then try __radd__ on the left-hand operand. Also, if the right-hand operand is a subclass of the left-hand operand then Python will try right-hand_operand.__radd__ first. Now, if the left-hand operand *does* know how (or thinks it does, which could be another matter entirely), and the right-hand operand is *not* a subclass of the left-hand operand, then you are correct -- the right-hand operand wil not be called. ~Ethan~ From brian.curtin at gmail.com Mon Sep 19 10:00:25 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 19 Sep 2011 09:00:25 -0500 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: On Sat, Sep 17, 2011 at 13:01, Kevin Walzer wrote: > I have been testing my Python application on the just-released developer > preview of Windows 8 and have noted an error: the application does not > create an app folder in the user's "application data" directory. This causes > the app to crash on startup. Manually creating the directory solves the > problem. Since the app uses an os.mkdir() call to create the directory, and > since the app runs fine on Windows 7, my guess is that the bug lies > somewhere in the interaction between Python (I'm using ActivePython 2.7) and > Windows. > > Here's the relevant code: > > ? ?#make preferences directory if it does not exist > ? ?def makePrefsDir(self): > ? ? ? ?self.appdir = os.path.join(os.path.join(os.environ['APPDATA'], > 'MyApp')) > ? ? ? ?if not os.path.exists(self.appdir): > ? ? ? ? ? ?os.mkdir(self.appdir) > > I realize that this developer preview of Windows is still at somewhere > between alpha- and beta-level, and it's possible things will get better. > Should I wait to report this as a bug until Windows 8 is released, or do the > Python developers test Python on pre-release versions of Windows? First, is your application actually crashing, or does it just exit due to an unhandled exception? I suspect the latter, so if that's true, what's the exception and message? You said "the application does not create an app folder in the user's 'application data' directory" -- what does this mean, or rather, what is the specific folder you're expecting to have? If Python can't create the directory but you can do it manually, there may be some permission or access differences new to Windows 8. What does "echo %APPDATA%" give you? I haven't installed Windows 8 yet, but I'm planning to get it up and running soon. If you submit issues to http://bugs.python.org, hopefully with specific test cases that we can run and work with, it'll be easier to track and fix. If you do that, add me to the nosy list on the issues - tracker id: brian.curtin, I'm one of the Windows people around there. From torpedoallen at gmail.com Mon Sep 19 11:21:10 2011 From: torpedoallen at gmail.com (Christian Ren) Date: Mon, 19 Sep 2011 08:21:10 -0700 (PDT) Subject: help for the parse of encrypted excel Message-ID: I used xlrd library for the parse of excel before. But now, I encounter a problem that the file has been encrypted for some security reason. On the official website, i found "xlrd will not attempt to decode password-protected (encrypted) files. " :(( And I also tried another library called pyExcelerator, Unfortunately, it failed all the same. Is there anybody can tell me what's the solution to the parse of encrypted excel? Thanks in advance. (PS: for the user experience reason, I don't hope to save this file as another copy) From tjreedy at udel.edu Mon Sep 19 11:25:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Sep 2011 11:25:04 -0400 Subject: Operator commutativity In-Reply-To: <4E773A07.6090505@stoneleaf.us> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <4E773A07.6090505@stoneleaf.us> Message-ID: On 9/19/2011 8:48 AM, Ethan Furman wrote: > Roy Smith wrote: >> __radd__() only solves the problem if the left-hand operand has no >> __add__() method itself. > > Only true if the left-hand operand is so ill-behaved it doesn't check to > see if it makes sense to add itself to the right-hand operand. If it > doesn't know how, it should `return NotImplemented` -- Python will then > try __radd__ on the left-hand operand. > > Also, if the right-hand operand is a subclass of the left-hand operand > then Python will try right-hand_operand.__radd__ first. The builtin classes like int are (should be, sans bug) well-behaved. > Now, if the left-hand operand *does* know how (or thinks it does, which > could be another matter entirely), and the right-hand operand is *not* a > subclass of the left-hand operand, then you are correct -- the > right-hand operand wil not be called. So the potential problems arise with two user classes. -- Terry Jan Reedy From mdickinson at enthought.com Mon Sep 19 12:12:01 2011 From: mdickinson at enthought.com (Mark Dickinson) Date: Mon, 19 Sep 2011 09:12:01 -0700 (PDT) Subject: help needed on decimal formatting issue References: Message-ID: <150e2270-84a7-45ae-ae56-681f0b26c62a@1g2000vbu.googlegroups.com> On Sep 19, 1:42?pm, Robin Becker wrote: > I'm not really very used to the decimal module so I'm asking here if any one can > help me with a problem in a well known third party web framework > > The code in question is > > def format_number(value, max_digits, decimal_places): > ? ? ?""" > ? ? ?Formats a number into a string with the requisite number of digits and > ? ? ?decimal places. > ? ? ?""" > ? ? ?if isinstance(value, decimal.Decimal): > ? ? ? ? ?context = decimal.getcontext().copy() > ? ? ? ? ?context.prec = max_digits > ? ? ? ? ?return u'%s' % str( > ? ? ? ? ? value.quantize(decimal.Decimal(".1") ** decimal_places, > ? ? ? ? ? ? ? ? ? ? ? ? context=context)) > ? ? ?else: > ? ? ? ? ?return u"%.*f" % (decimal_places, value) What's the meaning of the 'max_digits' argument here? Are you guaranteed that the incoming value is smaller than 10**max_digits in absolute value? If so, then a precision of max_digits + decimal_places + 1 should be enough. The +1 is there to cover the corner case where a value close to 10**max_digits is rounded up to 10**max_digits by the quantize operation. BTW, that's a fairly horrible way of creating the first argument to the quantize method, too. It would be more efficient to do something like: >>> decimal_places = 2 >>> decimal.Decimal('0.{}1'.format('0'*(decimal_places-1))) Decimal('0.01') (perhaps with suitable special-casing for the case where decimal_places <= 0; not sure whether this applies in your context). -- Mark From shilparani9030 at gmail.com Mon Sep 19 12:14:01 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Mon, 19 Sep 2011 09:14:01 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From anikom15 at gmail.com Mon Sep 19 12:45:53 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 19 Sep 2011 09:45:53 -0700 Subject: Operator commutativity In-Reply-To: References: Message-ID: <20110919164553.GA20521@Smoke> On Mon, Sep 19, 2011 at 01:11:51PM +0200, Henrik Faber wrote: > Hi there, > > when I have a python class X which overloads an operator, I can use that > operator to do any operation for example with an integer > > y = X() + 123 > > however, say I want the "+" operator to be commutative. Then > > y = 123 + X() > > should have the same result. However, since it does not call __add__ on > an instance of X, but on the int 123, this fails: > > TypeError: unsupported operand type(s) for +: 'int' and 'X' > > How can I make this commutative? > > Best regards, > Henri def __radd__(self, other): return self.__add__(self, other) From bahamutzero8825 at gmail.com Mon Sep 19 16:40:00 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 19 Sep 2011 15:40:00 -0500 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: Message-ID: <4E77A8A0.3030104@gmail.com> On 2011.09.19 09:00 AM, Brian Curtin wrote: > You said "the application does not create an app folder in the user's > 'application data' directory" -- what does this mean, or rather, what > is the specific folder you're expecting to have? If Python can't > create the directory but you can do it manually, there may be some > permission or access differences new to Windows 8. What does "echo > %APPDATA%" give you? I booted up the Win8 dev preview in a VM and os.environ['appdata'] gives me the same result it would for Windows 7. Perhaps the problem lies in the os.path.exists() call (that is, Win8 and Win7 react differently to this call). I personally would try to create the directory and then catch either a WindowsError (error 183) or an OSError (error 17) if the directory already exists. I might play around with this later and post some results. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 PGP/GPG Public Key ID: 0xF88E034060A78FCB From nobody at nowhere.com Mon Sep 19 17:54:49 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 19 Sep 2011 22:54:49 +0100 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) References: Message-ID: On Sun, 18 Sep 2011 23:41:29 -0600, Ian Kelly wrote: >> If the transaction object doesn't get its commit() called, it does no >> actions at all, thus eliminating all issues of locks. > > And what if the thread gets killed in the middle of the commit? The essence of a commit is that it involves an atomic operation, for which there is no "middle". From ian.g.kelly at gmail.com Mon Sep 19 18:04:17 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 19 Sep 2011 16:04:17 -0600 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Mon, Sep 19, 2011 at 12:25 AM, Chris Angelico wrote: > On Mon, Sep 19, 2011 at 3:41 PM, Ian Kelly wrote: >> And what if the thread gets killed in the middle of the commit? >> > > Database managers solved this problem years ago. It's not done by > preventing death until you're done - death can come from someone > brutally pulling out your power cord. There's no "except > PowerCordRemoved" to protect you from that! I'm aware of that. I'm not saying it's impossible, just that the example you gave is over-simplified, as writing atomic transactional logic is a rather complex topic. There may be an existing Python library to handle this, but I'm not aware of one. "PowerCordRemoved" is not relevant here, as that would kill the entire process, which renders the issue of broken shared data within a continuing process rather moot. Cheers, Ian From bahamutzero8825 at gmail.com Mon Sep 19 18:38:32 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 19 Sep 2011 17:38:32 -0500 Subject: logging.config and {-style formatting Message-ID: <4E77C468.30709@gmail.com> Is it possible to use {-style formatting with a logging config file? I can add style='{' to a logging.Formatter() call and it works fine, but I see no way of doing this from a config file. I tried adding a style option in the config file, but it has no effect. I see no mention of the {-style in the logging.config docs, so am I right to assume {-style formatting is not implemented in logging.config? -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From mindwalkernine at gmail.com Mon Sep 19 19:13:06 2011 From: mindwalkernine at gmail.com (Jordan Evans) Date: Mon, 19 Sep 2011 18:13:06 -0500 Subject: Dynamically Cause A Function To Return Message-ID: I want dynamically place the 'return' statement in a function via user input or achieve the same through some other means. If some other means, the user must be able initiate this at runtime during a raw_input(). This is what I have so far, this would be an awesome command line debugging tool if I can get it to work. def b(label="", *args): """Used to create breaks for debugging. Will break the function or continue the function it is place within based on user input. Has as a input loop for querying variables and executing code before a break or a continue.""" print label+":", for arg in args: print str(arg), if len(args): print x = "" while x != ".": command = raw_input() try: exec command except: pass -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridharr at activestate.com Mon Sep 19 19:27:40 2011 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Mon, 19 Sep 2011 16:27:40 -0700 Subject: ANN: ActivePython 3.2.2.3 is now available Message-ID: <9643CBF5-DC47-4A59-93B9-1610031E4ACF@activestate.com> ActiveState is pleased to announce ActivePython 3.2.2.3, a complete, ready-to-install binary distribution of Python 3.2. http://www.activestate.com/activepython/downloads What's New in ActivePython-3.2.2.3 ================================== New Features & Upgrades ----------------------- - Upgrade to Python 3.2.2 (`release notes `__) - [Windows] Security upgrade to openssl-1.0.0e - Upgraded the following packages: - Distribute-0.6.21 - virtualenv-1.6.4 What is ActivePython? ===================== ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux are made freely available. Solaris, HP-UX and AIX builds, and access to older versions are available in ActivePython Business, Enterprise and OEM editions: http://www.activestate.com/python ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. ActivePython also includes a binary package manager for Python (PyPM) that can be used to install packages much easily. For example: C:\>pypm install numpy [...] C:\>python >>> import numpy.linalg >>> See this page for full details: http://docs.activestate.com/activepython/3.2/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/3.2/ We would welcome any and all feedback to: activepython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/enter_bug.cgi?product=ActivePython Supported Platforms =================== ActivePython is available for the following platforms: - Windows (x86 and x64) - Mac OS X (x86 and x86_64; 10.5+) - Linux (x86 and x86_64) - Solaris/SPARC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) - Solaris/x86 (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/PA-RISC (32-bit) (Business, Enterprise or OEM edition only) - HP-UX/IA-64 (32-bit and 64-bit) (Enterprise or OEM edition only) - AIX/PowerPC (32-bit and 64-bit) (Business, Enterprise or OEM edition only) More information about the Business Edition can be found here: http://www.activestate.com/business-edition Custom builds are available in the Enterprise Edition: http://www.activestate.com/enterprise-edition Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From rosuav at gmail.com Mon Sep 19 20:18:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 20 Sep 2011 10:18:02 +1000 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 8:04 AM, Ian Kelly wrote: > "PowerCordRemoved" is not relevant here, as that would kill the entire > process, which renders the issue of broken shared data within a > continuing process rather moot. > Assuming that the "broken shared data" exists only in RAM on one single machine, and has no impact on the state of anything on the hard disk or on any other computer, yes. ChrisA From chunuan723 at gmail.com Mon Sep 19 20:37:31 2011 From: chunuan723 at gmail.com (he sharon) Date: Mon, 19 Sep 2011 17:37:31 -0700 (PDT) Subject: red bull hats, monster energy hats on www.popbaseballhats.com Message-ID: <7345edb4-a967-4c69-a212-d5072809e360@19g2000vbx.googlegroups.com> our products: red bull hats: http://www.popbaseballhats.com/wholesale-113-b0-Red-Bull-Hats.html red bull beanies: http://www.popbaseballhats.com/wholesale-112-b0-Red-Bull-Beanies.html red bull t shirts: http://www.popbaseballhats.com/wholesale-114-b0-Red-Bull-T-Shirts.html monster energy hats: http://www.popbaseballhats.com/wholesale-100-b0-Monster-Energy-Hats.html monster energy t shirts: http://www.popbaseballhats.com/wholesale-101-b0-Monster-Energy-T-Shirts.html and so on.on our site: http://www.popbaseballhats.com/ From greg.ewing at canterbury.ac.nz Mon Sep 19 20:51:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 20 Sep 2011 12:51:42 +1200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <9dq6cvF4ndU1@mid.individual.net> Antoon Pardon wrote: > int PyThreadState_SetAsyncExc(long id, PyObject *exc) > > To prevent > naive misuse, you must write your own C extension to call this. Not if we use ctypes! Muahahahaaa! -- Greg From steve+comp.lang.python at pearwood.info Mon Sep 19 21:22:41 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 11:22:41 +1000 Subject: Operator commutativity References: Message-ID: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > def __radd__(self, other): > return self.__add__(self, other) Which, inside a class, can be simplified to: __radd__ = __add__ -- Steven From roy at panix.com Mon Sep 19 22:26:30 2011 From: roy at panix.com (Roy Smith) Date: Mon, 19 Sep 2011 22:26:30 -0400 Subject: Operator commutativity References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > Westley Mart??nez wrote: > > > def __radd__(self, other): > > return self.__add__(self, other) > > Which, inside a class, can be simplified to: > > __radd__ = __add__ Ooh, I could see that leading to some weird diagnostics. For example: class Foo: def __add__(self, other): raise Exception __radd__ = __add__ f1 = Foo() print 1 + f1 produces: ./add.py Traceback (most recent call last): File "./add.py", line 11, in print 1 + f1 File "./add.py", line 5, in __add__ raise Exception Exception which leaves the user wondering why __add__() was called when clearly __radd__() should have been. The way Westley wrote it (modulo fixing the __add__() call signature) produces: ./add.py Traceback (most recent call last): File "./add.py", line 11, in print 1 + f1 File "./add.py", line 8, in __radd__ return self.__add__(other) File "./add.py", line 5, in __add__ raise Exception Exception which at least is a stack trace that shows that __radd__() was called. From steve+comp.lang.python at pearwood.info Mon Sep 19 22:43:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Sep 2011 02:43:25 GMT Subject: Operator commutativity References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e77fdcd$0$29995$c3e8da3$5496439d@news.astraweb.com> On Mon, 19 Sep 2011 22:26:30 -0400, Roy Smith wrote: > In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >> Westley Mart?nez wrote: >> >> > def __radd__(self, other): >> > return self.__add__(self, other) >> >> Which, inside a class, can be simplified to: >> >> __radd__ = __add__ > > Ooh, I could see that leading to some weird diagnostics. "Weird"? You've lived a sheltered life if you think a function being known under two names is weird. Wait until you discover monkey-patching built-ins for fun and profit! -- Steven From anikom15 at gmail.com Mon Sep 19 22:53:39 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 19 Sep 2011 19:53:39 -0700 Subject: Operator commutativity In-Reply-To: References: <4e77eae1$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110920025339.GA22418@Smoke> On Mon, Sep 19, 2011 at 10:26:30PM -0400, Roy Smith wrote: > In article <4e77eae1$0$29978$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > > > Westley Mart??nez wrote: > > > > > def __radd__(self, other): > > > return self.__add__(self, other) > > > > Which, inside a class, can be simplified to: > > > > __radd__ = __add__ > > Ooh, I could see that leading to some weird diagnostics. For example: > > class Foo: > def __add__(self, other): > raise Exception > > __radd__ = __add__ > > f1 = Foo() > print 1 + f1 > > produces: > > ./add.py > Traceback (most recent call last): > File "./add.py", line 11, in > print 1 + f1 > File "./add.py", line 5, in __add__ > raise Exception > Exception > > which leaves the user wondering why __add__() was called when clearly > __radd__() should have been. The way Westley wrote it (modulo fixing > the __add__() call signature) produces: > > ./add.py > Traceback (most recent call last): > File "./add.py", line 11, in > print 1 + f1 > File "./add.py", line 8, in __radd__ > return self.__add__(other) > File "./add.py", line 5, in __add__ > raise Exception > Exception > > which at least is a stack trace that shows that __radd__() was called. Calling __radd__ = __add__ simply creates a reference to __add__ named __radd__, it doesn't create a new method. From stars9820 at gmail.com Tue Sep 20 01:34:59 2011 From: stars9820 at gmail.com (star ship) Date: Mon, 19 Sep 2011 22:34:59 -0700 (PDT) Subject: DATA ENTRY JOB Message-ID: hi make money with online work at home so join it and earn more money at home. http://onlinejobforall100.blogspot.com/ thanks From zzzzysilence at gmail.com Tue Sep 20 03:55:20 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Tue, 20 Sep 2011 00:55:20 -0700 (PDT) Subject: red bull hats of http:www.discounthats.net Message-ID: <1dcd1d21-b168-4f73-8411-50903d6fd665@19g2000vbx.googlegroups.com> Welcome to the http:www.discounthats.net.The http:www.discounthats.net is a promotional shop from the red bull hats, monster energy hats, snapback hats.red bull hats: http:www.discounthats.net red bull hats: http://www.discounthats.net/category-2-b0-Red-Bull-Hats.html monster energy hats: http://www.discounthats.net/category-3-b0-Monster-Energy-Hats.html snapback hats: http://www.discounthats.net/category-79-b0-Snapback-Hats.html our site: www.discounthats.net From zzzzysilence at gmail.com Tue Sep 20 04:07:44 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Tue, 20 Sep 2011 01:07:44 -0700 (PDT) Subject: red bull hats of http:www.discounthats.net Message-ID: Welcome to the http:www.discounthats.net.The http:www.discounthats.net is a promotional shop from the red bull hats, monster energy hats, snapback hats.red bull hats: http:www.discounthats.net red bull hats: http://www.discounthats.net/category-2-b0-Red-Bull-Hats.html monster energy hats: http://www.discounthats.net/category-3-b0-Monster-Energy-Hats.html snapback hats: http://www.discounthats.net/category-79-b0-Snapback-Hats.html our site: www.discounthats.net From mateusz at loskot.net Tue Sep 20 06:34:42 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Tue, 20 Sep 2011 11:34:42 +0100 Subject: PyEval_EvalCodeEx return value Message-ID: <4E786C42.3050309@loskot.net> Hi, I'm trying to dig out details about what exactly is the return value the of PyEval_EvalCodeEx function in Python 3.x The documentation is sparse, unfortunately. Perhaps I'm looking at wrong function. My aim is simple, I need to execute Python code using Python interpreter embedded in my C++ application. The Python code is a simple script that always returns single value. For example: #! /usr/bin/env python def foo(a, b): return a + b f = foo(2, 3) But, f can be of different type for different script: one returns numeric value, another returns a sequence, so the type is not possible to be determined in advance. I know how to capture Python stdout/stderr. I also know how to access the "f" attribute using PyObject_GetAttrString and then I can convert "f" value to C++ type depending on PyObject type. However, I guess there shall be a way to access "f" value directly from PyEval_EvalCode return object: PyObject* evalRet = ::PyEval_EvalCode(...); But, I can't find any details what the "evalRet" actually is. Any pointers would be helpful. Best regards, -- Mateusz Loskot, http://mateusz.loskot.net Charter Member of OSGeo, http://osgeo.org Member of ACCU, http://accu.org From alec.taylor6 at gmail.com Tue Sep 20 08:32:53 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 20 Sep 2011 22:32:53 +1000 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: <4E77A8A0.3030104@gmail.com> References: <4E77A8A0.3030104@gmail.com> Message-ID: I can confirm that os.mkdir('C:\\h') and os.path.exists('C:\\h') work on Windows 8 Dev x64. On Tue, Sep 20, 2011 at 6:40 AM, Andrew Berg wrote: > On 2011.09.19 09:00 AM, Brian Curtin wrote: >> You said "the application does not create an app folder in the user's >> 'application data' directory" -- what does this mean, or rather, what >> is the specific folder you're expecting to have? If Python can't >> create the directory but you can do it manually, there may be some >> permission or access differences new to Windows 8. What does "echo >> %APPDATA%" give you? > I booted up the Win8 dev preview in a VM and os.environ['appdata'] gives > me the same result it would for Windows 7. Perhaps the problem lies in > the os.path.exists() call (that is, Win8 and Win7 react differently to > this call). I personally would try to create the directory and then > catch either a WindowsError (error 183) or an OSError (error 17) if the > directory already exists. I might play around with this later and post > some results. > > -- > CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 > PGP/GPG Public Key ID: 0xF88E034060A78FCB > -- > http://mail.python.org/mailman/listinfo/python-list > From kw at codebykevin.com Tue Sep 20 08:40:30 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 20 Sep 2011 08:40:30 -0400 Subject: Python bug in Windows 8--report now, or later? In-Reply-To: References: <4E77A8A0.3030104@gmail.com> Message-ID: On 9/20/11 8:32 AM, Alec Taylor wrote: > I can confirm that os.mkdir('C:\\h') and os.path.exists('C:\\h') work > on Windows 8 Dev x64. OK--looks like I will need to do a bit more digging into my own code. Thanks for clarifying. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mohammedimran115 at gmail.com Tue Sep 20 09:57:08 2011 From: mohammedimran115 at gmail.com (mohammed imran) Date: Tue, 20 Sep 2011 06:57:08 -0700 (PDT) Subject: mohammedimran Message-ID: <6cedda83-32da-4d4d-befa-1b6f89768111@f41g2000yqh.googlegroups.com> http://123maza.com/65/fun564/ From funthyme at gmail.com Tue Sep 20 10:40:06 2011 From: funthyme at gmail.com (John Pinner) Date: Tue, 20 Sep 2011 07:40:06 -0700 (PDT) Subject: PyEval_EvalCodeEx return value References: Message-ID: <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> On Sep 20, 11:34?am, Mateusz Loskot wrote: > Hi, > > I'm trying to dig out details about what exactly is the return > value the of PyEval_EvalCodeEx function in Python 3.x > The documentation is sparse, unfortunately. > > Perhaps I'm looking at wrong function. > My aim is simple, I need to execute Python code using Python interpreter > embedded in my C++ application. > The Python code is a simple script that always returns single value. > For example: > > #! /usr/bin/env python > def foo(a, b): > ? ? return a + b > f = foo(2, 3) > > But, f can be of different type for different script: one returns > numeric value, another returns a sequence, so the type is not > possible to be determined in advance. > > I know how to capture Python stdout/stderr. > > I also know how to access the "f" attribute using > PyObject_GetAttrString and then I can convert "f" value to C++ type > depending on PyObject type. > > However, I guess there shall be a way to access "f" value > directly from PyEval_EvalCode return object: > > PyObject* evalRet = ::PyEval_EvalCode(...); > > But, I can't find any details what the "evalRet" actually is. I assume that you have read the documentation at http://docs.python.org/c-api/veryhigh.html, and I agree that it's sparse, but the entry for the next entry, PyEval_EvalCodeEx, tells you a little more, as does that for PyEval_EvalFrameEx. Obviously, it's returning a pointer to a PyObject, and Looking at the source code, that may be NULL, to throw an exception, or an execution frame, or a generator,etc, etc, depending on the code it's been given. I guess that you should be able to inspect the PyObject to see what it is. What I'm wondering is, why are you eval-ing code ? A favourite device of C programmers coming to Python (and mea culpa in the past), it's fraught with potential problems and even security risks, and is difficult to debug, and maybe you should be using introspection instead. And maybe you should be working in Python, and not C++ at this point, do the dynamic stuff in the language best suited, and then return to C+ + when needed. Best wishes, John -- > Any pointers would be helpful. > > Best regards, > -- > Mateusz Loskot,http://mateusz.loskot.net > Charter Member of OSGeo,http://osgeo.org > Member of ACCU,http://accu.org From jasfreedom at gmail.com Tue Sep 20 11:09:21 2011 From: jasfreedom at gmail.com (jasmine jasmine) Date: Tue, 20 Sep 2011 08:09:21 -0700 (PDT) Subject: techology Message-ID: http://123maza.com/48/doll789/ From yasar11732 at gmail.com Tue Sep 20 12:44:46 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 20 Sep 2011 19:44:46 +0300 Subject: HTMLParser and non-ascii html pages Message-ID: Hi, I am using a simple sublclass of HTMLParser like this: class LinkCollector(HTMLParser): def reset(self): self.links = [] HTMLParser.reset(self) def handle_starttag(self,tag,attr): if tag in ("a","link"): key = "href" elif tag in ("img","script"): key = "src" else: return self.links.extend([v for k,v in attr if k == key]) This gives following error: Traceback (most recent call last): File "downloader.py", line 209, in if __name__ == "__main__": main() File "downloader.py", line 201, in main link_collect.feed(response) File "C:\Python27\lib\HTMLParser.py", line 108, in feed self.goahead(0) File "C:\Python27\lib\HTMLParser.py", line 148, in goahead k = self.parse_starttag(i) File "C:\Python27\lib\HTMLParser.py", line 252, in parse_starttag attrvalue = self.unescape(attrvalue) File "C:\Python27\lib\HTMLParser.py", line 393, in unescape return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s) File "C:\Python27\lib\re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: ordinal not in range(128) Rest of the code available as attachment. Does anyone know how to solve this? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: downloader.py Type: application/octet-stream Size: 6210 bytes Desc: not available URL: From ppearson at nowhere.invalid Tue Sep 20 13:07:35 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 20 Sep 2011 17:07:35 GMT Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <9drvinFngaU1@mid.individual.net> On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman wrote: [snip] > Also, if the right-hand operand is a subclass of the left-hand operand > then Python will try right-hand_operand.__radd__ first. I don't think it works that way for me: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>> class C1(): ... def __add__(self, other): ... print "C1.__add__()" ... >>> class C2(C1): ... def __radd__(self, other): ... print "C2.__radd__()" ... >>> C1() + C2() C1.__add__() >>> -- To email me, substitute nowhere->spamcop, invalid->net. From dreyemi at gmail.com Tue Sep 20 14:13:32 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:13:32 +0100 Subject: Why are my queues empty even though there are items in it? Message-ID: Hello friends, I'm writing some Python app that makes use of the multiprocessing and Queue api to perform transaction jobs. My problem is that, the queue always report empty even though I can confirm that there are items in it. Below is the code I'm working with: import multiprocessing from multiprocessing import Process, Queue from Queue import Empty def process(**kwargs): q = kwargs['q'] # Don't start the process if there's no item in queue if q.empty(): print 'empty queue' multiprocessing.Process() # Process defaults to None else: p = multiprocessing.Process(target=transaction_queue, args=(kwargs)) p.start() def put_in_queue(items={}): print items q = multiprocessing.Queue() try: for k,v in items.iteritems(): data = v #data is a dict timeout = data.get(u'timeout') # Put the transaction item in the queue at a specific timeout # period q.put(data, False, timeout) print "{0} put to queue".format(data) transaction_queue(q, data, timeout, False) except (KeyError, AttributeError, ValueError): print 'Incorrect data format' def transaction_queue(queue, item, timeout, block=False): queue = multiprocessing.Queue() if item is not {} and timeout is not 0: print "Items are {0}".format(item) for i in range(len(item)): try: d = queue.get(block) print d except Empty: print 'Fees queue empty at %s' % (i) else: return process(q=queue, i=d, t=timeout) else: print 'No item in the queue to get' A JSON POST from CURL calls put_in_queue callback: curl -v -H "Content-Type: application/json" -X POST --data 'fees={"fees":{"status":"pending","timeout":5}, "hostel":{"status":"pending","timeout": 3}}' http://127.0.0.1:8000/transaction/add/ > post_data.txt At code run, the output is: {u'status': u'pending', u'timeout': 3} put to queue Items are {u'status': u'pending', u'timeout': 3} Fees queue empty at 0 Fees queue empty at 1 {u'status': u'pending', u'timeout': 5} put to queue Items are {u'status': u'pending', u'timeout': 5} Fees queue empty at 0 Fees queue empty at 1 Q: Why are my queues empty even though there are items in it? Thanks you for the suggestions and answers. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From dreyemi at gmail.com Tue Sep 20 14:29:06 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:29:06 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 12:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user > input or achieve the same through some other means. If some other means, > the user must be able initiate this at runtime during a raw_input(). This > is what I have so far, this would be an awesome command line debugging tool > if I can get it to work. > > def b(label="", *args): > """Used to create breaks for debugging. Will break the function or > continue the function it is place within based on user input. Has as a > input loop for querying variables and executing code before a break or a > continue.""" > print label+":", > for arg in args: > print str(arg), > if len(args): > print > x = "" > while x != ".": > command = raw_input() > try: > exec command > except: > pass > Isn't this "call by reference" ? see http://docs.python.org/faq/programming.html?highlight=kwargs#how-do-i-write-a-function-with-output-parameters-call-by-reference -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Sep 20 14:35:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 21 Sep 2011 04:35:24 +1000 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 9:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user input > or achieve the same through some other means.? If some other means, the user > must be able initiate this at runtime during a raw_input().? This is what I > have so far, this would be an awesome command line debugging tool if I can > get it to work. Not entirely sure what you're trying to accomplish here. You want to pepper your code with calls to b() and then have the user be able to abort the function from there? If so, I can think of two ways: 1) Have b() raise an exception, which you catch at a high level. That'd unwind the stack all the way to the top, which may or may not be what you want. Pretty easy to do though. 2) Pepper your code with: if b(): return and then have b return 0 normally and 1 when the user asks to abort. This isn't truly an interactive debugger, though it does potentially have much value. ChrisA From dreyemi at gmail.com Tue Sep 20 14:35:47 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 19:35:47 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 12:13 AM, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user > input or achieve the same through some other means. If some other means, > the user must be able initiate this at runtime during a raw_input(). This > is what I have so far, this would be an awesome command line debugging tool > if I can get it to work. > > def b(label="", *args): > """Used to create breaks for debugging. Will break the function or > continue the function it is place within based on user input. Has as a > input loop for querying variables and executing code before a break or a > continue.""" > print label+":", > for arg in args: > print str(arg), > if len(args): > print > x = "" > while x != ".": > command = raw_input() > try: > exec command > except: > pass > It is also possible to create the function in your loop. for arg in args: def f(args): return args # You can make this a callback function if you want -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Tue Sep 20 14:42:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 20 Sep 2011 19:42:38 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: References: Message-ID: <4E78DE9E.3050100@mrabarnett.plus.com> On 20/09/2011 19:13, Kayode Odeyemi wrote: > Hello friends, > > I'm writing some Python app that makes use of the multiprocessing and > Queue api to perform > transaction jobs. > > My problem is that, the queue always report empty even though I can > confirm that there are items in it. > > Below is the code I'm working with: > [snip] > > def transaction_queue(queue, item, timeout, block=False): > queue = multiprocessing.Queue() This line creates a new empty queue, hiding the one which was passed in. > if item is not {} and timeout is not 0: `not {}` has the value True, so `item is not {}` means `item is True`. The `is` checks for identity, not equality, so this is true only if `item` actually has the value True or 1 (and this is an implementation-dependent behaviour). > print "Items are {0}".format(item) > for i in range(len(item)): You're trying to get as many items from the queue as there are items in the dict `item`, which looks wrong to me. > try: > d = queue.get(block) > print d > except Empty: > print 'Fees queue empty at %s' % (i) > else: > return process(q=queue, i=d, t=timeout) > else: > print 'No item in the queue to get' > > A JSON POST from CURL calls put_in_queue callback: > > curl -v -H "Content-Type: application/json" -X POST --data > 'fees={"fees":{"status":"pending","timeout":5}, > "hostel":{"status":"pending","timeout": 3}}' > http://127.0.0.1:8000/transaction/add/ > post_data.txt > > At code run, the output is: > > {u'status': u'pending', u'timeout': 3} put to queue > Items are {u'status': u'pending', u'timeout': 3} > Fees queue empty at 0 > Fees queue empty at 1 > {u'status': u'pending', u'timeout': 5} put to queue > Items are {u'status': u'pending', u'timeout': 5} > Fees queue empty at 0 > Fees queue empty at 1 > > Q: Why are my queues empty even though there are items in it? > What makes you think there are items in it? You print out `item`, which is not the queue. > Thanks you for the suggestions and answers. > From arnodel at gmail.com Tue Sep 20 15:04:29 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 20 Sep 2011 20:04:29 +0100 Subject: Dynamically Cause A Function To Return In-Reply-To: References: Message-ID: On 20 September 2011 00:13, Jordan Evans wrote: > I want dynamically place the 'return' statement in a function via user input > or achieve the same through some other means.? If some other means, the user > must be able initiate this at runtime during a raw_input().? This is what I > have so far, this would be an awesome command line debugging tool if I can > get it to work. > > def b(label="", *args): > ??? """Used to create breaks for debugging.? Will break the function or > continue the function it is place within based on user input.? Has as a > input loop for querying variables and executing code before a break or a > continue.""" > ??? print label+":", > ??? for arg in args: > ??? ??? print str(arg), > ??? if len(args): > ??? ??? print > ??? x = "" > ??? while x != ".": > ??? ??? command = raw_input() > ??? ??? try: > ??? ??? ??? exec command > ??? ??? except: > ??? ??? ??? pass > I don't really understand your dynamic return idea, but this reminds me of some debugging function I wrote some time ago. It pauses execution and you can evaluate expression in the current stack frame and any of its parents using the following syntax: executes in the stack frame where pause() was inserted . executes it in the parent of this stack frame .. in the grandparent (etc...) ? shows all accessible stack frames def pause(): import sys, inspect, re f = None print "\n*** Entering pause mode (EOF to resume)" try: while True: try: c = raw_input('pause> ') if c == '?': for i, fi in enumerate(inspect.stack()[1:]): print ('%s File "%s", line %s, in %s' % ('.'*i, fi[1], fi[2], fi[3])) continue dots = re.match(r'\.*', c) back = 0 if dots: back = len(dots.group()) f = sys._getframe(back+1) code_name = f.f_code.co_name cmd = c[back:] val = cmd and eval(cmd, f.f_globals, f.f_locals) print "(%s) %r" % (code_name, val) except Exception, e: if isinstance(e, EOFError): del f raise print "%s: %s" % (type(e).__name__, e) except EOFError: pass finally: print "\n*** Leaving pause mode" # Simple example of 'pause' in action: >>> def g(x): ... b = 5 ... pause() ... >>> def f(x, y): ... z = 2 ... g(x) ... print "And we carry on..." ... >>> f('spam', [4, 2]) *** Entering pause mode (EOF to resume) pause> ? File "", line 3, in g . File "", line 3, in f .. File "", line 1, in pause> b (g) 5 pause> b+1 (g) 6 pause> .z (f) 2 pause> .y (f) [4, 2] pause> .x (f) 'spam' pause> ..len () pause> ^D *** Leaving pause mode And we carry on... >>> -- Arnaud From schesis at gmail.com Tue Sep 20 15:09:12 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 20 Sep 2011 15:09:12 -0400 Subject: Why are my queues empty even though there are items in it? In-Reply-To: <4E78DE9E.3050100@mrabarnett.plus.com> References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: : On 20 September 2011 14:42, MRAB wrote: > On 20/09/2011 19:13, Kayode Odeyemi wrote: >> >> ? ? if item is not {} and timeout is not 0: > > `not {}` has the value True, so `item is not {}` means `item is True`. > The `is` checks for identity, not equality, so this is true only if `item` > actually has the value True or 1 (and this is an implementation-dependent > behaviour). Nitpick: "is not" is an operator: >>> "foo" is not {} True >>> "foo" is (not {}) False -[]z. From ethan at stoneleaf.us Tue Sep 20 15:09:15 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 20 Sep 2011 12:09:15 -0700 Subject: Operator commutativity In-Reply-To: <9drvinFngaU1@mid.individual.net> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> Message-ID: <4E78E4DB.4040606@stoneleaf.us> Peter Pearson wrote: > On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman wrote: > [snip] >> Also, if the right-hand operand is a subclass of the left-hand operand >> then Python will try right-hand_operand.__radd__ first. > > I don't think it works that way for me: > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>>> class C1(): > ... def __add__(self, other): > ... print "C1.__add__()" > ... >>>> class C2(C1): > ... def __radd__(self, other): > ... print "C2.__radd__()" > ... >>>> C1() + C2() > C1.__add__() Oh, it has to be a new-style class. Sorry. ~Ethan~ From python at mrabarnett.plus.com Tue Sep 20 15:43:18 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 20 Sep 2011 20:43:18 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: <4E78ECD6.3010705@mrabarnett.plus.com> On 20/09/2011 20:09, Zero Piraeus wrote: > : > > On 20 September 2011 14:42, MRAB wrote: >> On 20/09/2011 19:13, Kayode Odeyemi wrote: >>> >>> if item is not {} and timeout is not 0: >> >> `not {}` has the value True, so `item is not {}` means `item is True`. >> The `is` checks for identity, not equality, so this is true only if `item` >> actually has the value True or 1 (and this is an implementation-dependent >> behaviour). > > Nitpick: "is not" is an operator: > >>>> "foo" is not {} > True >>>> "foo" is (not {}) > False > Oops! True. However, it still doesn't do what the OP intended: >>> {} is {} False >>> {} is not {} True From dreyemi at gmail.com Tue Sep 20 15:51:23 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 20 Sep 2011 20:51:23 +0100 Subject: Why are my queues empty even though there are items in it? In-Reply-To: <4E78DE9E.3050100@mrabarnett.plus.com> References: <4E78DE9E.3050100@mrabarnett.plus.com> Message-ID: On Tue, Sep 20, 2011 at 7:42 PM, MRAB wrote: > On 20/09/2011 19:13, Kayode Odeyemi wrote: > > def transaction_queue(queue, item, timeout, block=False): >> queue = multiprocessing.Queue() >> > > This line creates a new empty queue, hiding the one which was passed in. Removed. > > > if item is not {} and timeout is not 0: >> > > `not {}` has the value True, so `item is not {}` means `item is True`. > The `is` checks for identity, not equality, so this is true only if `item` > actually has the value True or 1 (and this is an implementation-dependent > behaviour). changed to: if item != {} and timeout != None > > > print "Items are {0}".format(item) >> for i in range(len(item)): >> > > You're trying to get as many items from the queue as there are items in > the dict `item`, which looks wrong to me. > > > try: >> d = queue.get(block) >> print d >> except Empty: >> print 'Fees queue empty at %s' % (i) >> else: >> return process(q=queue, i=d, t=timeout) >> else: >> print 'No item in the queue to get' >> >> Effected this. d has a result in the output (output below). So obviously, it is not empty. What I'm trying to do in the initial code is to have all items in the queue evaluated at the same time such that each leaves the queue for processing when its timeout period has elapse. > >> Q: Why are my queues empty even though there are items in it? >> >> What makes you think there are items in it? You print out `item`, which > is not the queue. > I've made these changes but the queue still appears empty None put to queue {u'status': u'pending', u'timeout': 3} empty queue None put to queue {u'status': u'pending', u'timeout': 5} empty queue Why 'empty queue' in process()? Also, why "None put to queue" since d confirms the items in the queue? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Sep 20 15:59:14 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 20 Sep 2011 20:59:14 +0100 Subject: About MAKE_FUNCTION opcode in Python 3 Message-ID: Since Python 3.0 we have keyword only arguments in functions (see PEP 3102). Looking at the documentation for the dis module (where opcodes are documented), I see the following for MAKE_FUNCTION [1] """ MAKE_FUNCTION(argc) Pushes a new function object on the stack. TOS is the code associated with the function. The function object is defined to have argc default parameters, which are found below TOS. """ No mention of default values for keyword only arguments. Now let's try (Python 3.2): >>> def foo(): ... def bar(x, y, *args, z=1, t=2, **kwargs): pass ... >>> dis.dis(foo) 2 0 LOAD_CONST 1 ('z') 3 LOAD_CONST 2 (1) 6 LOAD_CONST 3 ('t') 9 LOAD_CONST 4 (2) 12 LOAD_CONST 5 (", line 2>) 15 MAKE_FUNCTION 512 18 STORE_FAST 0 (bar) 21 LOAD_CONST 0 (None) 24 RETURN_VALUE MAKE_FUNCTION has an argc of 512. So it seems that since Python 3.0: * the number of default values for normal arguments is argc & 0xFF * the number of default values for keyword only arguments is argc >> 8 Can anyone confirm this? I can then open a ticket on bugs.python.org [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION -- Arnaud From __peter__ at web.de Tue Sep 20 16:11:58 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Sep 2011 22:11:58 +0200 Subject: HTMLParser and non-ascii html pages References: Message-ID: Ya?ar Arabac? wrote: > I am using a simple sublclass of HTMLParser like this: > > class LinkCollector(HTMLParser): > > def reset(self): > self.links = [] > HTMLParser.reset(self) > > def handle_starttag(self,tag,attr): > if tag in ("a","link"): > key = "href" > elif tag in ("img","script"): > key = "src" > else: > return > self.links.extend([v for k,v in attr if k == key]) > > This gives following error: > > Traceback (most recent call last): > File "downloader.py", line 209, in > if __name__ == "__main__": main() > File "downloader.py", line 201, in main > link_collect.feed(response) > File "C:\Python27\lib\HTMLParser.py", line 108, in feed > self.goahead(0) > File "C:\Python27\lib\HTMLParser.py", line 148, in goahead > k = self.parse_starttag(i) > File "C:\Python27\lib\HTMLParser.py", line 252, in parse_starttag > attrvalue = self.unescape(attrvalue) > File "C:\Python27\lib\HTMLParser.py", line 393, in unescape > return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, > s) > File "C:\Python27\lib\re.py", line 151, in sub > return _compile(pattern, flags).sub(repl, string, count) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13: > ordinal not in range(128) Trying to reproduce the error: >>> from HTMLParser import HTMLParser >>> class P(HTMLParser): ... def handle_starttag(self, tag, attrs): ... key, value = attrs[0] ... print tag, key, "=", value ... >>> def feed(s): ... P().feed(s) ... >>> feed("") a href = yadda >>> feed("") a href = ? yadda >>> feed("") Traceback (most recent call last): File "", line 1, in File "", line 2, in feed File "/usr/local/lib/python2.7/HTMLParser.py", line 108, in feed self.goahead(0) File "/usr/local/lib/python2.7/HTMLParser.py", line 148, in goahead k = self.parse_starttag(i) File "/usr/local/lib/python2.7/HTMLParser.py", line 252, in parse_starttag attrvalue = self.unescape(attrvalue) File "/usr/local/lib/python2.7/HTMLParser.py", line 390, in unescape return re.sub(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));", replaceEntities, s) File "/usr/local/lib/python2.7/re.py", line 151, in sub return _compile(pattern, flags).sub(repl, string, count) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) It seems that the exception is triggered by an attribute value that contains both entities and non-ascii bytes. >>> feed(u"") a href = ? ? > Rest of the code available as attachment. Does anyone know how to solve > this? The documentation doesn't mention unicode, but it seems to work anyway: >>> feed(u"") a href = ? ? So one fix might be to convert the data to unicode before passing it to the HTMLParser. From ericsnowcurrently at gmail.com Tue Sep 20 17:56:41 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Tue, 20 Sep 2011 15:56:41 -0600 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On Tue, Sep 20, 2011 at 1:59 PM, Arnaud Delobelle wrote: > Since Python 3.0 we have keyword only arguments in functions (see PEP > 3102). ?Looking at the documentation for the dis module (where opcodes > are documented), I see the following for MAKE_FUNCTION [1] > > """ > MAKE_FUNCTION(argc) > Pushes a new function object on the stack. TOS is the code associated > with the function. The function object is defined to have argc default > parameters, which are found below TOS. > """ > > No mention of default values for keyword only arguments. ?Now let's > try (Python 3.2): > >>>> def foo(): > ... ? def bar(x, y, *args, z=1, t=2, **kwargs): pass > ... >>>> dis.dis(foo) > ?2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 1 ('z') > ? ? ? ? ? ? ?3 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > ? ? ? ? ? ? ?6 LOAD_CONST ? ? ? ? ? ? ? 3 ('t') > ? ? ? ? ? ? ?9 LOAD_CONST ? ? ? ? ? ? ? 4 (2) > ? ? ? ? ? ? 12 LOAD_CONST ? ? ? ? ? ? ? 5 ( 0x1005ec8b0, file "", line 2>) > ? ? ? ? ? ? 15 MAKE_FUNCTION ? ? ? ? ?512 > ? ? ? ? ? ? 18 STORE_FAST ? ? ? ? ? ? ? 0 (bar) > ? ? ? ? ? ? 21 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > ? ? ? ? ? ? 24 RETURN_VALUE > > MAKE_FUNCTION has an argc of 512. ?So it seems that since Python 3.0: > > * the number of default values for normal arguments is argc & 0xFF > * the number of default values for keyword only arguments is argc >> 8 > > Can anyone confirm this? ?I can then open a ticket on bugs.python.org You're mostly right. http://hg.python.org/cpython/file/default/Python/ceval.c#l2684 2684 int posdefaults = oparg & 0xff; 2685 int kwdefaults = (oparg>>8) & 0xff; 2686 int num_annotations = (oparg >> 16) & 0x7fff; -eric > > [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Tue Sep 20 21:07:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 21 Sep 2011 11:07:15 +1000 Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> Message-ID: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Ethan Furman wrote: > Peter Pearson wrote: >> On Mon, 19 Sep 2011 05:48:07 -0700, Ethan Furman >> wrote: >> [snip] >>> Also, if the right-hand operand is a subclass of the left-hand operand >>> then Python will try right-hand_operand.__radd__ first. >> >> I don't think it works that way for me: >> >> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >>>>> class C1(): >> ... def __add__(self, other): >> ... print "C1.__add__()" >> ... >>>>> class C2(C1): >> ... def __radd__(self, other): >> ... print "C2.__radd__()" >> ... >>>>> C1() + C2() >> C1.__add__() > > Oh, it has to be a new-style class. Sorry. Even so, I still don't think it quite works the way you have suggested. class C1(object): def __add__(self, other): return "__add__(%s, %s)" % (self, other) def __radd__(self, other): return "__radd__(%s, %s)" % (self, other) class C2(C1): pass >>> C1() + C2() '__add__(<__main__.C1 object at 0xb7f79b0c>, <__main__.C2 object at 0xb7f79b6c>)' I've tried that in both Python 2.6 and 3.2 and get the same result. However, consider this slight variation: class D1(object): def __add__(self, other): return "__add__(%s, %s)" % (self, other) class D2(D1): def __radd__(self, other): return "__radd__(%s, %s)" % (self, other) >>> D1() + D2() '__radd__(<__main__.D2 object at 0xb7c2c36c>, <__main__.D1 object at 0xb7c2cb0c>)' After playing around with various combinations of C1, C2, D1 and D2, it seems to me that the rule is: If the right-hand argument is a subclass of the left-hand argument, AND also defines __radd__ directly rather than inheriting it, then its __radd__ method is called before the left-hand argument's __add__ method. which strikes me as a strangely specific and not very useful rule. I suspect it might be an accident of implementation rather than a deliberate feature. -- Steven From rosuav at gmail.com Tue Sep 20 21:31:57 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 21 Sep 2011 11:31:57 +1000 Subject: Operator commutativity In-Reply-To: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 21, 2011 at 11:07 AM, Steven D'Aprano wrote: > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. It makes sense, but in a weird way. (Maybe I understand it because I'm half Dutch? heh) It means that a subclass can override addition for itself - presumably, it'll define __add__ and __radd__ both - and that the only time you'd get a false positive (where a function thinks it can handle the addition but actually there's a better one) is when it's a subclass. So this is probably correct behaviour, but it's a fairly weird and esoteric rule. ChrisA From tjreedy at udel.edu Tue Sep 20 23:09:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 Sep 2011 23:09:30 -0400 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On 9/20/2011 5:56 PM, Eric Snow wrote: > On Tue, Sep 20, 2011 at 1:59 PM, Arnaud Delobelle wrote: >> Since Python 3.0 we have keyword only arguments in functions (see PEP >> 3102). Looking at the documentation for the dis module (where opcodes >> are documented), I see the following for MAKE_FUNCTION [1] >> >> """ >> MAKE_FUNCTION(argc) >> Pushes a new function object on the stack. TOS is the code associated >> with the function. The function object is defined to have argc default >> parameters, which are found below TOS. >> """ >> >> No mention of default values for keyword only arguments. Now let's >> try (Python 3.2): >> >>>>> def foo(): >> ... def bar(x, y, *args, z=1, t=2, **kwargs): pass >> ... >>>>> dis.dis(foo) >> 2 0 LOAD_CONST 1 ('z') >> 3 LOAD_CONST 2 (1) >> 6 LOAD_CONST 3 ('t') >> 9 LOAD_CONST 4 (2) >> 12 LOAD_CONST 5 (> 0x1005ec8b0, file "", line 2>) >> 15 MAKE_FUNCTION 512 >> 18 STORE_FAST 0 (bar) >> 21 LOAD_CONST 0 (None) >> 24 RETURN_VALUE >> >> MAKE_FUNCTION has an argc of 512. So it seems that since Python 3.0: >> >> * the number of default values for normal arguments is argc& 0xFF >> * the number of default values for keyword only arguments is argc>> 8 >> >> Can anyone confirm this? I can then open a ticket on bugs.python.org > > You're mostly right. > > http://hg.python.org/cpython/file/default/Python/ceval.c#l2684 > > 2684 int posdefaults = oparg& 0xff; > 2685 int kwdefaults = (oparg>>8)& 0xff; > 2686 int num_annotations = (oparg>> 16)& 0x7fff; >> [1] http://docs.python.org/dev/library/dis.html#opcode-MAKE_FUNCTION I agree that doc should be updated for 3.x. Please suggest a new working if you can, as well as copying the source snippet above. Add me terry.reedy as nosy. -- Terry Jan Reedy From martin at v.loewis.de Wed Sep 21 01:41:50 2011 From: martin at v.loewis.de (Martin v. Loewis) Date: Wed, 21 Sep 2011 07:41:50 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: References: Message-ID: <4E79791E.7000903@v.loewis.de> > Is it just that nobody's implemented it, or is there a good reason for > avoiding offering this sort of thing? I've been considering to implement killing threads several times for the last 15 years (I think about it once every year), and every time I give up because it's too complex and just not implementable. To start with, a simple flag in the thread won't do any good. It will not cancel blocking system calls, so people will complain that the threads they meant to cancel continue to run forever. Instead, you have to use some facility to interrupt blocking system calls. You then have to convince callers of those blocking system calls not to retry when they see that the first attempt to call it was interrupted. And so on. Regards, Martin From vraichur at cisco.com Wed Sep 21 02:42:21 2011 From: vraichur at cisco.com (Vinay) Date: Wed, 21 Sep 2011 12:12:21 +0530 Subject: Tunneling using paramiko to establish tunnel with lab-router Message-ID: <000001cc7829$9d79f6f0$d86de4d0$@com> Hello Friends, I am looking to implement tunneling in python and using "Paramiko" for this.. Sending theTunneling script using Paramiko -Python. It's facing some prob, hangs on running the script..output message it says ".. Missing Handlers". Plz let me know the corrections to be done in this script to making tunneling successful (I hv hard-coded the jump server IP address 10.64.116.34 and password - "Cisco123" in the script to test it once). It's urgent, plz giv me solution ASAP!! Thanks n regards, Vinay -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: create_tunnel.py URL: From k.sahithi2862 at gmail.com Wed Sep 21 05:00:38 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Wed, 21 Sep 2011 02:00:38 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: <41a22645-676f-4f95-852f-a6986d5efea1@h9g2000yqi.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From Antoon.Pardon at rece.vub.ac.be Wed Sep 21 05:25:02 2011 From: Antoon.Pardon at rece.vub.ac.be (Antoon Pardon) Date: Wed, 21 Sep 2011 11:25:02 +0200 Subject: Killing threads (was Re: Cancel or timeout a long running regular expression) In-Reply-To: <4E79791E.7000903@v.loewis.de> References: <4E79791E.7000903@v.loewis.de> Message-ID: <20110921092502.GF3410@trout.vub.ac.be> On Wed, Sep 21, 2011 at 07:41:50AM +0200, Martin v. Loewis wrote: > > Is it just that nobody's implemented it, or is there a good reason for > > avoiding offering this sort of thing? > > I've been considering to implement killing threads several times for the > last 15 years (I think about it once every year), and every time > I give up because it's too complex and just not implementable. > > To start with, a simple flag in the thread won't do any good. I don't agree. Now if you had written that it wouldn't solve all problem, I could understand that. But I have been in circumstances where a simple flag in the thread implementation would have been helpfull. > It will > not cancel blocking system calls, so people will complain that the > threads they meant to cancel continue to run forever. Instead, you > have to use some facility to interrupt blocking system calls. You > then have to convince callers of those blocking system calls not to > retry when they see that the first attempt to call it was interrupted. > And so on. But this is no longer an implementation problem but a use problem. If someone gets an IOError for writing on a closed pipe and he cathes the exception and retries the write in a loop, then this a problem of the author of this loop, not of exceptions. So if one thread throws an exception to an other thread for instance to indicate a timeout for the latter and the latter catches that exception and tries again what it was doing in a loop, that is entirely the problem of the author of that loop and not of the abilty of one thread throwing an exception in an other. Unless of course there may be a lot of such problematic loops within the internal python code. -- Antoon Pardon From csf178 at 163.com Wed Sep 21 05:44:52 2011 From: csf178 at 163.com (=?GBK?B?s8zbv7fH?=) Date: Wed, 21 Sep 2011 17:44:52 +0800 (CST) Subject: Where can I find a lexical spec of python? Message-ID: Hi, everyone, I've found there was several tokens used in python's grammar(http://docs.python.org/reference/grammar.html) but I didn't see their definition anywhere. The tokens listed here: NEWLINE ENDMARKER NAME INDENT DEDENT NUMBER STRING I've got some infomations from the source code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but I'm not sure which feature is only for this specified implementaion. (I saw tabstop could be modified with comments using "tab-width:", ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From t at jollybox.de Wed Sep 21 07:41:33 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 13:41:33 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: References: Message-ID: <4E79CD6D.2030206@jollybox.de> On 21/09/11 11:44, ??? wrote: > Hi, everyone, > I've found there was several tokens used in python's > grammar(http://docs.python.org/reference/grammar.html) but I didn't see > their definition anywhere. The tokens listed here: They should be documented in http://docs.python.org/py3k/reference/lexical_analysis.html - though apparently not using these exact terms. > NEWLINE Trivial: U+000A > ENDMARKER End of file. > NAME documented as "identifier" in 2.3 > INDENT > DEDENT Documented in 2.1.8. > NUMBER Documented in 2.4.3 - 2.4.6 > STRING Documented in 2.4.2 > I've got some infomations from the source > code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but > I'm not sure which feature is only for this specified implementaion. (I > saw tabstop could be modified with comments using "tab-width:", > ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) That sounds like a legacy feature that is no longer used. Somebody familiar with the early history of Python might be able to shed more light on the situation. It is inconsisten with the spec (section 2.1.8): """ Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case. """ - Thomas From info at wingware.com Wed Sep 21 10:15:14 2011 From: info at wingware.com (Wingware) Date: Wed, 21 Sep 2011 10:15:14 -0400 Subject: Wing IDE 4.0.4 released Message-ID: <4E79F172.3070106@wingware.com> Hi, Wingware has released version 4.0.4 of Wing IDE, an integrated development environment designed specifically for the Python programming language. Wing IDE is a cross-platform Python IDE that provides a professional code editor with vi, emacs, and other key bindings, auto-completion, call tips, refactoring, a powerful graphical debugger, version control, unit testing, search, and many other features. **Changes in Version 4.0.4** This is a maintenance release with the following changes: * Shell history operates on whole blocks and filters by entered prefix * Auto-editing (must be enabled with Editor > Auto-Editing preferences): * Auto-enter closing quotes, comments, and parentheses, braces, etc * Tab through auto-entered invocation arguments * Apply quote, comment character, or parenthesis to selection * Use dynamic analysis for goto-definition in the editor, when available * Support ## comments and new block syntax in Mako files * Allow scrolling editor one page below the last line * Refactoring can move symbols to a new file * PyLint panel improvements, including support for version 0.23+ * Commands to copy editor and project file names to clipboard * About 70 other minor features and bug fixes included vi mode improvements See the change log for details. **New Features in Version 4.0** Version 4.0 adds the following new major features: * Refactoring -- Rename/move symbols, extract to function/method, and introduce variable * Find Uses -- Find all points of use of a symbol * Diff/Merge -- Graphical file and repository comparison and merge * Django Support -- Debug Django templates, run Django unit tests, and more * matplotlib Support -- Maintains live-updating plots in shell and debugger * Simplified Licensing -- Includes all OSes and adds Support+Upgrades subscriptions Complete change log: http://wingware.com/pub/wingide/4.0.4/CHANGELOG.txt Details on licensing changes: http://wingware.com/news/2011-02-16 **About Wing IDE** Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful editing, testing, and debugging features that help reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE can be used to develop Python code for web, GUI, and embedded scripting applications. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching beginning programming courses with Python. Version 4.0 of Wing IDE Professional includes the following major features: * Professional quality code editor with vi, emacs, and other keyboard personalities * Code intelligence for Python: Auto-completion, call tips, find uses, goto-definition, error indicators, refactoring, smart indent and rewrapping, and source navigation * Advanced multi-threaded debugger with graphical UI, command line interaction, conditional breakpoints, data value tooltips over code, watch tool, and externally launched and remote debugging * Powerful search and replace options including keyboard driven and graphical UIs, multi-file, wild card, and regular expression search and replace * Version control integration for Subversion, CVS, Bazaar, git, Mercurial, and Perforce * Integrated unit testing with unittest, nose, and doctest frameworks * Django support: Debugs Django templates, provides project setup tools, and runs Django unit tests * Many other features including project manager, bookmarks, code snippets, diff/merge tool, OS command integration, indentation manager, PyLint integration, and perspectives * Extremely configurable and may be extended with Python scripts * Extensive product documentation and How-Tos for Django, matplotlib, Plone, wxPython, PyQt, mod_wsgi, Autodesk Maya, and many other frameworks Please refer to http://wingware.com/wingide/features for a detailed listing of features by product level. System requirements are Windows 2000 or later, OS X 10.3.9 or later (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE supports Python versions 2.0.x through 3.2.x and Stackless Python. For more information, see the http://wingware.com/ **Downloads** Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial can be obtained directly from the product when launched. Wing IDE Pro -- Full-featured product: http://wingware.com/downloads/wingide/4.0 Wing IDE Personal -- A simplified IDE: http://wingware.com/downloads/wingide-personal/4.0 Wing IDE 101 -- For teaching with Python: http://wingware.com/downloads/wingide-101/4.0 **Purchasing and Upgrading** Wing 4.0 requires an upgrade for Wing IDE 2.x and 3.x users at a cost of 1/2 the full product pricing. Upgrade a license: https://wingware.com/store/upgrade Purchase a new license: https://wingware.com/store/purchase Optional Support+Upgrades subscriptions are available for expanded support coverage and free upgrades to new major releases: http://wingware.com/support/agreement Thanks! -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From frank.ruiz at gmail.com Wed Sep 21 11:44:13 2011 From: frank.ruiz at gmail.com (Frank Ruiz) Date: Wed, 21 Sep 2011 08:44:13 -0700 Subject: Graphing Message-ID: I am looking to plot some data points related to system metrics. Benchmarking, etc. Can someone give some recommendations on a good way to graph these datapoints in python. I started looking into matplotlib, however was interested in others experiences. From invalid at invalid.invalid Wed Sep 21 12:27:32 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 21 Sep 2011 16:27:32 +0000 (UTC) Subject: Graphing References: Message-ID: On 2011-09-21, Frank Ruiz wrote: > I am looking to plot some data points related to system metrics. > Benchmarking, etc. Can someone give some recommendations on a good > way to graph these datapoints in python. I started looking into > matplotlib, however was interested in others experiences. I've always liked gnuplot-py, but I was a gnuplot user for 10+ years before I started using Python. If you don't already know how to use gnuplot, then perhaps gnuplot-py might not seem as intuitive. http://gnuplot-py.sourceforge.net/ -- Grant Edwards grant.b.edwards Yow! Hmmm ... an arrogant at bouquet with a subtle gmail.com suggestion of POLYVINYL CHLORIDE ... From ppearson at nowhere.invalid Wed Sep 21 12:28:34 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2011 16:28:34 GMT Subject: Graphing References: Message-ID: <9duhliFopmU1@mid.individual.net> On Wed, 21 Sep 2011 08:44:13 -0700, Frank Ruiz wrote: > I am looking to plot some data points related to system metrics. > Benchmarking, etc. Can someone give some recommendations on a good way > to graph these datapoints in python. I started looking into > matplotlib, however was interested in others experiences. I like biggles. Reasonably straightforward, well defaulted. Simple plots require only simple code. biggles.sourceforge.net -- To email me, substitute nowhere->spamcop, invalid->net. From csf178 at 163.com Wed Sep 21 12:33:03 2011 From: csf178 at 163.com (=?utf-8?B?56iL5Yqt6Z2e?=) Date: Thu, 22 Sep 2011 00:33:03 +0800 (CST) Subject: Where can I find a lexical spec of python? In-Reply-To: <4E79CD6D.2030206@jollybox.de> References: <4E79CD6D.2030206@jollybox.de> Message-ID: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Thanks Thomas. I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html but I worried it might leak some language features like "tab magic". For I'm working on a parser with JavaScript I need a more strictly defined spec. Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html (Also the lexer http://shaofei.name/python/PyLexer.html) As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? Please help me. Thanks a lot. ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >On 21/09/11 11:44, ??? wrote: >> Hi, everyone, >> I've found there was several tokens used in python's >> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >> their definition anywhere. The tokens listed here: > >They should be documented in >http://docs.python.org/py3k/reference/lexical_analysis.html - though >apparently not using these exact terms. > >> NEWLINE >Trivial: U+000A > >> ENDMARKER >End of file. > >> NAME >documented as "identifier" in 2.3 > >> INDENT >> DEDENT >Documented in 2.1.8. > >> NUMBER >Documented in 2.4.3 - 2.4.6 > >> STRING >Documented in 2.4.2 > >> I've got some infomations from the source >> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >> I'm not sure which feature is only for this specified implementaion. (I >> saw tabstop could be modified with comments using "tab-width:", >> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) > >That sounds like a legacy feature that is no longer used. Somebody >familiar with the early history of Python might be able to shed more >light on the situation. It is inconsisten with the spec (section 2.1.8): > >""" >Indentation is rejected as inconsistent if a source file mixes tabs and >spaces in a way that makes the meaning dependent on the worth of a tab >in spaces; a TabError is raised in that case. >""" > >- Thomas >-- >http://mail.python.org/mailman/listinfo/python-list From clp2 at rebertia.com Wed Sep 21 12:53:57 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 09:53:57 -0700 Subject: Where can I find a lexical spec of python? In-Reply-To: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> References: <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: On Wed, Sep 21, 2011 at 9:33 AM, ??? wrote: > Thanks Thomas. > I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html > > but I worried it might leak some language features like "tab magic". > > For I'm working on a parser with JavaScript I need a more strictly defined spec. > > Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html > (Also the lexer ?http://shaofei.name/python/PyLexer.html) > > As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. > > Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? Closest thing would be http://docs.python.org/py3k/reference/grammar.html Cheers, Chris From t at jollybox.de Wed Sep 21 12:55:45 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 18:55:45 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> References: <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: <4E7A1711.8000007@jollybox.de> On 21/09/11 18:33, ??? wrote: > Thanks Thomas. > I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html > > but I worried it might leak some language features like "tab magic". > > For I'm working on a parser with JavaScript I need a more strictly defined spec. > > Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html > (Also the lexer http://shaofei.name/python/PyLexer.html) > > As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. > > Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? I believe the language documentation on docs.python.org is all the documentation of the language there is. It may not be completely formal, and in parts it concentrates not on the actual rules but on the original implementation, but, as far as I can tell, it tells you everything you need to know to write a new parser for the Python language, without any ambiguity. You appear to be anxious about implementing the indentation mechanism correctly. The language documentation describes a behaviour precisely. What is the problem? Thomas > > Please help me. Thanks a lot. > ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >> On 21/09/11 11:44, ??? wrote: >>> Hi, everyone, >>> I've found there was several tokens used in python's >>> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >>> their definition anywhere. The tokens listed here: >> >> They should be documented in >> http://docs.python.org/py3k/reference/lexical_analysis.html - though >> apparently not using these exact terms. >> >>> NEWLINE >> Trivial: U+000A >> >>> ENDMARKER >> End of file. >> >>> NAME >> documented as "identifier" in 2.3 >> >>> INDENT >>> DEDENT >> Documented in 2.1.8. >> >>> NUMBER >> Documented in 2.4.3 - 2.4.6 >> >>> STRING >> Documented in 2.4.2 >> >>> I've got some infomations from the source >>> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >>> I'm not sure which feature is only for this specified implementaion. (I >>> saw tabstop could be modified with comments using "tab-width:", >>> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) >> >> That sounds like a legacy feature that is no longer used. Somebody >> familiar with the early history of Python might be able to shed more >> light on the situation. It is inconsisten with the spec (section 2.1.8): >> >> """ >> Indentation is rejected as inconsistent if a source file mixes tabs and >> spaces in a way that makes the meaning dependent on the worth of a tab >> in spaces; a TabError is raised in that case. >> """ >> >> - Thomas >> -- >> http://mail.python.org/mailman/listinfo/python-list > From dickinsm at gmail.com Wed Sep 21 13:03:15 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 21 Sep 2011 10:03:15 -0700 (PDT) Subject: Operator commutativity References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> On Sep 21, 2:07?am, Steven D'Aprano wrote: > After playing around with various combinations of C1, C2, D1 and D2, it > seems to me that the rule is: > > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. I'm 99.9% sure it's deliberate rather than an accident of implementation. See the note in the docs at: http://docs.python.org/reference/datamodel.html#emulating-numeric-types Support that you're subclassing int, (class MyInt(int): ...) and you want to intercept additions of the form 3 + MyInt(4) (perhaps because you want MyInt to be 'contagious', so that an arithmetic operation that combines an int and a MyInt returns a MyInt). How would you achieve this without this rule? -- Mark From csf178 at 163.com Wed Sep 21 14:01:14 2011 From: csf178 at 163.com (Shaofei Cheng) Date: Thu, 22 Sep 2011 02:01:14 +0800 (CST) Subject: Where can I find a lexical spec of python? In-Reply-To: <4E7A1711.8000007@jollybox.de> References: <4E7A1711.8000007@jollybox.de> <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> Message-ID: <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> Yes, I'm using this document now but I was wondering if there is a formal spec for lexical grammar? It looks like some part of the doc "http://docs.python.org/py3k/reference/grammar.html" is missing. We can find some replacement in lexical_analysis.html but it seems this document is write for a python user instead of a guy trying to implement python. ? 2011-09-22 00:55:45?"Thomas Jollans" ??? >On 21/09/11 18:33, ??? wrote: >> Thanks Thomas. >> I've read the document http://docs.python.org/py3k/reference/lexical_analysis.html >> >> but I worried it might leak some language features like "tab magic". >> >> For I'm working on a parser with JavaScript I need a more strictly defined spec. >> >> Currently I have a highlighter here ->http://shaofei.name/python/PyHighlighter.html >> (Also the lexer http://shaofei.name/python/PyLexer.html) >> >> As you can see, I just make its behavior align with CPython, but I'm not sure what the real python lexical grammar is like. >> >> Does anyone know if there is a lexical grammar spec like other languages(e.g. http://bclary.com/2004/11/07/#annex-a)? > >I believe the language documentation on docs.python.org is all the >documentation of the language there is. It may not be completely formal, >and in parts it concentrates not on the actual rules but on the original >implementation, but, as far as I can tell, it tells you everything you >need to know to write a new parser for the Python language, without any >ambiguity. > >You appear to be anxious about implementing the indentation mechanism >correctly. The language documentation describes a behaviour precisely. >What is the problem? > >Thomas > >> >> Please help me. Thanks a lot. >> ? 2011-09-21 19:41:33?"Thomas Jollans" ??? >>> On 21/09/11 11:44, ??? wrote: >>>> Hi, everyone, >>>> I've found there was several tokens used in python's >>>> grammar(http://docs.python.org/reference/grammar.html) but I didn't see >>>> their definition anywhere. The tokens listed here: >>> >>> They should be documented in >>> http://docs.python.org/py3k/reference/lexical_analysis.html - though >>> apparently not using these exact terms. >>> >>>> NEWLINE >>> Trivial: U+000A >>> >>>> ENDMARKER >>> End of file. >>> >>>> NAME >>> documented as "identifier" in 2.3 >>> >>>> INDENT >>>> DEDENT >>> Documented in 2.1.8. >>> >>>> NUMBER >>> Documented in 2.4.3 - 2.4.6 >>> >>>> STRING >>> Documented in 2.4.2 >>> >>>> I've got some infomations from the source >>>> code(http://svn.python.org/projects/python/trunk/Parser/tokenizer.c) but >>>> I'm not sure which feature is only for this specified implementaion. (I >>>> saw tabstop could be modified with comments using "tab-width:", >>>> ":tabstop=", ":ts=" or "set tabsize=", is this feature really in spec?) >>> >>> That sounds like a legacy feature that is no longer used. Somebody >>> familiar with the early history of Python might be able to shed more >>> light on the situation. It is inconsisten with the spec (section 2.1.8): >>> >>> """ >>> Indentation is rejected as inconsistent if a source file mixes tabs and >>> spaces in a way that makes the meaning dependent on the worth of a tab >>> in spaces; a TabError is raised in that case. >>> """ >>> >>> - Thomas >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> > From ethan at stoneleaf.us Wed Sep 21 14:15:56 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 21 Sep 2011 11:15:56 -0700 Subject: Operator commutativity In-Reply-To: <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> <2f4e4d92-a1c9-4aaa-affa-d21e41f82774@w28g2000yqw.googlegroups.com> Message-ID: <4E7A29DC.2060205@stoneleaf.us> Mark Dickinson wrote: > On Sep 21, 2:07 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> After playing around with various combinations of C1, C2, D1 and D2, it >> seems to me that the rule is: >> >> If the right-hand argument is a subclass of the left-hand argument, AND also >> defines __radd__ directly rather than inheriting it, then its __radd__ >> method is called before the left-hand argument's __add__ method. >> >> which strikes me as a strangely specific and not very useful rule. I suspect >> it might be an accident of implementation rather than a deliberate feature. > > I'm 99.9% sure it's deliberate rather than an accident of > implementation. See the note in the docs at: > > http://docs.python.org/reference/datamodel.html#emulating-numeric-types > > Support that you're subclassing int, (class MyInt(int): ...) and you > want to intercept additions of the form 3 + MyInt(4) (perhaps because > you want MyInt to be 'contagious', so that an arithmetic operation > that combines an int and a MyInt returns a MyInt). How would you > achieve this without this rule? I think Steven's objection was in not calling subclass.__radd__ when __radd__ is inherited rather than directly overridden. Interestingly enough, the following works as expected (at least, as I expected ;)... class C1(object): def __add__(self, other): print "C1.__add__(%r, %r)" % (self, other) class C2(C1): def __radd__(self, other): print "C2.__radd__(%r, %r)" % (self, other) class C3(C2): pass C1() + C2() # --> C2.__radd__(<...C2...>, <...C1...) C1() + C3() # --> C2.__radd__(<...C3...>, <...C1...>) C2() + C3() # --> C1.__add__(<...C2...>, <...C3...>) ~Ethan~ From t at jollybox.de Wed Sep 21 14:22:27 2011 From: t at jollybox.de (Thomas Jollans) Date: Wed, 21 Sep 2011 20:22:27 +0200 Subject: Where can I find a lexical spec of python? In-Reply-To: <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> References: <4E7A1711.8000007@jollybox.de> <4E79CD6D.2030206@jollybox.de> <4521e081.ded3.1328cd55581.Coremail.csf178@163.com> <33db1987.e15d.1328d260e2f.Coremail.csf178@163.com> Message-ID: <4E7A2B63.4030505@jollybox.de> On 21/09/11 20:01, Shaofei Cheng wrote: > Yes, I'm using this document now but I was wondering if there is a formal spec for lexical grammar? It looks like some part of the doc "http://docs.python.org/py3k/reference/grammar.html" is missing. > We can find some replacement in lexical_analysis.html but it seems this document is write for a python user instead of a guy trying to implement python. Yes, I understood alright what you were asking. As I said, I don't believe there is any more formal documentation of the Python language than what you have already seen. However, I am of the opinion that it gives you all the information you need, and that a complete formal grammar, while perhaps, for you, easier to interpret, would not add any information. Thomas From ethan at stoneleaf.us Wed Sep 21 15:11:12 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 21 Sep 2011 12:11:12 -0700 Subject: Operator commutativity In-Reply-To: <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> References: <87hb48ixmj.fsf@no-fixed-abode.cable.virginmedia.net> <9drvinFngaU1@mid.individual.net> <4e7938c4$0$29969$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7A36D0.6030603@stoneleaf.us> Steven D'Aprano wrote: > After playing around with various combinations of C1, C2, D1 and D2, it > seems to me that the rule is: > > If the right-hand argument is a subclass of the left-hand argument, AND also > defines __radd__ directly rather than inheriting it, then its __radd__ > method is called before the left-hand argument's __add__ method. > > > which strikes me as a strangely specific and not very useful rule. I suspect > it might be an accident of implementation rather than a deliberate feature. Update to rule: If the right-hand argument is a subclass of the left-hand argument AND a __radd__ is defined anywhere between the left-hand argument's class up to and including the right-hand argument's class, then __radd__ is called, otherwise the left-hand arguments __add__ is called. And it makes perfect sense -- a + b is, after all, an __add__ function; the only reason to call __radd__ instead is if it has been defined for a subclass, and the only reason to define it is because it needs something different from a + b that a doesn't know about. Probably not a clear explanation -- maybe somebody else can dress it up a bit. ~Ethan~ From arnodel at gmail.com Wed Sep 21 18:04:18 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 21 Sep 2011 23:04:18 +0100 Subject: About MAKE_FUNCTION opcode in Python 3 In-Reply-To: References: Message-ID: On 21 September 2011 04:09, Terry Reedy wrote: > I agree that doc should be updated for 3.x. Please suggest a new working if > you can, as well as copying the source snippet above. Add me terry.reedy as > nosy. Done: http://bugs.python.org/issue13026 -- Arnaud From missive at hotmail.com Wed Sep 21 21:35:44 2011 From: missive at hotmail.com (Lee Harr) Date: Thu, 22 Sep 2011 06:05:44 +0430 Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) Message-ID: Pynguin is a python-based turtle graphics application. ??? It combines an editor, interactive interpreter, and ??? graphics display area. It is meant to be an easy environment for introducing ??? some programming concepts to beginning programmers. http://pynguin.googlecode.com/ This release fixes problems which prevented the program ??? from working properly on Windows systems. Pynguin is tested with Python 2.7.1 and PyQt 4.8.3 and ??? will use Pygments syntax highlighting if available. Pynguin is released under GPLv3. Changes in pynguin-0.12: ??? Important fixes ??????? - Fixed menu items and dialogs not working on Windows ??????? - Fixed error on Windows when trying to write backup files ??? Pynguin API ??????? - bgcolor() ??????? - raise exception if using color component outside of 0-255 ??????? - make util.nudge_color() API match util.choose_color() ??? Canvas ??????? - allow setting background color ??????? - fix custom svg avatars to allow any size avatar ??? Integrated Editor ??????? - comment / uncomment line / region ??? Integrated Console ??????? - added command to clear history ??????? - clears line before writing commands selected in menu ??? Examples ??????? - added fractals example file From bahamutzero8825 at gmail.com Wed Sep 21 21:53:04 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 20:53:04 -0500 Subject: Odd behavior with imp.reload and logging Message-ID: <4E7A9500.2070101@gmail.com> When using a logger in a module and then using imp.reload to reload the module, logger messages are repeated in direct proportion to the number of times the modules was loaded. That is, on the first import, the message is written once, but on the second run, each message is written twice, three times on the third run, and so on. With this code: > import logging > > test_logger = logging.getLogger(__name__) > console_handler = logging.StreamHandler() > console_formatter = logging.Formatter('{asctime} - {module} - {funcName} - line {lineno} - {levelname} - {message}', style='{') > console_handler.setFormatter(console_formatter) > test_logger.addHandler(console_handler) > test_logger.setLevel(logging.DEBUG) > > test_logger.info('Test info') I get this in the interpreter: > Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os, imp >>>> import test2 > 2011-09-21 20:51:02,421 - test2 - - line 11 - INFO - Test info >>>> imp.reload(test2) > 2011-09-21 20:51:10,665 - test2 - - line 11 - INFO - Test info > 2011-09-21 20:51:10,665 - test2 - - line 11 - INFO - Test info > What causes this, and how can I fix it (or at least work around it)? Due to the nature of the program, it's much more convenient to reload a module than to restart the entire program (especially when testing). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 PGP/GPG Public Key ID: 0xF88E034060A78FCB From rosuav at gmail.com Wed Sep 21 21:57:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 11:57:42 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7A9500.2070101@gmail.com> References: <4E7A9500.2070101@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 11:53 AM, Andrew Berg wrote: > What causes this, and how can I fix it (or at least work around it)? Due > to the nature of the program, it's much more convenient to reload a > module than to restart the entire program (especially when testing). > Unfortunately, Python doesn't really like modules to be reloaded. Are you able to explicitly close the logger before reloading? ChrisA From bahamutzero8825 at gmail.com Wed Sep 21 22:44:20 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 21:44:20 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4E7A9500.2070101@gmail.com> Message-ID: <4E7AA104.7050009@gmail.com> On 2011.09.21 08:57 PM, Chris Angelico wrote: > Unfortunately, Python doesn't really like modules to be reloaded. Are > you able to explicitly close the logger before reloading? The reload isn't controlled by the module, but I have no problem clearing out any loggers at the beginning. I'm looking through the logging docs, but I don't see what you mean by explicitly closing the logger. Handler.close() doesn't help. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From rosuav at gmail.com Wed Sep 21 22:48:04 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 12:48:04 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7AA104.7050009@gmail.com> References: <4E7A9500.2070101@gmail.com> <4E7AA104.7050009@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 12:44 PM, Andrew Berg wrote: > The reload isn't controlled by the module, but I have no problem > clearing out any loggers at the beginning. I'm thinking more along the lines of closing them in the old module before firing imp.reload() - maybe have a function in the module that cleans itself up and then reloads itself. And yes, I had been thinking of closing the handler, but I don't know the logging module much. ChrisA From atherun at gmail.com Wed Sep 21 23:09:05 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 20:09:05 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate Message-ID: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> This is on windows with python 2.6. I can't seem to remove a possibility of a deadlock in one of my scripts at the moment. Its not a constant deadlock but it appears from time to time. The code is below: try: process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) NotDone = True data = [] while NotDone: NotDone = False result = process.poll() if result == None: NotDone = True if NotDone: out, err = process.communicate() Log(out) I was able to get the program to write out the stack trace for my threads and it is usually deadlocked on sys.stdout.read or _internal_poll of subproceess. I've even tried the above, with using "with tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but it still deadlocks. In the past I work around this by running fewer processes asynchronously but I would really like to get this solved so I don't have to wait to see if it'll be caused with any changes I make. Any tips would be appreciated. From roy at panix.com Wed Sep 21 23:32:19 2011 From: roy at panix.com (Roy Smith) Date: Wed, 21 Sep 2011 23:32:19 -0400 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: In article <098f3d78-85f5-44e7-ba72-f2270a24d1b0 at o9g2000vbo.googlegroups.com>, Atherun wrote: > This is on windows with python 2.6. > I can't seem to remove a possibility of a deadlock in one of my > scripts at the moment. Its not a constant deadlock but it appears > from time to time. The code is below: > > try: > > process = > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > NotDone = True > data = [] > while NotDone: > NotDone = False > > result = process.poll() > if result == None: > NotDone = True > if NotDone: > out, err = process.communicate() > Log(out) > > I was able to get the program to write out the stack trace for my > threads and it is usually deadlocked on sys.stdout.read or > _internal_poll of subproceess. > > I've even tried the above, with using "with > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > it still deadlocks. In the past I work around this by running fewer > processes asynchronously but I would really like to get this solved so > I don't have to wait to see if it'll be caused with any changes I > make. > > Any tips would be appreciated. My reading of the docs (http://docs.python.org/release/2.6.7/library/subprocess.html#popen-objec ts) says that Popen.poll() doesn't return a value, it sets the object's return code attribute, which you can then interrogate. More than that, your loop logic looks amazingly complicated for what's basically a simple thing. I suggest something along the lines of: # assuming process.returncode is initially None while process.returncode is None: out, err = process.communicate() Log(out) I haven't tested that, but I think (from reading the docs) that's the right idea. From clp2 at rebertia.com Wed Sep 21 23:33:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 20:33:37 -0700 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: On Wed, Sep 21, 2011 at 8:09 PM, Atherun wrote: > This is on windows with python 2.6. > I can't seem to remove a possibility of a ?deadlock in one of my > scripts at the moment. ?Its not a constant deadlock but it appears > from time to time. ?The code is below: > > try: > > ? ? ? ?process = > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > ? ? ? ?NotDone = True > ? ? ? ?data = [] > ? ? ? ?while NotDone: > ? ? ? ? ? ?NotDone = False > > ? ? ? ? ? ?result = process.poll() > ? ? ? ? ? ?if result == None: > ? ? ? ? ? ? ? ?NotDone = True > ? ? ? ? ? ?if NotDone: > ? ? ? ? ? ? ? ?out, err = process.communicate() > ? ? ? ? ? ? ? ?Log(out) > > I was able to get the program to write out the stack trace for my > threads and it is usually deadlocked on sys.stdout.read or > _internal_poll of subproceess. > > I've even tried the above, with using "with > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > it still deadlocks. ?In the past I work around this by running fewer > processes asynchronously but I would really like to get this solved so > I don't have to wait to see if it'll be caused with any changes I > make. > > Any tips would be appreciated. Your polling loop is completely pointless. The code can be simplified to: process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) out, err = process.communicate() log(out) Depending on the particular program you're running in a subprocess, you may need to take heed of the Note in the communicate() docs: "Note: The data read is buffered in memory, so *do not use this method* if the data size is large or unlimited." [Emphasis added] Cheers, Chris -- http://rebertia.com From atherun at gmail.com Wed Sep 21 23:42:53 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 20:42:53 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> On Sep 21, 8:33?pm, Chris Rebert wrote: > On Wed, Sep 21, 2011 at 8:09 PM, Atherun wrote: > > This is on windows with python 2.6. > > I can't seem to remove a possibility of a ?deadlock in one of my > > scripts at the moment. ?Its not a constant deadlock but it appears > > from time to time. ?The code is below: > > > try: > > > ? ? ? ?process = > > subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > > > ? ? ? ?NotDone = True > > ? ? ? ?data = [] > > ? ? ? ?while NotDone: > > ? ? ? ? ? ?NotDone = False > > > ? ? ? ? ? ?result = process.poll() > > ? ? ? ? ? ?if result == None: > > ? ? ? ? ? ? ? ?NotDone = True > > ? ? ? ? ? ?if NotDone: > > ? ? ? ? ? ? ? ?out, err = process.communicate() > > ? ? ? ? ? ? ? ?Log(out) > > > I was able to get the program to write out the stack trace for my > > threads and it is usually deadlocked on sys.stdout.read or > > _internal_poll of subproceess. > > > I've even tried the above, with using "with > > tempfile.NamedTemporaryFiles() as buff:" and writing to the file, but > > it still deadlocks. ?In the past I work around this by running fewer > > processes asynchronously but I would really like to get this solved so > > I don't have to wait to see if it'll be caused with any changes I > > make. > > > Any tips would be appreciated. > > Your polling loop is completely pointless. The code can be simplified to: > > process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) > out, err = process.communicate() > log(out) > > Depending on the particular program you're running in a subprocess, > you may need to take heed of the Note in the communicate() docs: > "Note: The data read is buffered in memory, so *do not use this > method* if the data size is large or unlimited." [Emphasis added] > > Cheers, > Chris > --http://rebertia.com I'm pretty sure thats the problem, this is a generic catch all function for running subprocesses. It can be anything to a simple command to a complex command with a ton of output. I'm looking for a better solution to handle the case of running subprocesses that have an undetermined amount of output. (i.e. p4 edit's or tools that have an excessive amount of logging) I'll definitely simplify the loop, thanks for the tip on that part. From clp2 at rebertia.com Wed Sep 21 23:52:02 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 21 Sep 2011 20:52:02 -0700 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: On Wed, Sep 21, 2011 at 8:32 PM, Roy Smith wrote: > My reading of the docs > (http://docs.python.org/release/2.6.7/library/subprocess.html#popen-objec > ts) says that Popen.poll() doesn't return a value, it sets the object's > return code attribute, which you can then interrogate. Popen.poll(): Check if child process has terminated. Set **and return** returncode attribute. [Direct quote from the docs; emphasis added] > More than that, your loop logic looks amazingly complicated for what's > basically a simple thing. ?I suggest something along the lines of: > > ? # assuming process.returncode is initially None > ? while process.returncode is None: > ? ? ?out, err = process.communicate() > ? ? ?Log(out) > > I haven't tested that, but I think (from reading the docs) that's the > right idea. There is no point in communicate()-ing multiple times; communicate() reads until EOF and only returns after subprocess termination! Cheers, Chris From roy at panix.com Wed Sep 21 23:58:19 2011 From: roy at panix.com (Roy Smith) Date: Wed, 21 Sep 2011 23:58:19 -0400 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: In article , Chris Rebert wrote: > Popen.poll(): > Check if child process has terminated. Set **and return** > returncode attribute. > [Direct quote from the docs; emphasis added] Doh. I read right past that and didn't see it. Thanks for the correction. From steve+comp.lang.python at pearwood.info Thu Sep 22 00:22:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 04:22:39 GMT Subject: Odd behavior with imp.reload and logging References: Message-ID: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> On Wed, 21 Sep 2011 20:53:04 -0500, Andrew Berg wrote: > When using a logger in a module and then using imp.reload to reload the > module, logger messages are repeated in direct proportion to the number > of times the modules was loaded. That is, on the first import, the > message is written once, but on the second run, each message is written > twice, three times on the third run, and so on. [...] > What causes this, and how can I fix it (or at least work around it)? Due > to the nature of the program, it's much more convenient to reload a > module than to restart the entire program (especially when testing). You unconditionally add a handler every time you reload the module, regardless of whether or not the old handler is still there. You could try something like this (untested): import logging test_logger = logging.getLogger(__name__) if not test_logger.handlers: console_handler = logging.StreamHandler() console_formatter = logging.Formatter( '{asctime} - {module} - {funcName} - line {lineno} - ' '{levelname} - {message}', style='{' ) console_handler.setFormatter(console_formatter) test_logger.addHandler(console_handler) test_logger.setLevel(logging.DEBUG) test_logger.info('Test info') -- Steven From bahamutzero8825 at gmail.com Thu Sep 22 00:47:55 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Wed, 21 Sep 2011 23:47:55 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7ABDFB.5020509@gmail.com> On 2011.09.21 11:22 PM, Steven D'Aprano wrote: > You could > try something like this (untested): That works. Thanks! This makes me wonder what else stays around after a reload and what side effects there are, though. I would really like to purge everything from the previous import. The main program has no dependence on the module whatsoever. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From atherun at gmail.com Thu Sep 22 00:52:42 2011 From: atherun at gmail.com (Atherun) Date: Wed, 21 Sep 2011 21:52:42 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> Message-ID: <56b9526d-fdd5-4f9d-bd39-d17b84f12141@h7g2000yqm.googlegroups.com> On Sep 21, 8:58?pm, Roy Smith wrote: > In article , > ?Chris Rebert wrote: > > > Popen.poll(): > > ? ? Check if child process has terminated. Set **and return** > > returncode attribute. > > [Direct quote from the docs; emphasis added] > > Doh. ?I read right past that and didn't see it. ?Thanks for the > correction. I removed the loop and changed it to a single communicate now, still get a deadlock. All threads just stop, even threads that have nothing to do with the ongoing subprocesses. I specifically created a thread that dumps the stack trace of all threads so I can try and view the deadlocks, but that stops responding at the same time as the deadlock. This wasn't happening before so not sure why it changed suddenly. From rosuav at gmail.com Thu Sep 22 01:09:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 15:09:49 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7ABDFB.5020509@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 2:47 PM, Andrew Berg wrote: > This makes me wonder what else stays around after a reload and what side > effects there are, though. I would really like to purge everything from > the previous import. The main program has no dependence on the module > whatsoever. > On-the-fly reloading of modules isn't really one of Python's strengths. Everyone who asks about it seems to be doing rapid development/debugging and wanting to save on startup time (as opposed to, say, running a server and updating code in it while it's active and serving clients), so the question becomes: Which is more of a problem, startup delay or the risk that it's not the same as a clean start? Python doesn't guarantee that your debugging session is going to be useful - if you reload that module and weird things happen, it could be because of reload(), not because of a module bug. Ranting Rick will probably expect me to mention Pike here, but I won't. Muahahahaha..... oh. I just did. Oh well! ChrisA From yves at zioup.com Thu Sep 22 01:24:03 2011 From: yves at zioup.com (yves at zioup.com) Date: Wed, 21 Sep 2011 23:24:03 -0600 Subject: with statements does not delete the object Message-ID: Is this the expected behaviour: with mylib.token() as t: do_something dir() In the last dir(), after the with "loop" is finished, t still shows up... I expected it to be unreferenced by then. -- Yves. http://www.SollerS.ca/ http://ipv6.SollerS.ca http://blog.zioup.org/ From bahamutzero8825 at gmail.com Thu Sep 22 01:54:10 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 00:54:10 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> Message-ID: <4E7ACD82.4080302@gmail.com> On 2011.09.22 12:09 AM, Chris Angelico wrote: > On-the-fly reloading of modules isn't really one of Python's > strengths. Everyone who asks about it seems to be doing rapid > development/debugging and wanting to save on startup time (as opposed > to, say, running a server and updating code in it while it's active > and serving clients), so the question becomes: Which is more of a > problem, startup delay or the risk that it's not the same as a clean > start? Python doesn't guarantee that your debugging session is going > to be useful - if you reload that module and weird things happen, it > could be because of reload(), not because of a module bug. The main program is an IRC bot, which could potentially be in use by many people in several channels on a network. As it is, the bot can only connect to one server, but it could probably be set up to connect to any number of networks. Making a number of quick fixes or changes to one module could be very irritating to users if the bot has to terminate each time, especially if those users don't know or care about that specific module. Startup time is an issue because it must connect to a network before it can take any input. Also, many disconnects/reconnects could easily cause problems (like the network refusing the connection as a DoS prevention measure). I'm not tied to any particular solution, and it's quite possible I'm missing something since I am still a beginner. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From ben+python at benfinney.id.au Thu Sep 22 02:01:05 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 16:01:05 +1000 Subject: with statements does not delete the object References: Message-ID: <871uv92k0u.fsf@benfinney.id.au> yves at zioup.com writes: > Is this the expected behaviour: You can learn the expected behaviour for ?with? in the documentation . > with mylib.token() as t: > do_something > > dir() > > In the last dir(), after the with "loop" is finished, t still shows up... I > expected it to be unreferenced by then. What gives you that expectation, when it's not the case for any of ?if?, ?for?, ?while?, ?try?, and so on? The set of statements which introduce a new scope is small, and ?with? is not one of them. -- \ ?No smoothen the lion.? ?lion cage, zoo, Czech Republic | `\ | _o__) | Ben Finney From steve+comp.lang.python at pearwood.info Thu Sep 22 02:12:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 06:12:01 GMT Subject: Environment variables not visible from Python Message-ID: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> I don't understand why some environment variables are not visible from Python. [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM 30 140 xterm [steve at wow-wow ~]$ python2.6 Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) (None, None, 'xterm') -- Steven From airween at gmail.com Thu Sep 22 02:37:22 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Thu, 22 Sep 2011 08:37:22 +0200 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110922063721.GA3655@arxnet.hu> hello, On Thu, Sep 22, 2011 at 06:12:01AM +0000, Steven D'Aprano wrote: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import os > >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') I think TERM is inherited from parent shell, but LINES and COLUMNS are re-created every child shell. IMHO it's normally, cause TERM will not change in child, but another variables should changed... Look at this: airween at sebulba:~$ export LINES COLUMNS TERM airween at sebulba:~$ python2.6 Python 2.6.6 (r266:84292, Mar 25 2011, 19:24:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) ('65', '210', 'rxvt-256color') a. From kushal.kumaran+python at gmail.com Thu Sep 22 02:40:08 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 22 Sep 2011 12:10:08 +0530 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Sep 22, 2011 at 11:42 AM, Steven D'Aprano wrote: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') > > I have this: $ python Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getenv('LINES') >>> $ python -S Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 >>> import os >>> os.getenv('LINES') '35' >>> I hope it helps narrow things down somewhat. -- regards, kushal From rosuav at gmail.com Thu Sep 22 02:46:59 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 16:46:59 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7ACD82.4080302@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 3:54 PM, Andrew Berg wrote: > The main program is an IRC bot, which could potentially be in use by > many people in several channels on a network. As it is, the bot can only > connect to one server, but it could probably be set up to connect to any > number of networks. Making a number of quick fixes or changes to one > module could be very irritating to users if the bot has to terminate > each time, especially if those users don't know or care about that > specific module. > Startup time is an issue because it must connect to a network before it > can take any input. Also, many disconnects/reconnects could easily cause > problems (like the network refusing the connection as a DoS prevention > measure). Playing with networking and the desire to reload without restarting? I think Pike may be a good choice for you. It has a C-like syntax but Python-like guts; you use braces to delimit blocks of code, but arrays and mappings and such are first-class objects that you can pass around and use. It's a favorite of mine, but quite off-topic for this mailing list; I'd be happy to help you get started with it. Chris Angelico From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 03:21:59 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 09:21:59 +0200 Subject: Environment variables not visible from Python In-Reply-To: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 22.09.2011 08:12 schrieb Steven D'Aprano: > I don't understand why some environment variables are not visible from > Python. > > [steve at wow-wow ~]$ echo $LINES $COLUMNS $TERM > 30 140 xterm > [steve at wow-wow ~]$ python2.6 > Python 2.6.6 (r266:84292, Dec 21 2010, 18:12:50) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os >>>> (os.getenv('LINES'), os.getenv('COLUMNS'), os.getenv('TERM')) > (None, None, 'xterm') > They are no environment variables, but merely shell variables. You can turn them into environment variables with the shell command "export". After exporting them, they are visible by Python. The environment can be obtained with env. So try: $ python -c 'import os; print "\n".join(sorted("%s=%s" % (k,v) for k,v in os.environ.iteritems()))' | diff -u - <(env|LANG=C sort) @@ -61,4 +61,4 @@ XDG_DATA_DIRS=/usr/share XKEYSYMDB=/usr/share/X11/XKeysymDB XNLSPATH=/usr/share/X11/nls -_=/usr/bin/python +_=/usr/bin/env and you see that they (nearly) match. Try as well $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' linux $ export LINES $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' 24 linux $ export COLUMNS $ python -c 'import os; print "\n".join(os.getenv(k) or "" for k in ("LINES","COLUMNS","TERM"))' 24 80 linux $ HTH, Thomas From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 03:24:53 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 09:24:53 +0200 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: Am 22.09.2011 05:42 schrieb Atherun: > I'm pretty sure thats the problem, this is a generic catch all > function for running subprocesses. It can be anything to a simple > command to a complex command with a ton of output. I'm looking for a > better solution to handle the case of running subprocesses that have > an undetermined amount of output. Just handle process.stdout/stderr by yourself - read it out until EOF and then wait() for the process. Thomas From ericsnowcurrently at gmail.com Thu Sep 22 03:45:20 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 22 Sep 2011 01:45:20 -0600 Subject: static statements and thread safety Message-ID: A recent thread on the python-ideas list got me thinking about the possibility of a static statement (akin to global and nonlocal). I am wondering if an implementation would have to address thread safety concerns. I would expect that static variables would work pretty much the same way as default arguments, with a list of names on the code object and a list of values on the function object. And I would guess that the values from the static variables would get updated on the function object at the end of the call. If multiple threads are executing the function at the same time won't there be a problem with that end-of-call update? -eric p.s. It probably shows that I haven't done a lot of thread-related programming, so perhaps this is not a hard question. From bahamutzero8825 at gmail.com Thu Sep 22 03:59:42 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 02:59:42 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> Message-ID: <4E7AEAEE.20504@gmail.com> On 2011.09.22 01:46 AM, Chris Angelico wrote: > I think Pike may be a good choice for you. That's quite unappealing for a few reasons. First, that would likely require writing an entirely new bot (I'm not even that familiar with the current one; I've only been writing a module for it). Also, I don't really enjoy programming (I'm aware I'm likely in the minority on this list); I tolerate it enough to get certain things done, so learning another language, especially when I'm still learning Python, is not something I want to do. Python is probably not the best tool for this particular job, but I am not nearly dedicated to this project enough to learn another programming language. So, is there any way to at least monitor what happens after a reload? I haven't noticed anything odd until I came across this logging issue. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From rosuav at gmail.com Thu Sep 22 04:06:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:06:45 +1000 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow wrote: > I would expect that static variables would work pretty much the same > way as default arguments Could you just abuse default arguments to accomplish this? def accumulate(n,statics={'sum':0}): statics['sum']+=n return statics['sum'] >>> accumulate(1) 1 >>> accumulate(10) 11 >>> accumulate(20) 31 >>> accumulate(14) 45 This eliminates any sort of "end of function write-back" by writing to static storage immediately. Of course, syntactic assistance would make this look cleaner, for instance: def accumulate(n): static sum=0 sum+=n return sum Both of these would, of course, have thread-safety issues. But these can be resolved by figuring out exactly what you're trying to accomplish with your static data, and what it really means when two threads are affecting it at once. ChrisA From rosuav at gmail.com Thu Sep 22 04:12:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:12:49 +1000 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4E7AEAEE.20504@gmail.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> <4E7AEAEE.20504@gmail.com> Message-ID: On Thu, Sep 22, 2011 at 5:59 PM, Andrew Berg wrote: > That's quite unappealing for a few reasons. First, that would likely > require writing an entirely new bot (I'm not even that familiar with the > current one; I've only been writing a module for it). Ah, then yeah, it's probably not a good idea to change languages. But you may end up finding other issues with reload() as well. I wonder whether this would work... modules=[] # instead of 'import mymodule' use: modules.append(__import__('mymodule')); mymodule=modules[-1] In theory, this should mean that you load it fresh every time - I think. If not, manually deleting entries from sys.modules might help, either with or without the list of modules. ChrisA From ladasky at my-deja.com Thu Sep 22 04:13:12 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 22 Sep 2011 01:13:12 -0700 (PDT) Subject: Graphing References: Message-ID: I'm using matplotlib and I'm happy with it. Quick plotting is easy using the pyplot interface, which resembles the popular software package MATLAB. As your ambitions grow, matplotlib has many sophisticated tools waiting for you. From ericsnowcurrently at gmail.com Thu Sep 22 04:16:11 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Thu, 22 Sep 2011 02:16:11 -0600 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 2:06 AM, Chris Angelico wrote: > On Thu, Sep 22, 2011 at 5:45 PM, Eric Snow wrote: >> I would expect that static variables would work pretty much the same >> way as default arguments > > Could you just abuse default arguments to accomplish this? > > def accumulate(n,statics={'sum':0}): > ? ?statics['sum']+=n > ? ?return statics['sum'] > >>>> accumulate(1) > 1 >>>> accumulate(10) > 11 >>>> accumulate(20) > 31 >>>> accumulate(14) > 45 > > This eliminates any sort of "end of function write-back" by writing to > static storage immediately. Of course, syntactic assistance would make > this look cleaner, for instance: > > def accumulate(n): > ? ?static sum=0 > ? ?sum+=n > ? ?return sum > > Both of these would, of course, have thread-safety issues. But these > can be resolved by figuring out exactly what you're trying to > accomplish with your static data, and what it really means when two > threads are affecting it at once. That's a good point. So, isn't the default arguments hack in the same boat with regards to threads? Maybe I'm just misunderstanding the thread concept in Python. Threads have separate execution stacks but share interpreter global state, right? -eric > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Thu Sep 22 04:18:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 22 Sep 2011 18:18:28 +1000 Subject: static statements and thread safety In-Reply-To: References: Message-ID: On Thu, Sep 22, 2011 at 6:16 PM, Eric Snow wrote: > That's a good point. ?So, isn't the default arguments hack in the same > boat with regards to threads? > > Maybe I'm just misunderstanding the thread concept in Python. ?Threads > have separate execution stacks but share interpreter global state, > right? I would say it probably is, but others on this list will know more of threading in Python. I tend not to write multithreaded programs in Python - the main reason for me to use Python is rapid scriptwriting, which usually doesn't demand threads. ChrisA From steve+comp.lang.python at pearwood.info Thu Sep 22 04:25:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Sep 2011 08:25:39 GMT Subject: Odd behavior with imp.reload and logging References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> On Wed, 21 Sep 2011 23:47:55 -0500, Andrew Berg wrote: > On 2011.09.21 11:22 PM, Steven D'Aprano wrote: >> You could >> try something like this (untested): > That works. Thanks! > This makes me wonder what else stays around after a reload Practically everything. A reload doesn't delete anything, except as a side-effect of running the module again. Don't think of reloading as: * Revert anything the module is responsible for. * Delete the module object from the import cache. * Import the module in a fresh environment. Instead, think of it as: * Re-import the module in the current environment. In practice, you won't often see such side-effects, because most modules don't store state outside of themselves. If they store state *inside* themselves, then they will (almost always) overwrite that state. E.g. this will work as expected: state = [something] But this leaves state hanging around in other modules and will be surprising: import another_module another_module.state.append(something) My guess is that the logging module uses a cache to save the logger, hence there is state inadvertently stored outside your module. Another place where reload() doesn't work as expected: >>> import module >>> a = module.MyClass() >>> reload(module) >>> b = module.MyClass() >>> type(a) is type(b) False Objects left lying around from before the reload will keep references open to the way things were before the reload. This often leads to confusion when modules are edited, then reloaded. (Been there, done that.) -- Steven From bahamutzero8825 at gmail.com Thu Sep 22 05:02:48 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 22 Sep 2011 04:02:48 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4e7af102$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7AF9B8.7020802@gmail.com> On 2011.09.22 03:25 AM, Steven D'Aprano wrote: > Objects left lying around from before the reload will keep references > open to the way things were before the reload. This often leads to > confusion when modules are edited, then reloaded. (Been there, done that.) I'll keep that in mind. My module does have a class, but instances are kept inside dictionaries, which are explicitly set to {} at the beginning (can't use the update() method for dictionaries that don't exist). Also, class instances get pickled after creation and unpickled when the module is imported. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From chris at simplistix.co.uk Thu Sep 22 05:27:36 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 22 Sep 2011 10:27:36 +0100 Subject: python install on locked down windows box? Message-ID: <4E7AFF88.2040308@simplistix.co.uk> Hi All, Is there a way to install python on a locked down Windows desktop? (ie: no compilers, no admin rights, etc) cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From ben+python at benfinney.id.au Thu Sep 22 06:16:47 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 20:16:47 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wrd0286o.fsf@benfinney.id.au> Steven D'Aprano writes: > I don't understand why some environment variables are not visible from > Python. Not all variables are environment variables. Variables only become environment variables if exported to the environment; the ?export? command is one way to do that. -- \ ?As far as the laws of mathematics refer to reality, they are | `\ not certain, and as far as they are certain, they do not refer | _o__) to reality.? ?Albert Einstein, 1983 | Ben Finney From zondo42 at gmail.com Thu Sep 22 06:19:05 2011 From: zondo42 at gmail.com (Glenn Hutchings) Date: Thu, 22 Sep 2011 03:19:05 -0700 (PDT) Subject: python install on locked down windows box? In-Reply-To: References: Message-ID: <13828134.867.1316686745332.JavaMail.geo-discussion-forums@yqbr29> You could try Portable Python (http://www.portablepython.com). No need to install anything! From zondo42 at gmail.com Thu Sep 22 06:19:05 2011 From: zondo42 at gmail.com (Glenn Hutchings) Date: Thu, 22 Sep 2011 03:19:05 -0700 (PDT) Subject: python install on locked down windows box? In-Reply-To: References: Message-ID: <13828134.867.1316686745332.JavaMail.geo-discussion-forums@yqbr29> You could try Portable Python (http://www.portablepython.com). No need to install anything! From gavinpanella at gmail.com Thu Sep 22 06:21:28 2011 From: gavinpanella at gmail.com (Gavin Panella) Date: Thu, 22 Sep 2011 03:21:28 -0700 (PDT) Subject: Context manager with class methods Message-ID: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Hi, On Python 2.6 and 3.1 the following code works fine: class Foo(object): @classmethod def __enter__(cls): print("__enter__") @classmethod def __exit__(cls, exc_type, exc_value, traceback): print("__exit__") with Foo: pass However, in 2.7 and 3.2 I get: Traceback (most recent call last): File "", line 1, in AttributeError: __exit__ Is this a regression or a deliberate change? Off the top of my head I can't think that this pattern is particularly useful, but it seems like something that ought to work. Gavin. From vs at it.uu.se Thu Sep 22 06:25:30 2011 From: vs at it.uu.se (Virgil Stokes) Date: Thu, 22 Sep 2011 12:25:30 +0200 Subject: Execute code after Shut Down command given --- How? Message-ID: <4E7B0D1A.7040306@it.uu.se> I would like to execute some Python code (popup message to be displayed) when Windows Vista/7 is shut down. That is, this code should execute after "Shut Down" is given from the "Shut Down Windows" popup, but before the actual shut down sequence starts. How to write Python code to accomplish this task? From yasar11732 at gmail.com Thu Sep 22 06:43:48 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 22 Sep 2011 13:43:48 +0300 Subject: httplib's HEAD request, and https protocol Message-ID: Hi, I wrote a function to get thorugh redirections and find a final page for a given web-page. But following function gives maximum recursion error for any https pages I tried. Do you know what might be the problem here? def getHeadResponse(url,response_cache = {}): try: return response_cache[url] except KeyError: url = urlparse.urlparse(url) conn = httplib.HTTPConnection(url.netloc) try: conn.request("HEAD",url.path) except: # Anything can happen, this is SPARTA! return None response = conn.getresponse() response_cache[url.geturl()] = response return response def getFinalUrl(url): "Navigates through redirections to get final url." response = getHeadResponse(url) try: if str(response.status).startswith("3"): return getFinalUrl(response.getheader("location")) except AttributeError: pass return url -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From shilparani9030 at gmail.com Thu Sep 22 06:48:47 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Thu, 22 Sep 2011 03:48:47 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From steve+comp.lang.python at pearwood.info Thu Sep 22 07:07:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 21:07:31 +1000 Subject: Execute code after Shut Down command given --- How? References: Message-ID: <4e7b16f4$0$29979$c3e8da3$5496439d@news.astraweb.com> Virgil Stokes wrote: > I would like to execute some Python code (popup message to be displayed) > when > Windows Vista/7 is shut down. That is, this code should execute after > "Shut Down" is given from the "Shut Down Windows" popup, but before the > actual shut down sequence starts. > > How to write Python code to accomplish this task? Exactly the same way you would write it in any other language. This is not a Python question. It is a Windows question: "How do I execute code after the user calls Shut Down Windows, but before the shut down sequence starts?" Find out how to do that, and then do it using Python instead of another language. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 22 07:09:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 21:09:00 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: <4e7b174c$0$29979$c3e8da3$5496439d@news.astraweb.com> Ben Finney wrote: > Steven D'Aprano writes: > >> I don't understand why some environment variables are not visible from >> Python. > > Not all variables are environment variables. Variables only become > environment variables if exported to the environment; the ?export? > command is one way to do that. I see. Thank you to everyone who answered. -- Steven From joni8135 at gmail.com Thu Sep 22 07:16:34 2011 From: joni8135 at gmail.com (joni) Date: Thu, 22 Sep 2011 04:16:34 -0700 (PDT) Subject: Negativ nearest interger? Message-ID: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Have a simple question in the Integer calculator in Python 2.65 and also 2.7.. The consol showing: Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 7.0/3 #fist to show floiting-point calculation 2.3333333333333335 >>> -7.0/3 -2.3333333333333335 >>> -7/-3 #Rounding to nearest interger. 2 >>> 7/3 2 >>> 7/-3 #Now to the problem with interger rounding with negative anwser. -3 >>> -7/3 -3 >>> -3 are more wrong than -2. Negativ number seems not to round to nearest interger, but the integer UNDER the anwser!! Or? Why? From yasar11732 at gmail.com Thu Sep 22 07:42:12 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Thu, 22 Sep 2011 14:42:12 +0300 Subject: httplib's HEAD request, and https protocol In-Reply-To: References: Message-ID: Ok, nevermind. Appereantly there is such a thing as HTTPSConnection. I thought httplib auto-handled https connections.. 22 Eyl?l 2011 13:43 tarihinde Ya?ar Arabac? yazd?: > Hi, > > I wrote a function to get thorugh redirections and find a final page for a > given web-page. But following function gives maximum recursion error for any > https pages I tried. Do you know what might be the problem here? > > def getHeadResponse(url,response_cache = {}): > try: > return response_cache[url] > except KeyError: > url = urlparse.urlparse(url) > conn = httplib.HTTPConnection(url.netloc) > try: > conn.request("HEAD",url.path) > except: > # Anything can happen, this is SPARTA! > return None > response = conn.getresponse() > response_cache[url.geturl()] = response > return response > > def getFinalUrl(url): > "Navigates through redirections to get final url." > > response = getHeadResponse(url) > try: > if str(response.status).startswith("3"): > return getFinalUrl(response.getheader("location")) > except AttributeError: > pass > return url > -- > http://yasar.serveblog.net/ > > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 07:43:52 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 13:43:52 +0200 Subject: Environment variables not visible from Python In-Reply-To: <87wrd0286o.fsf@benfinney.id.au> References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: Am 22.09.2011 12:16 schrieb Ben Finney: > -- > \ ?As far as the laws of mathematics refer to reality, they are | > `\ not certain, and as far as they are certain, they do not refer | > _o__) to reality.? ?Albert Einstein, 1983 | > Ben Finney So, he said what in 1983? Wow. From jpiitula at ling.helsinki.fi Thu Sep 22 07:44:15 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 22 Sep 2011 14:44:15 +0300 Subject: Negativ nearest interger? References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: joni writes: > Have a simple question in the Integer calculator in Python 2.65 and > also 2.7.. > > The consol showing: > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) ... > >>> -7/3 > -3 > >>> > > -3 are more wrong than -2. Negativ number seems not to round to > nearest interger, but the integer UNDER the anwser!! Or? > > Why? It simply does not round to the nearest integer. It floors. This has nicer mathematical properties. In particular, it allows the remainder (notated as "per cent") operation (n % m) to return a number that differs from n by a multiple of m ("is congruent to n modulo m"). These two operations go together. From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Thu Sep 22 07:47:15 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Thu, 22 Sep 2011 13:47:15 +0200 Subject: Context manager with class methods In-Reply-To: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Am 22.09.2011 12:21 schrieb Gavin Panella: > Hi, > > On Python 2.6 and 3.1 the following code works fine: > > class Foo(object): > > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass > > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ Same here. But with Foo(): pass works, and that is more important and more logical. Thomas From ben+python at benfinney.id.au Thu Sep 22 08:26:15 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 22 Sep 2011 22:26:15 +1000 Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> <87wrd0286o.fsf@benfinney.id.au> Message-ID: <87r538226w.fsf@benfinney.id.au> Thomas Rachel writes: > Am 22.09.2011 12:16 schrieb Ben Finney: > > -- > > \ ?As far as the laws of mathematics refer to reality, they are | > > `\ not certain, and as far as they are certain, they do not refer | > > _o__) to reality.? ?Albert Einstein, 1983 | > > Ben Finney > > So, he said what in 1983? Wow. Or at least, in a work of his published in 1983: ?Sidelights on Relativity?. According to Wikiquote, anyway . -- \ ?[Entrenched media corporations will] maintain the status quo, | `\ or die trying. Either is better than actually WORKING for a | _o__) living.? ?ringsnake.livejournal.com, 2007-11-12 | Ben Finney From mwilson at the-wire.com Thu Sep 22 08:45:18 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 22 Sep 2011 08:45:18 -0400 Subject: Context manager with class methods References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Gavin Panella wrote: > Hi, > > On Python 2.6 and 3.1 the following code works fine: > > class Foo(object): > > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass > > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ > > Is this a regression or a deliberate change? Off the top of my head I > can't think that this pattern is particularly useful, but it seems > like something that ought to work. This seems to work: class MetaWith (type): @classmethod def __enter__(cls): print("__enter__") @classmethod def __exit__(cls, exc_type, exc_value, traceback): print("__exit__") class With (object): __metaclass__ = MetaWith with With: pass Mel. From mwilson at the-wire.com Thu Sep 22 08:53:21 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 22 Sep 2011 08:53:21 -0400 Subject: Context manager with class methods References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: Mel wrote: > This seems to work: > > > > class MetaWith (type): > @classmethod > def __enter__(cls): > print("__enter__") > > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > class With (object): > __metaclass__ = MetaWith > > with With: > pass It seems to work equally well without the `@classmethod`s Mel. From steve+comp.lang.python at pearwood.info Thu Sep 22 08:58:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 22 Sep 2011 22:58:00 +1000 Subject: python install on locked down windows box? References: Message-ID: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Chris Withers wrote: > Hi All, > > Is there a way to install python on a locked down Windows desktop? > (ie: no compilers, no admin rights, etc) (1) Bribe or blackmail the fascist system administrator. (2) Hack into the system with any of dozens of unpatched vulnerabilities that will give you admin rights. (3) Sneak into the office at 3 in the morning and replace the desktop with an identical machine which you have admin rights to. (4) Guess the admin password -- it's not hard, most fascist system administrators can't remember words with more than four letters, so the password is probably something like "passw" or, if he's being especially cunning, "drows". (5) "Accidentally" install Linux on the machine and use that instead. (6) Take hostages. (7) If all else fails, as an absolute last resort, simply run the Windows installer as a regular, unprivileged user, after selecting the option for a Non-Admin Install under Advanced Options first. You could also try the ActivePython installer. http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ http://diveintopython.org/installing_python/windows.html -- Steven From joni8135 at gmail.com Thu Sep 22 10:13:54 2011 From: joni8135 at gmail.com (joni) Date: Thu, 22 Sep 2011 07:13:54 -0700 (PDT) Subject: Negativ nearest interger? References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: On Sep 22, 1:44?pm, Jussi Piitulainen wrote: > joni writes: > > Have a simple question in the Integer calculator in Python 2.65 and > > also 2.7.. > > > The consol showing: > > > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) > ... > > >>> -7/3 > > -3 > > > -3 are more wrong than -2. Negativ number seems not to round to > > nearest interger, but the integer UNDER the anwser!! Or? > > > Why? > > It simply does not round to the nearest integer. It floors. This has > nicer mathematical properties. In particular, it allows the remainder > (notated as "per cent") operation (n % m) to return a number that > differs from n by a multiple of m ("is congruent to n modulo m"). > These two operations go together. Thanx. See if I can understand it.... /Cheers From ian at excess.org Thu Sep 22 11:05:00 2011 From: ian at excess.org (Ian Ward) Date: Thu, 22 Sep 2011 11:05:00 -0400 Subject: ANN: Urwid 1.0.0 - Console UI Library Message-ID: <4E7B4E9C.7060704@excess.org> Announcing Urwid 1.0.0 ---------------------- Urwid home page: http://excess.org/urwid/ Manual: http://excess.org/urwid/wiki/UrwidManual Tarball: http://excess.org/urwid/urwid-1.0.0.tar.gz About this release: =================== This is a major feature release for Urwid: It's the first official release that has support for Python 3. There's a new experimental Terminal widget so you can terminal while you terminal or write a screen-clone. There's a new example showing how to serve Urwid interfaces to many users simultaneously over ssh with Twisted. There are new classes to help with creating dynamic tree views of anything you have that's tree-like. There are new widgets for working with pop-ups so you can now have all the menu bars, drop-downs and combo-boxes you can write. The old requirement to sprinkle draw_screen() calls around your callbacks is gone. Urwid now updates the screen automatically after everything else is done. There's a new simple MainLoop method for catching updates from other threads and processes. No need to manually fumble with os.pipe() and event loops. And lots more... Happy 1.0 Urwid! It's been a great nearly-seven years since our first release. Huge thanks to everyone that's contributed code, docs, bug reports and help on the mailing list and IRC. New in this release: ==================== * New support for Python 3.2 from the same 2.x code base, requires distribute instead of setuptools (by Kirk McDonald, Wendell, Marien Zwart) everything except TwistedEventLoop and GLibEventLoop is supported * New experimental Terminal widget with xterm emulation and terminal.py example program (by aszlig) * Edit widget now supports a mask (for passwords), has a insert_text_result() method for full-field validation and normalizes input text to Unicode or bytes based on the caption type used * New TreeWidget, TreeNode, ParentNode, TreeWalker and TreeListBox classes for lazy expanding/collapsing tree views factored out of browse.py example program, with new treesample.py example program (by Rob Lanphier) * MainLoop now calls draw_screen() just before going idle, so extra calls to draw_screen() in user code may now be removed * New MainLoop.watch_pipe() method for subprocess or threaded communication with the process/thread updating the UI, and new subproc.py example demonstrating its use * New PopUpLauncher and PopUpTarget widgets and MainLoop option for creating pop-ups and drop-downs, and new pop_up.py example program * New twisted_serve_ssh.py example (by Ali Afshar) that serves multiple displays over ssh from the same application using Twisted and the TwistedEventLoop * ListBox now includes a get_cursor_coords() method, allowing nested ListBox widgets * Columns widget contents may now be marked to always be treated as flow widgets for mixing flow and box widgets more easily * New lcd_display module with support for CF635 USB LCD panel and lcd_cf635.py example program with menus, slider controls and a custom font * Shared command_map instance is now stored as Widget._command_map class attribute and may be overridden in subclasses or individual widgets for more control over special keystrokes * Overlay widget parameters may now be adjusted after creation with set_overlay_parameters() method * New WidgetPlaceholder widget useful for swapping widgets without having to manipulate a container widget's contents * LineBox widgets may now include title text * ProgressBar text content and alignment may now be overridden * Use reactor.stop() in TwistedEventLoop and document that Twisted's reactor is not designed to be stopped then restarted * curses_display now supports AttrSpec and external event loops (Twisted or GLib) just like raw_display * raw_display and curses_display now support the IBMPC character set (currently only used by Terminal widget) * Fix for a gpm_mev bug preventing user input when on the console * Fix for leaks of None objects in str_util extension * Fix for WidgetWrap and AttrMap not working with fixed widgets * Fix for a lock up when attempting to wrap text containing wide characters into a single character column About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, Unicode support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From python at mrabarnett.plus.com Thu Sep 22 11:19:04 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 22 Sep 2011 16:19:04 +0100 Subject: static statements and thread safety In-Reply-To: References: Message-ID: <4E7B51E8.10200@mrabarnett.plus.com> On 22/09/2011 08:45, Eric Snow wrote: > A recent thread on the python-ideas list got me thinking about the > possibility of a static statement (akin to global and nonlocal). I am > wondering if an implementation would have to address thread safety > concerns. > > I would expect that static variables would work pretty much the same > way as default arguments, with a list of names on the code object and > a list of values on the function object. And I would guess that the > values from the static variables would get updated on the function > object at the end of the call. If multiple threads are executing the > function at the same time won't there be a problem with that > end-of-call update? > It's no different from using a global, except that it's not in the global (module) namespace, but attached to a function object. > -eric > > > p.s. It probably shows that I haven't done a lot of thread-related > programming, so perhaps this is not a hard question. From atherun at gmail.com Thu Sep 22 11:55:40 2011 From: atherun at gmail.com (Atherun) Date: Thu, 22 Sep 2011 08:55:40 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Sep 22, 12:24?am, Thomas Rachel wrote: > Am 22.09.2011 05:42 schrieb Atherun: > > > I'm pretty sure thats the problem, this is a generic catch all > > function for running subprocesses. ?It can be anything to a simple > > command to a complex command with a ton of output. ?I'm looking for a > > better solution to handle the case of running subprocesses that have > > an undetermined amount of output. > > Just handle process.stdout/stderr by yourself - read it out until EOF > and then wait() for the process. > > Thomas Thats what confuses me though, the documentation says process.stdout.read()/stderr.read() can deadlock and apparently so can communicate, how do you read the stdout/stderr on yourself if its documented using them can cause a deadlock? From navkirat.py at gmail.com Thu Sep 22 12:00:18 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Thu, 22 Sep 2011 21:30:18 +0530 Subject: Decision on python technologies Message-ID: Hi Guys, I have been a python developer for a bit now and for the life of me I am not being able to decide something. I am trying to develop a web based application in python. I am torn between using python 2 or 3. All the good frameworks are still in 2.x. Now, cherrypy, sqlalchemy and jinja2 support python 3. But do I really want to do all the boilerplate work again? I have this strong urge to use python 3 and call it my indecisiveness , I am somehow not wanting to use 2.x, though it has everything I need to build my app. Hence, I finally decided to turn to the community for helping me make this decision. Please help. Regards, Nav -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Thu Sep 22 12:28:52 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 22 Sep 2011 09:28:52 -0700 (PDT) Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) In-Reply-To: References: Message-ID: <19309769.959.1316708932280.JavaMail.geo-discussion-forums@prdy8> Thank you! My kids *love* it. From miki.tebeka at gmail.com Thu Sep 22 12:28:52 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 22 Sep 2011 09:28:52 -0700 (PDT) Subject: [ANNC] pynguin-0.12 (fixes problems running on Windows) In-Reply-To: References: Message-ID: <19309769.959.1316708932280.JavaMail.geo-discussion-forums@prdy8> Thank you! My kids *love* it. From ppearson at nowhere.invalid Thu Sep 22 12:51:39 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 22 Sep 2011 16:51:39 GMT Subject: Environment variables not visible from Python References: <4e7ad1b1$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9e17crFamfU1@mid.individual.net> On Thu, 22 Sep 2011 09:21:59 +0200, Thomas Rachel wrote: [snip] > $ python -c 'import os; print "\n".join(sorted("%s=%s" % (k,v) for k,v > in os.environ.iteritems()))' | diff -u - <(env|LANG=C sort) [standing ovation] -- To email me, substitute nowhere->spamcop, invalid->net. From rosuav at gmail.com Thu Sep 22 13:39:54 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 03:39:54 +1000 Subject: random.randint() slow, esp in Python 3 Message-ID: The standard library function random.randint() seems to be quite slow compared to random.random(), and worse in Python 3 than Python 2 (specifically that's 3.3a0 latest from Mercurial, and 2.6.6 that came default on my Ubuntu install). My test involves building a list of one million random integers between 0 and ten million (for tinkering with sorting algorithms), using a list comprehension: import random import time sz=1000000 start=time.time() a=[random.randint(0,sz*10-1) for i in range(sz)] print("Time taken: ",time.time()-start) The code works fine in either version of Python (although the display looks a bit odd in Py2). But on my test system, it takes about 5 seconds to run in Py2, and about 10 seconds for Py3. (The obvious optimization of breaking sz*10-1 out and storing it in a variable improves both times, but leaves the dramatic difference.) Replacing randint with random(): a=[int(random.random()*top) for i in range(sz)] cuts the times down to about 1.5 secs for Py2, and 1.8 secs for Py3. I suspect that the version difference is (at least in part) due to the merging of the 'int' and 'long' types in Py3. This is supported experimentally by rerunning the second list comp but using int() in place of long() - the time increases to about 1.7-1.8 secs, matching Py3. But this still doesn't explain why randint() is so much slower. In theory, randint() should be doing basically the same thing that I've done here (multiply by the top value, truncate the decimal), only it's in C instead of Python - if anything, it should be faster than doing it manually, not slower. A minor point of curiosity, nothing more... but, I think, a fascinating one. ChrisA From nobody at nowhere.com Thu Sep 22 13:44:09 2011 From: nobody at nowhere.com (Nobody) Date: Thu, 22 Sep 2011 18:44:09 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Thu, 22 Sep 2011 08:55:40 -0700, Atherun wrote: >> Just handle process.stdout/stderr by yourself - read it out until EOF >> and then wait() for the process. > > Thats what confuses me though, the documentation says > process.stdout.read()/stderr.read() can deadlock and apparently so can > communicate, how do you read the stdout/stderr on yourself if its > documented using them can cause a deadlock? If you try to read/write two or more of stdin/stdout/stderr via the "naive" approach, you run the risk of the child process writing more than a pipe's worth of data to one stream (and thus blocking) while the parent is performing a blocking read/write on another stream, resulting in deadlock. The .communicate() method avoids the deadlock by either: 1. On Unix, using non-blocking I/O and select(), or 2. On Windows, creating a separate thread for each stream. Either way, the result is that it can always read/write whichever streams are ready, so the child will never block indefinitely while waiting for the parent. If .communicate() is blocking indefinitely, it suggests that the child process never terminates. There are many reasons why this might happen, and most of them depend upon exactly what the child process is doing. I suggest obtaining a copy of Process Explorer, and using it to investigate the state of both processes (but especially the child) at the point that the "deadlock" seems to occur. From steve+comp.lang.python at pearwood.info Thu Sep 22 14:14:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 23 Sep 2011 04:14:16 +1000 Subject: random.randint() slow, esp in Python 3 References: Message-ID: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > The standard library function random.randint() seems to be quite slow > compared to random.random(), and worse in Python 3 than Python 2 [...] > But this still doesn't explain why randint() is so much slower. In > theory, randint() should be doing basically the same thing that I've > done here (multiply by the top value, truncate the decimal), only it's > in C instead of Python - if anything, it should be faster than doing > it manually, not slower. What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the random module is mostly Python. There is an import of _random, which presumably is in C, but it doesn't have a randint method: >>> import _random >>> _random.Random.randint Traceback (most recent call last): File "", line 1, in AttributeError: type object '_random.Random' has no attribute 'randint' I'm not seeing any significant difference in speed between 2.6 and 3.2: [steve at sylar ~]$ python2.6 -m timeit -s "from random import randint" "randint(0, 1000000)" 100000 loops, best of 3: 4.29 usec per loop [steve at sylar ~]$ python3.2 -m timeit -s "from random import randint" "randint(0, 1000000)" 100000 loops, best of 3: 4.98 usec per loop (The times are quite variable: the above are the best of three attempts.) -- Steven From emile at fenx.com Thu Sep 22 14:16:05 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 22 Sep 2011 11:16:05 -0700 Subject: Decision on python technologies In-Reply-To: References: Message-ID: On 9/22/2011 9:00 AM Navkirat Singh said... > Hi Guys, > > I have been a python developer for a bit now and for the life of me I am > not being able to decide something. I am trying to develop a web based > application in python. I am torn between using python 2 or 3. All the > good frameworks are still in 2.x. Now, cherrypy, sqlalchemy and jinja2 > support python 3. But do I really want to do all the boilerplate work > again? I have this strong urge to use python 3 and call it my > indecisiveness , I am somehow not wanting to use 2.x, though it has > everything I need to build my app. Hence, I finally decided to turn to > the community for helping me make this decision. > I'd consider the development timeframe -- if it'll still be under development within the timeframe of migration and availability of desired tools then I'd start with 3 and focus on those parts that can be worked on. If your development timeframe is measured in weeks instead of quarters or years, I'd just get it done with 2. Emile From atherun at gmail.com Thu Sep 22 14:19:28 2011 From: atherun at gmail.com (Atherun) Date: Thu, 22 Sep 2011 11:19:28 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Sep 22, 10:44?am, Nobody wrote: > On Thu, 22 Sep 2011 08:55:40 -0700, Atherun wrote: > >> Just handle process.stdout/stderr by yourself - read it out until EOF > >> and then wait() for the process. > > > Thats what confuses me though, the documentation says > > process.stdout.read()/stderr.read() can deadlock and apparently so can > > communicate, how do you read the stdout/stderr on yourself if its > > documented using them can cause a deadlock? > > If you try to read/write two or more of stdin/stdout/stderr via the > "naive" approach, you run the risk of the child process writing more than > a pipe's worth of data to one stream (and thus blocking) while the > parent is performing a blocking read/write on another stream, resulting in > deadlock. > > The .communicate() method avoids the deadlock by either: > > 1. On Unix, using non-blocking I/O and select(), or > 2. On Windows, creating a separate thread for each stream. > > Either way, the result is that it can always read/write whichever > streams are ready, so the child will never block indefinitely while > waiting for the parent. > > If .communicate() is blocking indefinitely, it suggests that the child > process never terminates. There are many reasons why this might happen, > and most of them depend upon exactly what the child process is doing. > > I suggest obtaining a copy of Process Explorer, and using it to > investigate the state of both processes (but especially the child) at the > point that the "deadlock" seems to occur. In the one case I can easily reproduce, its in a p4.exe call that I'm making both python and p4.exe have nearly the same stack for their threads: python: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!__misaligned_access+0xba4 ntoskrnl.exe!__misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!NtWaitForSingleObject+0xde ntoskrnl.exe!KeSynchronizeExecution+0x3a43 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x6c0 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x4a8 wow64.dll!Wow64SystemServiceEx+0x1ce wow64.dll!Wow64LdrpInitialize+0x429 ntdll.dll!RtlUniform+0x6e6 ntdll.dll!RtlCreateTagHeap+0xa7 ntdll.dll!LdrInitializeThunk+0xe ntdll.dll!ZwWaitForSingleObject+0x15 kernel32.dll!WaitForSingleObjectEx+0x43 kernel32.dll!WaitForSingleObject+0x12 python26.dll!_Py_svnversion+0xcf8 p4: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForSingleObject+0x19f ntoskrnl.exe!_misaligned_access+0xba4 ntoskrnl.exe!_misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForSingleObject+0x19f ntoskrnl.exe!NtCreateFile+0x4c9 ntoskrnl.exe!NtWriteFile+0x7e3 ntoskrnl.exe!KeSynchronizeExecution+0x3a43 ntdll.dll!ZwWriteFile+0xa KERNELBASE.dll!WriteFile+0x7b kernel32.dll!WriteFile+0x36 p4.exe+0x42d4b p4.exe+0x42ed8 To me it looks like they're both waiting on each other. From mattj.morrison at gmail.com Thu Sep 22 17:14:39 2011 From: mattj.morrison at gmail.com (Matt) Date: Thu, 22 Sep 2011 14:14:39 -0700 (PDT) Subject: Python Mixins Message-ID: I'm curious about what people's opinions are about using mixins in Python. I really like, for example, the way that class based views were implemented in Django 1.3 using mixins. It makes everything extremely customizable and reusable. I think this is a very good practice to follow, however, in Python mixins are achieved by using (or perhaps misusing) inheritance and often multiple inheritance. Inheritance is a very powerful tool, and multiple inheritance is an even more powerful tool. These tools have their uses, but I feel like "mixing in" functionality is not one of them. There are much different reasons and uses for inheriting functionality from a parent and mixing in functionality from elsewhere. As a person, you learn certain things from your parents, you learn other things from your peers all of those things put together becomes you. Your peers are not your parents, that would not be possible. You have completely different DNA and come from a completely different place. In terms of code, lets say we have the following classes: class Animal class Yamlafiable class Cat(Animal, Yamlafiable) class Dog(Animal, Yamlafiable) I've got an Animal that does animal things, a Cat that does cat things and a Dog that does dog things. I've also got a Yamlafiable class that does something clever to generically convert an object into Yaml in some way. Looking at these classes I can see that a Cat is an Animal, a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a Yamlafiable? and a Cat is a Yamlafiable? Is that really true? If my objects are categorized correctly, in the correct inheritance hierarchy shouldn't that make more sense? Cats and Dogs aren't Yamlafiable, that doesn't define what they are, rather it defines something that they can do because of things that they picked up from their friend the Yamlafile. This is just a ridiculous example, but I think it is valid to say that these things shouldn't be limited to inherit functionality only from their parents, that they can pick other things up along the way as well. Which is easy to do, right? Dog.something_new = something_new (I wish my stupid dog would learn that easily) Ideally, what I would like to see is something like Ruby's mixins. It seems to me like Ruby developed this out of necessity due to the fact that it does not support multiple inheritance, however I think the implementation is much more pure than inheriting from things that aren't your parents. (although having only a single parent doesn't make much sense either, I believe there are very few actual documented cases of that happening). Here is a Ruby snippet: module ReusableStuff def one_thing "something cool" end end class MyClass < MyParent include ReusableStuff end x = MyClass.new x.one_thing == "something cool" MyClass.superclass == Object So I'm inheriting from MyParent and mixing in additional functionality from ReusableStuff without affecting who my Parents are. This, to me, makes much more sense than using inheritance to just grab a piece of functionality that I want to reuse. I wrote a class decorator for Python that does something similar (https://gist.github.com/1233738) here is a snippet from that: class MyMixin(object): def one_thing(self): return "something cool" @mixin(MyMixin) class MyClass(object): pass x = MyClass() x.one_thing() == 'something cool' x.__class__.__bases__ == (object,) To me, this is much more concise. By looking at this I can tell what MyClass IS, who it's parents are and what else it can do. I'm very interested to know if there are others who feel as dirty as I do when using inheritance for mixins or if there are other things that Python developers are doing to mix in functionality without using inheritance or if the general populous of the Python community disagrees with me and thinks that this is a perfectly valid use of inheritance. I look forward to hearing back. Thanks, Matthew J Morrison www.mattjmorrison.com P.S. - This is a good article about not using inheritance as a code reuse tool: http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/ From rantingrick at gmail.com Thu Sep 22 17:44:03 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 22 Sep 2011 14:44:03 -0700 (PDT) Subject: Python Mixins References: Message-ID: <1b1998c1-150c-49d5-b42b-56fe117e7ad6@eb1g2000vbb.googlegroups.com> On Sep 22, 4:14?pm, Matt wrote: > (although having only a single parent doesn't > make much sense either, I believe there are very few actual documented > cases of that happening). There is nothing wrong with an object having only one parent. Most times the reasons are for maintainability. I might have a TextEditor that exposes all the generic functionality that are ubiquitous to text editors and then a FancyTextEditor(TextEditor) that exposes functionality that is unique to a confined set of text editing uses. A silly example, but proves the point. Do not judge an object by the number of prodigy. From t at jollybox.de Thu Sep 22 18:09:08 2011 From: t at jollybox.de (Thomas Jollans) Date: Fri, 23 Sep 2011 00:09:08 +0200 Subject: Python Mixins In-Reply-To: References: Message-ID: <4E7BB204.90902@jollybox.de> On 2011-09-22 23:14, Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. > > Inheritance is a very powerful tool, and multiple inheritance is an > even more powerful tool. These tools have their uses, but I feel like > "mixing in" functionality is not one of them. There are much different > reasons and uses for inheriting functionality from a parent and mixing > in functionality from elsewhere. > > As a person, you learn certain things from your parents, you learn > other things from your peers all of those things put together becomes > you. Your peers are not your parents, that would not be possible. You > have completely different DNA and come from a completely different > place. > > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > I think this is an excellent use of multiple inheritance. One could also have a construction like this: class Dog (Animal) class YamlafialbleDog (Dog, Yamlafiable) ... which you may be more comfortable with. In you above example, yes, a Dog object is a Yamlafiable object. If you need a Yamlafiable object, you can use a Cat or Dog. That's what inheritance is about. In Python or Ruby, this way of doing things is not all that different from the one you present below. Here, it doesn't really matter. In strictly typed languages, it makes a world of difference. What if you don't care what kind of object you're dealing with, as long as it supports the interface a certain mixin provides? In Python, true, duck typing will do the trick. In C++, for example, where you could use the C preprocessor to do something like Ruby mixins, multiple inheritance is a lot more useful for mixing in something that has a public interface. The Vala language, and, I suppose the GObject type system, actually allows interfaces to act as mixins. This is really a more formalised way of doing just this: using multiple inheritance (which, beyond interfaces, Vala does not support) to mix in functionality. Oh and your thing looks kind of neat. Thomas > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. > > This is just a ridiculous example, but I think it is valid to say that > these things shouldn't be limited to inherit functionality only from > their parents, that they can pick other things up along the way as > well. Which is easy to do, right? > > Dog.something_new = something_new > > (I wish my stupid dog would learn that easily) > > Ideally, what I would like to see is something like Ruby's mixins. It > seems to me like Ruby developed this out of necessity due to the fact > that it does not support multiple inheritance, however I think the > implementation is much more pure than inheriting from things that > aren't your parents. (although having only a single parent doesn't > make much sense either, I believe there are very few actual documented > cases of that happening). Here is a Ruby snippet: > > module ReusableStuff > def one_thing > "something cool" > end > end > class MyClass < MyParent > include ReusableStuff > end > > x = MyClass.new > x.one_thing == "something cool" > MyClass.superclass == Object > > So I'm inheriting from MyParent and mixing in additional functionality > from ReusableStuff without affecting who my Parents are. This, to me, > makes much more sense than using inheritance to just grab a piece of > functionality that I want to reuse. I wrote a class decorator for > Python that does something similar (https://gist.github.com/1233738) > here is a snippet from that: > > class MyMixin(object): > def one_thing(self): > return "something cool" > > @mixin(MyMixin) > class MyClass(object): > pass > > x = MyClass() > x.one_thing() == 'something cool' > x.__class__.__bases__ == (object,) > > To me, this is much more concise. By looking at this I can tell what > MyClass IS, who it's parents are and what else it can do. I'm very > interested to know if there are others who feel as dirty as I do when > using inheritance for mixins or if there are other things that Python > developers are doing to mix in functionality without using inheritance > or if the general populous of the Python community disagrees with me > and thinks that this is a perfectly valid use of inheritance. > > I look forward to hearing back. > > Thanks, > Matthew J Morrison > www.mattjmorrison.com > > > P.S. - This is a good article about not using inheritance as a code > reuse tool: http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/ From tjreedy at udel.edu Thu Sep 22 18:56:54 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Sep 2011 18:56:54 -0400 Subject: Context manager with class methods In-Reply-To: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: On 9/22/2011 6:21 AM, Gavin Panella wrote: > On Python 2.6 and 3.1 the following code works fine: > class Foo(object): > @classmethod > def __enter__(cls): > print("__enter__") > @classmethod > def __exit__(cls, exc_type, exc_value, traceback): > print("__exit__") > > with Foo: pass This could be regarded as a bug, see below. > However, in 2.7 and 3.2 I get: > > Traceback (most recent call last): > File "", line 1, in > AttributeError: __exit__ type(Foo) == type and type has no such attribute. Unless otherwise specified, 'method' typically means 'instance method'. In particular, the '__xxx__' special methods are (all?) (intended to be) instance methods, which is to say, functions that are attributes of an object's class. So it is normal to look for special methods on the class (and superclasses) of an object rather than starting with the object itself. For instance, when executing 'a+b', the interpreter never looks for __add__ as an attribute of a itself (in a.__dict__) but starts the search looking for with type(a).__add__ > Is this a regression or a deliberate change? Off the top of my head I > can't think that this pattern is particularly useful, but it seems > like something that ought to work. I suspect there was a deliberate change to correct an anomaly, though this might have been done as part of some other change. As Thomas noted, *instances* of Foo work and as Mei noted, making Foo an instance of a (meta)class with the needed methods also works. -- Terry Jan Reedy From tjreedy at udel.edu Thu Sep 22 19:14:42 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Sep 2011 19:14:42 -0400 Subject: Negativ nearest interger? In-Reply-To: References: <485699e2-7cfd-4614-bf77-906ae84547e5@h6g2000vbc.googlegroups.com> Message-ID: On 9/22/2011 7:44 AM, Jussi Piitulainen wrote: > joni writes: >> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) > ... >>>>> -7/3 >> -3 In late Python 2 you *can* and in Python 3 you *must* use // rather than / to get an int result. >> -3 are more wrong than -2. Negativ number seems not to round to >> nearest interger, but the integer UNDER the anwser!! Or? >> Why? > > It simply does not round to the nearest integer. It floors. This has > nicer mathematical properties. In particular, it allows the remainder > (notated as "per cent") operation (n % m) to return a number that > differs from n by a multiple of m ("is congruent to n modulo m"). > These two operations go together. The Python doc set has a FAQ collection. I recommend you read the questions for those you might be interested in. In the Programming FAQ: "Why does -22 // 10 return -3? It?s primarily driven by the desire that i % j have the same sign as j. If you want that, and also want: i == (i // j) * j + (i % j) then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate i // j need to make i % j have the same sign as i. There are few real use cases for i % j when j is negative. When j is positive, there are many, and in virtually all of them it?s more useful for i % j to be >= 0. If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite." -- Terry Jan Reedy From rosuav at gmail.com Thu Sep 22 19:22:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 09:22:44 +1000 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 23, 2011 at 4:14 AM, Steven D'Aprano wrote: > What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the > random module is mostly Python. There is an import of _random, which > presumably is in C, but it doesn't have a randint method: True. It seems to be defined in cpython/lib/random.py as a reference to randrange, which does a pile of error checking and calls _randbelow... which does a whole lot of work as well as calling random(). Guess I should have checked the code before asking! There's probably good reasons for using randint(), but if you just want a pile of more-or-less random integers, int(random.random()*top) is the best option. > I'm not seeing any significant difference in speed between 2.6 and 3.2: > > [steve at sylar ~]$ python2.6 -m timeit -s "from random import > randint" "randint(0, 1000000)" > 100000 loops, best of 3: 4.29 usec per loop > > [steve at sylar ~]$ python3.2 -m timeit -s "from random import > randint" "randint(0, 1000000)" > 100000 loops, best of 3: 4.98 usec per loop That might be getting lost in the noise. Try the list comp that I had above and see if you can see a difference - or anything else that calls randint that many times. Performance-testing with a heapsort (and by the way, it's _ridiculously_ slower implementing it in Python instead of just calling a.sort(), but we all knew that already!) shows a similar difference in performance. As far as I know, everything's identical between the two (I use // division so there's no floating point getting in the way, for instance), but what takes 90 seconds on Py2 takes 150 seconds on Py3. As with the randint test, I switched int() to long() to test Py2, and that slowed it down a little, but still far far below the Py3 time. I've pasted the code I'm using here: http://pastebin.com/eQPHQhD0 Where's the dramatic performance difference? Or doesn't it matter, since anything involving this sort of operation needs to be done in C anyway? ChrisA From skippy.hammond at gmail.com Thu Sep 22 19:47:12 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 23 Sep 2011 09:47:12 +1000 Subject: PyEval_EvalCodeEx return value In-Reply-To: <4E786C42.3050309@loskot.net> References: <4E786C42.3050309@loskot.net> Message-ID: <4E7BC900.9010103@gmail.com> On 20/09/2011 8:34 PM, Mateusz Loskot wrote: > Hi, > > I'm trying to dig out details about what exactly is the return > value the of PyEval_EvalCodeEx function in Python 3.x > The documentation is sparse, unfortunately. > > Perhaps I'm looking at wrong function. > My aim is simple, I need to execute Python code using Python interpreter > embedded in my C++ application. > The Python code is a simple script that always returns single value. > For example: > > #! /usr/bin/env python > def foo(a, b): > return a + b > f = foo(2, 3) > > But, f can be of different type for different script: one returns > numeric value, another returns a sequence, so the type is not > possible to be determined in advance. > > I know how to capture Python stdout/stderr. > > I also know how to access the "f" attribute using > PyObject_GetAttrString and then I can convert "f" value to C++ type > depending on PyObject type. > > However, I guess there shall be a way to access "f" value > directly from PyEval_EvalCode return object: > > PyObject* evalRet = ::PyEval_EvalCode(...); > > But, I can't find any details what the "evalRet" actually is. Eval is to eval an expression. If you simply eval the expression "f" in the context of the module you should get the result returned. Obviously though it is designed to eval more complex expressions and in your specific example, doing the getattr thing will also work fine. Mark From jesus.ramirez.utexas at gmail.com Thu Sep 22 20:36:45 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Thu, 22 Sep 2011 17:36:45 -0700 (PDT) Subject: Python 2.5 zlib trouble Message-ID: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Hello, I am trying to deploy an app on google app engine using bottle, a micro-framework, similar to flask. I am running on ubuntu which comes with python 2.7 installed but GAE needs version 2.5, so I installed 2.5. I then realized I didn't use make altinstall so I may have a default version problem now. But my real problem is that when I try to use the gae server to test locally I get the following error: Traceback (most recent call last): File "/opt/google/appengine/dev_appserver.py", line 77, in run_file(__file__, globals()) File "/opt/google/appengine/dev_appserver.py", line 73, in run_file execfile(script_path, globals_) File "/opt/google/appengine/google/appengine/tools/ dev_appserver_main.py", line 156, in from google.appengine.tools import dev_appserver File "/opt/google/appengine/google/appengine/tools/ dev_appserver.py", line 94, in import zlib ImportError: No module named zlib Can you help me with this? From anacrolix at gmail.com Fri Sep 23 01:44:25 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Fri, 23 Sep 2011 15:44:25 +1000 Subject: python install on locked down windows box? In-Reply-To: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: 5 is the best solution, followed by 2 and 3. On Sep 22, 2011 11:02 PM, "Steven D'Aprano" < steve+comp.lang.python at pearwood.info> wrote: > Chris Withers wrote: > >> Hi All, >> >> Is there a way to install python on a locked down Windows desktop? >> (ie: no compilers, no admin rights, etc) > > (1) Bribe or blackmail the fascist system administrator. > > (2) Hack into the system with any of dozens of unpatched vulnerabilities > that will give you admin rights. > > (3) Sneak into the office at 3 in the morning and replace the desktop with > an identical machine which you have admin rights to. > > (4) Guess the admin password -- it's not hard, most fascist system > administrators can't remember words with more than four letters, so the > password is probably something like "passw" or, if he's being especially > cunning, "drows". > > (5) "Accidentally" install Linux on the machine and use that instead. > > (6) Take hostages. > > (7) If all else fails, as an absolute last resort, simply run the Windows > installer as a regular, unprivileged user, after selecting the option for a > Non-Admin Install under Advanced Options first. You could also try the > ActivePython installer. > > http://www.richarddooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/ > http://diveintopython.org/installing_python/windows.html > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Fri Sep 23 01:59:12 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 23 Sep 2011 06:59:12 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Thu, 22 Sep 2011 11:19:28 -0700, Atherun wrote: >> I suggest obtaining a copy of Process Explorer, and using it to >> investigate the state of both processes (but especially the child) at the >> point that the "deadlock" seems to occur. > > In the one case I can easily reproduce, its in a p4.exe call that I'm > making both python and p4.exe have nearly the same stack for their > threads: > python: > kernel32.dll!WaitForSingleObject+0x12 > python26.dll!_Py_svnversion+0xcf8 I haven't a clue how this happens. _Py_svnversion just returns a string: _Py_svnversion(void) { /* the following string can be modified by subwcrev.exe */ static const char svnversion[] = SVNVERSION; if (svnversion[0] != '$') return svnversion; /* it was interpolated, or passed on command line */ return "Unversioned directory"; } It doesn't even From rosuav at gmail.com Fri Sep 23 03:08:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 23 Sep 2011 17:08:39 +1000 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > It doesn't even > You intrigue me, sir. Does it odd? What is the remainder of this aborted sentence? ChrisA From chris at simplistix.co.uk Fri Sep 23 03:46:41 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 08:46:41 +0100 Subject: TestFixtures 2.0.0 Released! Message-ID: <4E7C3961.8020107@simplistix.co.uk> Hi All, I'm happy to announce a new release major release of TestFixtures. This release is 99% backwards compatible, but a lot has changed under the hood and there's some major new functionality, so thought it was time for a bump. The big changes are: - compare now uses a registry of comparers in the same way that unitest2's assertEquals does. You can register your own globally, register the default comparers for your own types and use a specific registry for a specific call to compare. - The handling of timezones has been reworked in `test_datetime` again. (did anyone ever mention that timezones are hard ;-) ) It feels more intuitive now, but it is backwards incompatible in the case where the `tzinfo` parameter to the `test_datetime` constructor was used. For details, read: http://packages.python.org/testfixtures/datetime.html#timezones The full list of changes can be found here: http://packages.python.org/testfixtures/changes.html The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From steve+comp.lang.python at pearwood.info Fri Sep 23 04:11:03 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 23 Sep 2011 18:11:03 +1000 Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> Jesramz wrote: > Hello, > > I am trying to deploy an app on google app engine using bottle, a > micro-framework, similar to flask. [...] > ImportError: No module named zlib What happens if you explicitly launch Python2.5 and then try to import zlib? -- Steven From andrea.crotti.0 at gmail.com Fri Sep 23 05:12:10 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 10:12:10 +0100 Subject: extending class Message-ID: <4E7C4D6A.8050107@gmail.com> I wanted to add a couple of parameters to a class from a given library (paste-script), but without changing the original code. So I thought, I create a wrapper class which adds what I need, and then dispatch all the calls to the super class. My following attempt gives, however, a recursion error, but why? class PSIVar(object): """Extend var implementation from the paste-script, to add the ability of correlating variables >>> v = var("name", "desc") >>> v.name == 'name' True >>> v1 = PSIVar(v) >>> v1.name == 'name' True """ def __init__(self, first_var, other=None, fun=None): # this is of type defined there self.first_var = first_var if other is not None: self.other = other self.fun = fun assert callable(self.fun) # now try to dispatch every method call to the other class # must probably call the super class def __getattribute__(self, attr): return self.first_var.__getattribute__(attr) From duncan.booth at invalid.invalid Fri Sep 23 05:19:09 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Sep 2011 09:19:09 GMT Subject: Python Mixins References: Message-ID: Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. > I think Mixins are great, in moderation, but wait until you have to debug code on an object with 70 base classes. Reinout van Rees wrote a very insightful article recently about Django's use of multiple inheritance: http://reinout.vanrees.org/weblog/2011/08/23/class-based-views.html He points out the problems that arise from overuse of mixins; why Zope went through so much upheaval to get away from mixins everywhere and switched to a component architecture instead; and suggests that Django will do the same in a few years time. -- Duncan Booth http://kupuguy.blogspot.com From __peter__ at web.de Fri Sep 23 05:31:30 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Sep 2011 11:31:30 +0200 Subject: extending class References: <4E7C4D6A.8050107@gmail.com> Message-ID: Andrea Crotti wrote: > I wanted to add a couple of parameters to a class from a given library > (paste-script), but without changing the original code. > So I thought, I create a wrapper class which adds what I need, and then > dispatch all the calls to the super class. > > My following attempt gives, however, a recursion error, but why? Inside __getattribute__() you ask for self.first_var which triggers another __getattribute__() call that once again trys to determine the first_var attribute before it returns... Try using __getattr__() instead which is only triggered for non-existent attributes def __getattr__(self, name): return getattr(self.first_var, name) or check for the attributes you don't want to delegate explicitly: def __getattribute__(self, name): if name == "first_var": return super(PSIVar, self).__getattribute__(name) return getattr(self.first_var, name) > class PSIVar(object): > """Extend var implementation from the paste-script, to add the > ability of correlating variables > >>> v = var("name", "desc") > >>> v.name == 'name' > True > >>> v1 = PSIVar(v) > >>> v1.name == 'name' > True > """ > def __init__(self, first_var, other=None, fun=None): > # this is of type defined there > self.first_var = first_var > if other is not None: > self.other = other > self.fun = fun > assert callable(self.fun) > > # now try to dispatch every method call to the other class > # must probably call the super class > def __getattribute__(self, attr): > return self.first_var.__getattribute__(attr) From andrea.crotti.0 at gmail.com Fri Sep 23 05:35:49 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 10:35:49 +0100 Subject: extending class In-Reply-To: References: <4E7C4D6A.8050107@gmail.com> Message-ID: <4E7C52F5.5060301@gmail.com> On 09/23/2011 10:31 AM, Peter Otten wrote: > > Inside __getattribute__() you ask for self.first_var which triggers another > __getattribute__() call that once again trys to determine the first_var > attribute before it returns... > > Try using __getattr__() instead which is only triggered for non-existent > attributes > > def __getattr__(self, name): > return getattr(self.first_var, name) > > or check for the attributes you don't want to delegate explicitly: > > def __getattribute__(self, name): > if name == "first_var": > return super(PSIVar, self).__getattribute__(name) > Right thanks a lot it works perfectly. I don't like too much, however, to mess around in this way, maybe it's better if I just fork the project and patch the original code. In this way maybe I can also contribute to it with patches (if they are accepted)... From mateusz at loskot.net Fri Sep 23 05:54:43 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Fri, 23 Sep 2011 10:54:43 +0100 Subject: PyEval_EvalCodeEx return value In-Reply-To: <4E7BC900.9010103@gmail.com> References: <4E786C42.3050309@loskot.net> <4E7BC900.9010103@gmail.com> Message-ID: <4E7C5763.3060106@loskot.net> On 23/09/11 00:47, Mark Hammond wrote: > On 20/09/2011 8:34 PM, Mateusz Loskot wrote: >> >> I'm trying to dig out details about what exactly is the return >> value the of PyEval_EvalCodeEx function in Python 3.x >> The documentation is sparse, unfortunately. >> >> Perhaps I'm looking at wrong function. >> My aim is simple, I need to execute Python code using Python interpreter >> embedded in my C++ application. >> The Python code is a simple script that always returns single value. >> For example: >> >> #! /usr/bin/env python >> def foo(a, b): >> return a + b >> f = foo(2, 3) >> >> But, f can be of different type for different script: one returns >> numeric value, another returns a sequence, so the type is not >> possible to be determined in advance. >> >> I know how to capture Python stdout/stderr. >> >> I also know how to access the "f" attribute using >> PyObject_GetAttrString and then I can convert "f" value to C++ type >> depending on PyObject type. >> >> However, I guess there shall be a way to access "f" value >> directly from PyEval_EvalCode return object: >> >> PyObject* evalRet = ::PyEval_EvalCode(...); >> >> But, I can't find any details what the "evalRet" actually is. > > Eval is to eval an expression. If you simply eval the expression "f" in > the context of the module you should get the result returned. Obviously > though it is designed to eval more complex expressions and in your > specific example, doing the getattr thing will also work fine. Hi Mark, So, the result of PyEval_EvalCode strictly depends on the code being evaluated. It makes sense. Thanks for help! Best regards, -- Mateusz Loskot, http://mateusz.loskot.net Charter Member of OSGeo, http://osgeo.org Member of ACCU, http://accu.org From gelonida at gmail.com Fri Sep 23 06:23:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Fri, 23 Sep 2011 12:23:57 +0200 Subject: cProfile and name spaces. Message-ID: Hi I have following piece of code in file f1.py ##### f1.py starts here ####### def f(): pass def main(): import profile profile.run('f()') if __name__ == '__main__': main() # ------ end of f1.py ---- executing f1.py works as expected. Now I have a file f2.py ##### f2.py starts here ####### import f1 f1.main() # ------ end of f2.py ---- If I run f2.py I get the error message: . . . . > File "C:\Python26\lib\profile.py", line 70, in run > prof = prof.run(statement) > File "C:\Python26\lib\profile.py", line 456, in run > return self.runctx(cmd, dict, dict) > File "C:\Python26\lib\profile.py", line 462, in runctx > exec cmd in globals, locals > File "", line 1, in > NameError: name 'f' is not defined So cProfile doesn't find my function f any more. I can fix this by changing the code in f1.py to profile.run('f1.f()') However now I can't run f1.py anymore. Is it intentional, that cProfile always uses the name space of the initial module? I consider it surprising especially as I did not find any mentioning of this particularity in the documentation, which states: > cProfile.run(command[, filename]) > > This function takes a single argument that can be passed to the exec > statement, and an optional file name. In all cases this routine attempts > to exec its first argument, and gather profiling statistics from the > execution. If no file name is present, then this function automatically > prints a simple profiling report, sorted by the standard name string > (file/line/function-name) that is presented in each line. The following > is a typical output from such a call: I'm using python 2.6.5 The reason why I don't profile at the top level is, that I do not want to profile some parts of the code and as I want to conditionally profile a cetain function within different contexts / applications WI have also difficulties implementing something like this in a module, which is not the main module. arg1 = f(1) arg2 = f2() if do_profile: CProfile('result = function_name(arg1, arg2)', fname) else: result = function_name(arg1, arg2) Any tips / suggestions?? From andrea.crotti.0 at gmail.com Fri Sep 23 07:02:00 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 12:02:00 +0100 Subject: Develop inter-dependent eggs Message-ID: <4E7C6728.7040500@gmail.com> Develop inter-dependent eggs: On a Linux machine I have many eggs to develop, for example - egg1 - egg2 ... Now the eggs depend from each other, so running "python setup.py develop" in order, doesn't work, because if the dependency required is not already installed then easy_install tries to fetch it from PyPi. I looked around everywhere, but I can't find any feasible option, how do I tell easy_install to install the dependencies needed from a filesystem position and not from the PyPi server? From yasar11732 at gmail.com Fri Sep 23 07:44:27 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Fri, 23 Sep 2011 14:44:27 +0300 Subject: Need help with file encoding-decoding Message-ID: Hi, I'am trying to write a mass html downloader, and it processes files after it downloaded them. I have problems with encodings, and decodings. Sometimes I get UnicodeDecodeErrors, or I get half-pages in after processing part. Or more generally, some things don't feel right. Can you check my approach, and provide me some feedback please? Here is what I am doing. 1) send a HEAD request to file's source to get file encoding, set encoding variable accordingly. 2) if server doesn't provide an encoding, set encoding variable as utf-8 3) read html page from internet, read it to a variable let's say content. 4) in this step, I need to parse the content I get, because I will search for further links \ I feed content to parser (subclass of HTMLParser.HTMLParser) like this -> content.decode(encoding) 5) open a file in binary mod open(file_path,"wb") 6) I write as I read without modifing. ########## # After processing part.... ########## (Note: encoding variable is same as the downloading part) 1) open local file in binary mod for reading file_name = open(file_path,"rb") 2) decode the file contents into a variable => decoded_content = file_name.read().decode(encoding) 3) send decoded content to a parser, parser contstruct new html content. (as str) 4) open same file for writing, in binary mod, write parsers output like this: file_name.write(parser.output.encode(encoding)) -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Fri Sep 23 07:52:40 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 12:52:40 +0100 Subject: [TIP] TestFixtures 2.0.0 Released! In-Reply-To: <4E7C3961.8020107@simplistix.co.uk> References: <4E7C3961.8020107@simplistix.co.uk> Message-ID: <4E7C7308.7020709@simplistix.co.uk> On 23/09/2011 08:46, Chris Withers wrote: > I'm happy to announce a new release major release of TestFixtures. > This release is 99% backwards compatible, but a lot has changed under > the hood and there's some major new functionality, so thought it was > time for a bump. Of course, a 2.0.0 release wouldn't be complete without a fairly show-stopping lack of backwards compatibility... Thankfully, I've managed to return the case (comparison of generators with iterators) to its previous state with the 2.0.1 release I've just pushed out... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From python at bdurham.com Fri Sep 23 08:09:40 2011 From: python at bdurham.com (python at bdurham.com) Date: Fri, 23 Sep 2011 08:09:40 -0400 Subject: python install on locked down windows box? In-Reply-To: References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1316779780.12406.140258146888625@webmail.messagingengine.com> Hi Matt, Enjoyed your list options :) I'm a consultant and have to do what your subject line asks at most clients I work at. Here's the technique I recommend: Install Python for the ***current user*** on another workstation with the appropriate priviledges. Then xcopy this Python folder to a USB drive. Then xcopy this folder from your USB drive to a matching folder on your locked down workstation. The xcopy-ed version of Python will run without problems when you start the python.exe executable from a command line with a python script as a command line parameter. The only thing you won't be able to do is click on .py* files and have them automatically invoke the Python interpreter because file associations require admin rights to update the registery. I don't consider this a big deal. Good luck! Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Fri Sep 23 09:14:15 2011 From: philip at semanchuk.com (Philip Semanchuk) Date: Fri, 23 Sep 2011 09:14:15 -0400 Subject: Need help with file encoding-decoding In-Reply-To: References: Message-ID: <6CE93FA9-E24F-4FB7-ABA2-24F2F611978A@semanchuk.com> On Sep 23, 2011, at 7:44 AM, Ya?ar Arabac? wrote: > Hi, > > I'am trying to write a mass html downloader, and it processes files after it > downloaded them. I have problems with encodings, and decodings. Sometimes I > get UnicodeDecodeErrors, or > I get half-pages in after processing part. Or more generally, some things > don't feel right. Can you check my approach, and provide me some feedback > please? Here is what I am doing. > > 1) send a HEAD request to file's source to get file encoding, set encoding > variable accordingly. Hi Ya?ar This is a pretty optimistic algorithm, at least by the statistics from 2008 (see below). > 2) if server doesn't provide an encoding, set encoding variable as utf-8 This is statistically a good guess but it doesn't follow the HTTP specification. > 4) in this step, I need to parse the content I get, because I will search > for further links \ > I feed content to parser (subclass of HTMLParser.HTMLParser) like Does HTMLParser.HTMLParser handle broken HTML? Because there's lots of it out there. I used to run an automated site validator, and I wrote a couple of articles you might find interesting. One is about how to get the encoding of a Web page: http://NikitaTheSpider.com/articles/EncodingDivination.html I also wrote an article examining the statistics I'd seen run through the crawler/validator. One thing I saw was that almost 2/3 of Web pages specified the encoding in the META HTTP-EQUIV Content-Type tag rather than in the HTTP Content-Type header. Mind you, this was three years ago so the character of the Web has likely changed since then, but probably not too dramatically. http://NikitaTheSpider.com/articles/ByTheNumbers/fall2008.html You can also do some straightforward debugging. Save the raw bytes you get from each site, and when you encounter a decode error, check the raw bytes. Are they really in the encoding specified? Webmasters make all kinds of mistakes. Hope this helps Philip > this -> content.decode(encoding) > 5) open a file in binary mod open(file_path,"wb") > 6) I write as I read without modifing. > > ########## > # After processing part.... > ########## > > (Note: encoding variable is same as the downloading part) > > 1) open local file in binary mod for reading file_name = > open(file_path,"rb") > 2) decode the file contents into a variable => decoded_content = > file_name.read().decode(encoding) > 3) send decoded content to a parser, parser contstruct new html content. (as > str) > 4) open same file for writing, in binary mod, write parsers output like > this: file_name.write(parser.output.encode(encoding)) > -- > http://yasar.serveblog.net/ > -- > http://mail.python.org/mailman/listinfo/python-list From jeanmichel at sequans.com Fri Sep 23 09:17:53 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 23 Sep 2011 15:17:53 +0200 Subject: extending class In-Reply-To: <4E7C52F5.5060301@gmail.com> References: <4E7C4D6A.8050107@gmail.com> <4E7C52F5.5060301@gmail.com> Message-ID: <4E7C8701.5020302@sequans.com> Andrea Crotti wrote: > On 09/23/2011 10:31 AM, Peter Otten wrote: >> >> Inside __getattribute__() you ask for self.first_var which triggers >> another >> __getattribute__() call that once again trys to determine the first_var >> attribute before it returns... >> >> Try using __getattr__() instead which is only triggered for non-existent >> attributes >> >> def __getattr__(self, name): >> return getattr(self.first_var, name) >> >> or check for the attributes you don't want to delegate explicitly: >> >> def __getattribute__(self, name): >> if name == "first_var": >> return super(PSIVar, self).__getattribute__(name) >> > > Right thanks a lot it works perfectly. > I don't like too much, however, to mess around in this way, maybe it's > better if I just fork the project > and patch the original code. > > In this way maybe I can also contribute to it with patches (if they > are accepted)... Did you consider subclassing your Var class ? This is how you extend a class behavior in OOP. class PSIVar(var): def __init__(self, name, desc, other=None, fun=None): var.__init__(self, name, desc) if other is not None: self.other = other self.fun = fun assert callable(self.fun) v1 = PSIVar('name', 'desc') that's it. By the way, don't create instance attribute conditionally. Your PSIVar instance should always have a 'other' attribute, its value can be None though. JM From bahamutzero8825 at gmail.com Fri Sep 23 09:57:32 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Fri, 23 Sep 2011 08:57:32 -0500 Subject: Odd behavior with imp.reload and logging In-Reply-To: References: <4e7ab80f$0$30000$c3e8da3$5496439d@news.astraweb.com> <4E7ABDFB.5020509@gmail.com> <4E7ACD82.4080302@gmail.com> <4E7AEAEE.20504@gmail.com> Message-ID: <4E7C904C.3020604@gmail.com> On 2011.09.22 03:12 AM, Chris Angelico wrote: > In theory, this should mean that you load it fresh every time - I > think. If not, manually deleting entries from sys.modules might help, > either with or without the list of modules. I've played around with sys.modules, and it seems there are issues with logging being reloaded (not sure if it's fair to call it a bug), not my module. The only reliable way I've found to start fresh is to delete at least logging from sys.modules (I can even do this from within my module). Even if the module that imports logging is deleted, things in logging persist (I can confirm at least handlers and handles to log files; the latter requiring garbage collection as well to free up). However, this would probably wreak havoc on other code that uses logging (although, I could always import logging as something else). On a side note, this actually gives me a good way to detect that the module is reloaded (I can't think of any other way to detect it, at least not off the top of my head). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 6.0.2 From andrea.crotti.0 at gmail.com Fri Sep 23 09:59:56 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Fri, 23 Sep 2011 14:59:56 +0100 Subject: extending class In-Reply-To: <4E7C8701.5020302@sequans.com> (Jean-Michel Pichavant's message of "Fri, 23 Sep 2011 15:17:53 +0200") References: <4E7C4D6A.8050107@gmail.com> <4E7C52F5.5060301@gmail.com> <4E7C8701.5020302@sequans.com> Message-ID: <87pqirnyub.fsf@gmail.com> Jean-Michel Pichavant writes: > Did you consider subclassing your Var class ? This is how you extend a > class behavior in OOP. > > class PSIVar(var): > def __init__(self, name, desc, other=None, fun=None): > var.__init__(self, name, desc) > if other is not None: > self.other = other > self.fun = fun > assert callable(self.fun) > > v1 = PSIVar('name', 'desc') > > that's it. > > By the way, don't create instance attribute conditionally. Your PSIVar > instance should always have a 'other' attribute, its value can be None > though. > > > > JM Yes thanks, first I tried that, but I didn't want to have to change my class definition if the one from the library changes. So I started to mess with *args and **kwargs and it was really not beautiful ;) Anyway since I want to other and more deep changes I just forked the project and start work on that... From gmszone at gmail.com Fri Sep 23 10:01:27 2011 From: gmszone at gmail.com (gmszone) Date: Fri, 23 Sep 2011 07:01:27 -0700 (PDT) Subject: Could anybody tell me how to make a version of Nokia Symbian os Message-ID: <9e03e15b-4d1e-4af7-8e80-751ab9e2f35f@f12g2000yqi.googlegroups.com> I like the Python in my mobile phone.But a don't have the enough money to buy a new phone.And my mobile type is Nokia N72 which is a part of S60v2.And I could program in some boring classes.But the version of my mobile's python is to old.So I hope I coule learn how to compile it for my N72.My notebook has the Windows 7 and Ubuntu GNU/Linux.Ask for help..... From steve+comp.lang.python at pearwood.info Fri Sep 23 10:21:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 00:21:53 +1000 Subject: extending class References: Message-ID: <4e7c9602$0$30000$c3e8da3$5496439d@news.astraweb.com> Andrea Crotti wrote: > I wanted to add a couple of parameters to a class from a given library > (paste-script), but without changing the original code. > So I thought, I create a wrapper class which adds what I need, and then > dispatch all the calls to the super class. You don't need to use a wrapper class if all you want is to add additional attributes to an instance. >>> class Spam(object): ... def __init__(self): ... self.x = 1 ... >>> s = Spam() >>> s.name = "Fred" >>> s.name 'Fred' > My following attempt gives, however, a recursion error, but why? Here is an old recipe showing how to do automatic delegation correctly: http://code.activestate.com/recipes/52295/ -- Steven From w.g.sneddon at gmail.com Fri Sep 23 10:25:55 2011 From: w.g.sneddon at gmail.com (python) Date: Fri, 23 Sep 2011 07:25:55 -0700 (PDT) Subject: pyWin build 216 Message-ID: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> I have used pyWin for several years now with out issue. I recently installed build 216 for python 2.7 on windows XP pro. The program crashes every time I exit a wxPython program and has crashed a few other times. I does not seem that pyWin has been updated since February of this year. Is there a direction change for the windows extensions? Is it time I make the move to 3.x? Mark Hammond has given much to the Python community and I do not intend for this post to be negative in any way. From atherun at gmail.com Fri Sep 23 10:58:07 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 07:58:07 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: <5bd0c088-0f46-4e4a-b5c5-9d8de668b50d@v18g2000yqj.googlegroups.com> On Sep 23, 12:08?am, Chris Angelico wrote: > On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > > It doesn't even > > You intrigue me, sir. Does it odd? > > What is the remainder of this aborted sentence? > > ChrisA That is odd, I also find it odd that it deadlocks the entire python system, even threads that have nothing to do with the subprocess stop working, the entire thing just stops. I may not have pasted the full stack trace looking at it again, I'll double check in a few. I was able to repro this on a tool I have the source for, when I attach to it to debug visual studio tells me the threads are deadlocked and the only stack trace I have available to me is a low level os call to a WriteFile function. From brian.curtin at gmail.com Fri Sep 23 11:01:04 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Fri, 23 Sep 2011 10:01:04 -0500 Subject: pyWin build 216 In-Reply-To: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: On Fri, Sep 23, 2011 at 09:25, python wrote: > I have used pyWin for several years now with out issue. ? I recently > installed build 216 for python 2.7 on windows XP pro. ? The program > crashes every time I exit a wxPython program and has crashed a few > other times. ?I does not seem that pyWin has been updated since > February of this year. ? Is there a direction change for the windows > extensions? ?Is it time I make the move to 3.x? ?Mark Hammond has > given much to the Python community and I do not intend for this post > to be negative in any way. pywin32 has been available for 3.x for some time, but you wouldn't be able to use it since you're currently using wxPython. You may want to post a more detailed question to http://mail.python.org/mailman/listinfo/python-win32 -- Mark hangs out there and there are plenty of pywin32 experts around who could help as well. From jesus.ramirez.utexas at gmail.com Fri Sep 23 11:41:59 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 08:41:59 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Python 2.5.6 (r256:88840, Sep 22 2011, 13:45:58) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import zlib Traceback (most recent call last): File "", line 1, in ImportError: No module named zlib >>> But if I run Python2.7 I get: Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import zlib >>> It seems to work. From chris at simplistix.co.uk Fri Sep 23 13:06:19 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 23 Sep 2011 18:06:19 +0100 Subject: python install on locked down windows box? In-Reply-To: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> References: <4e7b30da$0$29976$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E7CBC8B.8000501@simplistix.co.uk> Hi Steve On 22/09/2011 13:58, Steven D'Aprano wrote: > (7) If all else fails, as an absolute last resort, simply run the Windows > installer as a regular, unprivileged user, after selecting the option for a > Non-Admin Install under Advanced Options first. Thanks for this, will send on to my friend in need... Hadn't seen this before, but it's a long time since I've run the Windows installer ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From atherun at gmail.com Fri Sep 23 13:07:56 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 10:07:56 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <5bd0c088-0f46-4e4a-b5c5-9d8de668b50d@v18g2000yqj.googlegroups.com> Message-ID: <7133358a-3fd0-4dfd-8af7-d8afaa9c6597@z7g2000vbp.googlegroups.com> On Sep 23, 7:58?am, Atherun wrote: > On Sep 23, 12:08?am, Chris Angelico wrote: > > > On Fri, Sep 23, 2011 at 3:59 PM, Nobody wrote: > > > It doesn't even > > > You intrigue me, sir. Does it odd? > > > What is the remainder of this aborted sentence? > > > ChrisA > > That is odd, I also find it odd that it deadlocks the entire python > system, even threads that have nothing to do with the subprocess stop > working, the entire thing just stops. I may not have pasted the full > stack trace looking at it again, I'll double check in a few. > > I was able to repro this on a tool I have the source for, when I > attach to it to debug visual studio tells me the threads are > deadlocked and the only stack trace I have available to me is a low > level os call to a WriteFile function. Ya heres the full python stack: ntoskrnl.exe!memset+0x64a ntoskrnl.exe!KeWaitForMultipleObjects+0xd52 ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!__misaligned_access+0xba4 ntoskrnl.exe!__misaligned_access+0x1821 ntoskrnl.exe!KeWaitForMultipleObjects+0xf5d ntoskrnl.exe!KeWaitForMutexObject+0x19f ntoskrnl.exe!NtWaitForSingleObject+0xde ntoskrnl.exe!KeSynchronizeExecution+0x3a43 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x6c0 wow64cpu.dll!TurboDispatchJumpAddressEnd+0x4a8 wow64.dll!Wow64SystemServiceEx+0x1ce wow64.dll!Wow64LdrpInitialize+0x429 ntdll.dll!RtlUniform+0x6e6 ntdll.dll!RtlCreateTagHeap+0xa7 ntdll.dll!LdrInitializeThunk+0xe ntdll.dll!ZwWaitForSingleObject+0x15 kernel32.dll!WaitForSingleObjectEx+0x43 kernel32.dll!WaitForSingleObject+0x12 python26.dll!_Py_svnversion+0xcf8 python26.dll!PyObject_AsReadBuffer+0x46d python26.dll!PyEval_EvalCodeEx+0x738 python26.dll!PyEval_EvalFrameEx+0x467 python26.dll!PyObject_Realloc+0x90 python26.dll!PyEval_EvalCodeEx+0x8ef python26.dll!PyEval_EvalFrameEx+0x467 From msoulier at digitaltorque.ca Fri Sep 23 13:15:25 2011 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Fri, 23 Sep 2011 13:15:25 -0400 Subject: ANN: Urwid 1.0.0 - Console UI Library In-Reply-To: <4E7B4E9C.7060704@excess.org> References: <4E7B4E9C.7060704@excess.org> Message-ID: <20110923171525.GH2703@digitaltorque.ca> On 22/09/11 Ian Ward said: > Announcing Urwid 1.0.0 > ---------------------- Congrats. From nobody at nowhere.com Fri Sep 23 13:47:20 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 23 Sep 2011 18:47:20 +0100 Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: >> kernel32.dll!WaitForSingleObject+0x12 >> python26.dll!_Py_svnversion+0xcf8 > > I haven't a clue how this happens. _Py_svnversion just returns a string: In retrospect, I think that's a red herring. 0xcf8 seems like too large an offset for such a small function. I think that it's more likely to be in a non-exported function, and _Py_svnversion just happens to be the last exported symbol prior to that point in the code. From atherun at gmail.com Fri Sep 23 13:59:27 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 10:59:27 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> Message-ID: <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> On Sep 23, 10:47?am, Nobody wrote: > On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: > >> kernel32.dll!WaitForSingleObject+0x12 > >> python26.dll!_Py_svnversion+0xcf8 > > > I haven't a clue how this happens. _Py_svnversion just returns a string: > > In retrospect, I think that's a red herring. 0xcf8 seems like too large an > offset for such a small function. I think that it's more likely to be in a > non-exported function, and _Py_svnversion just happens to be the last > exported symbol prior to that point in the code. I have the call stacks for each python thread running up until the dead lock: # ThreadID: 992 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 5516 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) # ThreadID: 2668 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in run self.stacktraces() File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in stacktraces fout.write(stacktraces()) File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in stacktraces for filename, lineno, name, line in traceback.extract_stack(stack): # ThreadID: 3248 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 7700 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) # ThreadID: 8020 out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() # ThreadID: 4252 File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) The StackTracer thread freezes trying to update my output file, and yes I'm trying to 3 tasks in parallel which each one starts by creating a changelist in perforce. This is just an easy repro case for me, it happens with commands other then p4. This almost looks like a threading issue more then the output deadlock. From luch at ank-sia.com Fri Sep 23 14:21:56 2011 From: luch at ank-sia.com (Alexey Luchko) Date: Fri, 23 Sep 2011 21:21:56 +0300 Subject: comments on runpy module Message-ID: <4E7CCE44.8030508@ank-sia.com> Hi! I've just had fun with the runpy module in Python 2.7. I'm writing to share it :) What I've tried is to "load" a python script using runpy.run_path(), take a function from the resulting namespace and call it with arbitrary arguments. All the functions in the namespace seem to be ok. repr(namespace["f"]) gives "". But if the f() is referring the modules namespace (I supposed it is the same as the returned one), all the values appear to be None. Example script.py: """ def f(arg): return g(arg) def g(arg): return arg """ Then running main.py: """ import runpy namespace = runpy.run_path("./script.py") print namespace["f"] print namespace["g"] print namespace["f"]("abc") """ gives such an output """ Traceback (most recent call last): File "main.py", line 7, in print namespace["f"]("abc") File "./script.py", line 2, in f return g(arg) TypeError: 'NoneType' object is not callable """ Reading the Lib/runpy.py I've found, that the temporary module created inside the run_path() calls, is destroyed right after the script.py code executed in the resulting namespace. I suppose that it is ether an issue or a feature that should be documented :) -- Have a good time and a good mood! Alex. From luch at ank-sia.com Fri Sep 23 14:38:36 2011 From: luch at ank-sia.com (Alexey Luchko) Date: Fri, 23 Sep 2011 21:38:36 +0300 Subject: comments on runpy module In-Reply-To: <4E7CCE44.8030508@ank-sia.com> References: <4E7CCE44.8030508@ank-sia.com> Message-ID: <4E7CD22C.5040308@ank-sia.com> > Example script.py: """ > def f(arg): > return g(arg) > > def g(arg): > return arg > """ > Reading the Lib/runpy.py I've found, that the temporary module created > inside the run_path() calls, is destroyed right after the script.py code > executed in the resulting namespace. I've got an idea. It would be nice if there existed such a way to use it: with runpy.run_path("script.py") as a_namespace: a_namespace["f"]("abc") -- Regards, Alex. From Phillip.M.Feldman at gmail.com Fri Sep 23 16:09:32 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Fri, 23 Sep 2011 13:09:32 -0700 (PDT) Subject: strange behavior from recursive generator Message-ID: <32503886.post@talk.nabble.com> A few weeks ago, I wrote a class that creates an iterator for solving the general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert converted my code to a generator, which made the code cleaner, and I subsequently simplified it somewhat further. My problem is the following: All of these versions of the code work fine for very small problems, but do not produce the full set of occupancy distributions for larger problems. The following sample input and output show what happens with two balls and two boxes (to keep things simple, I've made the boxes large enough so that each box can hold both balls). In [6]: x= balls_in_labeled_boxes(2,[2,2]) In [7]: list(x) balls=2, box_sizes=[2, 2] About to make recursive call. balls_in_other_boxes=0, box_sizes=[2] i=0, distribution_other=(0,) About to make recursive call. balls_in_other_boxes=1, box_sizes=[2] i=0, distribution_other=(1,) About to make recursive call. balls_in_other_boxes=2, box_sizes=[2] i=0, distribution_other=(2,) Out[7]: [(2, 0), (1, 1), (0, 2)] Note that Out[7] above gives the correct result, showing all three possible distributions. Now lets try the same thing with three boxes. In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) In [9]: list(x) balls=2, box_sizes=[2, 2, 2] About to make recursive call. balls_in_other_boxes=0, box_sizes=[2, 2] i=0, distribution_other=(0, 0) About to make recursive call. balls_in_other_boxes=1, box_sizes=[2, 2] i=0, distribution_other=(1, 0) About to make recursive call. balls_in_other_boxes=2, box_sizes=[2, 2] i=0, distribution_other=(2, 0) i=1, distribution_other=(1, 1) Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] When there are no balls in the initial box, the recursive call should produce the same three occupancy distributions that we saw above, but one of them is now missing. If someone can shed light on why this is happening, I'd be grateful. Phillip http://old.nabble.com/file/p32503886/balls_in_labeled_boxes.py balls_in_labeled_boxes.py -- View this message in context: http://old.nabble.com/strange-behavior-from-recursive-generator-tp32503886p32503886.html Sent from the Python - python-list mailing list archive at Nabble.com. From arnodel at gmail.com Fri Sep 23 16:26:13 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Fri, 23 Sep 2011 21:26:13 +0100 Subject: strange behavior from recursive generator In-Reply-To: <32503886.post@talk.nabble.com> References: <32503886.post@talk.nabble.com> Message-ID: On 23 September 2011 21:09, Dr. Phillip M. Feldman wrote: > > A few weeks ago, I wrote a class that creates an iterator for solving the > general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert > converted my code to a generator, which made the code cleaner, and I > subsequently simplified it somewhat further. > > My problem is the following: All of these versions of the code work fine for > very small problems, but do not produce the full set of occupancy > distributions for larger problems. The following sample input and output > show what happens with two balls and two boxes (to keep things simple, I've > made the boxes large enough so that each box can hold both balls). > > In [6]: x= balls_in_labeled_boxes(2,[2,2]) > > In [7]: list(x) > balls=2, box_sizes=[2, 2] > About to make recursive call. ?balls_in_other_boxes=0, box_sizes=[2] > i=0, distribution_other=(0,) > About to make recursive call. ?balls_in_other_boxes=1, box_sizes=[2] > i=0, distribution_other=(1,) > About to make recursive call. ?balls_in_other_boxes=2, box_sizes=[2] > i=0, distribution_other=(2,) > Out[7]: [(2, 0), (1, 1), (0, 2)] > > Note that Out[7] above gives the correct result, showing all three possible > distributions. Now lets try the same thing with three boxes. > > In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) > > In [9]: list(x) > balls=2, box_sizes=[2, 2, 2] > About to make recursive call. ?balls_in_other_boxes=0, box_sizes=[2, 2] > i=0, distribution_other=(0, 0) > About to make recursive call. ?balls_in_other_boxes=1, box_sizes=[2, 2] > i=0, distribution_other=(1, 0) > About to make recursive call. ?balls_in_other_boxes=2, box_sizes=[2, 2] > i=0, distribution_other=(2, 0) > i=1, distribution_other=(1, 1) > Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] > > When there are no balls in the initial box, the recursive call should > produce the same three occupancy distributions that we saw above, but one of > them is now missing. If someone can shed light on why this is happening, I'd > be grateful. Line 46: for distribution_other in _balls_in_unlabeled_boxes( Should be: for distribution_other in _balls_in_labeled_boxes( HTH -- Arnaud From lists at cheimes.de Fri Sep 23 17:20:44 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 23 Sep 2011 23:20:44 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Message-ID: Am 23.09.2011 17:41, schrieb Jesramz: > Python 2.5.6 (r256:88840, Sep 22 2011, 13:45:58) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import zlib > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named zlib Are you running a self-compiled installation of Python 2.5 on recent Debian or Ubuntu? Check out my blog http://lipyrary.blogspot.com/2011/05/how-to-compile-python-on-ubuntu-1104.html Christian From jesus.ramirez.utexas at gmail.com Fri Sep 23 17:34:16 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 14:34:16 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> Message-ID: <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Thank You Christian Im running on Ubuntu Natty and I am not running a self-compiled install, its a regular release. In order to do this: $ make distclean $ export LDFLAGS="-L/usr/lib/$(dpkg-architecture - qDEB_HOST_MULTIARCH)" $ ./configure $ make $ make install $ unset LDFLAGS If you can, can you explain the steps for this, can I run this in a regular release of Python2.5? From phillip.m.feldman at gmail.com Fri Sep 23 19:42:13 2011 From: phillip.m.feldman at gmail.com (Phillip Feldman) Date: Fri, 23 Sep 2011 16:42:13 -0700 Subject: strange behavior from recursive generator In-Reply-To: References: <32503886.post@talk.nabble.com> Message-ID: I don't know how many times I stared at that code without seeing the error. Thanks so much! Phillip On Fri, Sep 23, 2011 at 1:26 PM, Arnaud Delobelle wrote: > On 23 September 2011 21:09, Dr. Phillip M. Feldman > wrote: > > > > A few weeks ago, I wrote a class that creates an iterator for solving the > > general unlabeled-balls-in-labeled boxes occupancy problem. Chris Rebert > > converted my code to a generator, which made the code cleaner, and I > > subsequently simplified it somewhat further. > > > > My problem is the following: All of these versions of the code work fine > for > > very small problems, but do not produce the full set of occupancy > > distributions for larger problems. The following sample input and output > > show what happens with two balls and two boxes (to keep things simple, > I've > > made the boxes large enough so that each box can hold both balls). > > > > In [6]: x= balls_in_labeled_boxes(2,[2,2]) > > > > In [7]: list(x) > > balls=2, box_sizes=[2, 2] > > About to make recursive call. balls_in_other_boxes=0, box_sizes=[2] > > i=0, distribution_other=(0,) > > About to make recursive call. balls_in_other_boxes=1, box_sizes=[2] > > i=0, distribution_other=(1,) > > About to make recursive call. balls_in_other_boxes=2, box_sizes=[2] > > i=0, distribution_other=(2,) > > Out[7]: [(2, 0), (1, 1), (0, 2)] > > > > Note that Out[7] above gives the correct result, showing all three > possible > > distributions. Now lets try the same thing with three boxes. > > > > In [8]: x= balls_in_labeled_boxes(2,[2,2,2]) > > > > In [9]: list(x) > > balls=2, box_sizes=[2, 2, 2] > > About to make recursive call. balls_in_other_boxes=0, box_sizes=[2, 2] > > i=0, distribution_other=(0, 0) > > About to make recursive call. balls_in_other_boxes=1, box_sizes=[2, 2] > > i=0, distribution_other=(1, 0) > > About to make recursive call. balls_in_other_boxes=2, box_sizes=[2, 2] > > i=0, distribution_other=(2, 0) > > i=1, distribution_other=(1, 1) > > Out[9]: [(2, 0, 0), (1, 1, 0), (0, 2, 0), (0, 1, 1)] > > > > When there are no balls in the initial box, the recursive call should > > produce the same three occupancy distributions that we saw above, but one > of > > them is now missing. If someone can shed light on why this is happening, > I'd > > be grateful. > > Line 46: > > for distribution_other in _balls_in_unlabeled_boxes( > > Should be: > > > for distribution_other in _balls_in_labeled_boxes( > > HTH > > -- > Arnaud > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Fri Sep 23 20:07:54 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 24 Sep 2011 12:07:54 +1200 Subject: Context manager with class methods In-Reply-To: References: <33427117.1421.1316686888275.JavaMail.geo-discussion-forums@yqog21> Message-ID: <9e4lasFv7sU1@mid.individual.net> Terry Reedy wrote: > it is normal to look for special methods on the class (and superclasses) > of an object rather than starting with the object itself. > I suspect there was a deliberate change to correct an anomaly, though > this might have been done as part of some other change. It's a necessary consequence of the fact that new-style classes are also instances. Without it, there would be an ambiguity as to whether a special method defined the behaviour of instances of a class or of the class object itself. It also increases efficiency, because for those special methods that correspond to C-level type slots, you only have to look in the type slot to find an implementation of the method, rather than having to look in the instance dict first. -- Greg From alec.taylor6 at gmail.com Fri Sep 23 20:53:06 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 24 Sep 2011 10:53:06 +1000 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: No idea, as I said before, if you ask for it they might put in the alpha. On Sat, Sep 24, 2011 at 8:30 AM, Jesse Ramirez wrote: > > Thanks Alec, might you know when the 2.7 support might come? From jesus.ramirez.utexas at gmail.com Fri Sep 23 21:19:39 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Fri, 23 Sep 2011 18:19:39 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> Message-ID: <5f064e18-57ab-4a7a-b855-e212bb84711d@l4g2000vbz.googlegroups.com> Thank You Christian Im running on Ubuntu Natty and I am not running a self-compiled install, its a regular release. In order to do this: $ make distclean $ export LDFLAGS="-L/usr/lib/$(dpkg-architecture - qDEB_HOST_MULTIARCH)" $ ./configure $ make $ make install $ unset LDFLAGS If you can, can you explain the steps for this, can I run this in a regular release of Python2.5? From ricky85.phone at gmail.com Fri Sep 23 21:42:44 2011 From: ricky85.phone at gmail.com (Ricardo) Date: Fri, 23 Sep 2011 20:42:44 -0500 Subject: can't load an script from html... Message-ID: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Hi everyone I'm trying to use the cgi library to create a python script and loading it from a web page. I have already done the necessary imports, and the default commands to receive data from "html" are written too. The final version is something like this: #!/usr/bin/python import subprocess import cgi import cgitb cgitb.enable() input = cgi.FieldStorage() ?. my code (do something with input)?. #printing the response print "Content-Type: text/html" print print "My title:" print "" print "" print ?.. bla bla ? print "%s"%theoutput print "" Besides, my call from my index.html is like this:


well, the thing is that when i do the call from the browser: http://localhost/index.html | V put the data and click on the "accept" button | V http:/localhost/scripts/python_script.py I only get the python_script.py as a plain test by response (the script printed on my browser). I have already changed the permissions for python_script.py. I have checked the import cgi,cgitb in the python shell (i am using v2.7) and they work fine. So, i don't know what it is going wrong here. A little help please? any idea? Thanks anyway for your time. From python at mrabarnett.plus.com Fri Sep 23 21:57:37 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 02:57:37 +0100 Subject: can't load an script from html... In-Reply-To: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> References: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Message-ID: <4E7D3911.9030803@mrabarnett.plus.com> On 24/09/2011 02:42, Ricardo wrote: > Hi everyone > I'm trying to use the cgi library to create a python script and loading it from a web page. I have already done the necessary imports, and the default commands to receive data from "html" are written too. The final version is something like this: > > #!/usr/bin/python > > import subprocess > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > ?. my code (do something with input)?. > > > #printing the response > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print ?.. bla bla ? > print "%s"%theoutput > print "" > > Besides, my call from my index.html is like this: > >
>

> >
> > well, the thing is that when i do the call from the browser: > > http://localhost/index.html > | > V > put the data and click on the "accept" button > | > V > http:/localhost/scripts/python_script.py > > I only get the python_script.py as a plain test by response (the script printed on my browser). > I have already changed the permissions for python_script.py. I have checked the import cgi,cgitb in the python shell (i am using v2.7) and they work fine. So, i don't know what it is going wrong here. > > A little help please? any idea? > Thanks anyway for your time. > If it helps, the responses on my home-make stuff start something like this: From anacrolix at gmail.com Fri Sep 23 22:03:01 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Sat, 24 Sep 2011 12:03:01 +1000 Subject: Python deadlock using subprocess.popen and communicate In-Reply-To: <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> Message-ID: how do you get the call stacks like this? On Sat, Sep 24, 2011 at 3:59 AM, Atherun wrote: > On Sep 23, 10:47?am, Nobody wrote: >> On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: >> >> kernel32.dll!WaitForSingleObject+0x12 >> >> python26.dll!_Py_svnversion+0xcf8 >> >> > I haven't a clue how this happens. _Py_svnversion just returns a string: >> >> In retrospect, I think that's a red herring. 0xcf8 seems like too large an >> offset for such a small function. I think that it's more likely to be in a >> non-exported function, and _Py_svnversion just happens to be the last >> exported symbol prior to that point in the code. > > I have the call stacks for each python thread running up until the > dead lock: > > # ThreadID: 992 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > # ThreadID: 5516 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > # ThreadID: 2668 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in > run > ?self.stacktraces() > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in > stacktraces > ?fout.write(stacktraces()) > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in > stacktraces > ?for filename, lineno, name, line in traceback.extract_stack(stack): > > # ThreadID: 3248 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > > # ThreadID: 7700 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > # ThreadID: 8020 > ?out, err = proc.communicate("change: new\ndescription: %s > \n"%changelistDesc) > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > communicate > ?return self._communicate(input) > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > _communicate > ?stdout_thread.join() > File: "c:\src\extern\python\lib\threading.py", line 637, in join > ?self.__block.wait() > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > ?waiter.acquire() > > # ThreadID: 4252 > File: "c:\src\extern\python\lib\threading.py", line 497, in > __bootstrap > ?self.__bootstrap_inner() > File: "c:\src\extern\python\lib\threading.py", line 525, in > __bootstrap_inner > ?self.run() > File: "c:\src\extern\python\lib\threading.py", line 477, in run > ?self.__target(*self.__args, **self.__kwargs) > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > _readerthread > ?buffer.append(fh.read()) > > The StackTracer thread freezes trying to update my output file, and > yes I'm trying to 3 tasks in parallel which each one starts by > creating a changelist in perforce. ?This is just an easy repro case > for me, it happens with commands other then p4. ?This almost looks > like a threading issue more then the output deadlock. > -- > http://mail.python.org/mailman/listinfo/python-list > From flt.johnson at gmail.com Fri Sep 23 23:36:05 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 23 Sep 2011 20:36:05 -0700 (PDT) Subject: Why is the shutil module called shutil? Message-ID: The topic says it all: Why is shutil named shutil? What does it stand for? This is just a mild curiosity of mine. The shutil module for reference: http://docs.python.org/library/shutil.html#module-shutil From skippy.hammond at gmail.com Fri Sep 23 23:43:45 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 24 Sep 2011 13:43:45 +1000 Subject: pyWin build 216 In-Reply-To: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: <4E7D51F1.7010209@gmail.com> On 24/09/2011 12:25 AM, python wrote: > I have used pyWin for several years now with out issue. I recently > installed build 216 for python 2.7 on windows XP pro. The program > crashes every time I exit a wxPython program and has crashed a few > other times. There are a number of issues using Pythonwin to run a program which uses a different UI toolkit (eg, wx, Tkinter) and while these have been around for many years I don't plan on trying to fix it. IOW, "don't do that" :) > I does not seem that pyWin has been updated since > February of this year. Is there a direction change for the windows > extensions? Is it time I make the move to 3.x? Mark Hammond has > given much to the Python community and I do not intend for this post > to be negative in any way. No problem. There have been no updates as there is very little to update (ie, the code hasn't change a huge amount in hg since then). There will probably be a new version in the next month or so, but that is quite orthogonal to whether you should move to 3.x - the 3.x version of Pythonwin hasn't been updated in the same period and is built from the same source tree, so is likely to have exactly the same problems (infact is likely to have a few more - there are probably a few 3.x specific issues still hiding away). Mark From clp2 at rebertia.com Fri Sep 23 23:58:41 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 23 Sep 2011 20:58:41 -0700 Subject: Why is the shutil module called shutil? In-Reply-To: References: Message-ID: On Fri, Sep 23, 2011 at 8:36 PM, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. "sh" is short for "shell", in line with Unix convention, where the default shell is located at /bin/sh. http://en.wikipedia.org/wiki/Shell_(computing) http://en.wikipedia.org/wiki/Unix_shell "util" is short for "utilities". shutil is a utility module used to accomplish tasks which one often does when in the shell, such as copying, moving, or removing directory trees. But shutil (to my knowledge) is not implemented using shell commands or by running external programs, so it thus avoids a whole host of shell-related issues. It's not the best name, but what with backwards compatibility and all, it's unlikely to change any time soon. Cheers, Chris -- http://rebertia.com From 1248283536 at qq.com Sat Sep 24 00:11:17 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Sat, 24 Sep 2011 12:11:17 +0800 Subject: parse html:strange tr problem Message-ID: here is my code: import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() t = root.xpath("//table[@class='yfnc_datamodoutline1']")[0] trs=t.xpath(".//tr") for i, tr in enumerate(trs): print (i, len(tr),tr.text_content()) the output is: 0 1 StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 1 8 StrikeSymbolLastChgBidAskVolOpen Int 2 8 25.00A111022C0002500010.70 0.007.007.45315 3 8 28.00A111022C000280004.35 0.004.654.75201210 4 8 29.00A111022C000290003.80 0.003.954.05426425 5 8 30.00A111022C000300003.110.013.253.355597 6 8 31.00A111022C000310002.700.162.662.717407 7 8 32.00A111022C000320002.110.082.122.172364 8 8 33.00A111022C000330001.870.311.651.7029568 9 8 34.00A111022C000340001.360.151.261.3026649 10 8 35.00A111022C000350000.960.040.940.9845477 11 8 36.00A111022C000360000.720.120.690.7243786 12 8 37.00A111022C000370000.510.030.490.52511,435 13 8 38.00A111022C000380000.35 0.000.340.3544293 14 8 39.00A111022C000390000.16 0.000.220.269149 15 8 40.00A111022C000400000.180.030.150.1853301 16 8 41.00A111022C000410000.33 0.000.100.142184 17 8 42.00A111022C000420000.08 0.000.060.103147 18 8 45.00A111022C000450000.10 0.000.010.05200243 i want to know why i=0 the tr.text_content()'s value is : StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 it's strannge thing for me to understand. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contropinion at gmail.com Sat Sep 24 00:49:10 2011 From: contropinion at gmail.com (contro opinion) Date: Sat, 24 Sep 2011 12:49:10 +0800 Subject: parse html to get tr content Message-ID: here is my code: import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() t = root.xpath("//table[@class='yfnc_datamodoutline1']")[0] trs=t.xpath(".//tr") for i, tr in enumerate(trs): print (i, len(tr),tr.text_content()) the output is: 0 1 StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 1 8 StrikeSymbolLastChgBidAskVolOpen Int 2 8 25.00A111022C0002500010.70 0.007.007.45315 3 8 28.00A111022C000280004.35 0.004.654.75201210 4 8 29.00A111022C000290003.80 0.003.954.05426425 5 8 30.00A111022C000300003.110.013.253.355597 6 8 31.00A111022C000310002.700.162.662.717407 7 8 32.00A111022C000320002.110.082.122.172364 8 8 33.00A111022C000330001.870.311.651.7029568 9 8 34.00A111022C000340001.360.151.261.3026649 10 8 35.00A111022C000350000.960.040.940.9845477 11 8 36.00A111022C000360000.720.120.690.7243786 12 8 37.00A111022C000370000.510.030.490.52511,435 13 8 38.00A111022C000380000.35 0.000.340.3544293 14 8 39.00A111022C000390000.16 0.000.220.269149 15 8 40.00A111022C000400000.180.030.150.1853301 16 8 41.00A111022C000410000.33 0.000.100.142184 17 8 42.00A111022C000420000.08 0.000.060.103147 18 8 45.00A111022C000450000.10 0.000.010.05200243 i want to know why i=0 the tr.text_content()'s value is : StrikeSymbolLastChgBidAskVolOpen Int25.00A111022C0002500010.70 0.007.007.4531528.00A111022C000280004.35 0.004.654.7520121029.00A111022C000290003.80 0.003.954.0542642530.00A111022C000300003.110.013.253.35559731.00A111022C000310002.700.162.662.71740732.00A111022C000320002.110.082.122.17236433.00A111022C000330001.870.311.651.702956834.00A111022C000340001.360.151.261.302664935.00A111022C000350000.960.040.940.984547736.00A111022C000360000.720.120.690.724378637.00A111022C000370000.510.030.490.52511,43538.00A111022C000380000.35 0.000.340.354429339.00A111022C000390000.16 0.000.220.26914940.00A111022C000400000.180.030.150.185330141.00A111022C000410000.33 0.000.100.14218442.00A111022C000420000.08 0.000.060.10314745.00A111022C000450000.10 0.000.010.05200243 it's strannge thing for me to understand. -------------- next part -------------- An HTML attachment was scrubbed... URL: From flt.johnson at gmail.com Sat Sep 24 00:58:58 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 23 Sep 2011 21:58:58 -0700 (PDT) Subject: Why is the shutil module called shutil? References: Message-ID: On Sep 23, 11:58?pm, Chris Rebert wrote: > On Fri, Sep 23, 2011 at 8:36 PM, Fletcher Johnson wrote: > > The topic says it all: > > Why is shutil named shutil? What does it stand for? This is just a > > mild curiosity of mine. > > "sh" is short for "shell", in line with Unix convention, where the > default shell is located at /bin/sh.http://en.wikipedia.org/wiki/Shell_(computing)http://en.wikipedia.org/wiki/Unix_shell > > "util" is short for "utilities". > > shutil is a utility module used to accomplish tasks which one often > does when in the shell, such as copying, moving, or removing directory > trees. But shutil (to my knowledge) is not implemented using shell > commands or by running external programs, so it thus avoids a whole > host of shell-related issues. > > It's not the best name, but what with backwards compatibility and all, > it's unlikely to change any time soon. > > Cheers, > Chris > --http://rebertia.com I had a hunch it might have been that. From atherun at gmail.com Sat Sep 24 02:00:34 2011 From: atherun at gmail.com (Atherun) Date: Fri, 23 Sep 2011 23:00:34 -0700 (PDT) Subject: Python deadlock using subprocess.popen and communicate References: <098f3d78-85f5-44e7-ba72-f2270a24d1b0@o9g2000vbo.googlegroups.com> <5f15781e-ca1c-404f-8984-f6c532047db9@8g2000yqm.googlegroups.com> <2c7c883a-07b3-491c-b9f9-c7da8dc82399@f17g2000yqh.googlegroups.com> Message-ID: <15570090-f674-46e6-8c2e-747b68da5672@n12g2000yqh.googlegroups.com> On Sep 23, 7:03?pm, Matt Joiner wrote: > how do you get the call stacks like this? > > > > > > > > On Sat, Sep 24, 2011 at 3:59 AM, Atherun wrote: > > On Sep 23, 10:47?am, Nobody wrote: > >> On Fri, 23 Sep 2011 06:59:12 +0100, Nobody wrote: > >> >> kernel32.dll!WaitForSingleObject+0x12 > >> >> python26.dll!_Py_svnversion+0xcf8 > > >> > I haven't a clue how this happens. _Py_svnversion just returns a string: > > >> In retrospect, I think that's a red herring. 0xcf8 seems like too large an > >> offset for such a small function. I think that it's more likely to be in a > >> non-exported function, and _Py_svnversion just happens to be the last > >> exported symbol prior to that point in the code. > > > I have the call stacks for each python thread running up until the > > dead lock: > > > # ThreadID: 992 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 5516 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > # ThreadID: 2668 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 69, in > > run > > ?self.stacktraces() > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 86, in > > stacktraces > > ?fout.write(stacktraces()) > > File: "c:\src\scripts\auto\Autobuilder\StackTracer.py", line 26, in > > stacktraces > > ?for filename, lineno, name, line in traceback.extract_stack(stack): > > > # ThreadID: 3248 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 7700 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > # ThreadID: 8020 > > ?out, err = proc.communicate("change: new\ndescription: %s > > \n"%changelistDesc) > > File: "c:\src\extern\python\lib\subprocess.py", line 689, in > > communicate > > ?return self._communicate(input) > > File: "c:\src\extern\python\lib\subprocess.py", line 903, in > > _communicate > > ?stdout_thread.join() > > File: "c:\src\extern\python\lib\threading.py", line 637, in join > > ?self.__block.wait() > > File: "c:\src\extern\python\lib\threading.py", line 237, in wait > > ?waiter.acquire() > > > # ThreadID: 4252 > > File: "c:\src\extern\python\lib\threading.py", line 497, in > > __bootstrap > > ?self.__bootstrap_inner() > > File: "c:\src\extern\python\lib\threading.py", line 525, in > > __bootstrap_inner > > ?self.run() > > File: "c:\src\extern\python\lib\threading.py", line 477, in run > > ?self.__target(*self.__args, **self.__kwargs) > > File: "c:\src\extern\python\lib\subprocess.py", line 877, in > > _readerthread > > ?buffer.append(fh.read()) > > > The StackTracer thread freezes trying to update my output file, and > > yes I'm trying to 3 tasks in parallel which each one starts by > > creating a changelist in perforce. ?This is just an easy repro case > > for me, it happens with commands other then p4. ?This almost looks > > like a threading issue more then the output deadlock. > > -- > >http://mail.python.org/mailman/listinfo/python-list I found the code for it here: http://code.activestate.com/recipes/577334-how-to-debug-deadlocked-multi-threaded-programs/ There is some bugs in the code given but its pretty straight forward to fix it. From __peter__ at web.de Sat Sep 24 02:48:29 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 24 Sep 2011 08:48:29 +0200 Subject: can't load an script from html... References: <88319FFD-88A4-49B6-B5CC-8748CC71D97C@elkasoluciones.com> Message-ID: Ricardo wrote: > Hi everyone > I'm trying to use the cgi library to create a python script and loading it > from a web page. I have already done the necessary imports, and the > default commands to receive data from "html" are written too. The final > version is something like this: > > #!/usr/bin/python > > import subprocess > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > ?. my code (do something with input)?. > > > #printing the response > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print ?.. bla bla ? > print "%s"%theoutput > print "" > > Besides, my call from my index.html is like this: > >
>

> >
> > well, the thing is that when i do the call from the browser: > > http://localhost/index.html > | > V > put the data and click on the "accept" button > | > V > http:/localhost/scripts/python_script.py > > I only get the python_script.py as a plain test by response (the script > printed on my browser). I have already changed the permissions for > python_script.py. I have checked the import cgi,cgitb in the python shell > (i am using v2.7) and they work fine. So, i don't know what it is going > wrong here. > > A little help please? any idea? Is your webserver configured to allow cgi scripts? In the scripts directory? For Apache see http://httpd.apache.org/docs/current/howto/cgi.html Python also comes with a CGI Server. A quick-and-dirty setup goes like this: $ cat cgi-bin/script.py #!/usr/bin/python # -*- coding: utf-8 -*- import cgi import cgitb cgitb.enable() input = cgi.FieldStorage() print "Content-Type: text/html" print print "My title:" print "" print "" print "Hello world" print "" $ chmod a+x cgi-bin/script.py $ python -m CGIHTTPServer Serving HTTP on 0.0.0.0 port 8000 ... If you then point your browser to http://localhost:8000/cgi-bin/script.py you should see Hello world in the browser and (something like) localhost - - [24/Sep/2011 08:41:27] "GET /cgi-bin/script.py HTTP/1.1" 200 - in the shell. Note that the script must be in cgi-bin (or htbin) unless you start the server with a custom script that modifies CGIHTTPRequestHandler.cgi_directories accordingly. From steve+comp.lang.python at pearwood.info Sat Sep 24 02:55:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 16:55:18 +1000 Subject: random.randint() slow, esp in Python 3 References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Fri, Sep 23, 2011 at 4:14 AM, Steven D'Aprano > wrote: >> What makes you think it's in C? I don't have Python 3.3a, but in 3.2 the >> random module is mostly Python. There is an import of _random, which >> presumably is in C, but it doesn't have a randint method: > > True. It seems to be defined in cpython/lib/random.py as a reference > to randrange, which does a pile of error checking and calls > _randbelow... which does a whole lot of work as well as calling > random(). Guess I should have checked the code before asking! > > There's probably good reasons for using randint(), If you want unbiased, random (or at least pseudo-random) integers chosen from an uniform distribution with proper error checking, you should use randint or randrange. > but if you just > want a pile of more-or-less random integers, int(random.random()*top) > is the best option. "I only need random-ish ints, but I need 'em yesterday!!!" If you want biased, not-quite-uniformly distributed integers with no error checking, then the above will save you a few nanoseconds per call. So if your application needs a million such ints, you might save a full five seconds or so. Sounds like premature optimization to me, but what do I know? If you have an application where the quality of randomness is unimportant and generating random ints is a genuine performance bottleneck, then go right ahead. >> I'm not seeing any significant difference in speed between 2.6 and 3.2: >> >> [steve at sylar ~]$ python2.6 -m timeit -s "from random import >> randint" "randint(0, 1000000)" >> 100000 loops, best of 3: 4.29 usec per loop >> >> [steve at sylar ~]$ python3.2 -m timeit -s "from random import >> randint" "randint(0, 1000000)" >> 100000 loops, best of 3: 4.98 usec per loop > > That might be getting lost in the noise. Try the list comp that I had > above and see if you can see a difference - or anything else that > calls randint that many times. If you want to measure the speed of randint, you should measure the speed of randint. That's what the timeit call does: it calls randint 100000 times. You can't measure the speed of: [random.randint(0,sz*10-1) for i in range(sz)] and draw conclusions about randint alone. Roughly speaking, you are measuring the time taken to: lookup range lookup sz, twice call range, possibly generating a massive list iterate over the list/range object lookup random lookup random.randint multiply sz by 10 and subtract 1 build a list of the results, repeatedly resizing it as you go (in no particular order) There is MUCH more noise in your suggestion, not my version. But for what it's worth, I get these results: [steve at sylar ~]$ python3.2 -m timeit -s "import random" -s "sz = 1000000" "[random.randint(0,sz*10-1) for i in range(sz)]" 10 loops, best of 3: 6.09 sec per loop [steve at sylar ~]$ python2.6 -m timeit -s "import random" -s "sz = 1000000" "[random.randint(0,sz*10-1) for i in range(sz)]" 10 loops, best of 3: 4.67 sec per loop So Python 3.2 is about 30% slower for the whole mess. (I would, however, give little confidence in those results: at 4-6 seconds per loop, I expect that OS-level noise will be significant.) For what (little) it's worth, it seems that Python 3.2 should be a bit faster than 2.6, at least if you consider the Pystone benchmark to mean anything. http://www.levigross.com/post/2340736877/pystone-benchmark-on-2-6-2-7-3-2 > Performance-testing with a heapsort (and by the way, it's > _ridiculously_ slower implementing it in Python instead of just > calling a.sort(), but we all knew that already!) shows a similar > difference in performance. You do know that Python's heap implementation is written in C? Don't be fooled by the heapq module being in Python. About 2/3rds of the way down, there's a sneaky little trick: # If available, use C implementation try: from _heapq import * except ImportError: pass -- Steven From Phillip.M.Feldman at gmail.com Sat Sep 24 03:06:01 2011 From: Phillip.M.Feldman at gmail.com (Dr. Phillip M. Feldman) Date: Sat, 24 Sep 2011 00:06:01 -0700 (PDT) Subject: multinomial combinations Message-ID: <32503896.post@talk.nabble.com> I wrote a small generator function that produces multinomial combinations. (Python's itertools module does ordinary combinations, but not multinomial combinations). The code essentially works, except that the the last combination in each tuple is not enclosed in a nested tuple: In [2]: x= multinomial_combinations(range(7),[2,1,2]) In [3]: x.next() Out[3]: ((0, 1), (2,), 3, 4) (The 3 and 4 should be enclosed in a nested tuple). Any suggestions as to what I'm doing wrong will be appreciated. My code follows: def multinomial_combinations(items, ns): if len(ns) == 1: for c in itertools.combinations(items, ns[0]): yield c else: for c_first in itertools.combinations(items, ns[0]): items_remaining= set(items) - set(c_first) for c_other in multinomial_combinations(items_remaining, ns[1:]): yield (c_first,) + c_other -- View this message in context: http://old.nabble.com/multinomial-combinations-tp32503896p32503896.html Sent from the Python - python-list mailing list archive at Nabble.com. From clp2 at rebertia.com Sat Sep 24 03:35:42 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 24 Sep 2011 00:35:42 -0700 Subject: multinomial combinations In-Reply-To: <32503896.post@talk.nabble.com> References: <32503896.post@talk.nabble.com> Message-ID: On Sat, Sep 24, 2011 at 12:06 AM, Dr. Phillip M. Feldman wrote: > > I wrote a small generator function that produces multinomial combinations. > (Python's itertools module does ordinary combinations, but not multinomial > combinations). ?The code essentially works, except that the the last > combination in each tuple is not enclosed in a nested tuple: > > In [2]: x= multinomial_combinations(range(7),[2,1,2]) > > In [3]: x.next() > Out[3]: ((0, 1), (2,), 3, 4) > > (The 3 and 4 should be enclosed in a nested tuple). > > Any suggestions as to what I'm doing wrong will be appreciated. ?My code > follows: > > def multinomial_combinations(items, ns): > > ? if len(ns) == 1: > ? ? ?for c in itertools.combinations(items, ns[0]): > ? ? ? ? yield c FWIW, changing the base case to: if not ns: yield () appears to fix the issue. (Disclaimer: Have not done additional testing.) Cheers, Chris > ? else: > ? ? ?for c_first in itertools.combinations(items, ns[0]): > ? ? ? ? items_remaining= set(items) - set(c_first) > ? ? ? ? for c_other in multinomial_combinations(items_remaining, ns[1:]): > ? ? ? ? ? ?yield (c_first,) + c_other From arnodel at gmail.com Sat Sep 24 03:43:17 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 08:43:17 +0100 Subject: multinomial combinations In-Reply-To: <32503896.post@talk.nabble.com> References: <32503896.post@talk.nabble.com> Message-ID: (sorry about the top posting) Change yield c to yield (c,) HTH Arnaud PS: you could also change the if ... To If not ns: Yield ((),) Else: ... On Sep 24, 2011 8:06 AM, "Dr. Phillip M. Feldman" < Phillip.M.Feldman at gmail.com> wrote: > > I wrote a small generator function that produces multinomial combinations. > (Python's itertools module does ordinary combinations, but not multinomial > combinations). The code essentially works, except that the the last > combination in each tuple is not enclosed in a nested tuple: > > In [2]: x= multinomial_combinations(range(7),[2,1,2]) > > In [3]: x.next() > Out[3]: ((0, 1), (2,), 3, 4) > > (The 3 and 4 should be enclosed in a nested tuple). > > Any suggestions as to what I'm doing wrong will be appreciated. My code > follows: > > def multinomial_combinations(items, ns): > > if len(ns) == 1: > for c in itertools.combinations(items, ns[0]): > yield c > > else: > for c_first in itertools.combinations(items, ns[0]): > items_remaining= set(items) - set(c_first) > for c_other in multinomial_combinations(items_remaining, ns[1:]): > yield (c_first,) + c_other > -- > View this message in context: http://old.nabble.com/multinomial-combinations-tp32503896p32503896.html > Sent from the Python - python-list mailing list archive at Nabble.com. > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From iamforufriends at gmail.com Sat Sep 24 04:34:26 2011 From: iamforufriends at gmail.com (hot girl) Date: Sat, 24 Sep 2011 01:34:26 -0700 (PDT) Subject: want to meet a new girlfriend for free Message-ID: <7f26bf3c-5fa9-4514-a5f3-0f4acbc57720@i9g2000yqe.googlegroups.com> want to meet a new girlfriend for free http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3v24v6e From steve+comp.lang.python at pearwood.info Sat Sep 24 04:57:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 18:57:01 +1000 Subject: Python Mixins References: Message-ID: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. Mixins considered harmful: http://www.artima.com/weblogs/viewpost.jsp?thread=246341 http://www.artima.com/weblogs/viewpost.jsp?thread=246483 Mixins are much too easy to abuse, but there are uses for them. I have found mixins useful for testing. If I have a bunch of functions that take mostly similar unit tests, I create a mixin for the common unit tests, then apply them to the tests. Suppose I have two functions, ham and spam, which are unrelated but do share some common behaviours. Since they are unrelated, I don't want the spam test suite to inherit from the ham test suite, or vice versa, but I don't want to write the same tests multiple times. (Especially when I add cheese, egg and tomato functions.) So I put the common behaviours in a mixin class: class StandardTestMixin: def test_requires_one_argument(self): self.assertRaises(TypeError, self.func) def test_has_docstring(self): self.assertTrue(self.func.__doc__) class TestHam(unittest.TestCase, StandardTestMixin): ... class TestSpam(unittest.TestCase, StandardTestMixin): ... In this case, I simply don't care that the use of a mixin implies that TestHam is a StandardTestMixin. I treat that as an accident of implementation: it makes no practical difference, since I write no code that depends on isinstance(instance, StandardTestMixin). [...] > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? That depends on what you want. Python says is that issubclass(Cat, Yamlafiable) will return True. The *interpretation* of that fact is entirely up to you. If you want to interpret it as meaning that cats are Yamlafiables, go right ahead. If you want to interpret it as a technical result with no semantic meaning, that's fine too. After all, just because "ram" in "programming" returns True doesn't actually mean anything about male sheep and computing. The map is not the territory, and object-oriented ancestor/descendant relationships are not the same as real life relationships. It's a tool, nothing more, and if the metaphor starts to creak at the edges, oh well, so much for the metaphor. In fact, even in real life, the ancestor/descendant metaphor creaks. What should we make of bacteria which exchange DNA with other species of bacteria? Which is the ancestor and which is the descendant? How about symbionts like lichen? What about when we splice genes from one species into another? So even in real life, there are multiple inheritance and mixins. > If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. The standard metaphor for inheritance in OOP doesn't include "learning things from a friend". It is a very simple metaphor: everything is either "is-a" or "has-a". If you inherit from a class, the is-a relationship holds. If you don't want that, you can use composition instead: class Cat(Animal): def __init__(self, yamlifier): self.yamlifier = yamlifier def make_yaml(self): self.yamlifier.make_yaml(self, self.spam) Now we say that a Cat has-a Yamlafiable. > This is just a ridiculous example, but I think it is valid to say that > these things shouldn't be limited to inherit functionality only from > their parents, that they can pick other things up along the way as > well. Which is easy to do, right? > > Dog.something_new = something_new And that works in Python. But the thing is, which would you rather write? #1 class Dog(Animal, Yamlafiable): pass or this? #2 class Dog(Animal): pass Dog.__dict__.update(Yamlafiable.__dict__) But wait! The two aren't the same. There are quite big differences in behaviour between inheritance and attribute injection: * In the case of inheritance, attributes defined by Animal take precedence over those defined by Yamlafiable. In the case of injection, the opposite is the case. * In the case of inheritance, attributes defined by Yamlafiable's superclasses are reachable. In the case of injection, they aren't (at least not without more work). * Inheritance is late-binding, injection is early-binding: if you dynamically add a new method to Yamlafiable, Dog will see the change in the first case but not the second. That's not to say that one is right and the other is wrong. They're just different. Use whichever tool you prefer. Another option is straits: http://www.artima.com/weblogs/viewpost.jsp?thread=246488 -- Steven From chris at simplistix.co.uk Sat Sep 24 05:27:07 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Sat, 24 Sep 2011 10:27:07 +0100 Subject: MailingLogger 3.5.0 Released! Message-ID: <4E7DA26B.5090202@simplistix.co.uk> I'm pleased to announce a new release of Mailinglogger. Mailinglogger provides two handlers for the standard python logging framework that enable log entries to be emailed either as the entries are logged or as a summary at the end of the running process. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with a configurable headers for easy filtering - flood protection to ensure the number of emails sent is not excessive - support for SMTP servers that require authentication - fully documented and tested The only change for this release was to add an X-Log-Level header to emails sent. For MailingLogger, this is the level of the log message being emailed. For SummarisingLogger this is the highest level of any of the messages handled. Full docs can be found here: http://packages.python.org/mailinglogger/ For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger or http://pypi.python.org/pypi/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From ian.g.kelly at gmail.com Sat Sep 24 05:38:14 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 24 Sep 2011 03:38:14 -0600 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 12:55 AM, Steven D'Aprano wrote: > If you want unbiased, random (or at least pseudo-random) integers chosen > from an uniform distribution with proper error checking, you should use > randint or randrange. > > >> but if you just >> want a pile of more-or-less random integers, int(random.random()*top) >> is the best option. > > "I only need random-ish ints, but I need 'em yesterday!!!" > > If you want biased, not-quite-uniformly distributed integers with no error > checking, then the above will save you a few nanoseconds per call. So if > your application needs a million such ints, you might save a full five > seconds or so. Sounds like premature optimization to me, but what do I > know? If you have an application where the quality of randomness is > unimportant and generating random ints is a genuine performance bottleneck, > then go right ahead. Peeking under the hood, after all the error-checking and extra features, randrange basically just does int(random.random() * top). Any bias present in the latter will also be present in the former. Cheers, Ian From pavlovevidence at gmail.com Sat Sep 24 05:58:37 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 Sep 2011 02:58:37 -0700 (PDT) Subject: Python Mixins In-Reply-To: References: Message-ID: <20110522.2658.1316858317611.JavaMail.geo-discussion-forums@prfb12> On Thursday, September 22, 2011 2:14:39 PM UTC-7, Matt wrote: [snip] > class MyMixin(object): > def one_thing(self): > return "something cool" > > @mixin(MyMixin) > class MyClass(object): > pass > > x = MyClass() > x.one_thing() == 'something cool' > x.__class__.__bases__ == (object,) > > To me, this is much more concise. By looking at this I can tell what > MyClass IS, who it's parents are and what else it can do. I'm very > interested to know if there are others who feel as dirty as I do when > using inheritance for mixins Not me. Inheritance perfectly encompasses the mixin relationship, and because inheritance is so thoroughly ingrained in Python, it makes sense not to create a completely different mechanism to share behavior just for the case of mixins. I know that, as someone who reads code, I would rather coders stick to well-known mechanisms than to create their own ad hoc mechanisms that don't actually add any new capability. Take your MyClass example above. If you had stuck to inheritance I could have seen what classes all the behavior was implemented by listing the __bases__. But since you used an ad hoc mechanism, now I have to track down where the hell that one_thing() method is coming from. No mechanism is ever perfect, and Python's MI is very far from perfect, but sticking to well-known and understood methods is usually more important than whatever little improvement you can make. (And it is little; best as I can tell, your main objection is that mixins make it harder to see what the "main" parent is. I'd say that's a dubious justification to spring a new behavior-sharing mechanism on a reader.) > or if there are other things that Python > developers are doing to mix in functionality without using inheritance > or if the general populous of the Python community disagrees with me > and thinks that this is a perfectly valid use of inheritance. I'd guess the majority just use inheritance, although I can't say I've seen enough code out there to gauge it. But there is something else a lot of Pythonistas will do in many cases: just define regular functions. In your example, instead of defining one_thing() as a method of a mixin, define it as a function. Personally, I find that I almost never use mixins, though I have absolutely nothing against them and I use MI and metaclasses all the time. It's just that for most things I'd use a mixin for, I find that one or two regular functions work perfectly well. Carl Banks From pavlovevidence at gmail.com Sat Sep 24 06:23:11 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 Sep 2011 03:23:11 -0700 (PDT) Subject: Python Mixins In-Reply-To: References: Message-ID: <16852897.463.1316859791599.JavaMail.geo-discussion-forums@prng5> On Thursday, September 22, 2011 2:14:39 PM UTC-7, Matt wrote: > In terms of code, lets say we have the following classes: > > class Animal > class Yamlafiable > class Cat(Animal, Yamlafiable) > class Dog(Animal, Yamlafiable) > > I've got an Animal that does animal things, a Cat that does cat things > and a Dog that does dog things. I've also got a Yamlafiable class that > does something clever to generically convert an object into Yaml in > some way. Looking at these classes I can see that a Cat is an Animal, > a Dog is an Animal, a Dog is not a Cat, a Cat is not a Dog, a Dog is a > Yamlafiable? and a Cat is a Yamlafiable? Is that really true? Yes. I hope you are not confusing Cats with cats. > If my > objects are categorized correctly, in the correct inheritance > hierarchy shouldn't that make more sense? Cats and Dogs aren't > Yamlafiable, that doesn't define what they are, rather it defines > something that they can do because of things that they picked up from > their friend the Yamlafile. The whole point of OOP is that objects are defined by their behavior. A Cat is whatever it can do. A Dog is whatever it can do. If a Cat is yamlafiable, then it's coorect to say that a Cat is a Yamlafible (even if a cat isn't). Carl Banks From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sat Sep 24 07:48:29 2011 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sat, 24 Sep 2011 13:48:29 +0200 Subject: pyWin build 216 References: <1419f880-35a8-4a9f-aff9-52c07742f347@c29g2000yqd.googlegroups.com> Message-ID: <4e7dc38c$0$18801$ba4acef3@reader.news.orange.fr> Hi! Me, because some bugs in 216, I come back to 214... (215 has another bugs). @-salutations -- MCi From rosuav at gmail.com Sat Sep 24 08:33:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 24 Sep 2011 22:33:50 +1000 Subject: random.randint() slow, esp in Python 3 In-Reply-To: <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 4:55 PM, Steven D'Aprano wrote: > Chris Angelico wrote: > > If you want unbiased, random (or at least pseudo-random) integers chosen > from an uniform distribution with proper error checking, you should use > randint or randrange. > > "I only need random-ish ints, but I need 'em yesterday!!!" All I want is some data to sort, so that I can verify that my implementation is doing the same thing in every language that I write it in. Doesn't have to be casino-level purity of randomness. > You can't measure the speed of: > > [random.randint(0,sz*10-1) for i in range(sz)] > > and draw conclusions about randint alone. Sure, but by comparing the two lines of code (one with randint and one with random()), the other aspects can be cancelled out. > For what (little) it's worth, it seems that Python 3.2 should be a bit > faster than 2.6, at least if you consider the Pystone benchmark to mean > anything. > > http://www.levigross.com/post/2340736877/pystone-benchmark-on-2-6-2-7-3-2 That's what I would normally expect, that the new version outperforms the old - regardless of the program and the context. Exceptions need justification (as in the case of int/long vs just int - Py2 often outperforms Py3 when all the numbers fit inside machine int). > You do know that Python's heap implementation is written in C? Don't be > fooled by the heapq module being in Python. I didn't know, but it doesn't surprise me. But my purpose wasn't to sort the integers, it was to play with a particular hand-rolled implementation of a heap sort in multiple languages and make sure it was producing consistent results. ChrisA From dickinsm at gmail.com Sat Sep 24 08:53:41 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 05:53:41 -0700 (PDT) Subject: random.randint() slow, esp in Python 3 References: <4e7b7afa$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7d7ed7$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <94662e3d-5551-4ead-a067-9a381a402b43@i28g2000yqn.googlegroups.com> On Sep 24, 10:38?am, Ian Kelly wrote: > On Sat, Sep 24, 2011 at 12:55 AM, Steven D'Aprano > > > > > > > > > > wrote: > > If you want unbiased, random (or at least pseudo-random) integers chosen > > from an uniform distribution with proper error checking, you should use > > randint or randrange. > > >> but if you just > >> want a pile of more-or-less random integers, int(random.random()*top) > >> is the best option. > > > "I only need random-ish ints, but I need 'em yesterday!!!" > > > If you want biased, not-quite-uniformly distributed integers with no error > > checking, then the above will save you a few nanoseconds per call. So if > > your application needs a million such ints, you might save a full five > > seconds or so. Sounds like premature optimization to me, but what do I > > know? If you have an application where the quality of randomness is > > unimportant and generating random ints is a genuine performance bottleneck, > > then go right ahead. > > Peeking under the hood, after all the error-checking and extra > features, randrange basically just does int(random.random() * top). > Any bias present in the latter will also be present in the former. > > Cheers, > Ian In Python 2.x that's true, and indeed randrange has some fairly bad behaviour for large arguments ( see http://bugs.python.org/issue9025 ). In Python 3.2 and up, randrange is more careful: it doesn't introduce any extra bias beyond that already present in the random source (Mersenne Twister). If you look at the source, you'll see that Python 2.x only calls _getrandbits for large arguments, while Python 3.2+ calls _getrandbits for *every* invocation of randrange. (All assuming that we're using the default MT random number generator.) This may well explain the difference in timings observed by the OP. -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 09:53:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 24 Sep 2011 23:53:26 +1000 Subject: Generating equally-spaced floats with least rounding error Message-ID: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> I'm trying to generate a sequence of equally-spaced numbers between a lower and upper limit. Given arbitrary limits, what is the best way to generate a list of equally spaced floats with the least rounding error for each point? For example, suppose I want to divide the range 0 to 2.1 into 7 equal intervals, then the end-points of each interval are: (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) and I'd like to return the values in the brackets. Using Decimal or Fraction is not an option, I must use floats. If the exact value isn't representable as a float, I'm okay with returning the nearest possible float. The width of each interval is: width = (2.1 - 0.0)/7 The relevant points can be calculated in either of two methods: #1 add multiples of the width to the starting value, 0. #2 subtract multiples of width from the ending value, 2.1. (Repeated addition or subtraction should be avoided, as it increases the amount of rounding error.) Mathematically the two are equivalent, but due to rounding, they may not be. Here's a run using Python 3.2: >>> [0.0 + i*width for i in range(8)] [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] The 4th and 7th values have rounding errors, the rest are exact. >>> [2.1 - (7-i)*width for i in range(8)] [0.0, 0.30000000000000027, 0.6000000000000001, 0.9000000000000001, 1.2000000000000002, 1.5, 1.8, 2.1] The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th value is exact here, but not above. Is there a way to pick between methods #1 and #2 (or some combination of the two) without human intervention so as to minimise the rounding error? Or is there some other way to generate equally-spaced floats? My efforts at googling have not been helpful. -- Steven From rosuav at gmail.com Sat Sep 24 09:58:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 24 Sep 2011 23:58:32 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano wrote: > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. #3, go half and half - generate the lower half by adding to the lower bound, and the upper half by subtracting from the upper bound. Not sure if it'll help or not but it might be worth a shot. ChrisA From vlastimil.brom at gmail.com Sat Sep 24 10:17:40 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 24 Sep 2011 16:17:40 +0200 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: 2011/9/24 Chris Angelico : > On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano > wrote: >> #1 add multiples of the width to the starting value, 0. >> >> #2 subtract multiples of width from the ending value, 2.1. > > #3, go half and half - generate the lower half by adding to the lower > bound, and the upper half by subtracting from the upper bound. Not > sure if it'll help or not but it might be worth a shot. > > ChrisA > -- Just a naive way: #4 compute the values in both directions and use the average of the results (of, course, given, there isn't a better way to distinguish the values showing rounding errors automatically). (I guess dealing manually with values obtained by .as_integer_ratio() doesn't count as pure float operation...) vbr From arnodel at gmail.com Sat Sep 24 10:18:44 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 15:18:44 +0100 Subject: Generating equally-spaced floats with least rounding error Message-ID: On Sep 24, 2011 2:59 PM, "Chris Angelico" wrote: > > On Sat, Sep 24, 2011 at 11:53 PM, Steven D'Aprano > wrote: > > #1 add multiples of the width to the starting value, 0. > > > > #2 subtract multiples of width from the ending value, 2.1. > > #3, go half and half - generate the lower half by adding to the lower > bound, and the upper half by subtracting from the upper bound. Not #4 the barycentric approach. ((n-i)*a + i*b)/n for i in range(n+1) Gives you n+1 equally spaced values between a and b inclusive Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Sat Sep 24 10:26:08 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 24 Sep 2011 10:26:08 -0400 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a > lower and upper limit. Given arbitrary limits, what is the best way to > generate a list of equally spaced floats with the least rounding error for > each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or > Fraction is not an option, I must use floats. If the exact value isn't > representable as a float, I'm okay with returning the nearest possible > float. > > The width of each interval is: > > width = (2.1 - 0.0)/7 > > The relevant points can be calculated in either of two methods: > > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. > > (Repeated addition or subtraction should be avoided, as it increases the > amount of rounding error.) > > Mathematically the two are equivalent, but due to rounding, they may not > be. Here's a run using Python 3.2: > >>>> [0.0 + i*width for i in range(8)] > [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] > > The 4th and 7th values have rounding errors, the rest are exact. > > >>>> [2.1 - (7-i)*width for i in range(8)] > [0.0, 0.30000000000000027, 0.6000000000000001, 0.9000000000000001, > 1.2000000000000002, 1.5, 1.8, 2.1] > > The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th > value is exact here, but not above. > > Is there a way to pick between methods #1 and #2 (or some combination of > the two) without human intervention so as to minimise the rounding error? > Or is there some other way to generate equally-spaced floats? My efforts > at googling have not been helpful. When I've done this with ints (usually in small embedded systems) I've always preferred low_limit + (total_width * i) / intervals since it does the rounding on the biggest numbers where proportional error will be least, and it's guaranteed to hit the low_limit and high_limit exactly (as exactly as they can be represented, anyway.) Mel. From lists at cheimes.de Sat Sep 24 10:56:59 2011 From: lists at cheimes.de (Christian Heimes) Date: Sat, 24 Sep 2011 16:56:59 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Message-ID: Am 23.09.2011 23:34, schrieb Jesramz: > Im running on Ubuntu Natty and I am not running a self-compiled > install, its a regular release. Ubuntu Natty doesn't come with Python 2.5. How did you install Python 2.5 on Natty? If you used some sort of installer or 3rd party repository, there is a big chance that the installer doesn't understand multiarch. Christian From dickinsm at gmail.com Sat Sep 24 11:17:49 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 08:17:49 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> On Sep 24, 2:53?pm, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. Can you explain why you're constrained not to use Fraction? Speed? Using Fraction for intermediate calculations actually works perfectly for this, since conversions from float to Fraction are exact, while conversions from Fraction to float are correctly rounded. So if you're using Python, you're not too bothered about efficiency, and you want provably correctly-rounded results, why not use Fraction? >>> from fractions import Fraction >>> start, stop, n = 0.0, 2.1, 7 >>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 12:46:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 02:46:39 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> Message-ID: <4e7e0971$0$30000$c3e8da3$5496439d@news.astraweb.com> Mark Dickinson wrote: > On Sep 24, 2:53?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> I'm trying to generate a sequence of equally-spaced numbers between a >> lower and upper limit. Given arbitrary limits, what is the best way to >> generate a list of equally spaced floats with the least rounding error >> for each point? >> >> For example, suppose I want to divide the range 0 to 2.1 into 7 equal >> intervals, then the end-points of each interval are: >> >> (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) >> >> and I'd like to return the values in the brackets. Using Decimal or >> Fraction is not an option, I must use floats. If the exact value isn't >> representable as a float, I'm okay with returning the nearest possible >> float. > > Can you explain why you're constrained not to use Fraction? Speed? Speed is important, but secondary to correctness. To be honest, I never even thought of using fractions as an intermediate result -- I was thinking of generating lists of Fractions. I think I can use this approach. But out of curiosity, how would you do it using nothing but floats? Is there a way? -- Steven From dickinsm at gmail.com Sat Sep 24 12:55:35 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 09:55:35 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0971$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <44c72615-2455-469c-964f-6aacedeb705f@d17g2000yqa.googlegroups.com> On Sep 24, 5:46?pm, Steven D'Aprano wrote: > Speed is important, but secondary to correctness. To be honest, I never even > thought of using fractions as an intermediate result -- I was thinking of > generating lists of Fractions. I think I can use this approach. Speed could be improved greatly by using integer arithmetic (with some help from the float.as_integer_ratio method) instead of using Fraction directly, though it would require writing quite a lot more code; Fraction's many and slow gcd calls for normalization are a problem here, and since all denominators will be powers of 2 they're largely unnecessary. > But out of curiosity, how would you do it using nothing but floats? Is there > a way? Hmm. Beyond writing my own multiple-precision integer library using floats as the base type, I can't think of anything obvious. :-) -- Mark From steve+comp.lang.python at pearwood.info Sat Sep 24 13:01:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 03:01:47 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> Message-ID: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Mark Dickinson wrote: > Using Fraction for intermediate calculations actually works perfectly > for this, since conversions from float to Fraction are exact, while > conversions from Fraction to float are correctly rounded. So if > you're using Python, you're not too bothered about efficiency, and you > want provably correctly-rounded results, why not use Fraction? > >>>> from fractions import Fraction >>>> start, stop, n = 0.0, 2.1, 7 >>>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) >>>> [for i in range(n+1)] > [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] Ah, I knew it was too easy! >>> from fractions import Fraction as F >>> start, stop, n = 1, 3.1, 7 >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>> >>> start, stop, n = -1, 1.1, 7 >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] -- Steven From rosuav at gmail.com Sat Sep 24 13:03:14 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 03:03:14 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 12:26 AM, Mel wrote: > low_limit + (total_width * i) / intervals > Definite improvement, if the range is comparatively small. Multiply first, then divide. ChrisA From rosuav at gmail.com Sat Sep 24 13:19:34 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 03:19:34 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:01 AM, Steven D'Aprano wrote: > Mark Dickinson wrote: > >> Using Fraction for intermediate calculations actually works perfectly >> for this, since conversions from float to Fraction are exact, while >> conversions from Fraction to float are correctly rounded. ?So if >> you're using Python, you're not too bothered about efficiency, and you >> want provably correctly-rounded results, why not use Fraction? >> > Ah, I knew it was too easy! Try using Fraction for the start and stop too: >>> from fractions import Fraction as F >>> start,stop,n = F(0),F(21,10),7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] (Tested in Py 3.2 for Win) ChrisA From passiday at gmail.com Sat Sep 24 13:31:21 2011 From: passiday at gmail.com (Passiday) Date: Sat, 24 Sep 2011 10:31:21 -0700 (PDT) Subject: Suggested coding style Message-ID: Hello, I have started to code random stuff in Python only recently, still lots to learn. So please bear with me if my question sounds like rant. I have been coding in many other languages, most of the time it was Java and C#. I don't like the function mess of PHP (ie, loads and loads of functions without any namespaces etc), but I'd like to think that Python is different. In my brief coding experience I have stumbled upon Python zfill(width) method, and I thought, really, do you have to include such a narrow- purpose method in the basic method set? Perhaps there are more such methods that are nice when you need them, but then again, you don't put all the possible methods in the standard set. Perhaps there is reason such method is in the basic library, and my complaints are unbased? Or, perhaps the language is on course to bloat out and get filled with tens and hundreds of special-purpose methods that render the language structure chaotic? Passiday From dickinsm at gmail.com Sat Sep 24 14:23:21 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 24 Sep 2011 11:23:21 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 24, 6:01?pm, Steven D'Aprano wrote: > Ah, I knew it was too easy! > > >>> from fractions import Fraction as F > >>> start, stop, n = 1, 3.1, 7 > >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > > [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] I believe that's still giving correctly-rounded results. Note that the stop value of 3.1 isn't exactly 3.1 here: it's 3.100000000000000088817841970012523233890533447265625 So the 4th value above is the closest float to 4/7 * 1.0 + 3/7 * 3.100000000000000088817841970012523233890533447265625. -- Mark From rick.mansilla at gmail.com Sat Sep 24 14:50:26 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Sat, 24 Sep 2011 13:50:26 -0500 Subject: Python-list Digest, Vol 96, Issue 137 In-Reply-To: References: Message-ID: <201109241350.27066.rick.mansilla@gmail.com> On Saturday 24 September 2011 01:48:29 you wrote: > Ricardo wrote: > > Hi everyone > > I'm trying to use the cgi library to create a python script and loading > > it from a web page. I have already done the necessary imports, and the > > default commands to receive data from "html" are written too. The final > > version is something like this: > > > > #!/usr/bin/python > > > > import subprocess > > import cgi > > import cgitb > > > > cgitb.enable() > > > > input = cgi.FieldStorage() > > > > ?. my code (do something with input)?. > > > > > > #printing the response > > > > print "Content-Type: text/html" > > print > > print "My title:" > > print "" > > print "" > > print ?.. bla bla ? > > print "%s"%theoutput > > print "" > > > > Besides, my call from my index.html is like this: > >
> > > >

> > > > > > > >
> > > > well, the thing is that when i do the call from the browser: > > > > http://localhost/index.html > > > > V > > > > put the data and click on the "accept" button > > > > V > > > > http:/localhost/scripts/python_script.py > > > > I only get the python_script.py as a plain test by response (the script > > printed on my browser). I have already changed the permissions for > > python_script.py. I have checked the import cgi,cgitb in the python shell > > (i am using v2.7) and they work fine. So, i don't know what it is going > > wrong here. > > > > A little help please? any idea? > > Is your webserver configured to allow cgi scripts? In the scripts > directory? For Apache see > > http://httpd.apache.org/docs/current/howto/cgi.html > > Python also comes with a CGI Server. A quick-and-dirty setup goes like > this: > > $ cat cgi-bin/script.py > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import cgi > import cgitb > > cgitb.enable() > > input = cgi.FieldStorage() > > print "Content-Type: text/html" > print > print "My title:" > print "" > print "" > print "Hello world" > print "" > $ chmod a+x cgi-bin/script.py > $ python -m CGIHTTPServer > Serving HTTP on 0.0.0.0 port 8000 ... > > If you then point your browser to http://localhost:8000/cgi-bin/script.py > you should see > > Hello world > > in the browser and (something like) > > localhost - - [24/Sep/2011 08:41:27] "GET /cgi-bin/script.py HTTP/1.1" 200 > - > > in the shell. Note that the script must be in cgi-bin (or htbin) unless you > start the server with a custom script that modifies > CGIHTTPRequestHandler.cgi_directories accordingly. Thanks a lot, for your answer. Yes, i can run scripts from /cgi-bin/. Actually I follow you example and it works really well. I didn't know at all about this CGI server. I am doing the hole thing over python now, it's nice. Thanks again. -- (...)Also, since that same law states that any system able to prove its consistency to itself must be inconsistent; any mind that believes it can prove its own sanity is, therefore, insane.(...) Kurt G?del. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Sep 24 15:03:31 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 20:03:31 +0100 Subject: Suggested coding style In-Reply-To: References: Message-ID: <4E7E2983.10506@mrabarnett.plus.com> On 24/09/2011 18:31, Passiday wrote: > Hello, > > I have started to code random stuff in Python only recently, still > lots to learn. So please bear with me if my question sounds like rant. > > I have been coding in many other languages, most of the time it was > Java and C#. I don't like the function mess of PHP (ie, loads and > loads of functions without any namespaces etc), but I'd like to think > that Python is different. > > In my brief coding experience I have stumbled upon Python zfill(width) > method, and I thought, really, do you have to include such a narrow- > purpose method in the basic method set? Perhaps there are more such > methods that are nice when you need them, but then again, you don't > put all the possible methods in the standard set. > > Perhaps there is reason such method is in the basic library, and my > complaints are unbased? Or, perhaps the language is on course to bloat > out and get filled with tens and hundreds of special-purpose methods > that render the language structure chaotic? > Considering that Python has been around for 20 years, there's not much bloat. Most of the risk of that was early on, when any interest in the language might have been welcomed. Now that its use has grown, it can be more choosy. .zfill does have its uses: >>> "-1".rjust(4, "0") '00-1' >>> "-1".zfill(4) '-001' From tim at akwebsoft.com Sat Sep 24 15:10:48 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sat, 24 Sep 2011 11:10:48 -0800 Subject: Suggested coding style In-Reply-To: References: Message-ID: <20110924191048.GH19422@johnsons-web.com> * Passiday [110924 09:47]: <...> > I have been coding in many other languages, most of the time it was > Java and C#. I don't like the function mess of PHP (ie, loads and > loads of functions without any namespaces etc), but I'd like to think > that Python is different. It is ... > In my brief coding experience I have stumbled upon Python zfill(width) > method, and I thought, really, do you have to include such a narrow- > purpose method in the basic method set? Perhaps there are more such > methods that are nice when you need them, but then again, you don't > put all the possible methods in the standard set. I think that you have raised an interesting question here. I've been coding in python for 9 years and I have never used it. > Perhaps there is reason such method is in the basic library, and my > complaints are unbased? It could be some sort of legacy. I imagine we will hear from some more senior pythonists on this matter. > Or, perhaps the language is on course to bloat > out and get filled with tens and hundreds of special-purpose methods > that render the language structure chaotic? From my observance, python has developed with care and prudence. I have a feeling (instinctive of course), that Guido van Rossum is/was more likely to say 'no' to a request for a new implementation that Rasmus Lerdorf. MTCW -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From python at mrabarnett.plus.com Sat Sep 24 15:34:36 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 24 Sep 2011 20:34:36 +0100 Subject: Suggested coding style In-Reply-To: <20110924191048.GH19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> Message-ID: <4E7E30CC.3040402@mrabarnett.plus.com> On 24/09/2011 20:10, Tim Johnson wrote: > * Passiday [110924 09:47]: > <...> >> I have been coding in many other languages, most of the time it was >> Java and C#. I don't like the function mess of PHP (ie, loads and >> loads of functions without any namespaces etc), but I'd like to think >> that Python is different. > It is ... > >> In my brief coding experience I have stumbled upon Python zfill(width) >> method, and I thought, really, do you have to include such a narrow- >> purpose method in the basic method set? Perhaps there are more such >> methods that are nice when you need them, but then again, you don't >> put all the possible methods in the standard set. > I think that you have raised an interesting question here. I've > been coding in python for 9 years and I have never used it. > >> Perhaps there is reason such method is in the basic library, and my >> complaints are unbased? > > It could be some sort of legacy. I imagine we will hear from some > more senior pythonists on this matter. > The documentation says "New in version 2.2.2". >> Or, perhaps the language is on course to bloat >> out and get filled with tens and hundreds of special-purpose methods >> that render the language structure chaotic? > > From my observance, python has developed with care and prudence. I > have a feeling (instinctive of course), that Guido van Rossum > is/was more likely to say 'no' to a request for a new > implementation that Rasmus Lerdorf. > From arnodel at gmail.com Sat Sep 24 15:54:28 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 20:54:28 +0100 Subject: Suggested coding style In-Reply-To: <4E7E30CC.3040402@mrabarnett.plus.com> References: <20110924191048.GH19422@johnsons-web.com> <4E7E30CC.3040402@mrabarnett.plus.com> Message-ID: On 24 September 2011 20:34, MRAB wrote: >>> In my brief coding experience I have stumbled upon Python zfill(width) >>> method, [...] >> ? It could be some sort of legacy. I imagine we will hear from some >> ? more senior pythonists on this matter. >> > The documentation says "New in version 2.2.2". But zfill has been in the string module for a lot longer. -- Arnaud From arnodel at gmail.com Sat Sep 24 15:55:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sat, 24 Sep 2011 20:55:34 +0100 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24 September 2011 18:01, Steven D'Aprano wrote: > Mark Dickinson wrote: > >> Using Fraction for intermediate calculations actually works perfectly >> for this, since conversions from float to Fraction are exact, while >> conversions from Fraction to float are correctly rounded. ?So if >> you're using Python, you're not too bothered about efficiency, and you >> want provably correctly-rounded results, why not use Fraction? >> >>>>> from fractions import Fraction >>>>> start, stop, n = 0.0, 2.1, 7 >>>>> [float(Fraction(start) + i * (Fraction(stop) - Fraction(start)) / n) >>>>> [for i in range(n+1)] >> [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] > > > Ah, I knew it was too easy! > >>>> from fractions import Fraction as F >>>> start, stop, n = 1, 3.1, 7 >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>> start, stop, n = 1, 3.1, 7 >>> [((n-i)*start + i*stop)/n for i in range(n+1)] [1.0, 1.3, 1.5999999999999999, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1] >>>> start, stop, n = -1, 1.1, 7 >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, > 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] >>> start, stop, n = -1, 1.1, 7 >>> [((n-i)*start + i*stop)/n for i in range(n+1)] [-1.0, -0.7000000000000001, -0.39999999999999997, -0.09999999999999996, 0.20000000000000004, 0.5, 0.8, 1.1] On these examples, using fractions is no better than what I suggested in my previous post. -- Arnaud From stefan-usenet at bytereef.org Sat Sep 24 16:30:45 2011 From: stefan-usenet at bytereef.org (Stefan Krah) Date: Sat, 24 Sep 2011 22:30:45 +0200 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110924203045.GA2014@sleipnir.bytereef.org> Arnaud Delobelle wrote: > >>>> start, stop, n = -1, 1.1, 7 > >>>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)] > > [-1.0, -0.7, -0.39999999999999997, -0.09999999999999996, > > 0.20000000000000004, 0.5000000000000001, 0.8, 1.1] > > >>> start, stop, n = -1, 1.1, 7 > >>> [((n-i)*start + i*stop)/n for i in range(n+1)] > [-1.0, -0.7000000000000001, -0.39999999999999997, > -0.09999999999999996, 0.20000000000000004, 0.5, 0.8, 1.1] > > On these examples, using fractions is no better than what I suggested > in my previous post. Why not use Decimal if one needs exact endpoints? Something like: def drange(start, stop, step=1): if (step == 0): raise ValueError("step must be != 0") with localcontext() as ctx: ctx.traps[Inexact] = True x = start cmp = -1 if step > 0 else 1 while x.compare(stop) == cmp: yield float(x) x += step >>> list(drange(Decimal(1), Decimal("3.1"), Decimal("0.3"))) [1.0, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal("0.3"))) [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal("0.1823612873"))) [-1.0, -0.8176387127, -0.6352774254, -0.4529161381, -0.2705548508, -0.0881935635, 0.0941677238, 0.2765290111, 0.4588902984, 0.6412515857, 0.823612873, 1.0059741603] >>> list(drange(Decimal(-1), Decimal("1.1"), Decimal(1)/3)) Traceback (most recent call last): File "", line 1, in File "", line 10, in drange File "/usr/lib/python3.2/decimal.py", line 1178, in __add__ ans = ans._fix(context) File "/usr/lib/python3.2/decimal.py", line 1652, in _fix context._raise_error(Inexact) File "/usr/lib/python3.2/decimal.py", line 3836, in _raise_error raise error(explanation) decimal.Inexact: None Stefan Krah From mateusz at loskot.net Sat Sep 24 16:52:46 2011 From: mateusz at loskot.net (Mateusz Loskot) Date: Sat, 24 Sep 2011 13:52:46 -0700 (PDT) Subject: PyEval_EvalCodeEx return value In-Reply-To: <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> References: <4E786C42.3050309@loskot.net> <3520ac5c-9e75-45b2-a4f1-fc29658bea4b@l4g2000vbv.googlegroups.com> Message-ID: <32503908.post@talk.nabble.com> John Pinner-3 wrote: > > I assume that you have read the documentation at > http://docs.python.org/c-api/veryhigh.html, > and I agree that it's sparse, but the entry for the next entry, > PyEval_EvalCodeEx, tells you a little more, as does that for > PyEval_EvalFrameEx. > It does help, but only a bit. John Pinner-3 wrote: > > Obviously, it's returning a pointer to a PyObject, and Looking at the > source code, that may be NULL, to throw an exception, or an execution > frame, or a generator,etc, etc, depending on the code it's been given. > I guess that you should be able to inspect the PyObject to see what it is. > Yes, that's one possibility. I tried to investigate others. John Pinner-3 wrote: > > What I'm wondering is, why are you eval-ing code ? A favourite device > of C programmers coming to Python (and mea culpa in the past), it's > fraught with potential problems and even security risks, and is > difficult to debug, and maybe you should be using introspection instead. > My application accepts Python scripts from user and executes using embedded Python interpreter. So, I use this particular API. Could you elaborate on the "using introspection"? John Pinner-3 wrote: > > And maybe you should be working in Python, and not C++ at this point, > do the dynamic stuff in the language best suited, and then return to C++ > when needed. > My application in C++ interacts with Python programs provided by users. Depending on what these programs request, various PyObject objects are created and returned back, etc. I understand it's difficult to discuss it without long essays or without providing the code, etc. So, I can only discuss and investigate building blocks I use. Anyway, thanks for your comments. Best regards, ----- -- Mateusz Loskot http://mateusz.loskot.net -- View this message in context: http://old.nabble.com/PyEval_EvalCodeEx-return-value-tp32501833p32503908.html Sent from the Python - python-list mailing list archive at Nabble.com. From f.derainville at gmail.com Sat Sep 24 16:54:16 2011 From: f.derainville at gmail.com (f.derainville at gmail.com) Date: Sat, 24 Sep 2011 13:54:16 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <16897112.251.1316897656322.JavaMail.geo-discussion-forums@yqmw31> >>> import numpy >>> numpy.arange(0, 3, 0.3) array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7]) From rantingrick at gmail.com Sat Sep 24 17:05:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 14:05:36 -0700 (PDT) Subject: Python Mixins References: Message-ID: <210c9d0b-d0f0-4fec-9d7b-11ef32127d6e@q26g2000vby.googlegroups.com> On Sep 22, 4:14?pm, Matt wrote: > I'm curious about what people's opinions are about using mixins in > Python. I really like, for example, the way that class based views > were implemented in Django 1.3 using mixins. It makes everything > extremely customizable and reusable. I think this is a very good > practice to follow, however, in Python mixins are achieved by using > (or perhaps misusing) inheritance and often multiple inheritance. Have a look at this article also. Even though he uses java source code anyone can follow along: http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/ From tim at akwebsoft.com Sat Sep 24 17:09:35 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sat, 24 Sep 2011 13:09:35 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4E7E30CC.3040402@mrabarnett.plus.com> Message-ID: <20110924210935.GI19422@johnsons-web.com> * Arnaud Delobelle [110924 12:04]: > On 24 September 2011 20:34, MRAB wrote: > > >>> In my brief coding experience I have stumbled upon Python zfill(width) > >>> method, > [...] > >> ? It could be some sort of legacy. I imagine we will hear from some > >> ? more senior pythonists on this matter. > >> > > The documentation says "New in version 2.2.2". > > But zfill has been in the string module for a lot longer. :) Like I said. See timestamp. http://mail.python.org/pipermail/python-bugs-list/1999-July/000035.html I was coding C/C++ and ASM back then.... -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From tjreedy at udel.edu Sat Sep 24 18:10:29 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 18:10:29 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/24/2011 9:53 AM, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. > > The width of each interval is: > > width = (2.1 - 0.0)/7 Calculating width is the fundamental problem. .3 cannot be exactly represented in binary, and higher multiples with multiply the error. > > The relevant points can be calculated in either of two methods: > > #1 add multiples of the width to the starting value, 0. > > #2 subtract multiples of width from the ending value, 2.1. > > (Repeated addition or subtraction should be avoided, as it increases the > amount of rounding error.) > > Mathematically the two are equivalent, but due to rounding, they may not be. > Here's a run using Python 3.2: > >>>> [0.0 + i*width for i in range(8)] > [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] > > The 4th and 7th values have rounding errors, the rest are exact No they are not. Their errors are just smaller and not visible with 16 digits. >>> width = (2.1 - 0.0)/7 >>> ['%20.18f' % x for x in [0.0 + i*width for i in range(8)]] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.899999999999999911', '1.199999999999999956', '1.500000000000000000', '1.799999999999999822', '2.100000000000000089'] On 9/24/2011 10:18 AM, Arnaud Delobelle wrote: > ((n-i)*a + i*b)/n for i in range(n+1) >>> ['%20.18f' % x for x in [((7-i)*0.0 + i*2.1)/7 for i in range(8)]] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000133', '1.199999999999999956', '1.500000000000000000', '1.800000000000000266', '2.100000000000000089'] In the two places where this disagrees with the previous result, I believe it is worse. The *0.0 adds nothing. You are still multiplying an inexactly represented 2.1 by increasingly large numbers. Even 7*2.1/7 is not exact! My answer is the same as Mark's. Do exact calculation with fractions (whether using Fraction or not) and convert to float. I believe the least common multiple of a.as_integer_ratio[1], b.as_integer_ratio[1], and n is the common denominator needed to convert the numerators to a range() output. For the current problem, that is lcm(10,7) = 70. The best you can do for this example is >>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', '1.800000000000000044', '2.100000000000000089'] Notice that the last place errors are all less than 50, so printing to 16 places will make them appear 'exact'. Without being fancy (to see than you can cancel 7), you get the same output with >>> ['%20.18f' % (i/70 ) for i in range(0, 148, 21)] ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', '1.800000000000000044', '2.100000000000000089'] In the two places where these disagree with the first (your original) they are *better*, with absolute error in the last places of 22 versus 89 and 44 versus 178 for .9 and 1.8. The last place errors greater than 50 gave you the 'inexact' answers in your post, and indeed, they are not the best possible. -- Terry Jan Reedy From rantingrick at gmail.com Sat Sep 24 18:36:44 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 15:36:44 -0700 (PDT) Subject: Why is the shutil module called shutil? References: Message-ID: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> On Sep 23, 10:36?pm, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. > The shutil module for reference:http://docs.python.org/library/shutil.html#module-shutil Because even after 20 freaking years of evolution Python "heads of state" (or states of head) cannot be bi-partisan enough to agree on a freaking File and/or path object; remind you of any "body" we know? From rantingrick at gmail.com Sat Sep 24 18:41:22 2011 From: rantingrick at gmail.com (rantingrick) Date: Sat, 24 Sep 2011 15:41:22 -0700 (PDT) Subject: Python Mixins References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> On Sep 24, 3:57?am, Steven D'Aprano wrote: > class StandardTestMixin: > ? ? def test_requires_one_argument(self): > ? ? ? ? self.assertRaises(TypeError, self.func) > ? ? def test_has_docstring(self): > ? ? ? ? self.assertTrue(self.func.__doc__) And this is another example of why we need doc-string reforms. Here we have a well know "pythonista" (for lack of better word) who needs to write a test for doc-string inclusion because he refuses to get in the habit of writing them. People, EVERY method and function MUST have a doc-string! What is the purpose of having doc-strings if we are too lazy to use them! From jesus.ramirez.utexas at gmail.com Sat Sep 24 19:08:21 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Sat, 24 Sep 2011 16:08:21 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> Message-ID: <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> I installed it from here: http://www.python.org/getit/releases/2.5.6/ What do you think a solution might be? From benjamin.kaplan at case.edu Sat Sep 24 19:33:35 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 24 Sep 2011 19:33:35 -0400 Subject: Python 2.5 zlib trouble In-Reply-To: <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: On Sat, Sep 24, 2011 at 7:08 PM, Jesramz wrote: > > I installed it from here: http://www.python.org/getit/releases/2.5.6/ > > What do you think a solution might be? > There is no binary installer on that page. That means you downloaded the source code and compiled it yourself. Yes, you didn't patch it. But it's still a self-compiled version of Python. In order to get zlib in a self-compiled version of Python, you need to install the appropriate -dev package. From a quick look at the repository, I think it's zlib1g-dev but I'm not sure. On Ubuntu, the development headers are in a different package than the libraries themselves. The development headers aren't needed when you're installing a binary that someone else compiled (for instance, anything you get from the package manager) but are needed if you're trying to build anything that uses the library. Since a good chunk of the Python stdlib isn't actually necessary to run Python, you can successfully build Python without getting a good chunk of the modules. ./configure will give you a list of the modules that won't get built at the end of its output. From python.list at tim.thechases.com Sat Sep 24 19:36:56 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 24 Sep 2011 18:36:56 -0500 Subject: Python Mixins In-Reply-To: <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> <3baeef0c-1dbf-4067-a73e-d6bfbc059f17@5g2000yqo.googlegroups.com> Message-ID: <4E7E6998.80102@tim.thechases.com> On 09/24/11 17:41, rantingrick wrote: > On Sep 24, 3:57 am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> class StandardTestMixin: >> def test_requires_one_argument(self): >> self.assertRaises(TypeError, self.func) >> def test_has_docstring(self): >> self.assertTrue(self.func.__doc__) > > And this is another example of why we need doc-string reforms. Here we > have a well know "pythonista" (for lack of better word) who needs to > write a test for doc-string inclusion because he refuses to get in the > habit of writing them. People, EVERY method and function MUST have a > doc-string! What is the purpose of having doc-strings if we are too > lazy to use them! http://www.python.org/dev/peps/pep-0257/ """ The aim of this PEP is to standardize the high-level structure of docstrings: what they should contain, and how to say it (without touching on any markup syntax within docstrings). The PEP contains conventions, not laws or syntax. """ You keep saying the word "MUST". I do not think it means what you think it means. Just for the record [1], [2], [3], [4] all in my first page of search Google search results. Pot, meet kettle. -tkc [1] http://mail.python.org/pipermail/python-list/2009-September/1220068.html [2] http://mail.python.org/pipermail//python-list/2011-July/1276021.html [3] http://mail.python.org/pipermail/python-list/2010-March/1237898.html [4] http://mail.python.org/pipermail/python-list/2010-June/1246305.html From tjreedy at udel.edu Sat Sep 24 20:31:06 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 20:31:06 -0400 Subject: Python Mixins In-Reply-To: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e7d9b5e$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/24/2011 4:57 AM, Steven D'Aprano wrote: > Python says is that issubclass(Cat, Yamlafiable) will return True. The > *interpretation* of that fact is entirely up to you. If you want to > interpret it as meaning that cats are Yamlafiables, go right ahead. If you > want to interpret it as a technical result with no semantic meaning, that's > fine too. After all, just because "ram" in "programming" returns True > doesn't actually mean anything about male sheep and computing. Today's comics had a strip in which girl A suggests to girl B that they go to a disco to disco-ver someone interesting. > In fact, even in real life, the ancestor/descendant metaphor creaks. What > should we make of bacteria which exchange DNA with other species of > bacteria? That the human concept of 'species' does not really apply to bacteria. And similarly, that the CompSci concept of 'class' may also not always fit what we want to model. > Which is the ancestor and which is the descendant? How about > symbionts like lichen? What about when we splice genes from one species > into another? So even in real life, there are multiple inheritance and > mixins. Good point. -- Terry Jan Reedy From tjreedy at udel.edu Sat Sep 24 20:40:36 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 Sep 2011 20:40:36 -0400 Subject: Why is the shutil module called shutil? In-Reply-To: References: Message-ID: On 9/23/2011 11:36 PM, Fletcher Johnson wrote: > The topic says it all: > Why is shutil named shutil? What does it stand for? This is just a > mild curiosity of mine. > The shutil module for reference: http://docs.python.org/library/shutil.html#module-shutil I think it would be nice if the doc explained. Feel free to open a doc issue to add '(sh-ell util-ities)' or something after "The shutil " and add me, terry.reedy, as nosy. -- Terry Jan Reedy From lists at cheimes.de Sat Sep 24 20:51:28 2011 From: lists at cheimes.de (Christian Heimes) Date: Sun, 25 Sep 2011 02:51:28 +0200 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: Am 25.09.2011 01:33, schrieb Benjamin Kaplan: > There is no binary installer on that page. That means you downloaded > the source code and compiled it yourself. Yes, you didn't patch it. > But it's still a self-compiled version of Python. > > In order to get zlib in a self-compiled version of Python, you need to > install the appropriate -dev package. From a quick look at the > repository, I think it's zlib1g-dev but I'm not sure. > > On Ubuntu, the development headers are in a different package than the > libraries themselves. The development headers aren't needed when > you're installing a binary that someone else compiled (for instance, > anything you get from the package manager) but are needed if you're > trying to build anything that uses the library. Since a good chunk of > the Python stdlib isn't actually necessary to run Python, you can > successfully build Python without getting a good chunk of the modules. > ../configure will give you a list of the modules that won't get built > at the end of its output. On recent Ubuntu and Debian versions, the dev packages aren't enough for old versions of Python. Anything older than Python 2.7.2 requires a tweak in order to make Python find the shared libraries. It's all explained in my blog posting. Debian's new multiarch features has broken Python's main setup.py because it tries to find the libraries itself instead of relying on ld.so and gcc. Barry has already fixed the issue for 2.7.2 and recent 3.2. Christian PS: Linux 3.x is going to cause trouble with older versions of Python, too. Wanna know more? Have a look: http://lipyrary.blogspot.com/ From steve+comp.lang.python at pearwood.info Sat Sep 24 22:13:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 12:13:26 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7e8e47$0$29966$c3e8da3$5496439d@news.astraweb.com> Arnaud Delobelle wrote: > On these examples, using fractions is no better than what I suggested > in my previous post. I'm sorry, I can't see your previous post. Perhaps it isn't available on my news provider? -- Steven From steve+comp.lang.python at pearwood.info Sat Sep 24 22:36:42 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 12:36:42 +1000 Subject: Suggested coding style References: <20110924191048.GH19422@johnsons-web.com> Message-ID: <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> MRAB wrote: > On 24/09/2011 20:10, Tim Johnson wrote: >> * Passiday [110924 09:47]: >> <...> >>> I have been coding in many other languages, most of the time it was >>> Java and C#. I don't like the function mess of PHP (ie, loads and >>> loads of functions without any namespaces etc), but I'd like to think >>> that Python is different. >> It is ... >> >>> In my brief coding experience I have stumbled upon Python zfill(width) >>> method, and I thought, really, do you have to include such a narrow- >>> purpose method in the basic method set? Perhaps there are more such >>> methods that are nice when you need them, but then again, you don't >>> put all the possible methods in the standard set. >> I think that you have raised an interesting question here. I've >> been coding in python for 9 years and I have never used it. >> >>> Perhaps there is reason such method is in the basic library, and my >>> complaints are unbased? >> >> It could be some sort of legacy. I imagine we will hear from some >> more senior pythonists on this matter. >> > The documentation says "New in version 2.2.2". Which is about nine years old, so roughly half as old as Python itself. It's hardly a new feature. Just because Passiday and Tim don't use zfill doesn't mean it's not useful to some people. Here are examples of it in use, or people asking how to format numbers with leading zeroes: http://www.ruby-forum.com/topic/67378 http://stackoverflow.com/questions/134934/display-number-with-leading-zeros http://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros http://msdn.microsoft.com/en-us/library/dd260048.aspx http://www.ozgrid.com/forum/showthread.php?t=64193&page=1 http://www.google.com/codesearch#algXCqBNNP0/utils/zip2rep.py&q=lang:%5Epython$%20zfill%20case:yes&ct=rc&cd=7 http://www.google.com/codesearch#Wnd3W7C0RPM/lives_guide.tar.bz2%7C0MIk12cLwTg/desub.py&q=lang:%5Epython$%20zfill%20case:yes Padding numbers with leading zeroes is very common. I'm surprised that more languages don't make it a string method. -- Steven From jeanpierreda at gmail.com Sat Sep 24 22:55:10 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 24 Sep 2011 22:55:10 -0400 Subject: Suggested coding style In-Reply-To: <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: > Padding numbers with leading zeroes is very common. I'm surprised that > more languages don't make it a string method. By making it a string method, instead of a function, we force all implementations of strings to implement that method. That sort of sucks, and it's a reason not to include it as a method. It can, after all, be implemented as a function, and in doing so (with the appropriate operator overloading) that function could work with multiple implementations of strings. Instead any implementation of a string must implement that method. That's a waste. Of course, one could argue that there are very few string implementations. On the other hand, there were three in the stdlib in 2.x, and there are other concepts of strings (like ropes) that are more efficient for different use-cases. The third string in the stdlib, mmap, didn't even bother implementing the full string interface. It's just so damned big. (Also some methods didn't apply, like zfill, but hey!) At the very least, it's sort of ugly from my perspective to tack on trivial things like this to be string methods. But sure, yeah, as a bonus you get to do fewer imports. That's pretty great too, I guess. Devin On Sat, Sep 24, 2011 at 10:36 PM, Steven D'Aprano wrote: > MRAB wrote: > >> On 24/09/2011 20:10, Tim Johnson wrote: >>> * Passiday ?[110924 09:47]: >>> <...> >>>> I have been coding in many other languages, most of the time it was >>>> Java and C#. I don't like the function mess of PHP (ie, loads and >>>> loads of functions without any namespaces etc), but I'd like to think >>>> that Python is different. >>> ? ?It is ... >>> >>>> In my brief coding experience I have stumbled upon Python zfill(width) >>>> method, and I thought, really, do you have to include such a narrow- >>>> purpose method in the basic method set? Perhaps there are more such >>>> methods that are nice when you need them, but then again, you don't >>>> put all the possible methods in the standard set. >>> ? ?I think that you have raised an interesting question here. I've >>> ? ?been coding in python for 9 years and I have never used it. >>> >>>> Perhaps there is reason such method is in the basic library, and my >>>> complaints are unbased? >>> >>> ? ?It could be some sort of legacy. I imagine we will hear from some >>> ? ?more senior pythonists on this matter. >>> >> The documentation says "New in version 2.2.2". > > Which is about nine years old, so roughly half as old as Python itself. > It's hardly a new feature. > > Just because Passiday and Tim don't use zfill doesn't mean it's not useful > to some people. Here are examples of it in use, or people asking how to > format numbers with leading zeroes: > > http://www.ruby-forum.com/topic/67378 > http://stackoverflow.com/questions/134934/display-number-with-leading-zeros > http://stackoverflow.com/questions/733454/best-way-to-format-integer-as-string-with-leading-zeros > http://msdn.microsoft.com/en-us/library/dd260048.aspx > http://www.ozgrid.com/forum/showthread.php?t=64193&page=1 > > http://www.google.com/codesearch#algXCqBNNP0/utils/zip2rep.py&q=lang:%5Epython$%20zfill%20case:yes&ct=rc&cd=7 > > http://www.google.com/codesearch#Wnd3W7C0RPM/lives_guide.tar.bz2%7C0MIk12cLwTg/desub.py&q=lang:%5Epython$%20zfill%20case:yes > > Padding numbers with leading zeroes is very common. I'm surprised that > more languages don't make it a string method. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From anacrolix at gmail.com Sun Sep 25 00:56:15 2011 From: anacrolix at gmail.com (Matt Joiner) Date: Sun, 25 Sep 2011 14:56:15 +1000 Subject: Why is the shutil module called shutil? In-Reply-To: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> Message-ID: Please continue On Sun, Sep 25, 2011 at 8:36 AM, rantingrick wrote: > On Sep 23, 10:36?pm, Fletcher Johnson wrote: >> The topic says it all: >> Why is shutil named shutil? What does it stand for? This is just a >> mild curiosity of mine. >> The shutil module for reference:http://docs.python.org/library/shutil.html#module-shutil > > Because even after 20 freaking years of evolution Python "heads of > state" (or states of head) cannot be bi-partisan enough to agree on a > freaking File and/or path object; remind you of any "body" we know? > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Sun Sep 25 01:21:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 15:21:31 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > On 9/24/2011 9:53 AM, Steven D'Aprano wrote: [...] >>>>> [0.0 + i*width for i in range(8)] >> [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] >> >> The 4th and 7th values have rounding errors, the rest are exact > > No they are not. Their errors are just smaller and not visible with 16 > digits. Pardon. I meant that they were as close to exact as is possible in binary floats. With the exception of 0.8999... and 1.7999... I don't believe any other float can be closer to the exact value. I did mention that "If the exact value isn't representable as a float, I'm okay with returning the nearest possible float." :) -- Steven From steve+comp.lang.python at pearwood.info Sun Sep 25 01:31:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 15:31:14 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Sun, Sep 25, 2011 at 3:01 AM, Steven D'Aprano > wrote: >> Mark Dickinson wrote: >> >>> Using Fraction for intermediate calculations actually works perfectly >>> for this, since conversions from float to Fraction are exact, while >>> conversions from Fraction to float are correctly rounded. ?So if >>> you're using Python, you're not too bothered about efficiency, and you >>> want provably correctly-rounded results, why not use Fraction? >>> >> Ah, I knew it was too easy! > > Try using Fraction for the start and stop too: If you look again at the code I used, I did. I just did it inside the list comp. >>>> from fractions import Fraction as F >>>> start,stop,n = F(0),F(21,10),7 >>>> [float(start+i*(stop-start)/n) for i in range(n+1)] > [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>>> [float(start+i*(stop-start)/n) for i in range(n+1)] > [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] Something looks a tad suspicious here... the two list comps are identical, but give completely different results, even though you don't re-assign start and stop between calls. You're not editing your results are you? But seriously, you were freaking me out there for a bit. I couldn't see why pulling the conversion to fraction outside of the list comp was giving different results. And then it hit me... >>> 2.1 == F(21, 10) False You're testing different numbers from me. Try again with F(2.1) as the stop value. -- Steven From ladasky at my-deja.com Sun Sep 25 01:38:14 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 24 Sep 2011 22:38:14 -0700 (PDT) Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 24, 6:53?am, Steven D'Aprano wrote: > I'm trying to generate a sequence of equally-spaced numbers between a lower > and upper limit. Given arbitrary limits, what is the best way to generate a > list of equally spaced floats with the least rounding error for each point? > > For example, suppose I want to divide the range 0 to 2.1 into 7 equal > intervals, then the end-points of each interval are: > > (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1) > > and I'd like to return the values in the brackets. Using Decimal or Fraction > is not an option, I must use floats. If the exact value isn't representable > as a float, I'm okay with returning the nearest possible float. Use numpy. >>> from numpy import mgrid >>> seq = mgrid[0.0:2.1:8j] >>> seq array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1]) >>> for x in seq: print repr(x) 0.0 0.29999999999999999 0.59999999999999998 0.89999999999999991 1.2 1.5 1.7999999999999998 2.1000000000000001 From rosuav at gmail.com Sun Sep 25 02:02:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 16:02:47 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:31 PM, Steven D'Aprano wrote:>> If you look again at the code I used, I did. I just did it inside the list> comp. You did, but you created a Fraction from a float; my version used Fraction(21,10) instead of (effectively) Fraction(2.1). My description was a little sloppy, but what I meant was to use Fraction for the actual arguments to the "function" that this is implementing. > Something looks a tad suspicious here... the two list comps are identical, > but give completely different results, even though you don't re-assign > start and stop between calls. You're not editing your results are you? > Whooops! I had a whole lot of other commands in the scrollback (displaying intermediate results and such), and elided the rather crucial reassignment of parameters along with them! Fortunately, thanks to my reiplophobia, I still have the original session up in IDLE. This is even the most recent thing in it. >>> sys.version '3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]' >>> from fractions import Fraction as F >>> start,stop,n = F(0),F(21,10),7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1] >>> start, stop, n = F(-1), F(11,10), 7 >>> [float(start+i*(stop-start)/n) for i in range(n+1)] [-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1] There, now it's honest. Sorry about that!! ChrisA From tjreedy at udel.edu Sun Sep 25 02:07:25 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 Sep 2011 02:07:25 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/25/2011 1:21 AM, Steven D'Aprano wrote: > Terry Reedy wrote: > >> On 9/24/2011 9:53 AM, Steven D'Aprano wrote: > [...] >>>>>> [0.0 + i*width for i in range(8)] >>> [0.0, 0.3, 0.6, 0.8999999999999999, 1.2, 1.5, 1.7999999999999998, 2.1] >>> >>> The 4th and 7th values have rounding errors, the rest are exact >> >> No they are not. Their errors are just smaller and not visible with 16 >> digits. > > Pardon. I meant that they were as close to exact as is possible in binary > floats. With the exception of 0.8999... and 1.7999... I don't believe any > other float can be closer to the exact value. > > I did mention that "If the exact value isn't representable as a float, I'm > okay with returning the nearest possible float." :) I do hope you did not stop with my lead-in sentence, and read to the end, where I gave you most of the answer you were looking for, without using the fractions module. -- Terry Jan Reedy From rosuav at gmail.com Sun Sep 25 02:09:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 25 Sep 2011 16:09:01 +1000 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <9ccee36b-e50a-4d24-92c6-d66a9c9fe12e@8g2000yqm.googlegroups.com> <4e7e0cfd$0$29992$c3e8da3$5496439d@news.astraweb.com> <4e7ebca3$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Sep 25, 2011 at 3:31 PM, Steven D'Aprano wrote: >>>> 2.1 == F(21, 10) > False > Ahh, but that may just mean that Fraction doesn't implement an == that compares with floats. >>> 2.1==float(F(21,10)) True This may be because one oughtn't to use == with floats anyway. >>> F(2.1)==F(21,10) False >>> F(2.1) Fraction(4728779608739021, 2251799813685248) That denominator is a power of 2 (2**51 as it happens), which is unsurprising for something created from an IEEE floating point value. Rounding F(21,10) off to fit into float produces this same value. ChrisA From jialiuonlineshoe01 at 163.com Sun Sep 25 02:42:44 2011 From: jialiuonlineshoe01 at 163.com (amy) Date: Sat, 24 Sep 2011 23:42:44 -0700 (PDT) Subject: paypal wholesale NBA shoes (paypal payment)( http://www.24hour-buy.com/ ) Message-ID: <400cec1f-767d-4f99-9f2d-2188105f6d2b@k10g2000vbn.googlegroups.com> paypal wholesale d&g shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale lv shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale NBA shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale nike (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale adidas shoes (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale gucci shoes (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale bape hoody (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale antick jeans (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale diesel jeans (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale artful dudger (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale bag(lv gucci coach chanel d&g dior ed fendi ) (paypal payment)(http://www.24hour-buy.com/) paypal wholesale clothing (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale lrg,jeans,hoody, (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale evisu jeans,hoody,shirt (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Prada (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Puma (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Sand (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Shox (paypal payment)( http://www.24hour-buy.com/) paypal wholesale soccer (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale gucci (paypal payment)( http://www.24hour-buy.com/) paypal wholesale Versace (paypal payment) ( http://www.24hour-buy.com/ ) paypal wholesale Women (paypal payment) ( http://www.24hour-buy.com/) paypal wholesale Y-3 (paypal payment)( http://www.24hour-buy.com/ ) From ramapraba2653 at gmail.com Sun Sep 25 02:57:09 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 24 Sep 2011 23:57:09 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: <31d837d8-5274-4b9a-a1e8-f11cfc7779b1@i9g2000yqe.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ FOR FAST UPDATES IN TELUGU FILM INDUSTRY TAMIL ACTRESS HOT PHOTO SHOOT http://allyouwants.blogspot.com/2011/08/tamil-actress.html SOUTH INDIAN HOT ACTRESS PICS http://allyouwants.blogspot.com/2011/08/hot-actress.html DEEPIKA PADUKONE IN DUM MARO DUM MOVIE http://allyouwants.blogspot.com/2011/08/deepika-in-dum-maro-dum.html PRIYAMANI SPICY PHOTOS IN COW GIRL http://allyouwants.blogspot.com/2011/02/priyamani-spicy-photo-shoot-cow-girl.html KAJAL HOT PHOTOS IN SAREE http://allyouwants.blogspot.com/2011/06/kajal-very-spice-pics.html FOR ONLY HOT GUYS SEE THIS KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From arnodel at gmail.com Sun Sep 25 03:36:23 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 25 Sep 2011 08:36:23 +0100 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 24 September 2011 23:10, Terry Reedy wrote: > On 9/24/2011 10:18 AM, Arnaud Delobelle wrote: >> ? ? ?((n-i)*a + i*b)/n for i in range(n+1) > >>>> ['%20.18f' % x for x in [((7-i)*0.0 + i*2.1)/7 for i in range(8)]] > ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', > '0.900000000000000133', '1.199999999999999956', '1.500000000000000000', > '1.800000000000000266', '2.100000000000000089'] > > In the two places where this disagrees with the previous result, I believe > it is worse. The *0.0 adds nothing. You are still multiplying an inexactly > represented 2.1 by increasingly large numbers. Even 7*2.1/7 is not exact! Of course *0.0 adds nothing in this case. I was suggesting a general solution to the problem of partitioning the interval (a, b) into n subintervals of equal length. As for 7*2.1/7 it is exactly the same as 21/10 to 18 decimal places as the output of your own solution shows below. [...] > The best you can do for this example is >>>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] > ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', > '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', > '1.800000000000000044', '2.100000000000000089'] Can you give an implementation for any interval (a, b) where a, b are floats and any partition size n where n is a positive int? My suggestion was a simple answer which tries to avoid the obvious pitfalls that the naive approaches may fall into, as shown >>> def bary(start, stop, n): ... return [((n-i)*start + i*stop)/n for i in range(n+1)] ... >>> def width(start, stop, n): ... width = stop - start ... return [start + i*width/n for i in range(n+1)] ... Here is where the 'width' approach will fail: >>> width(-1.0, 1e-20, 4) [-1.0, -0.75, -0.5, -0.25, 0.0] >>> bary(-1.0, 1e-20, 4) [-1.0, -0.75, -0.5, -0.25, 1e-20] -- Arnaud From steve+comp.lang.python at pearwood.info Sun Sep 25 05:30:03 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 25 Sep 2011 19:30:03 +1000 Subject: Generating equally-spaced floats with least rounding error References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> <4e7eba5c$0$30000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e7ef49b$0$29987$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > I do hope you did not stop with my lead-in sentence, and read to the > end, where I gave you most of the answer you were looking for, without > using the fractions module. Yes, I read your entire post, thank you, and for my purposes I'm happy with the fractions module. -- Steven From t.omahony.dublin at gmail.com Sun Sep 25 08:31:50 2011 From: t.omahony.dublin at gmail.com (Timmy O'Mahony) Date: Sun, 25 Sep 2011 05:31:50 -0700 (PDT) Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server Message-ID: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Hey, I have a question on Stackoverflow at the moment that I thought I would put up here as it might get some more eyes (It has a bounty so feel free to answer there if you have a SO account!) ---- I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: - Log in to a remote website (this works) - Move to another page (this works) - Perform a POST by filling in a form (read on ...!) I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with different versions of python but the exact same packages (via pip requirements file), and the code only works on the two virtualenvs on my local development machine(2.6.1 and 2.7.2) - it won't work on either of my production VPSs :( In the failing cases, I can log in successfully, move to the correct page but when I submit the form, the remote server replies telling me that there has been an error - it's an application server error page ('we couldn't complete your request') and not a webserver error. - because I can successfully log in and maneuver to a second page, this doesn't seem to be a session or a cookie problem - it's particular to the final POST - because I can perform the operation on a particular machine with the EXACT same headers and data, this doesn't seem to be a problem with what I am requesting/posting - because I am trying the code on two separate VPS rented from different companies, this doesn't seem to be a problem with the VPS physical environment - because the code works on 2 different python versions, I can't imagine it being an incompabilty problem I'm completely lost at this stage as to why this wouldn't work. I've even 'turned-it-off-and-turn-it-on-again' because I just can't see what the problem could be. I've tried everything I can think of to get this working. I've been through all of the headers of the requests & responses and they are all the same between machines. The server I am trying to contact is a Tomcat server. It gives me a cookie called JSESSIONID and it also requires an apache.struct.token in the POST data which I am succesfully extracting with BeautifulSoup/lxml. Again, this works on 2 machines, so I don't think it's an ommision on my behalf, I think it's a compatibility or an encoding error. Any ideas welcome! From eaglebalti at gmail.com Sun Sep 25 09:47:43 2011 From: eaglebalti at gmail.com (Ashraf Ali) Date: Sun, 25 Sep 2011 06:47:43 -0700 (PDT) Subject: Information About Bollywood Famous Actresses Just For You Message-ID: <353fde50-2433-4cae-84b0-73b36871c95d@q26g2000vby.googlegroups.com> Just Visit and know about bollywood beautiful actresses http://bollywoodhotwallpaperz.blogspot.com/ From jeanpierreda at gmail.com Sun Sep 25 11:53:59 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 11:53:59 -0400 Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server In-Reply-To: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> References: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Message-ID: It might help to give more information about the machines. In particular, what versions of Python are on the production machines? Devin On Sun, Sep 25, 2011 at 8:31 AM, Timmy O'Mahony wrote: > Hey, I have a question on Stackoverflow at the moment that I thought I would put up here as it might get some more eyes (It has a bounty so feel free to answer there if you have a SO account!) > > ---- > > I have some test code (as a part of a webapp) that uses urllib2 to perform an operation I would usually perform via a browser: > > - Log in to a remote website (this works) > - Move to another page (this works) > - Perform a POST by filling in a form (read on ...!) > > I've created 4 separate, clean virtualenvs (with --no-site-packages) on 3 different machines, all with different versions of python but the exact same packages (via pip requirements file), and the code only works on the two virtualenvs on my local development machine(2.6.1 and 2.7.2) - it won't work on either of my production VPSs :( > > In the failing cases, I can log in successfully, move to the correct page but when I submit the form, the remote server replies telling me that there has been an error - it's an application server error page ('we couldn't complete your request') and not a webserver error. > > - because I can successfully log in and maneuver to a second page, this doesn't seem to be a session or a cookie problem - it's particular to the final POST > > - because I can perform the operation on a particular machine with the EXACT same headers and data, this doesn't seem to be a problem with what I am requesting/posting > > - because I am trying the code on two separate VPS rented from different companies, this doesn't seem to be a problem with the VPS physical environment > > - because the code works on 2 different python versions, I can't imagine it being an incompabilty problem > I'm completely lost at this stage as to why this wouldn't work. I've even 'turned-it-off-and-turn-it-on-again' because I just can't see what the problem could be. > > I've tried everything I can think of to get this working. I've been through all of the headers of the requests & responses and they are all the same between machines. > > The server I am trying to contact is a Tomcat server. It gives me a cookie called JSESSIONID and it also requires an apache.struct.token in the POST data which I am succesfully extracting with BeautifulSoup/lxml. Again, this works on 2 machines, so I don't think it's an ommision on my behalf, I think it's a compatibility or an encoding error. > > Any ideas welcome! > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From t.omahony.dublin at gmail.com Sun Sep 25 12:48:22 2011 From: t.omahony.dublin at gmail.com (Timmy O'Mahony) Date: Sun, 25 Sep 2011 09:48:22 -0700 (PDT) Subject: Inexplicable Urllib2 problem between virtualenv's when POSTing to a Tomcat server In-Reply-To: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> References: <27195078.132.1316953910769.JavaMail.geo-discussion-forums@yqgn17> Message-ID: <21653630.520.1316969302334.JavaMail.geo-discussion-forums@yqjw35> Good point. The two machines that the code works with are running python 2.6.1 and 2.7.2 and are running on my Mac (Snow Leopard) The two non-working machines are running python 2.6.6 and 2.7.1 and are on Debian 6 and Debian 5 respectively. They are VPSs managed by different providers. All of the installs are on separate virtuaenvs. From tim at akwebsoft.com Sun Sep 25 14:46:14 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 10:46:14 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110925184614.GK19422@johnsons-web.com> * Devin Jeanpierre [110924 19:07]: > > Padding numbers with leading zeroes is very common. I'm surprised that > > more languages don't make it a string method. > > By making it a string method, instead of a function, we force all > implementations of strings to implement that method. That sort of > sucks, and it's a reason not to include it as a method. Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) Just answer the first question, the second is rhetorical. I think that your answer, regardless of whether I agree with it may edify me serendipitously. > It can, after all, be implemented as a function, and in doing so > (with the appropriate operator overloading) that function could > work with multiple implementations of strings. Instead any > implementation of a string must implement that method. That's a > waste. I'm not sure what you mean. I've written my own `split' function. I don't believe that there would be any conflict if you wrote your own `zfill' function. Or if there would be, I'd want to know before I hurt myself. regards -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From petite.abeille at gmail.com Sun Sep 25 14:54:28 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Sun, 25 Sep 2011 20:54:28 +0200 Subject: Suggested coding style In-Reply-To: <20110925184614.GK19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> Message-ID: <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) It's a technical term: http://www.osnews.com/images/comics/wtfm.jpg From rantingrick at gmail.com Sun Sep 25 16:30:41 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 13:30:41 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> Message-ID: <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> On Sep 24, 11:56?pm, Matt Joiner wrote: > Please continue Well specifically we should have a look over the Ruby API's of "File", "Dir", and "IO". I don't believe we should copy them verbatim --as the Ruby API is not Pythonic-- however, it may be a good starting point for something that has been decades overdue within this community. There was the rejected Path object from PEP 355: http://www.python.org/dev/peps/pep-0355/ But it seems the "Anointed One" tossed the idea due to it's "versatility" and it being a subclass of string... is he joking? o_O First of all, what the hell is wrong with versatility Mr Van Rossum? Where else would you put these methods? True it may be a large collection, however, can YOU offer any suggestions as to where else we would put them or are YOU just going to latch on to your prejudices of path objects like your irrational fears of functional programming? Do you remember the map and lambda fiasco? We need you to get on board and push something through. When you hide your head in the sand and imagine everything is "peachy cream" you expose your backside for a swift kicking. [References:] Ruby File Object: http://www.ruby-doc.org/core/classes/File.html Ruby Dir Object: http://ruby-doc.org/core/classes/Dir.html Ruby IO Object: http://www.ruby-doc.org/core/classes/IO.html From rosuav at gmail.com Sun Sep 25 17:48:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 07:48:29 +1000 Subject: Suggested coding style In-Reply-To: <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille wrote: > > On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > >> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) > > It's a technical term: > > http://www.osnews.com/images/comics/wtfm.jpg Also, because technical people are opinionated windbags. Goes with the territory. :) Actually, it's partly because it's so easy to create standards. You don't like X? Create your own language in which it doesn't exist! You absolutely detest Y? Ignore it and use something else! But since we can't ignore _everything_ we dislike, there ends up a happy medium in which we all use the things that we dislike least, all the while ranting about those aspects of them that "absolutely, totally suck", and vowing that we could have done way better if we'd been in the position of Some Famous Guy back when he had that perfect opportunity to create a new and perfect standard, but he *blew it* by having a small and narrow view, etc, etc, etc... Of course, some of us manage to still be courteous and objective when discussing the things that suck, while others just go off on lengthy rants. And if you're willing to learn, it's not uncommon to start off complaining and end up appreciating. :) Chris Angelico From jeanpierreda at gmail.com Sun Sep 25 17:52:35 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 17:52:35 -0400 Subject: Why is the shutil module called shutil? In-Reply-To: <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: > Well specifically we should have a look over the Ruby API's of "File", > "Dir", and "IO". I don't believe we should copy them verbatim --as the > Ruby API is not Pythonic-- however, it may be a good starting point > for something that has been decades overdue within this community. Perhaps you would be interested in one of the recent threads on Python-Ideas. http://mail.python.org/pipermail/python-ideas/2011-September/011559.html Also please stop being abrasive and personally attacking other members of the Python community. Devin On Sun, Sep 25, 2011 at 4:30 PM, rantingrick wrote: > On Sep 24, 11:56?pm, Matt Joiner wrote: >> Please continue > > Well specifically we should have a look over the Ruby API's of "File", > "Dir", and "IO". I don't believe we should copy them verbatim --as the > Ruby API is not Pythonic-- however, it may be a good starting point > for something that has been decades overdue within this community. > > There was the rejected Path object from PEP 355: > ? ?http://www.python.org/dev/peps/pep-0355/ > > But it seems the "Anointed One" tossed the idea due to it's > "versatility" and it being a subclass of string... is he joking? o_O > > First of all, what the hell is wrong with versatility Mr Van Rossum? > Where else would you put these methods? True it may be a large > collection, however, can YOU offer any suggestions as to where else we > would put them or are YOU just going to latch on to your prejudices of > path objects like your irrational fears of functional programming? Do > you remember the map and lambda fiasco? > > We need you to get on board and push something through. When you hide > your head in the sand and imagine everything is "peachy cream" you > expose your backside for a swift kicking. > > [References:] > > Ruby File Object: > ? ? http://www.ruby-doc.org/core/classes/File.html > > Ruby Dir Object: > ? ?http://ruby-doc.org/core/classes/Dir.html > > Ruby IO Object: > ? ?http://www.ruby-doc.org/core/classes/IO.html > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at gmail.com Sun Sep 25 18:39:47 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 25 Sep 2011 23:39:47 +0100 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Sep 25, 2011 10:49 PM, "Chris Angelico" wrote: > And if you're willing to learn, it's not uncommon to start off > complaining and end up appreciating. :) +1 QOTW -- Arnaud -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Sun Sep 25 18:50:17 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 15:50:17 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: Here is a *very* rough outline of my ideas. There are probably a few mistakes in there. I've decided on three main main objects. A File object, a Path object, and a Dir object. ## START ENLIGHTENMENT ## class Path: def __init__(self, path): # # Properties about the path: drive => str directory => str filename => str extension => str uncshare[1]=> ??? # # Mutations. def coerce(self) => File or Dir def normalize(self): => ip or Path? #normcase/normpath def expand_user(self): => ip or Path? def expand_vars(self): => ip or Path? def absolute(self) => ip or Path? #realpath/abspath def strip(self) => ip => remove one extension. def chmod(self, mode) => None def chown(self, uid, gid) => None [1] def rename(self, newname) => None def access(self, mode): => None #access def chroot(self) => None # # Introspection. def is_valid(self): # exists def is_absolute(self): #isabs def is_directory(self): #isdir def is_file(self): #isfile def is_link(self): #islnk def is_mount(self): #ismount def is_identical(self, other): #issamefile def time_accessed(self): #atime def time_modified(self): #mtime def time_changed(self): #ctime ## def utime(self, times) => None # # Inspection. def info_stat(self): #stat def info_lstat(self): #lstat def info_statvfs(self): #statvfs # # Extraction. def basename(self): => str #Do we need basename when properties exist? def partition(self) => (drive, path, filename, extension) #Do we need partition when properties exist? def splitunc(self): ??? def splitall(self): ??? def relpathto(self, dest): => ??? def pathconf(self, name): #pathconfig # # Modifying operations on links def link(self, newpath): ... def symlink(self, newlink): ... def readlink(self): ... def readlinkabs(self): ... class File: def new(path) (...All existing file methods here...) # # Mutate, Clone, Destroy. def rename(self, newname) => ip or File? def delete(self, overwrites=3) => None def copy(self, dst) => File def unlink(self) => None # # # Attribute mutation. def update(self) => None #touch def copy_mode(src) => None #copymode def copy_stat(src) => None #copystat def update_mode(dst) => None def update_stat(dst) => None # # Other def bytes(self): => int => 1292894 def size(self, fmtstr="{0:0.2f}") => str => "1.23 MB" def backup(self) => filename.bak{count} class Dir: def new(path) def open(path) # # Mutate, Clone, Destroy. def delete(self, onerror=None): => None def copy(self, dst, symlinks=True): => Dir # # Introspection. def get_paths(self, pattern=None): [Path, Path, ...] def get_dirs(self, pattern=None): => [Dir, Dir, ...] def get_files(self, pattern=None): => [File, File, ...] # def walk_paths(self, pattern=None): itereach->PathObj def walk_dirs(self, pattern=None): itereach->DirObj def walk_files(self, pattern=None): itereach->FileObj # def match(self, pattern) => bool def glob(self, pattern): => [Path, Path, ...] ####################################### # Not sure what to do with these yet. ####################################### def startfile(self) # startfile should part of os anyway. ## END ENLIGHTENMENT ## From rantingrick at gmail.com Sun Sep 25 19:50:13 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 25 Sep 2011 16:50:13 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> Message-ID: <605ac6e9-0a83-4658-9240-8889980b1862@8g2000yqm.googlegroups.com> Oh the creative juices are flowing now!!! class Path: def __init__(self, path): def __coerce__(self) => File or Dir # # Properties about the path: drive => str directory => str filename => str extension => str ## uncshare[1]=> ??? # # Mutations. def expand_user(self): => ip or Path? def expand_vars(self): => ip or Path? def to_normpath(self): => ip #normcase/normpath def to_abspath(self) => ip #realpath/abspath def set_access(self, mode) => None def set_owner(self, uid, gid) => None def set_root(self, path) => None # # Introspection. def is_accessable(self, mode) => bool #access def is_valid(self) => bool # exists def is_absolute(self) => bool #isabs def is_directory(self) => bool #isdir def is_file(self) => bool #isfile def is_link(self) => bool #islnk def is_mount(self) => bool #ismount def is_same(self, path_Dir_or_File) => bool #issamefile # # Inspection, Extraction def get_abspath(self)=> Path def get_normpath(self) => Path ## def get_atime(self) => str #atime ## def get_mtime(self) => str #mtime ## def get_ctime(self) => str #ctime def get_stat(self) => stat #stat,lstat ## def get_statvfs(self) => stat #statvfs ## # do we really need this antiquity? ############################################################ # Question # ############################################################ # Should all the stat stuff like get_mtime, get_ctime, # # get_atime, etc... be accessed only under get_stat? I # # believe so! # ############################################################ def get_drive(self): => str def get_directory(self): => str def get_filename(self): => str (empty if is_dir) def get_extension(self): => str (empty if is_dir) # def split(self) => (drive, path, filename, extension) ## def splitunc(self): ??? ## def splitall(self): ??? ## def relpathto(self, dest): => ??? ## def pathconf(self, name): #pathconfig # # Modifying operations on links def link_new(self, newpath, symbolic=False): ... def link_read(self): ... def link_readabs(self): ... class File: def new(path) (...All existing file methods here...) # # Mutate, Clone, Destroy. def rename(self, newname) => ip or File? def delete(self, overwrites=3) => None def copy(self, dst) => File def unlink(self) => None # # # Attribute mutation. def update(self) => None #touch def copy_mode(src) => None #copymode def copy_stat(src) => None #copystat def update_mode(dst) => None def update_stat(dst) => None # # Other def get_bytes(self): => int => 1292894 def get_size(self, fmtstr="{0:0.2f}") => str => "1.23 MB" def backup(self) => filename.bak{count} class Dir: def new(path) def open(path) # # Mutate, Clone, Destroy. def delete(self, onerror=None): => None def copy(self, dst, symlinks=True): => Dir # # Introspection. def get_paths(self, pattern=None): [Path, Path, ...] def get_dirs(self, pattern=None): => [Dir, Dir, ...] def get_files(self, pattern=None): => [File, File, ...] def walk_paths(self, pattern=None): itereach->PathObj def walk_dirs(self, pattern=None): itereach->DirObj def walk_files(self, pattern=None): itereach->FileObj ############################################################ # Question # ############################################################ # Do we really need "get_*" AND "walk_*"? I believe we # # should choose one set of three # ############################################################ def match(self, pattern) => bool # Do we need match when re would suffice? def glob(self, pattern): => [Path, Path, ...] ############################################################ # Excommunicated Methods. ############################################################ def startfile(self) # startfile should part of os anyway. From jeanpierreda at gmail.com Sun Sep 25 20:23:47 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 20:23:47 -0400 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: > Why does it suck? The gist of what I was saying is that it's possible to define functions that do this "generically" so that one implementation of zfill can work with multiple implementations of strings. Having to reimplement every time when one implementation would do is bothersome and generally isn't done unless it has to be (thus why mmap lacks a zfill method). Having to do more work than necessary "sucks", as does having partial str implementations that don't do everything str does. Ideally, I would claim that if some interface will have multiple implementations, it should have as few methods as possible to make implementation as easy as possible, and move as much as possible _away_ from methods and into functions that work with arbitrary implementations of the interface. This minimizes the amount of work that must be done for implementors and thus makes life better. It's also true that it's "bad practice" to have objects with large APIs, not for convenience reasons but because it increases object coupling, something that "good" object oriented design seeks to eliminate. The idea there is that the less ways you can have your object interacted with / interact with other objects, the easier it is to think of the way state flows. I agree with this in principle, but it doesn't really matter for strings. The situation I see with something like zfill as-a-method is that it has nearly negligible benefit (less imports vs function?) and some detriment. So I would conclude it should not exist. Other people look at this differently. > Also, because technical people are opinionated windbags. Pardon? Devin On Sun, Sep 25, 2011 at 5:48 PM, Chris Angelico wrote: > On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille > wrote: >> >> On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: >> >>> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) >> >> It's a technical term: >> >> http://www.osnews.com/images/comics/wtfm.jpg > > Also, because technical people are opinionated windbags. Goes with the > territory. :) Actually, it's partly because it's so easy to create > standards. You don't like X? Create your own language in which it > doesn't exist! You absolutely detest Y? Ignore it and use something > else! But since we can't ignore _everything_ we dislike, there ends up > a happy medium in which we all use the things that we dislike least, > all the while ranting about those aspects of them that "absolutely, > totally suck", and vowing that we could have done way better if we'd > been in the position of Some Famous Guy back when he had that perfect > opportunity to create a new and perfect standard, but he *blew it* by > having a small and narrow view, etc, etc, etc... > > Of course, some of us manage to still be courteous and objective when > discussing the things that suck, while others just go off on lengthy > rants. And if you're willing to learn, it's not uncommon to start off > complaining and end up appreciating. :) > > Chris Angelico > -- > http://mail.python.org/mailman/listinfo/python-list > From python at mrabarnett.plus.com Sun Sep 25 20:47:58 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 26 Sep 2011 01:47:58 +0100 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <4E7FCBBE.4070806@mrabarnett.plus.com> On 26/09/2011 01:23, Devin Jeanpierre wrote: >> Why does it suck? > > The gist of what I was saying is that it's possible to define > functions that do this "generically" so that one implementation of > zfill can work with multiple implementations of strings. Having to > reimplement every time when one implementation would do is bothersome > and generally isn't done unless it has to be (thus why mmap lacks a > zfill method). Having to do more work than necessary "sucks", as does > having partial str implementations that don't do everything str does. > > Ideally, I would claim that if some interface will have multiple > implementations, it should have as few methods as possible to make > implementation as easy as possible, and move as much as possible > _away_ from methods and into functions that work with arbitrary > implementations of the interface. This minimizes the amount of work > that must be done for implementors and thus makes life better. > [snip] I would have thought that a better solution would be to specify a minimal set of methods in an abstract superclass and write the additional methods using that minimal set. The concrete string implementations would be descended from the superclass and would still be able to override the additional methods with more efficient code were desired, such as in the 'str' class. From tjreedy at udel.edu Sun Sep 25 20:58:57 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 Sep 2011 20:58:57 -0400 Subject: Generating equally-spaced floats with least rounding error In-Reply-To: References: <4e7de0d7$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 9/25/2011 3:36 AM, Arnaud Delobelle wrote: > On 24 September 2011 23:10, Terry Reedy wrote: >> The best you can do for this example is >>>>> ['%20.18f' % (i/10 ) for i in range(0, 22, 3)] >> ['0.000000000000000000', '0.299999999999999989', '0.599999999999999978', >> '0.900000000000000022', '1.199999999999999956', '1.500000000000000000', >> '1.800000000000000044', '2.100000000000000089'] > > Can you give an implementation for any interval (a, b) where a, b are > floats and any partition size n where n is a positive int? I was leaving that as an exercise for Stephen ;-) but since he is satisfied with using Franctions ... I accepted the challenge and (I believe) did it. I first separated float-fractions conversions from generating equally spaced fractions. While this does not make much if any difference if and when one converts back to floats, testing with (21,10), for instance, as input is much easier than with (2.1).as_integer_ratio() == (4728779608739021, 2251799813685248). In some applications, small integer ratios are wanted anyway instead of floats. The main complication in the code is getting all outputs to have the smallest possible common denominator across the entire series. #! python3 -- frange.py # Copyright 2011 Terry Jan Reedy: use with acknowledgement '''Generate n+1 equally spaced fractions or float given two endpoints and the number n of intervals''' from fractions import gcd def floatrange(a, b, n): '''Yield floats a, b, and n-1 equally spaced floats in between.''' for num,dem in fracrange(a.as_integer_ratio(), b.as_integer_ratio(), n): yield num/dem def fracrange(frac1, frac2, n): '''Yield fractions frac1, frac2 and n-1 equally spaced fractions in between. Fractions are represented as (numerator, denominator > 0) pairs. For output, use the smallest common denominator of the inputs that makes the numerator range an even multiple of n. ''' n1, d1 = frac1 n2, d2 = frac2 dem = d1 * d2 // gcd(d1, d2) start = n1 * (dem // d1) stop = n2 * (dem // d2) rang = stop - start q, r = divmod(rang, n) if r: gcd_r_n = gcd(r, n) m = n // gcd_r_n dem *= m start *= m stop *= m step = rang // gcd_r_n # rang * m // n else: step = q # if r==0: gcd(r,n)==n, m==1, rang//n == q for num in range(start, stop+1, step): yield num,dem for (i,j), x in zip(fracrange((0,1), (21,10), 7), floatrange(0.0, 2.1, 7)): print((i,j), '%20.18f' % (i/j ), '%20.18f' % x ) print() for i,j in fracrange((1,10), (22,10), 7): print(i,j) print() for i,j in fracrange((1,5), (1,1), 6): print(i,j) # output (0, 10) 0.000000000000000000 0.000000000000000000 (3, 10) 0.299999999999999989 0.299999999999999989 (6, 10) 0.599999999999999978 0.599999999999999978 (9, 10) 0.900000000000000022 0.900000000000000022 (12, 10) 1.199999999999999956 1.199999999999999956 (15, 10) 1.500000000000000000 1.500000000000000000 (18, 10) 1.800000000000000044 1.800000000000000044 (21, 10) 2.100000000000000089 2.100000000000000089 1 10 4 10 7 10 10 10 13 10 16 10 19 10 22 10 3 15 5 15 7 15 9 15 11 15 13 15 15 15 -- Terry Jan Reedy From jeanpierreda at gmail.com Sun Sep 25 21:15:49 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 25 Sep 2011 21:15:49 -0400 Subject: Suggested coding style In-Reply-To: <4E7FCBBE.4070806@mrabarnett.plus.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <4E7FCBBE.4070806@mrabarnett.plus.com> Message-ID: > I would have thought that a better solution would be to specify a > minimal set of methods in an abstract superclass and write the > additional methods using that minimal set. > > The concrete string implementations would be descended from the > superclass and would still be able to override the additional methods > with more efficient code were desired, such as in the 'str' class. This does sound better to me too! Devin On Sun, Sep 25, 2011 at 8:47 PM, MRAB wrote: > On 26/09/2011 01:23, Devin Jeanpierre wrote: >>> >>> ?Why does it suck? >> >> The gist of what I was saying is that it's possible to define >> functions that do this "generically" so that one implementation of >> zfill can work with multiple implementations of strings. Having to >> reimplement every time when one implementation would do is bothersome >> and generally isn't done unless it has to be (thus why mmap lacks a >> zfill method). Having to do more work than necessary "sucks", as does >> having partial str implementations that don't do everything str does. >> >> Ideally, I would claim that if some interface will have multiple >> implementations, it should have as few methods as possible to make >> implementation as easy as possible, and move as much as possible >> _away_ from methods and into functions that work with arbitrary >> implementations of the interface. This minimizes the amount of work >> that must be done for implementors and thus makes life better. >> > [snip] > I would have thought that a better solution would be to specify a > minimal set of methods in an abstract superclass and write the > additional methods using that minimal set. > > The concrete string implementations would be descended from the > superclass and would still be able to override the additional methods > with more efficient code were desired, such as in the 'str' class. > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Sun Sep 25 21:42:55 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 11:42:55 +1000 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: On Mon, Sep 26, 2011 at 10:23 AM, Devin Jeanpierre wrote: >> Also, because technical people are opinionated windbags. > > Pardon? No offense intended; just look at this list and you'll see how opinionated people can be, and how willing to express those opinions in many words! Frank and courteous exchange of views, one of the best ways to learn about the subject matter... and about the other programmers too. ChrisA From tim at akwebsoft.com Sun Sep 25 22:55:26 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 18:55:26 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <20110926025526.GN19422@johnsons-web.com> * Devin Jeanpierre [110925 16:37]: > > Why does it suck? > > The gist of what I was saying is that it's possible to define > functions that do this "generically" so that one implementation of > zfill can work with multiple implementations of strings. That is kind of 'spot on' for me. Before I started using python, I worked in rebol - where (at that time), there was a limited number of function names available because of limited namespacing (and the binary was a fraction the size of python). So I learned to take that approach. > Having to > reimplement every time when one implementation would do is bothersome > and generally isn't done unless it has to be (thus why mmap lacks a > zfill method). Having to do more work than necessary "sucks", as does > having partial str implementations that don't do everything str does. > > Ideally, I would claim that if some interface will have multiple > implementations, it should have as few methods as possible to make > implementation as easy as possible, and move as much as possible > _away_ from methods and into functions that work with arbitrary > implementations of the interface. This minimizes the amount of work > that must be done for implementors and thus makes life better. > > It's also true that it's "bad practice" to have objects with large > APIs, not for convenience reasons but because it increases object > coupling, something that "good" object oriented design seeks to > eliminate. The idea there is that the less ways you can have your > object interacted with / interact with other objects, the easier it is > to think of the way state flows. I agree with this in principle, but > it doesn't really matter for strings. > > The situation I see with something like zfill as-a-method is that it > has nearly negligible benefit (less imports vs function?) and some > detriment. So I would conclude it should not exist. Other people look > at this differently. Good response. Thank you. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From tim at akwebsoft.com Sun Sep 25 22:59:20 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Sun, 25 Sep 2011 18:59:20 -0800 Subject: Suggested coding style In-Reply-To: References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> Message-ID: <20110926025920.GO19422@johnsons-web.com> * Chris Angelico [110925 13:50]: > On Mon, Sep 26, 2011 at 4:54 AM, Petite Abeille > wrote: > > > > On Sep 25, 2011, at 8:46 PM, Tim Johnson wrote: > > > >> ?Why does it suck? And why do people say 'suck' so much, especially in technical venues? :) > > > > It's a technical term: > > > > http://www.osnews.com/images/comics/wtfm.jpg > > Also, because technical people are opinionated windbags. Goes with the > territory. :) I always felt that to be courteous, to the point and reserved cost me less typing time. And since I'm self-employed and only charge for productive time for clients, that's being cost-conscious for me. Of course I've been known to get a little crazy about PHP. So don't let me get started... BTW: If you like ranting as a spectator sport, I have found the Common Lisp newsgroup to be among the most spectacular. But that's just me. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From rosuav at gmail.com Sun Sep 25 23:41:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 26 Sep 2011 13:41:29 +1000 Subject: Suggested coding style In-Reply-To: <20110926025920.GO19422@johnsons-web.com> References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <20110926025920.GO19422@johnsons-web.com> Message-ID: On Mon, Sep 26, 2011 at 12:59 PM, Tim Johnson wrote: > BTW: If you like ranting as a spectator sport, I have found the > ?Common Lisp newsgroup to be among the most spectacular. But that's > ?just me. > I do, actually, but I don't need to add another newsgroup. Rick provides plenty of material here, and I can easily sate myself in just a few other places that I frequent. It's quite amusing to watch those holy wars erupt... And every once in a while, they actually prove quite educative. I'm not sure how it happens, nor how to trigger it - hmm, perhaps this should be the subject of a scientific paper. "On ranting newsgroups and how to make them productive". ChrisA From wuwei23 at gmail.com Mon Sep 26 00:18:27 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 25 Sep 2011 21:18:27 -0700 (PDT) Subject: Why is the shutil module called shutil? References: <0af2c0b5-b901-49fb-901c-275e1bd41a66@fx14g2000vbb.googlegroups.com> <683887a6-4a2d-4fef-803f-fb7e694a7845@k34g2000yqm.googlegroups.com> <605ac6e9-0a83-4658-9240-8889980b1862@8g2000yqm.googlegroups.com> Message-ID: <098aa3ae-070f-46c5-99e4-f8b712561029@i33g2000yqm.googlegroups.com> On Sep 26, 9:50?am, rantingrick wrote: > Oh the creative juices are flowing now!!! It's a pity they won't flow into a PyPI project to aggregate interest in such replacement objects. But please, spam us some more with your code stubs. It's a nice change from invective. From bmacinnis at comcast.net Mon Sep 26 03:45:11 2011 From: bmacinnis at comcast.net (bmacinnis at comcast.net) Date: Mon, 26 Sep 2011 03:45:11 -0400 Subject: Counting bits in large string / bit vector Message-ID: In Perl I can create a large bit vector as follows: vec($bitmap,10000000,1) = 0; # this will create a bit string of all zeros To set bits I may using commands like: vec($bitmap,1000, 1) = 1 # turn on bit 1000 vec($bitmap,10000, 1) = 1 # turn on bit 10000 vec($bitmap,1000000, 1) = 1 # turn on bit 10000000 which would set three bits in the string $bitmap - Note: in perl I don't even have to declare $bitmap until I use it in the vec command. Anyway there is a very cool perl command which return the number of bits set in a large bitmap string instantly. The command is: $setbits = unpack("%32b*", $bitmap); Which in this case would store the number 3 in $setbits Is there an equivalent command in python that would immediately provide the number of set bits in a large bit vector/string I know I could loop through but when you have 10,000,000 or 100,000,000 bits, the looping takes quite a while the perl unpack is instant. Thanks for any help you could provide -------------- next part -------------- An HTML attachment was scrubbed... URL: From nizamov.shawkat at gmail.com Mon Sep 26 03:56:56 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Mon, 26 Sep 2011 09:56:56 +0200 Subject: Counting bits in large string / bit vector In-Reply-To: References: Message-ID: > Is there an equivalent command in python that would immediately provide the > number of set bits in a large bit vector/string > You might be able to achieve this using numpy boolean array and, e.g, the arithmetic sum function or something similar. There is also another library http://pypi.python.org/pypi/bitarray which resembles numpy's bit array. Hope it helps, S.Nizamov From gelonida at gmail.com Mon Sep 26 04:55:42 2011 From: gelonida at gmail.com (Gelonida N) Date: Mon, 26 Sep 2011 10:55:42 +0200 Subject: Hierarchical commnd line parsing / help texts Message-ID: Hi, So far I used optparse.OptionParser for parsing command line arguments for my python scripts. So far I was happy, with a one level approach, where I get only one help text Now I'd like to create a slightly different python script and wondered which approach / module might be best for implementing the parsing and generation of help texts. Please look at my example (let's emulate a shell in python) $ ./sh.py or $ ./sh.py -h Should create the top level help text and list possible commands .e.g. ls rm cat and list some commands with potential sub commands .e.g. net db then if I typed ./sh.py -h I'd like to get the helptext for the specified command. For some more complex commands I'd even like to be able to type /sh.py -h Ideally, I would like to be able to parse generic options before commands / sub commands and less generic options after the commands ./sh.py -v ls -a Thanks in advance for suggestions From clp2 at rebertia.com Mon Sep 26 05:10:17 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 26 Sep 2011 02:10:17 -0700 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 1:55 AM, Gelonida N wrote: > Hi, > > So far I used optparse.OptionParser for parsing command line arguments > for my python scripts. So far I was happy, with a one level approach, > where I get only one help text > > Now I'd like to create a slightly different python script and wondered > which approach / module might be best for implementing the parsing and > generation of help texts. > then if I typed ./sh.py -h > I'd like to get the helptext for the specified command. http://docs.python.org/library/argparse.html It is capable of handling sub-commands and the display of subcommand-specific help text. Cheers, Chris From __peter__ at web.de Mon Sep 26 05:11:07 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Sep 2011 11:11:07 +0200 Subject: Counting bits in large string / bit vector References: Message-ID: bmacinnis at comcast.net wrote: > In Perl I can create a large bit vector as follows: > vec($bitmap,10000000,1) = 0; # this will create a bit string of all > zeros > To set bits I may using commands like: > vec($bitmap,1000, 1) = 1 # turn on bit 1000 > vec($bitmap,10000, 1) = 1 # turn on bit 10000 > vec($bitmap,1000000, 1) = 1 # turn on bit 10000000 > which would set three bits in the string $bitmap - Note: in perl I don't > even have to declare $bitmap until I use it in the vec command. > Anyway there is a very cool perl command which return the number of bits > set in a large bitmap string instantly. > The command is: > $setbits = unpack("%32b*", $bitmap); > Which in this case would store the number 3 in $setbits > Is there an equivalent command in python that would immediately provide > the number of set bits in a large bit vector/string > I know I could loop through but when you have 10,000,000 or 100,000,000 > bits, the looping takes quite a while the perl unpack is instant. With numpy: >>> b = numpy.zeros(10**7, dtype=bool) >>> for x in 3, 4, 6: b[10**x] = True ... >>> b.sum() 3 I don't know how it's implemented, but it seems to be quite fast. From gelonida at gmail.com Mon Sep 26 05:28:59 2011 From: gelonida at gmail.com (Gelonida N) Date: Mon, 26 Sep 2011 11:28:59 +0200 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: On 09/26/2011 11:10 AM, Chris Rebert wrote: > On Mon, Sep 26, 2011 at 1:55 AM, Gelonida N wrote: >> Hi, >> >> So far I used optparse.OptionParser for parsing command line arguments >> for my python scripts. So far I was happy, with a one level approach, >> where I get only one help text >> >> Now I'd like to create a slightly different python script and wondered >> which approach / module might be best for implementing the parsing and >> generation of help texts. > >> then if I typed ./sh.py -h >> I'd like to get the helptext for the specified command. > > http://docs.python.org/library/argparse.html > > It is capable of handling sub-commands and the display of > subcommand-specific help text. > Thanks a lot. It seems it's time to start reading about argparse From arnodel at gmail.com Mon Sep 26 06:02:02 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Mon, 26 Sep 2011 11:02:02 +0100 Subject: Counting bits in large string / bit vector In-Reply-To: References: Message-ID: >>>> b = numpy.zeros(10**7, dtype=bool) >>>> for x in 3, 4, 6: b[10**x] = True > ... >>>> b.sum() > 3 Without numpy: >>> counts = [bin(i).count('1') for i in range(256)] >>> bytes = b"hello python"*100000 >>> len(bytes)*8 9600000 >>> sum(map(counts.__getitem__, bytes)) 4800000 Pretty fast as well. -- Arnaud From taleinat at gmail.com Mon Sep 26 07:23:04 2011 From: taleinat at gmail.com (Tal Einat) Date: Mon, 26 Sep 2011 04:23:04 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! Message-ID: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> The library is called RunningCalcs and is useful for running several calculations on a single iterable of values. https://bitbucket.org/taleinat/runningcalcs/ http://pypi.python.org/pypi/RunningCalcs/ I'd like some input on how this could be made more useful and how to spread the word about it. The library contains the base RunningCalc class and implementations of sub-classes for common calculations: sum, min/max, average, variance & standard deviation, n-largest & n-smallest. Additionaly a utility function apply_in_parallel() is supplied which makes running several calculations on an iterable easy (and fast!). Straight-forward example: mean_rc, stddev_rc = RunningMean(), RunningStdDev() for x in values: mean_rc.feed(x) stddev_rc.feed(x) mean, stddev = mean_rc.value, stddev_rc.value Examples using apply_in_parallel(): mean, stddev = apply_in_parallel(values, [RunningMean(), RunningStdDev()]) five_smallest, five_largest = apply_in_parallel(values, [RunningNSmallest(5), RunningNLargest(5)]) Comments and suggestions would be highly appreciated! From casevh at gmail.com Mon Sep 26 11:38:57 2011 From: casevh at gmail.com (casevh) Date: Mon, 26 Sep 2011 08:38:57 -0700 (PDT) Subject: Counting bits in large string / bit vector References: Message-ID: On Sep 26, 12:56?am, Nizamov Shawkat wrote: > > Is there an equivalent command in python that would immediately provide the > > number of set bits in a large bit vector/string > > You might be able to achieve this using numpy boolean array and, e.g, > the arithmetic sum function or something similar. > There is also another library ?http://pypi.python.org/pypi/bitarray > which resembles numpy's bit array. > > Hope it helps, > S.Nizamov You can also use gmpy or gmpy2. >>> a=gmpy2.mpz(123) >>> bin(a) '0b1111011' >>> gmpy2.hamdist(a,0) 6 >>> casevh From magguru.appalakonda at gmail.com Mon Sep 26 11:43:39 2011 From: magguru.appalakonda at gmail.com (Hot Hot) Date: Mon, 26 Sep 2011 08:43:39 -0700 (PDT) Subject: MY HOT BEAUTIFUL VIDEOS Message-ID: <980d6317-f747-498f-bb22-dd8432bf50be@i33g2000yqm.googlegroups.com> Mallika sharawath bolly wood bad sexy seens, Katrina Kaif very bad videos,Bipasa basu hot expose videos with John Abraham,Bollywood star Aishwarya rai romantic videos with Abhishek,At http://starsbikinihotshow140.co.cc/ Due to high sex cantest,I have hidden more details, click on right side of my website do not tell another person. From ian.g.kelly at gmail.com Mon Sep 26 12:39:16 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 26 Sep 2011 10:39:16 -0600 Subject: Counting bits in large string / bit vector Message-ID: On Sep 26, 2011 1:49 AM, wrote: > Is there an equivalent command in python that would immediately provide the number of set bits in a large bit vector/string Besides what others have said, if you expect the number of bits set to be small, you might just use a set. bits = set() # set bit 1000 bits.add(1000) # clear bit 2000000 bits.discard(2000000) # test bit 1000 if 1000 in bits: pass # get number of bits set len(bits) All of these operations are O(1), but if you expect to set a very large number of bits, then the space trade-off may not be practical. Cheers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From rahul_g_chaudhary at yahoo.com Mon Sep 26 13:45:42 2011 From: rahul_g_chaudhary at yahoo.com (Rahul) Date: Mon, 26 Sep 2011 10:45:42 -0700 (PDT) Subject: Python Weekly Message-ID: <13c6df6c-7ab5-4cf6-b82b-9e7631226a8b@i9g2000yqe.googlegroups.com> Hi Everyone, I have started a free weekly newsletter called Python Weekly which includes curated news, articles, new releases, software & tools, events, jobs etc about Python and related technologies. It's a great way to keep abreast of what's happening in Python land. You can subscribe to it here, http://www.pythonweekly.com/ Regards Rahul Chaudhary From jesus.ramirez.utexas at gmail.com Mon Sep 26 14:16:08 2011 From: jesus.ramirez.utexas at gmail.com (Jesramz) Date: Mon, 26 Sep 2011 11:16:08 -0700 (PDT) Subject: Python 2.5 zlib trouble References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> Message-ID: <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> I appreciate all the help, but I am still a little confused. Sorry, I'm a lay person. Should I download zlib1g-dev and install it to get the zlib module? and Alter the configure script to avoid future issues? Also about getting zlib I found the following: "I was able to recompile zlib $./configure --shared then recompile Python 2.5.1; I am now able to import the zlib module. cheers -sg" Does this mean that while in the zlib folder run ./configure shared and then install python? From ramit.prasad at jpmorgan.com Mon Sep 26 14:57:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 26 Sep 2011 14:57:52 -0400 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> > It seems it's time to start reading about argparse FYI, it only appears on Python 2.7+ Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From benjamin.kaplan at case.edu Mon Sep 26 15:04:45 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 26 Sep 2011 15:04:45 -0400 Subject: Python 2.5 zlib trouble In-Reply-To: <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> Message-ID: On Mon, Sep 26, 2011 at 2:16 PM, Jesramz wrote: > > I appreciate all the help, but I am still a little confused. Sorry, > I'm a lay person. > > Should I download zlib1g-dev and install it to get the zlib module? > > and Alter the configure script to avoid future issues? > > Also about getting zlib I found the following: > > "I was able to recompile zlib > > $./configure --shared > > then recompile Python 2.5.1; I am now able to import the zlib module. > > cheers > > -sg" > > Does this mean that while in the zlib folder run ./configure shared > and then install python? > -- Not quite. This person was talking about configuring zlib, not Python. Just about every Linux program out there has a ./configure file- it's part of GNU Autotools, which many programs use as an easy way to compile and install their software. Since the version of zlib on Ubuntu Natty doesn't work for Python 2.5, this person just compiled their own zlib (calling ./configure --shared; make; make install from the zlib *source* folder that they downloaded) and then compiled their own Python version (from the Python source folder that they downloaded) > http://mail.python.org/mailman/listinfo/python-list > From paul.nospam at rudin.co.uk Mon Sep 26 15:44:02 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Mon, 26 Sep 2011 20:44:02 +0100 Subject: Hierarchical commnd line parsing / help texts References: Message-ID: <874nzz3x8d.fsf@no-fixed-abode.cable.virginmedia.net> "Prasad, Ramit" writes: > This email is confidential... Probably a bad idea to post it to a world readable mailing list then :) From joncle at googlemail.com Mon Sep 26 16:07:43 2011 From: joncle at googlemail.com (Jon Clements) Date: Mon, 26 Sep 2011 13:07:43 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> Message-ID: On Sep 26, 12:23?pm, Tal Einat wrote: > The library is called RunningCalcs and is useful for running several > calculations on a single iterable of values. > > https://bitbucket.org/taleinat/runningcalcs/http://pypi.python.org/pypi/RunningCalcs/ > > I'd like some input on how this could be made more useful and how to > spread the word about it. > > The library contains the base RunningCalc class and implementations of > sub-classes for common calculations: sum, min/max, average, variance & > standard deviation, n-largest & n-smallest. Additionaly a utility > function apply_in_parallel() is supplied which makes running several > calculations on an iterable easy (and fast!). > > Straight-forward example: > > mean_rc, stddev_rc = RunningMean(), RunningStdDev() > for x in values: > ? ? mean_rc.feed(x) > ? ? stddev_rc.feed(x) > mean, stddev = mean_rc.value, stddev_rc.value > > Examples using apply_in_parallel(): > > mean, stddev = apply_in_parallel(values, [RunningMean(), > RunningStdDev()]) > five_smallest, five_largest = apply_in_parallel(values, > [RunningNSmallest(5), RunningNLargest(5)]) > > Comments and suggestions would be highly appreciated! You may not of heard of it, but the SAS language has something called PROC FREQ... I'm imagining that maybe this is where you should be taking this. Sorry I can't comment on the code, as I haven't really got time, but have a look! (I'd be willing to invest sometime with you, if you agree that's where something like this should be going...) Cheers, Jon. From python.list at tim.thechases.com Mon Sep 26 16:11:44 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 26 Sep 2011 15:11:44 -0500 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E80DC80.8090808@tim.thechases.com> On 09/26/11 13:57, Prasad, Ramit wrote: >> It seems it's time to start reading about argparse > FYI, it only appears on Python 2.7+ However I believe it can be uneventfully copied and run under several versions earlier (likely back to 2.5, perhaps to 2.4 -- I no longer have 2.4 at my fingertips to test). -tkc From ian.g.kelly at gmail.com Mon Sep 26 16:33:54 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 26 Sep 2011 14:33:54 -0600 Subject: Hierarchical commnd line parsing / help texts In-Reply-To: <4E80DC80.8090808@tim.thechases.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2073A804@EMARC112VS01.exchad.jpmchase.net> <4E80DC80.8090808@tim.thechases.com> Message-ID: On Mon, Sep 26, 2011 at 2:11 PM, Tim Chase wrote: > On 09/26/11 13:57, Prasad, Ramit wrote: >>> >>> It seems it's time to start reading about argparse >> >> FYI, it only appears on Python 2.7+ > > However I believe it can be uneventfully copied and run under several > versions earlier (likely back to 2.5, perhaps to 2.4 -- I no longer have 2.4 > at my fingertips to test). For older versions it would be best to use the Google project, which I think is still maintained and backported: http://code.google.com/p/argparse/ From jabba.laci at gmail.com Mon Sep 26 16:39:28 2011 From: jabba.laci at gmail.com (Jabba Laci) Date: Mon, 26 Sep 2011 16:39:28 -0400 Subject: install packages with pip to older Python versions Message-ID: Hi, I have Python 2.7 on my system. Today I wanted to try Google App Engine but it runs on Python 2.5 at Google so I installed this version on my machine next to v2.7 to avoid compatibility problems. However, when I start the Python shell v2.5 and try to import something from the GAE SDK (for instance "from google.appengine.ext import webapp"), I get an error: "ImportError: No module named webob". (Note that with v2.7 I don't have this problem.) So, how can I install packages for a specific version of Python (here, v2.5)? With 2.7 I use "sudo pip install ". Thanks, Laszlo From tgugger at bex.net Mon Sep 26 16:56:51 2011 From: tgugger at bex.net (TOM) Date: Mon, 26 Sep 2011 13:56:51 -0700 (PDT) Subject: QA Engineering/ Python/ Contract/ Austin, TX Message-ID: Tom Gugger Independent Recruiter tgugger at bex.net US Citizens or Greencard On Site QA Engineering/ Python/ Contract/ Austin, TX This is an immediate start, such as next week. I need three contractors for a 4--6 month contract in Austin, TX for Quality Assurance Engineers. The location is Austin, TX. This is an automation project. Must Have ? Good Network domain knowledge such as TCP/IP. Must Have --- experience testing Data, Voice, and IPTV traffic. Must Have --- Strong Python A Plus --- Fanfare Please make sure all the required skills show on the resume. If interested and qualified, email resume to tgugger at bex.net. From clp2 at rebertia.com Mon Sep 26 17:03:49 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 26 Sep 2011 14:03:49 -0700 Subject: QA Engineering/ Python/ Contract/ Austin, TX In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 1:56 PM, TOM wrote: > Tom Gugger > Independent Recruiter > tgugger at bex.net > > US Citizens or Greencard > On Site > > > QA Engineering/ Python/ Contract/ Austin, TX > > This is an immediate start, such as next week. I need three > contractors Such postings belong on the Python jobs board (http://www.python.org/community/jobs/ ), not python-list/comp.lang.python. Cheers, Chris From atherun at gmail.com Mon Sep 26 21:07:31 2011 From: atherun at gmail.com (Atherun) Date: Mon, 26 Sep 2011 18:07:31 -0700 (PDT) Subject: Race condition deadlock in communicate when threading? Message-ID: In python 2.6.4 I have a fairly complex system running (copying and pasting it would be quite difficult). At its core there are builders that inherit from threading.Thread. I have some builders that run external tasks via popen and read output using communicate. I have the ability to run any number of builders in parallel. All of this uses logging as well, where each builder has their own logger they create from the base logger i.e. logging.getLogger("Logger. %s"%self.Name). When running several threads in parallel that each call popen and communicate functions, python just hangs, about 95% of the time. All of it, parent threads, any threads I started before I got to this step, it just stops responding. Stepping through it with pdb trying to find the deadlock will always make it work, killing the external app I called via popen, after it has hung, will make it move along as well. Looking at the stack traces using the code found http://code.activestate.com/recipes/577334-how-to-debug-deadlocked-multi-threaded-programs/ the threads stop running with the following stacks, this is the last output from the tracer before it stops responding.: File: "c:\src\extern\python\lib\threading.py", line 497, in __bootstrap self.__bootstrap_inner() File: "c:\src\extern\python\lib\threading.py", line 525, in __bootstrap_inner self.run() File: "c:\src\extern\python\lib\threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) File: "c:\src\extern\python\lib\subprocess.py", line 877, in _readerthread buffer.append(fh.read()) And out, err = proc.communicate("change: new\ndescription: %s \n"%changelistDesc) File: "c:\src\extern\python\lib\subprocess.py", line 689, in communicate return self._communicate(input) File: "c:\src\extern\python\lib\subprocess.py", line 903, in _communicate stdout_thread.join() File: "c:\src\extern\python\lib\threading.py", line 637, in join self.__block.wait() File: "c:\src\extern\python\lib\threading.py", line 237, in wait waiter.acquire() I'm trying to track this down so I can eliminate it for good as it pops up in multiple places from time to time. Any tips would be appreciated. From wuwei23 at gmail.com Mon Sep 26 23:11:13 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 26 Sep 2011 20:11:13 -0700 (PDT) Subject: install packages with pip to older Python versions References: Message-ID: On Sep 27, 6:39?am, Jabba Laci wrote: > So, how can I install packages for a specific version of Python (here, > v2.5)? With 2.7 I use "sudo pip install ". It's amazing what you can find when you look at the documentation: http://www.pip-installer.org/en/latest/index.html "You can use pip install --upgrade SomePackage to upgrade to a newer version, or pip install SomePackage==1.0.4 to install a very specific version." However, if you're not using virtualenv, I'd recommend looking at it as well: http://pypi.python.org/pypi/virtualenv From devplayer at gmail.com Tue Sep 27 02:45:21 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 26 Sep 2011 23:45:21 -0700 (PDT) Subject: Suggested coding style References: <20110924191048.GH19422@johnsons-web.com> <4e7e93bc$0$29987$c3e8da3$5496439d@news.astraweb.com> <20110925184614.GK19422@johnsons-web.com> <53F42DEB-FC82-48C7-BB15-64F11F2395DC@gmail.com> <20110926025920.GO19422@johnsons-web.com> Message-ID: <492cb266-01df-493c-86d2-1a994933e570@p11g2000yqe.googlegroups.com> On Sep 25, 11:41?pm, Chris Angelico wrote: > On Mon, Sep 26, 2011 at 12:59 PM, Tim Johnson wrote: > > BTW: If you like ranting as a spectator sport, I have found the > > ?Common Lisp newsgroup to be among the most spectacular. But that's > > ?just me. > > I do, actually, but I don't need to add another newsgroup. Rick > provides plenty of material here, and I can easily sate myself in just > a few other places that I frequent. It's quite amusing to watch those > holy wars erupt... > > And every once in a while, they actually prove quite educative. I'm > not sure how it happens, nor how to trigger it - hmm, perhaps this > should be the subject of a scientific paper. "On ranting newsgroups > and how to make them productive". > > ChrisA I think intellectual growth from rants works like this: Ranter: Bla bla, bad logic, poor facts, some point. Others: Bla bla you rant Mr Ranter, some logic, few facts, same point. Ranter: bad mouthing Others: bad mouthing back Ranter: Bla Bla, I don't rant, better logic counter facts, lots of opinion (to not get called a ranter) Others: Bla bla, You do rant Ranter, good counter logic and facts, same point (some reason needs to put Ranter "in his place") Ranter: Super Bla, long winded logic with some strong points, random but accurate facts out the wazzu (tries to save face) Others: Acknowleges Ranters point are accurate but claims they don't apply Ranter: makes case his points do. Others: agrees to disagree, silently picks mute Ranter, Ranter: picks a new topic and starts over. From devplayer at gmail.com Tue Sep 27 02:51:08 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 26 Sep 2011 23:51:08 -0700 (PDT) Subject: Suggested coding style References: Message-ID: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> By the way OP Passiday the title of the topic is "Suggested coding style". Are you suggesting a coding style or asking for a Python coding style or are you asking what IS the Python coding style. If you are asking what is the Python coding style. Google The Zen of Python. It's pretty much the dictum of coding style and referred to alot by many Pythoneers. From pavlovevidence at gmail.com Tue Sep 27 03:17:50 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 27 Sep 2011 00:17:50 -0700 (PDT) Subject: Race condition deadlock in communicate when threading? In-Reply-To: References: Message-ID: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> There's really not enough information for us to debug this, but one possibility is that your subprocess is using buffered I/O; you're expecting the external task to write a string, but it doesn't actually write that string because it's sitting in a buffer. First thing to try is to see if the program accepts some kind of command line argument to run in unbuffered mode (for instance, if you are calling a Python interpreter you can pass it the -u switch to force unbuffered I/O). If (like most programs) it doesn't have an option to disable buffering, you can try running it on a pty device (if you're on Unix). If worse comes to worst, see if there's a way to get the external task to print lots of extra output (a verbosity setting, for instance); that could work in a pinch until you can debug it more thoroughly. Carl Banks From r32813 at freescale.com Tue Sep 27 05:08:54 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 09:08:54 +0000 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 In-Reply-To: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> Message-ID: <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Hello all, I encounter this issue whereby I am not able to load cPickle module into the python I newly built. There is no issue when I load it right from the folder where the python executable and libpython2.7.so is built. However, it gives me this error when I load the same module using the installed files (python and all its modules, shared library from default /use/local folder that contains bin, lib, include sub-folders) from "make install" command. Does anyone know why? Here is the error:- $ python Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import cPickle Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '_extension_registry' From r32813 at freescale.com Tue Sep 27 05:28:31 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 09:28:31 +0000 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> Message-ID: <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. $ python Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import random Traceback (most recent call last): File "", line 1, in File "random.py", line 49, in import hashlib as _hashlib File "hashlib.py", line 136, in globals()[__func_name] = __get_hash(__func_name) File "hashlib.py", line 74, in __get_builtin_constructor import _sha256 ImportError: No module named _sha256 >>> From clp2 at rebertia.com Tue Sep 27 05:51:30 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 27 Sep 2011 02:51:30 -0700 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 In-Reply-To: <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Tue, Sep 27, 2011 at 2:28 AM, Wong Wah Meng-R32813 wrote: > I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. > ?File "hashlib.py", line 74, in __get_builtin_constructor > ? ?import _sha256 > ImportError: No module named _sha256 Did you get a message along the lines of "Python build finished, but the necessary bits to build these modules were not found:" when you built Python? Cheers, Chris From r32813 at freescale.com Tue Sep 27 06:04:50 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 27 Sep 2011 10:04:50 +0000 Subject: Error 'No module named _sha256' when importing random in python 2.7.1 In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F5942D@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F59485@039-SN1MPN1-003.039d.mgd.msft.net> Yes I did. In fact earlier "make test" failed to execute due to _sha256 not found in one of the module testing. Earlier I ignored these failures from the build and make test as I thought they are not needed by my application. Now I can't use "random" module in my application. So I need to solve this issue. Here is the output of the build. Python build finished, but the necessary bits to build these modules were not found: _bsddb _curses _curses_panel _sqlite3 _ssl bsddb185 bz2 dl gdbm imageop linuxaudiodev ossaudiodev readline spwd sunaudiodev zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _ctypes termios Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Tuesday, September 27, 2011 5:52 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Error 'No module named _sha256' when importing random in python 2.7.1 On Tue, Sep 27, 2011 at 2:28 AM, Wong Wah Meng-R32813 wrote: > I just built python 2.7.1 on my HP Itanium 64-bit platform, using aCC. I encountered following issue when importing the random module. Does anyone know why am I getting this error? Thanks in advance for your reply. > ?File "hashlib.py", line 74, in __get_builtin_constructor > ? ?import _sha256 > ImportError: No module named _sha256 Did you get a message along the lines of "Python build finished, but the necessary bits to build these modules were not found:" when you built Python? Cheers, Chris From yixuan178 at gmail.com Tue Sep 27 06:48:07 2011 From: yixuan178 at gmail.com (yixuan) Date: Tue, 27 Sep 2011 03:48:07 -0700 (PDT) Subject: error when use portable python 2.7.2 Message-ID: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Hello, I copy python 2.7.2 folder from other machine to my new installed Windows XP. If I run python.exe it would say side by side error, it is caused by crt environment. I copy msvc90 runtime and manifest into my folder, python.exe seems working now. But when I used 'import FixTk', it would say "dll load failed", actually, it also a side by side error, if I paste crt libraries into Dlls folder, it can be solved. But I don't think it is a good solution. How can I set it to prevent above error? w/o install any microsoft package. I want to user can use my package when they unpack it. Thanks, Eugene From alec.taylor6 at gmail.com Tue Sep 27 07:01:32 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 27 Sep 2011 21:01:32 +1000 Subject: error when use portable python 2.7.2 In-Reply-To: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Message-ID: You're looking for this: http://www.portablepython.com/wiki/PortablePython2.7.2.1 On Tue, Sep 27, 2011 at 8:48 PM, yixuan wrote: > Hello, > I copy python 2.7.2 folder from other machine to my new installed > Windows XP. > If I run python.exe it would say side by side error, it is caused by > crt environment. > I copy msvc90 runtime and manifest into my folder, python.exe seems > working now. > But when I used 'import FixTk', it would say "dll load failed", > actually, it also a side by side error, if I paste crt libraries into > Dlls folder, it can be solved. But I don't think it is a good > solution. > How can I set it to prevent above error? w/o install any microsoft > package. I want to user can use my package when they unpack it. > > Thanks, > Eugene > -- > http://mail.python.org/mailman/listinfo/python-list > From mikehulluk at googlemail.com Tue Sep 27 07:54:10 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 04:54:10 -0700 (PDT) Subject: atexit handlers - getting the return code Message-ID: Hi, I work in neuroscience modelling and use python for lots of my work. One problem I have is management of scripts and results. To that end, I have written code that make its easier to keep track of scripts, to see which ones have run, or need to be rerun, to see output errors and generally organise running of scripts better. The way i have implemented it is that I register a function to the atexit module, which takes care of recording information about the script run; such as whether an exception was raised and not caught, and how long it took to run and the stdout/stderr streams; which can then be uploaded into a database. One thing I am struggling to get though is the 'return code' that the is going to be returned after my atexit handlers have finished. Could anyone tell me how it get at this!? Thanks Mike From yixuan178 at gmail.com Tue Sep 27 08:00:30 2011 From: yixuan178 at gmail.com (yixuan) Date: Tue, 27 Sep 2011 05:00:30 -0700 (PDT) Subject: error when use portable python 2.7.2 References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> Message-ID: <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> On Sep 27, 7:01?pm, Alec Taylor wrote: > You're looking for this:http://www.portablepython.com/wiki/PortablePython2.7.2.1 > > > > > > > > On Tue, Sep 27, 2011 at 8:48 PM, yixuan wrote: > > Hello, > > I copy python 2.7.2 folder from other machine to my new installed > > Windows XP. > > If I run python.exe it would say side by side error, it is caused by > > crt environment. > > I copy msvc90 runtime and manifest into my folder, python.exe seems > > working now. > > But when I used 'import FixTk', it would say "dll load failed", > > actually, it also a side by side error, if I paste crt libraries into > > Dlls folder, it can be solved. But I don't think it is a good > > solution. > > How can I set it to prevent above error? w/o install any microsoft > > package. I want to user can use my package when they unpack it. > > > Thanks, > > Eugene > > -- > >http://mail.python.org/mailman/listinfo/python-list Alec, Thanks for your information. But in that site, it seems how to rebuild python for another use. My issue is that, when I install python 2.7.2 in one windows, then I want to copy that folder to my new installed windows, and try to run python. It will ask CRT environment. Why I need that scenario, i want to package python in my package, so I want it to run one new installed windows which w/o any crt runtime installed. For more convenience, my issue seems like that in DLLs folder, there has some dlls, python would load them when needed, but when run application, it couldn't find crt files which stored in python root folder. So how to set that all dll can find that folder? Thanks, Eugene From drobinow at gmail.com Tue Sep 27 08:15:10 2011 From: drobinow at gmail.com (David Robinow) Date: Tue, 27 Sep 2011 08:15:10 -0400 Subject: install packages with pip to older Python versions In-Reply-To: References: Message-ID: On Mon, Sep 26, 2011 at 4:39 PM, Jabba Laci wrote: > Hi, > > I have Python 2.7 on my system. Today I wanted to try Google App > Engine but it runs on Python 2.5 at Google so I installed this version > on my machine next to v2.7 to avoid compatibility problems. However, > when I start the Python shell v2.5 and try to import something from > the GAE SDK (for instance "from google.appengine.ext import webapp"), > I get an error: "ImportError: No module named webob". (Note that with > v2.7 I don't have this problem.) > > So, how can I install packages for a specific version of Python (here, > v2.5)? With 2.7 I use "sudo pip install ". sudo pip-2.5 install (You may need to install pip in your 2.5) From nizamov.shawkat at gmail.com Tue Sep 27 08:35:38 2011 From: nizamov.shawkat at gmail.com (Nizamov Shawkat) Date: Tue, 27 Sep 2011 14:35:38 +0200 Subject: error when use portable python 2.7.2 In-Reply-To: <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> References: <701e2da1-5a1b-4004-afae-21f0291c6563@j1g2000yqj.googlegroups.com> <3f4dc714-17c7-4b27-82ff-9f1c50ad5846@g33g2000yqc.googlegroups.com> Message-ID: I bet that the difference is in the environment settings (PYTHONPATH). Look here for details how to set it manually: http://docs.python.org/using/windows.html Hope it helps, S.Nizamov From g.rodola at gmail.com Tue Sep 27 08:55:17 2011 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Tue, 27 Sep 2011 14:55:17 +0200 Subject: atexit handlers - getting the return code In-Reply-To: References: Message-ID: You mean the registered function return value or the process return code? In the first case you can do something such as: import atexit @atexit.register def cleanup(): def actual_function(): ... return something ret = actual_function() # do something with ret In the latter case you can use sys.exit(code). --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ 2011/9/27 Mike Hull : > Hi, > I work in neuroscience modelling and use python for lots of my work. > One problem I have is management of scripts and results. To that end, > I have > written code that make its easier to keep track of scripts, to see > which ones > have run, or need to be rerun, to see output errors and generally > organise running of scripts better. > > The way i have implemented it is that I register a function to the > atexit module, > which takes care of recording information about the script run; such > as whether an > exception was raised and not caught, and how long it took to run and > the > stdout/stderr streams; which can then be uploaded into a database. > > One thing I am struggling to get though is the 'return code' that the > is going to be returned after my > atexit handlers have finished. Could anyone tell me how it get at > this!? > > > Thanks > > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > From mikehulluk at googlemail.com Tue Sep 27 09:37:10 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 06:37:10 -0700 (PDT) Subject: atexit handlers - getting the return code References: Message-ID: Hi Giampaolo, Sorry, I didn't explain very clearly. I have a python file, 'simulation_logger.py', (given below). Then, in my scripts, I add the following lines to the top, #simulation1.py: ################### from simulation_logger import SimulationDecorator SimulationDecorator.Init() # Rest of the simulation script.... ##################### and at the end of the simulation, it should write the stdout/stderr, the return code and any top level exception details into a database. This is working except I can't work out how to get the return code the script is going to return. Any help would be gratefully appreciated, Thanks! Mike # simulation_logger.py ######################## import atexit import sys import os import cStringIO import time import traceback import datetime import inspect class SimulationRunInfo(object): def __init__(self, script_name ): self.return_code = None self.time_taken = None self.time_out = None self.std_out = None self.std_err = None self.exception_details = None,None self.script_name = script_name class IOStreamDistributor(object): def __init__(self, outputs): self.outputs = outputs def write(self, *args, **kwargs): for op in self.outputs: op.write(*args, **kwargs) class SimulationDecorator(object): start_time = None time_out = None is_initialised = False exception_details = None,None std_out = None std_err = None script_name = None @classmethod def exit_handler(cls, *args, **kwargs): print 'Exit Handler' print 'Args', args print 'KwArgs', kwargs info = SimulationRunInfo( cls.script_name) # Read and restore the StdOut/Err info.std_out = cls.std_out.getvalue() sys.stdout = sys.__stdout__ info.std_err = cls.std_err.getvalue() sys.stderr = sys.__stderr__ # Get the return value: info.return_code = 0 # Get the timing: info.time_taken = int( time.time() - cls.start_time ) # Has thier been an exception? info.exception_details = cls.exception_details if info.exception_details != (None,None): print 'Exception details', info.exception_details info.return_code = -1 # Write to SimulationDataBase # Save the information to a database: SimulationDBWriter.write_to_database(info) @classmethod def top_level_exception_handler(cls, exception_type, exception, traceback, *args): print 'TopLevel Exception Handler' cls.exception_details = exception_type, exception, traceback @classmethod def Init(cls, time_out=None): assert not cls.is_initialised if 'MF_TIMEOUT' in os.environ: timeout = int( os.environ['MF_TIMEOUT'] ) # Filename of the Simulation script cwd = os.getcwd() cls.script_name = os.path.join( cwd, traceback.extract_stack() [0][0] ) #cls.script_name = traceback.extract_stack()[0][2]. #cls.script_name = inspect.stack()[-1][1] #Intercept StdOut and StdErr: cls.std_out = cStringIO.StringIO() sys.stdout = IOStreamDistributor( [cls.std_out, sys.stdout] ) cls.std_err = cStringIO.StringIO() sys.stderr = IOStreamDistributor( [cls.std_err, sys.stderr] ) # Set an exit handler and a top level exception-handler # Set a top level exception handler: atexit.register( cls.exit_handler ) sys.excepthook = cls.top_level_exception_handler # Set a time-out alarm cls.start_time = time.time() cls.time_out = time_out From wescpy at gmail.com Tue Sep 27 10:00:55 2011 From: wescpy at gmail.com (wesley chun) Date: Tue, 27 Sep 2011 11:00:55 -0300 Subject: ANN: Intro+Intermediate Python course, SF, Oct 18-20 In-Reply-To: References: Message-ID: ** FINAL CALL ** http://sfbay.craigslist.org/sfc/cls/2495963854.html ---------- Forwarded message ---------- From: wesley chun Date: Mon, Jul 25, 2011 at 12:32 PM Subject: ANN: Intro+Intermediate Python course, SF, Oct 18-20 Need to get up-to-speed with Python as quickly and as in-depth as possible? Already coding Python but still have areas of uncertainty you need to fill? Then come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python" for a comprehensive intro/intermediate course coming up this May in Northern California, then enjoy a beautiful Fall weekend afterwards in San Francisco, the beautiful city by the bay. Please pass on this note to whomever you think may be interested. I look forward to meeting you and your colleagues! Feel free to pass around the PDF flyer linked down below. Write if you have questions. Since I hate spam, I'll only send out one reminder as the date gets closer. (Comprehensive) Intro+Intermediate Python Tue-Thu, 2011 Oct 18-20, 9am-5pm Hope to meet you soon! -Wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRO+INTERMEDIATE PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! PREVIEW 1: you will find (and can download) a video clip of a class session recorded live to get an idea of my lecture style and the interactive classroom environment (as well as sign-up) at: http://cyberwebconsulting.com PREVIEW 2: Partnering with O'Reilly and Pearson, Safari Books Online has asked me to deliver a 1-hour webcast a couple of years ago called "What is Python?". This was an online seminar based on a session that I've delivered at numerous conferences in the past. It will give you an idea of lecture style as well as an overview of the material covered in the course. info:http://www.safaribooksonline.com/events/WhatIsPython.html download (reg req'd): http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcastInfo.php?page=WhatIsPython - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com FLYER: http://cyberwebconsulting.com/flyerPP1.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. There is a significant discounts available for full-time students, secondary teachers, and others. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From taleinat at gmail.com Tue Sep 27 10:24:12 2011 From: taleinat at gmail.com (Tal Einat) Date: Tue, 27 Sep 2011 07:24:12 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> Message-ID: <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> I don't work with SAS so I have no reason to invest any time developing for it. Also, as far as I can tell, SAS is far from free or open-source, meaning I definitely am not interested in developing for it. My library solves a problem for which there is no existing solution in the world of Python programming, AFAIK. I'm certainly not surprised such solutions already exist in other computing environments, but that's not relevant for me. From robert.kern at gmail.com Tue Sep 27 11:49:47 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:49:47 -0400 Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> Message-ID: On 9/27/11 10:24 AM, Tal Einat wrote: > I don't work with SAS so I have no reason to invest any time developing for it. > > Also, as far as I can tell, SAS is far from free or open-source, meaning I definitely am not interested in developing for it. I don't think he's suggesting that you drop what you are doing in Python and start working with SAS. He is suggesting that you look at the similar procedures that exist in the SAS standard library for inspiration. -- 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 robert.kern at gmail.com Tue Sep 27 11:52:13 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:52:13 -0400 Subject: QA Engineering/ Python/ Contract/ Austin, TX In-Reply-To: References: Message-ID: On 9/26/11 5:03 PM, Chris Rebert wrote: > On Mon, Sep 26, 2011 at 1:56 PM, TOM wrote: >> Tom Gugger >> Independent Recruiter >> tgugger at bex.net >> >> US Citizens or Greencard >> On Site >> >> >> QA Engineering/ Python/ Contract/ Austin, TX >> >> This is an immediate start, such as next week. I need three >> contractors > > Such postings belong on the Python jobs board > (http://www.python.org/community/jobs/ ), not > python-list/comp.lang.python. While he should definitely also post to the Jobs Board, job postings have usually been welcomed on python-list provided that they are relevant and not too spammy. Using [JOB] in the Subject line also helps. -- 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 robert.kern at gmail.com Tue Sep 27 11:59:09 2011 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 27 Sep 2011 11:59:09 -0400 Subject: atexit handlers - getting the return code In-Reply-To: References: Message-ID: On 9/27/11 9:37 AM, Mike Hull wrote: > Hi Giampaolo, > Sorry, I didn't explain very clearly. > I have a python file, 'simulation_logger.py', (given below). > Then, in my scripts, I add the following lines to the top, > > > > #simulation1.py: > ################### > from simulation_logger import SimulationDecorator > SimulationDecorator.Init() > > # Rest of the simulation script.... > > ##################### > > and at the end of the simulation, it should write the stdout/stderr, > the return code and any top level exception details into a database. > This is working except I can't work out how to get the return code > the script is going to return. I don't think that's available inside the process. You may want to use a "runner" script that records this information. Additionally, the runner script could record the stdout/stderr information more cleanly than stubbing out sys.stdout/sys.stderr. For example, if you have C or Fortran modules that use their own mechanisms to print things directly to the STDOUT/STDERR file descriptors, your sys.stdout/sys.stderr stubs will never be informed about it. However, if the runner script directs stdout/stderr to a pipe, it can read every bit of text that gets printed. Timing is probably also best recorded by the runner script to record the startup overhead of the Python interpreter. Continue to use the SimulationDecorator to record the traceback information, though. -- 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 sakthi92 at gmail.com Tue Sep 27 13:21:24 2011 From: sakthi92 at gmail.com (sakthi) Date: Tue, 27 Sep 2011 10:21:24 -0700 (PDT) Subject: Multiplication error in python Message-ID: In the following code, >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... >>> t 45 Python gives an answer as 45. But i am getting 30 when i execute manually. Is there any different multiplication pattern in python? Thank yu. From steve+comp.lang.python at pearwood.info Tue Sep 27 13:33:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 28 Sep 2011 03:33:13 +1000 Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Robert Kern wrote: > On 9/27/11 10:24 AM, Tal Einat wrote: >> I don't work with SAS so I have no reason to invest any time developing >> for it. >> >> Also, as far as I can tell, SAS is far from free or open-source, meaning >> I definitely am not interested in developing for it. > > I don't think he's suggesting that you drop what you are doing in Python > and start working with SAS. He is suggesting that you look at the similar > procedures that exist in the SAS standard library for inspiration. Yeah, inspiration on what *not* to do. I googled on "SAS PROC FREQ" and found this: http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm All the words are in English, but I have no idea what the function does, how you would call it, and what it returns. Would it have been so hard to show a couple of examples? Documentation like that really makes me appreciate the sterling work done on Python's docs. This tutorial: http://www2.sas.com/proceedings/sugi30/263-30.pdf is much clearer. -- Steven From gherron at digipen.edu Tue Sep 27 13:41:02 2011 From: gherron at digipen.edu (Gary Herron) Date: Tue, 27 Sep 2011 10:41:02 -0700 Subject: Multiplication error in python In-Reply-To: References: Message-ID: <4E820AAE.2000405@digipen.edu> On 09/27/2011 10:21 AM, sakthi wrote: > In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: > ... p=2*a > ... t=p+i > ... i=t > ... >>>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. I think it's most likely you've made an error here. Running your exact lines in Python gives the expected result: >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... >>> t 30 Please try again. If you can reproduce the incorrect result -- then we have a real bug. However, the chance of that is really really tiny. Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 From pruebauno at latinmail.com Tue Sep 27 13:42:02 2011 From: pruebauno at latinmail.com (nn) Date: Tue, 27 Sep 2011 10:42:02 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <4082eb5c-9374-4409-a007-1133eb13bb36@i28g2000yqn.googlegroups.com> On Sep 27, 1:21?pm, sakthi wrote: > In the following code,>>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ...>>> t > > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. You must be doing something different than these steps: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: p=2*a t=p+i i=t >>> t 30 >>> From contato at abruno.com Tue Sep 27 13:42:20 2011 From: contato at abruno.com (Alysson Bruno (WebSite)) Date: Tue, 27 Sep 2011 14:42:20 -0300 Subject: Multiplication error in python In-Reply-To: References: Message-ID: In my python 3.2, no problem: >>> l=[1,2,3,4,5] >>> i=0 >>> for a in l: ... p=2*a ... t=p+i ... i=t ... print("p={}, t={}, i={}".format(p,t,i)) ... p=2, t=2, i=2 p=4, t=6, i=6 p=6, t=12, i=12 p=8, t=20, i=20 p=10, t=30, i=30 >>> t 30 >>> paz e amor (love and peace), Alysson Bruno Palmas(TO) Brasil http://abruno.com Leia: Heo Sargila: Hist?ria da Cria??o: http://heosargila.blogspot.com/2011/09/historia-da-criacao.html 2011/9/27 sakthi > In the following code, > >>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > ... p=2*a > ... t=p+i > ... i=t > ... > >>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bex.lewis at gmail.com Tue Sep 27 13:43:00 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 10:43:00 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <4dfd3a08-d5df-48a2-91d1-95a2a0f79c3e@j19g2000yqc.googlegroups.com> I tried running your code in ipython: In [1]: l = [1,2,3,4,5] In [2]: i = 0 In [3]: for a in l: ...: p = 2 * a ...: t = p + i ...: i = t ...: In [4]: In [4]: t Out[4]: 30 The output from Python was 30, not 45. What Python version are you running? On Sep 27, 6:21?pm, sakthi wrote: > In the following code,>>> l=[1,2,3,4,5] > >>> i=0 > >>> for a in l: > > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ...>>> t > > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. From clp2 at rebertia.com Tue Sep 27 13:43:22 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 27 Sep 2011 10:43:22 -0700 Subject: Multiplication error in python In-Reply-To: References: Message-ID: On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: > In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: > ... ? ? p=2*a > ... ? ? t=p+i > ... ? ? i=t > ... >>>> t > 45 > > Python gives an answer as 45. But i am getting 30 when i execute > manually. Is there any different multiplication pattern in python? > Thank yu. My Python gives 30; methinks perhaps you've elided some important part of your code. Also, I note that your loop body can be significantly simplified to just: i += 2*a Cheers, Chris -- http://rebertia.com From sakthi92 at gmail.com Tue Sep 27 13:50:23 2011 From: sakthi92 at gmail.com (sakthi) Date: Tue, 27 Sep 2011 10:50:23 -0700 (PDT) Subject: Multiplication error in python References: Message-ID: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> On Sep 27, 1:43?pm, Chris Rebert wrote: > On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: > > In the following code, > >>>> l=[1,2,3,4,5] > >>>> i=0 > >>>> for a in l: > > ... ? ? p=2*a > > ... ? ? t=p+i > > ... ? ? i=t > > ... > >>>> t > > 45 > > > Python gives an answer as 45. But i am getting 30 when i execute > > manually. Is there any different multiplication pattern in python? > > Thank yu. > > My Python gives 30; methinks perhaps you've elided some important part > of your code. > Also, I note that your loop body can be significantly simplified to > just: i += 2*a > > Cheers, > Chris > --http://rebertia.com if i put i += 2*a it returns 155. From bex.lewis at gmail.com Tue Sep 27 14:51:06 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 11:51:06 -0700 (PDT) Subject: Multiplication error in python References: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> Message-ID: I think you may be doing something wrong. If I run: >>> l = [1, 2, 3, 4, 5] >>> i = 0 >>> for a in l: ... i += 2 * a ... >>> i 30 The result is 30 as expected. Nowhere near the 155 that you are getting. :/ Again, could you state which version of python are you using (and what OS) so that we can run the code in the same environment as you. Becky Lewis > > > > Python gives an answer as 45. But i am getting 30 when i execute > > > manually. Is there any different multiplication pattern in python? > > > Thank yu. > > > My Python gives 30; methinks perhaps you've elided some important part > > of your code. > > Also, I note that your loop body can be significantly simplified to > > just: i += 2*a > > > Cheers, > > Chris > > --http://rebertia.com > > if i put i += 2*a it returns 155. From mikehulluk at googlemail.com Tue Sep 27 15:12:09 2011 From: mikehulluk at googlemail.com (Mike Hull) Date: Tue, 27 Sep 2011 12:12:09 -0700 (PDT) Subject: atexit handlers - getting the return code References: Message-ID: <662ee8e4-34af-42aa-b01b-edace3af133d@20g2000yqq.googlegroups.com> On Sep 27, 4:59?pm, Robert Kern wrote: > On 9/27/11 9:37 AM, Mike Hull wrote: > > > > > > > > > > > Hi Giampaolo, > > Sorry, I didn't explain very clearly. > > I have a python file, 'simulation_logger.py', (given below). > > Then, in my scripts, I add the following lines to the top, > > > #simulation1.py: > > ################### > > from simulation_logger ?import SimulationDecorator > > SimulationDecorator.Init() > > > # Rest of the simulation script.... > > > ##################### > > > and at the end of the simulation, it should write the stdout/stderr, > > the return code and any top level exception details into a database. > > This is working except I can't work out how to get the return code > > the script is going to return. > > I don't think that's available inside the process. You may want to use a > "runner" script that records this information. Additionally, the runner script > could record the stdout/stderr information more cleanly than stubbing out > sys.stdout/sys.stderr. For example, if you have C or Fortran modules that use > their own mechanisms to print things directly to the STDOUT/STDERR file > descriptors, your sys.stdout/sys.stderr stubs will never be informed about it. > However, if the runner script directs stdout/stderr to a pipe, it can read every > bit of text that gets printed. Timing is probably also best recorded by the > runner script to record the startup overhead of the Python interpreter. Continue > to use the SimulationDecorator to record the traceback information, though. > > -- > 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 Hi Robert, Thanks for this. The return code is not super important at this stage, but I thought I would try and get everything working neatly. Creating a separate runner script is probably the way to go. If i get some time I will implement it like that. My reason for wanting to do it 'in the same script' was that I also have another library that intercepts calls to matplotlib's show(), so I could ultimately create a pdf containing the script with figures interjected at the right place. Anyway, I will have to think about that some more. Thanks again! Mike From mwilson at the-wire.com Tue Sep 27 15:12:20 2011 From: mwilson at the-wire.com (Mel) Date: Tue, 27 Sep 2011 15:12:20 -0400 Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm > > All the words are in English, but I have no idea what the function does, > how you would call it, and what it returns. Would it have been so hard to > show a couple of examples? Hmm. Yeah. Very much so. That's the kind of documentation I call "syntax happy". It tells you how to create a well-formed PROC STAT without ever saying what would happen if you did, or why you might want that, whatever it was, to happen. I see that kind of documentation way too often. By comparison, even this might seem good. At least they try. "Does things to the stuff. By default, the most recent stuff is done things to." Mel. From tundra at tundraware.com Tue Sep 27 15:12:33 2011 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 27 Sep 2011 14:12:33 -0500 Subject: Multiplication error in python In-Reply-To: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> References: <2087b307-537c-4d01-9527-bcf04cc2449b@p11g2000yqe.googlegroups.com> Message-ID: <1qj9l8-t6b.ln1@ozzie.tundraware.com> On 9/27/2011 12:50 PM, sakthi said this: > On Sep 27, 1:43 pm, Chris Rebert wrote: >> On Tue, Sep 27, 2011 at 10:21 AM, sakthi wrote: >>> In the following code, >>>>>> l=[1,2,3,4,5] >>>>>> i=0 >>>>>> for a in l: >>> ... p=2*a >>> ... t=p+i >>> ... i=t >>> ... >>>>>> t >>> 45 >> >>> Python gives an answer as 45. But i am getting 30 when i execute >>> manually. Is there any different multiplication pattern in python? >>> Thank yu. >> >> My Python gives 30; methinks perhaps you've elided some important part >> of your code. >> Also, I note that your loop body can be significantly simplified to >> just: i += 2*a >> >> Cheers, >> Chris >> --http://rebertia.com > > if i put i += 2*a it returns 155. Are you sure you don't have something indented incorrectly? How about a plain text copy of your program (without the interactive stuff) so we can run it independently... -- ------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From joncle at googlemail.com Tue Sep 27 15:54:22 2011 From: joncle at googlemail.com (Jon Clements) Date: Tue, 27 Sep 2011 12:54:22 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <65466670-d990-4d7c-9cca-0ac3ec9881a6@db5g2000vbb.googlegroups.com> On Sep 27, 6:33?pm, Steven D'Aprano wrote: > Robert Kern wrote: > > On 9/27/11 10:24 AM, Tal Einat wrote: > >> I don't work with SAS so I have no reason to invest any time developing > >> for it. > > >> Also, as far as I can tell, SAS is far from free or open-source, meaning > >> I definitely am not interested in developing for it. > > > I don't think he's suggesting that you drop what you are doing in Python > > and start working with SAS. He is suggesting that you look at the similar > > procedures that exist in the SAS standard library for inspiration. > > Yeah, inspiration on what *not* to do. > > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/defau... > > All the words are in English, but I have no idea what the function does, how > you would call it, and what it returns. Would it have been so hard to show > a couple of examples? > > Documentation like that really makes me appreciate the sterling work done on > Python's docs. > > This tutorial: > > http://www2.sas.com/proceedings/sugi30/263-30.pdf > > is much clearer. > > -- > Steven Yes - I definitely do not like the SAS docs - in fact, when I last had to "buy" the product, it was something like ?5k for the "BASE" system, then if I wanted ODBC it was another ?900, and the "proper" manuals were something stupid like another ?1k (and only in hard copy) - this was a good 5/6 years ago though... (oh, and for a very basic course, it was ?1.2k a day for staff to train) *sighs* [oh, and if I wanted a 'site' licence, we were talking 6 digits] Anyway, Robert Kern correctly interpreted me. I was not suggesting to the OP that he move to SAS (heaven forbid), I was indeed suggesting that he look into what similar systems have (that I have experience with and appreciate), and he acknowledges that is not present in Python, and ummm, take inspiration and quite possibly "rip 'em off". A decent tabulate/cross-tabulation and statistics related there-to library is something I'd be willing to assist with and put time into. Cheers, Jon. From rantingrick at gmail.com Tue Sep 27 16:45:52 2011 From: rantingrick at gmail.com (rantingrick) Date: Tue, 27 Sep 2011 13:45:52 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> Message-ID: <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> On Sep 27, 1:51?am, DevPlayer wrote: > By the way OP Passiday the title of the topic is "Suggested coding > style". > > Are you suggesting a coding style or asking for a Python coding style > or are you asking what IS the Python coding style. > > If you are asking what is the Python coding style. Google The Zen of > Python. It's pretty much the dictum of coding style and referred to > alot by many Pythoneers. The Python zen is a very general outline of our collective religious beliefs concerning programming (and it could be applied to many fields). Every Python programmer should know the zen by heart. Which can be very beneficial in a war of words when some smart mouth decides to quote the zen in an attempt to defeat you. Since, like the bible the zen is self contradicting, any argument utilizing the zen can be defeated utilizing the zen. If however you want to learn about the accepted rules for formatting code then you need to read "PEP-8"! PEP 8 is our style guide. It is not perfect as i have pointed out on many occasions HOWEVER it is the only thing we have that keeps multiplicity from reproducing like leporidae. http://www.python.org/dev/peps/pep-0008/ From wanderer at dialup4less.com Tue Sep 27 16:54:48 2011 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 27 Sep 2011 13:54:48 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows Message-ID: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says "Python 2.6.6 has been replaced by a newer security-fix only source release of Python. Please download Python 2.6.7 instead." But there is no windows installer on the 2.6.7 page. Do I install 2.6.6 first and then update to 2.6.7? Thanks From arnodel at gmail.com Tue Sep 27 17:11:58 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 27 Sep 2011 22:11:58 +0100 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: On 27 September 2011 21:54, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? I don't know if it would suite your needs but there's ActivePython - they provide an installer for 2.6.7 http://www.activestate.com/activepython/downloads HTH -- Arnaud From brian.curtin at gmail.com Tue Sep 27 17:17:45 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 16:17:45 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: On Tue, Sep 27, 2011 at 15:54, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? As the text states, 2.6.7 is only a source code release. 2.6.6 is the last binary package available, but if you need what's in 2.6.7, you will have to compile the source yourself. Alternatively, you could upgrade to 2.7 as 2.6 will continue to only receive security fixes, or as Arnaud states, you could use an alternative distribution to get 2.6.6. From bex.lewis at gmail.com Tue Sep 27 17:19:33 2011 From: bex.lewis at gmail.com (becky_lewis) Date: Tue, 27 Sep 2011 14:19:33 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> Message-ID: <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> On Sep 27, 9:54?pm, Wanderer wrote: > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > "Python 2.6.6 has been replaced by a newer security-fix only source > release of Python. Please download Python 2.6.7 instead." > > But there is no windows installer on the 2.6.7 page. Do I install > 2.6.6 first and then update to 2.6.7? > > Thanks Hi, is there any reason that you specifically need the 2.6 branch or would it be possible to update to 2.7? As someone else already pointed out, there's the ActivePython route if you really need 2.6.7. From wanderer at dialup4less.com Tue Sep 27 17:32:43 2011 From: wanderer at dialup4less.com (Wanderer) Date: Tue, 27 Sep 2011 14:32:43 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> Message-ID: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> On Sep 27, 5:19?pm, becky_lewis wrote: > On Sep 27, 9:54?pm, Wanderer wrote: > > > How do I install Python 2.6.7 on Windows? The Python 2.6.6 page says > > > "Python 2.6.6 has been replaced by a newer security-fix only source > > release of Python. Please download Python 2.6.7 instead." > > > But there is no windows installer on the 2.6.7 page. Do I install > > 2.6.6 first and then update to 2.6.7? > > > Thanks > > Hi, > > is there any reason that you specifically need the 2.6 branch or would > it be possible to update to 2.7? > > As someone else already pointed out, there's the ActivePython route if > you really need 2.6.7. I need to stay in sink with the rest of the company which is still using 2.6 flavors. There was some investigation into going to Python 3 but not enough of the libraries we use were available. I'll install 2.6.6. I don't think the security stuff really effects me. I think it is strange to release a security update but not really expect people to use it. From iamforufriends at gmail.com Tue Sep 27 18:02:21 2011 From: iamforufriends at gmail.com (hot girl) Date: Tue, 27 Sep 2011 15:02:21 -0700 (PDT) Subject: hai date with girl for free Message-ID: <1239dc58-6fcd-4f7d-8795-1907e08af831@j10g2000vbb.googlegroups.com> want a gf for dating http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas http://tinyurl.com/3bj2zas From aljosa.mohorovic at gmail.com Tue Sep 27 18:54:37 2011 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Tue, 27 Sep 2011 15:54:37 -0700 (PDT) Subject: oauth2 server implementation Message-ID: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> i'm looking for oauth2 server implementation but other than https://github.com/simplegeo/python-oauth2 (oauth v1 implementation) it doesn't seem that people are using v2 implementations. anybody using some oauth2 implementation and can share some info? Aljosa Mohorovic From brian.curtin at gmail.com Tue Sep 27 18:59:35 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 17:59:35 -0500 Subject: PyCon 2012 Proposals Due October 12 Message-ID: The deadline for PyCon 2012 tutorial, talk, and poster proposals is under 15 days away, so be sure to get your submissions in by October 12, 2011. Whether you?re a first-timer or an experienced veteran, PyCon is depends on you, the community, coming together to build the best conference schedule possible. Our call for proposals (http://us.pycon.org/2012/cfp/) lays out the details it takes to be included in the lineup for the conference in Santa Clara, CA on March 7-15, 2012. If you?re unsure of what to write about, our recent survey yielded a large list of potential talk topics (http://pycon.blogspot.com/2011/09/need-talk-ideas.html), and plenty of ideas for tutorials (INSERT TUTORIAL POST). We?ve also come up with general tips on proposal writing at http://pycon.blogspot.com/2011/08/writing-good-proposal.html to ensure everyone has the most complete proposal when it comes time for review. As always, the program committee wants to put together an incredible conference, so they?ll be working with submitters to fine tune proposal details and help you produce the best submissions. We?ve had plenty of great news to share since we first announced the call for proposals. Paul Graham of Y Combinator was recently announced as a keynote speaker (http://pycon.blogspot.com/2011/09/announcing-first-pycon-2012-keynote.html), making his return after a 2003 keynote. David Beazley, famous for his mind-blowing talks on CPython?s Global Interpreter Lock, was added to the plenary talk series (http://pycon.blogspot.com/2011/09/announcing-first-pycon-2012-plenary.html). Sponsors can now list their job openings on the ?Job Fair? section of the PyCon site (http://pycon.blogspot.com/2011/09/announcing-pycon-2012-fair-page-sponsor.html). We?re hard at work to bring you the best conference yet, so stay tuned to PyCon news at http://pycon.blogspot.com/ and on Twitter at https://twitter.com/#!/pycon. We recently eclipsed last year?s sponsorship count of 40 and are currently at a record 52 organizations supporting PyCon. If you or your organization are interested in sponsoring PyCon, we?d love to hear from you, so check out our sponsorship page (http://us.pycon.org/2012/sponsors/). A quick thanks to all of our awesome PyCon 2012 Sponsors: - Diamond Level: Google and Dropbox. - Platinum Level: New Relic, SurveyMonkey, Microsoft, Eventbrite, Nasuni and Gondor.io - Gold Level: Walt Disney Animation Studios, CCP Games, Linode, Enthought, Canonical, Dotcloud, Loggly, Revsys, ZeOmega, Bitly, ActiveState, JetBrains, Caktus, Disqus, Spotify, Snoball, Evite, and PlaidCloud - Silver Level: Imaginary Landscape, WiserTogether, Net-ng, Olark, AG Interactive, Bitbucket, Open Bastion, 10Gen, gocept, Lex Machina, fwix, github, toast driven, Aarki, Threadless, Cox Media, myYearBook, Accense Technology, Wingware, FreshBooks, and BigDoor - Lanyard: Dreamhost - Sprints: Reddit - FLOSS: OSU/OSL, OpenHatch The PyCon Organizers - http://us.pycon.org/2012 Jesse Noller - Chairman - jnoller at python.org Brian Curtin - Publicity Coordinator - brian at python.org From gagsl-py2 at yahoo.com.ar Tue Sep 27 19:52:55 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 Sep 2011 20:52:55 -0300 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813 escribi?: > Hello all, > > I encounter this issue whereby I am not able to load cPickle module into > the python I newly built. There is no issue when I load it right from > the folder where the python executable and libpython2.7.so is built. > However, it gives me this error when I load the same module using the > installed files (python and all its modules, shared library from default > /use/local folder that contains bin, lib, include sub-folders) from > "make install" command. > > Does anyone know why? Here is the error:- > > $ python > Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import cPickle > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '_extension_registry' Looking at cPickle.c, it imports the copy_reg module and then looks for its "_extension_registry" attribute. Maybe your copy_reg.py is broken, or you have another copy_reg.py hiding the standard one. -- Gabriel Genellina From roy at panix.com Tue Sep 27 20:17:01 2011 From: roy at panix.com (Roy Smith) Date: Tue, 27 Sep 2011 20:17:01 -0400 Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> Message-ID: In article <4c93ff75-1d85-48ec-b6d1-b71f216c61ce at g33g2000yqc.googlegroups.com>, Aljosa Mohorovic wrote: > i'm looking for oauth2 server implementation but other than > https://github.com/simplegeo/python-oauth2 (oauth v1 implementation) > it doesn't seem that people are using v2 implementations. > anybody using some oauth2 implementation and can share some info? > > > Aljosa Mohorovic We rolled our own oauth2 client on top of basic urllib calls. It's not terribly difficult. Other than Twitter, I'm not aware of anybody still using oauth1. From brian.curtin at gmail.com Tue Sep 27 20:52:07 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Tue, 27 Sep 2011 19:52:07 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: On Tue, Sep 27, 2011 at 16:32, Wanderer wrote: > I think it is strange to release a security update but not really expect > people > to use it. We expect that people who need 2.6 but won't move to 2.7, and at the same time are vulnerable to the security issue(s), would be able to compile Python for themselves. Shortly after 2.7 was released, 2.6 went into security-fix mode, and that's true of any X.Y and X.Y-1 pair. For a look at how busy the release schedule has been at times, I wrote about all of the releases we were up to in June at http://blog.python.org/2011/06/june-releases-267-272-314.html. Consider the fact that the person creating the installer usually creates at least three installers for any release (usually two candidates, and the final - add in alphas for a new X.Y), for each branch, of which three branches were having binary installers produced. For the specifics on the 2.6.7 fix, http://blog.python.org/2011/04/urllib-security-vulnerability-fixed.html covers it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Sep 27 20:56:49 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 Sep 2011 20:56:49 -0400 Subject: Installing Python 2.6.7 on Windows In-Reply-To: <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: On 9/27/2011 5:32 PM, Wanderer wrote: > I need to stay in sink with the rest of the company which is still > using 2.6 flavors. There was some investigation into going to Python 3 > but not enough of the libraries we use were available. I'll install > 2.6.6. I don't think the security stuff really effects me. I think it > is strange to release a security update but not really expect people > to use it. It is used most, I presume, by security-conscious server people, especially *nix people, who expect to compile their own binary. The ordinary user is hardly affected by most of these issues. -- Terry Jan Reedy From wuwei23 at gmail.com Tue Sep 27 22:22:49 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 27 Sep 2011 19:22:49 -0700 (PDT) Subject: Wrote a new library - Comments and suggestions please! References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <553f821c-58c1-4b81-817e-078c148af209@j19g2000yqc.googlegroups.com> Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/defau... > > All the words are in English, but I have no idea what the function does, how > you would call it, and what it returns. Would it have been so hard to show > a couple of examples? I'm currently arms deep in converting a handful of randomisation algorithms written in SAS into Python. Pretty much ALL of the magic happens behind cryptic SAS calls like this. I'm having more success reverse-engineering the _results_ they produce and building something Pythonic and comprehensible. From wuwei23 at gmail.com Tue Sep 27 22:25:48 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 27 Sep 2011 19:25:48 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: rantingrick wrote: > Since, like the bible > the zen is self contradicting, any argument utilizing the zen can be > defeated utilizing the zen. And like the Bible, the Zen was created by humans as a joke. If you're taking it too seriously, that's your problem. > If however you want to learn about the accepted rules for formatting > code then you need to read "PEP-8"! PEP 8 is our style guide. PEP 8 is the _standard library style guide_. There's a difference. > It is > not perfect as i have pointed out on many occasions HOWEVER it is the > only thing we have that keeps multiplicity from reproducing like > leporidae. Yes, save us from multiplicity, variety and difference. Nothing good comes from them anyway. From steve+comp.lang.python at pearwood.info Wed Sep 28 00:25:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Sep 2011 04:25:05 GMT Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> Message-ID: <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> On Tue, 27 Sep 2011 14:32:43 -0700, Wanderer wrote: > I need to stay in sink with the rest of the company which is still using > 2.6 flavors. There was some investigation into going to Python 3 but not > enough of the libraries we use were available. I'll install 2.6.6. I > don't think the security stuff really effects me. I think it is strange > to release a security update but not really expect people to use it. More likely the person who builds the Windows installers just hasn't made a new release yet. The Python development team is relatively small and chronically busy: too much to do and not enough time to do it. As I understand it, most of them use Linux, so I'm afraid that Windows sometimes takes a back seat. (At least it's not Mac OS, which is stuck riding in the boot of the car, or the other semi-supported OSes, which are on a skateboard desperately hanging onto the bumper trying not to be left behind.) You could try installing from source, if you have the appropriate Windows development environment. -- Steven From timr at probo.com Wed Sep 28 02:28:32 2011 From: timr at probo.com (Tim Roberts) Date: Tue, 27 Sep 2011 23:28:32 -0700 Subject: Multiplication error in python References: Message-ID: sakthi wrote: >In the following code, >>>> l=[1,2,3,4,5] >>>> i=0 >>>> for a in l: >... p=2*a >... t=p+i >... i=t >... >>>> t >45 > >Python gives an answer as 45. But i am getting 30 when i execute >manually. Is there any different multiplication pattern in python? My guess is that you actually typed p=3*a instead of p=2*a That produces 45. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From r32813 at freescale.com Wed Sep 28 02:37:56 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 06:37:56 +0000 Subject: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F598F9@039-SN1MPN1-003.039d.mgd.msft.net> Thanks Gabriel, Indeed, there is corrupted copy_reg.py file residing in my $PYTHONPATH folder, as opposed to the standard one from the installed package. Thanks a lot for your helps! Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Gabriel Genellina Sent: Wednesday, September 28, 2011 7:53 AM To: python-list at python.org Subject: Re: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1 En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813 escribi?: > Hello all, > > I encounter this issue whereby I am not able to load cPickle module into > the python I newly built. There is no issue when I load it right from > the folder where the python executable and libpython2.7.so is built. > However, it gives me this error when I load the same module using the > installed files (python and all its modules, shared library from default > /use/local folder that contains bin, lib, include sub-folders) from > "make install" command. > > Does anyone know why? Here is the error:- > > $ python > Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import cPickle > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '_extension_registry' Looking at cPickle.c, it imports the copy_reg module and then looks for its "_extension_registry" attribute. Maybe your copy_reg.py is broken, or you have another copy_reg.py hiding the standard one. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From 1248283536 at qq.com Wed Sep 28 03:24:13 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 28 Sep 2011 15:24:13 +0800 Subject: how to run in xp? Message-ID: #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'w') url='http://www.nasdaq.com/screening/companies- \ by-industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print ('ok',down) myfile.close() it can run in ubuntu+python2.6 ,when it run in window xp+python32,the output is Traceback (most recent call last): File "C:\Python32\getcode.py", line 8, in file=urllib.urlopen(url).read() AttributeError: 'module' object has no attribute 'urlopen' i change it into: #coding:utf-8 import urllib.request exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'w') url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print ('ok',down) myfile.close() the output is : Traceback (most recent call last): File "C:\Python32\getcode.py", line 9, in myfile.write(file) TypeError: must be str, not bytes how to make it run in xp+python32? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Sep 28 03:31:16 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 17:31:16 +1000 Subject: Multiplication error in python In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 4:28 PM, Tim Roberts wrote: > My guess is that you actually typed > ? ?p=3*a > instead of > ? ?p=2*a > > That produces 45. > Or alternatively, that you used an interactive Python environment and didn't clear i between runs. ChrisA From __peter__ at web.de Wed Sep 28 04:04:46 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Sep 2011 10:04:46 +0200 Subject: how to run in xp? References: Message-ID: =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX From r32813 at freescale.com Wed Sep 28 04:37:13 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 08:37:13 +0000 Subject: python 2.7.1 built not supporting thread? In-Reply-To: References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F59952@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I couldn't detect this problem until I run my application that utilizes thread module in python that I just built on HP-UX 11.31 ia64 using aCC. Could it be the build did not include enable thread option? _REENTRANT as stated in the README file? If yes, it looks like threading may not work "out of the box". >>> thread.start_new_thread(testing, ()) Traceback (most recent call last): File "", line 1, in thread.error: can't start new thread >>> Excerpts from README file for python 2.7 build HP-UX: When using threading, you may have to add -D_REENTRANT to the OPT variable in the top-level Makefile; reported by Pat Knight, this seems to make a difference (at least for HP-UX 10.20) even though pyconfig.h defines it. This seems unnecessary when using HP/UX 11 and later - threading seems to work "out of the box". From xahlee at gmail.com Wed Sep 28 05:28:38 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 02:28:38 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or Message-ID: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> curious question. suppose you have 300 different strings and they need all be replaced to say "aaa". is it faster to replace each one sequentially (i.e. replace first string to aaa, then do the 2nd, 3rd,...) , or is it faster to use a regex with ?or? them all and do replace one shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) let's say the sourceString this replacement to be done on is 500k chars. Anyone? i suppose the answer will be similar for perl, python, ruby. btw, the origin of this question is about writing a emacs lisp function that replace ~250 html named entities to unicode char. Xah From aljosa.mohorovic at gmail.com Wed Sep 28 05:55:12 2011 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: Wed, 28 Sep 2011 02:55:12 -0700 (PDT) Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> Message-ID: <862e37e9-f4d2-4423-8d28-485923f1c76b@p11g2000yqe.googlegroups.com> On Sep 28, 2:17?am, Roy Smith wrote: > We rolled our own oauth2 client on top of basic urllib calls. ?It's not > terribly difficult. i'm asking about oauth2 server implementation, not client. it's easy to consume oauth2 stuff but what to do when you need to implement server side stuff? Aljosa From rosuav at gmail.com Wed Sep 28 06:04:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 20:04:43 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 7:28 PM, Xah Lee wrote: > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially Before you ask "is it faster", you need to first be sure it's correct. I would recommend doing all the replaces in a single function call to avoid risk of overlaps or other issues causing problems. ChrisA From r32813 at freescale.com Wed Sep 28 06:14:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 28 Sep 2011 10:14:08 +0000 Subject: python 2.7.1 HP-UX 11 ia64 built not supporting thread References: <29893638.744.1317107871111.JavaMail.geo-discussion-forums@prfp13> <02EA6D704E30CE499C5071776509A925F593B8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F599D0@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, I included --with-threads option into the configure script calling, which it failed to add the -D_REENTRANT into Makefile. So I manually added this into OPT of the Makefile. I ran make again and generated a new python binary. However, the new binary is still not able to start a new thread from the thread module. I reviewed the config.log file, I think this failure has caused the build with threads failed. Cthreads.h header file is missing. Should this be included in my HP UX Compiler or it comes from python source? In python source I only found pythread.h. Anyway, I am only guessing what is wrong. Hope to hear some feedback here, whether this is something missing or a bug. configure:8407: checking for --with-threads configure:8427: result: yes configure:8484: checking for _POSIX_THREADS in unistd.h configure:8503: result: yes configure:8508: checking cthreads.h usability configure:8508: cc +DD64 -I/home/r32813/local/include -c -g conftest.c >&5 "conftest.c", line 128: error #3696-D: cannot open source file "cthreads.h" #include ^ 1 error detected in the compilation of "conftest.c". | #define HAVE_LIBDLD 1 | #define _REENTRANT 1 | /* end confdefs.h. */ | #include configure:8508: result: no configure:8508: checking for cthreads.h configure:8508: result: no configure:8521: checking mach/cthreads.h usability configure:8521: cc +DD64 -I/home/r32813/local/include -c -g conftest.c >&5 "conftest.c", line 128: error #3696-D: cannot open source file "mach/cthreads.h" #include ^ 1 error detected in the compilation of "conftest.c". configure:8521: $? = 2 configure: failed program was: | /* confdefs.h */ | #define _GNU_SOURCE 1 | #define HAVE_LIBDLD 1 | #define _REENTRANT 1 | /* end confdefs.h. */ | #include configure:8521: result: no configure:8521: checking for mach/cthreads.h configure:8521: result: no configure:8533: checking for --with-pth configure:8548: result: no configure:8556: checking for pthread_create in -lpthread configure:8572: cc +DD64 -I/home/r32813/local/include -o conftest -g -L/home/r32813/local/lib -L/home/r32813/Build/2.7.1/Python-2.7.1 conftest.c -l nsl -lrt -ldld -ldl -lpthread >&5 Regards, Wah Meng Genesis Wafermap Support Ticket: To report a problem: http://dyno.freescale.net/Question/QuestionMain3.asp?location=zmy02&category=&tickettype=6820 To request a service: http://dyno.freescale.net/Question/Questionmain3.asp?location=74&category=2&tickettype=6819 Or if it is related to EWM or DSA: http://dyno.freescale.net/Question/Questionmain3.asp?location=ZMY02&tickettype=6539 -----Original Message----- From: Wong Wah Meng-R32813 Sent: Wednesday, September 28, 2011 4:37 PM To: python-list at python.org Subject: python 2.7.1 built not supporting thread? Hello there, I couldn't detect this problem until I run my application that utilizes thread module in python that I just built on HP-UX 11.31 ia64 using aCC. Could it be the build did not include enable thread option? _REENTRANT as stated in the README file? If yes, it looks like threading may not work "out of the box". >>> thread.start_new_thread(testing, ()) Traceback (most recent call last): File "", line 1, in thread.error: can't start new thread >>> Excerpts from README file for python 2.7 build HP-UX: When using threading, you may have to add -D_REENTRANT to the OPT variable in the top-level Makefile; reported by Pat Knight, this seems to make a difference (at least for HP-UX 10.20) even though pyconfig.h defines it. This seems unnecessary when using HP/UX 11 and later - threading seems to work "out of the box". From merlyn at stonehenge.com Wed Sep 28 06:57:44 2011 From: merlyn at stonehenge.com (Randal L. Schwartz) Date: Wed, 28 Sep 2011 03:57:44 -0700 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: <86bou553yv.fsf@red.stonehenge.com> >>>>> "Xah" == Xah Lee writes: Xah> curious question. Xah> suppose you have 300 different strings and they need all be replaced Xah> to say "aaa". And then suppose this isn't the *real* question, but one entirely of Fiction by Xah Lee. How helpful do you want to be? -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc. See http://methodsandmessages.posterous.com/ for Smalltalk discussion From 1248283536 at qq.com Wed Sep 28 07:50:04 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Wed, 28 Sep 2011 19:50:04 +0800 Subject: how to run in xp? Message-ID: it can run ,but there is still a problem ,nothing in my file. please run the code in xp+python32 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() print (file) what you get is: >>> b'' b'' b'' >>> how to fix it? ------------------ Original ------------------ From: "Peter Otten"<__peter__ at web.de>; Date: Wed, Sep 28, 2011 04:04 PM To: "python-list"; Subject: Re: how to run in xp? =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From devplayer at gmail.com Wed Sep 28 08:12:31 2011 From: devplayer at gmail.com (DevPlayer) Date: Wed, 28 Sep 2011 05:12:31 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: On Sep 27, 10:25?pm, alex23 wrote: > rantingrick wrote: > > Since, like the bible > > the zen is self contradicting, any argument utilizing the zen can be > > defeated utilizing the zen. > > And like the Bible, the Zen was created by humans as a joke. If you're > taking it too seriously, that's your problem. > > > If however you want to learn about the accepted rules for formatting > > code then you need to read "PEP-8"! PEP 8 is our style guide. > Contradiction is only seen by narrow perspectve. Calling the Bible a joke is used to hurt people, not enlighten them. Those words show bitter arrogance, not constructive critism as it ignores how others feel about that book. What benefit to others is gained by calling someones belief a joke? To put the "believers" minds straight? I think not. I think the unsensitive person who attackes others beliefs, even if illogical or unrealistic, is after some kind of self grandizement or to illude themself into thinking "they know the truth of the universe" and should attack others to prove they do. Although this is not the place to defend about such things it is also not the place to attack those same things (that being someone's faith). There is no real forum to defend a faith or religion, or words in a book about that, other then where such faiths are in fact attacked. However I did laugh at the ironic use of using any-kind of zen to seriously, even Python's, as that is very unzen-like. That is a contradiction by it's very own definitions! From xahlee at gmail.com Wed Sep 28 08:28:01 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 05:28:01 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> Message-ID: <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> On Sep 28, 3:57?am, mer... at stonehenge.com (Randal L. Schwartz) wrote: > >>>>> "Xah" == Xah Lee writes: > > Xah> curious question. > Xah> suppose you have 300 different strings and they need all be replaced > Xah> to say "aaa". > > And then suppose this isn't the *real* question, but one entirely of > Fiction by Xah Lee. > > How helpful do you want to be? it's a interesting question anyway. the question originally came from when i was coding elisp of a function that changes html entities to unicode char literal. The problem is slightly complicated, involving a few questions about speed in emacs. e.g. string vs buffer, and much more... i spent several hours on this but it's probably too boring to detail (but i'll do so if anyone wishes). But anyway, while digging these questions that's not clear in my mind, i thought of why not generate a regex or construct and do it in one shot, and wondered if that'd be faster. But afterwards, i realized this wouldn't be applicable to my problem because for my problem each string needs to be changed to a unique string, not all to the same string. Xah From michele.simionato at gmail.com Wed Sep 28 08:45:27 2011 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 28 Sep 2011 05:45:27 -0700 (PDT) Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <29931044.1310.1317213927830.JavaMail.geo-discussion-forums@yqnk41> plac is based on argparser and it is intended to be much easier to use. See http://plac.googlecode.com/hg/doc/plac.html Here is an example of usage. $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line plac.Interpreter.call instantiates the VCS class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments plac can also be used to write command interpreters. From michele.simionato at gmail.com Wed Sep 28 08:45:27 2011 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 28 Sep 2011 05:45:27 -0700 (PDT) Subject: Hierarchical commnd line parsing / help texts In-Reply-To: References: Message-ID: <29931044.1310.1317213927830.JavaMail.geo-discussion-forums@yqnk41> plac is based on argparser and it is intended to be much easier to use. See http://plac.googlecode.com/hg/doc/plac.html Here is an example of usage. $ cat vcs.py class VCS(object): "A fictitious version control tool" commands = ['checkout', 'commit'] def checkout(self, url): return 'ok' def commit(self): return 'ok' if __name__ == '__main__': import plac; plac.Interpreter.call(VCS) The line plac.Interpreter.call instantiates the VCS class by passing to it the arguments in the command line and then calls the appropriate method. You can use the script as follows: $ python vcs.py -h usage: vcs.py [-h] [args [args ...]] positional arguments: args optional arguments: -h, --help show this help message and exit $ python vcs.py checkout url ok $ python vcs.py commit ok plac takes care of parsing the command line, giving the correct error message if you pass wrong arguments or not enough arguments: $ python vcs.py checkout usage: checkout url checkout: error: too few arguments plac can also be used to write command interpreters. From roy at panix.com Wed Sep 28 08:53:06 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 08:53:06 -0400 Subject: oauth2 server implementation References: <4c93ff75-1d85-48ec-b6d1-b71f216c61ce@g33g2000yqc.googlegroups.com> <862e37e9-f4d2-4423-8d28-485923f1c76b@p11g2000yqe.googlegroups.com> Message-ID: In article <862e37e9-f4d2-4423-8d28-485923f1c76b at p11g2000yqe.googlegroups.com>, Aljosa Mohorovic wrote: > On Sep 28, 2:17?am, Roy Smith wrote: > > We rolled our own oauth2 client on top of basic urllib calls. ?It's not > > terribly difficult. > > i'm asking about oauth2 server implementation, not client. > it's easy to consume oauth2 stuff but what to do when you need to > implement server side stuff? Oh, my apologies, I read your post too fast and misunderstood what you were asking. I suspect writing an oauth2 provider will be on my plate soon, so let me know what you figure out :-) From xahlee at gmail.com Wed Sep 28 09:14:33 2011 From: xahlee at gmail.com (Xah Lee) Date: Wed, 28 Sep 2011 06:14:33 -0700 (PDT) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> here's more detail about the origin of this problem. Relevant to emacs lisp only. ------------------------------ in the definition of ?replace-regexp-in-string?, there's this comment: ;; To avoid excessive consing from multiple matches in long strings, ;; don't just call `replace-match' continually. Walk down the ;; string looking for matches of REGEXP and building up a (reversed) ;; list MATCHES. This comprises segments of STRING which weren't ;; matched interspersed with replacements for segments that were. ;; [For a `large' number of replacements it's more efficient to ;; operate in a temporary buffer; we can't tell from the function's ;; args whether to choose the buffer-based implementation, though it ;; might be reasonable to do so for long enough STRING.] note: ?For a `large' number of replacements it's more efficient to operate in a temporary buffer?. my question is, anyone got some idea, how ?large? is large? currently, i have a function replace-pairs-in-string which is implemented by repeatedly calling ?replace-pairs-in-string? like this: (while (< ii (length pairs)) (setq mystr (replace-regexp-in-string (elt tempMapPoints ii) (elt (elt pairs ii) 1) mystr t t)) (setq ii (1+ ii)) ) When there are 260 pairs of strings to be replaced on a file that's 26k in size, my function takes about 3 seconds (which i think is too slow). I'm at pain deciding whether my function should be implemented like this or whether it should create a temp buffer. The problem with temp buffer is that, if you repeatedly call it, the overhead of creating buffer is going to make it much slower. i was actually surprised that replace-regexp-in-string isn't written in C, which i thought it was. is there technical reason the replace-regexp-in-string isn't C? (i suppose only because nobody every did it and the need for speed didn't suffice?) and also, shouldn't there also be a replace-in-string (literal, not regex)? because i thought implementing replacement for string should be much simpler and faster, because buffers comes with it a whole structure such as ?point?, text properties, buffer names, buffier modifier, etc. Xah On Sep 28, 5:28?am, Xah Lee wrote: > On Sep 28, 3:57?am, mer... at stonehenge.com (Randal L. Schwartz) wrote: > > > >>>>> "Xah" == Xah Lee writes: > > > Xah> curious question. > > Xah> suppose you have 300 different strings and they need all be replaced > > Xah> to say "aaa". > > > And then suppose this isn't the *real* question, but one entirely of > > Fiction by Xah Lee. > > > How helpful do you want to be? > > it's a interesting question anyway. > > the question originally came from when i was coding elisp of a > function that changes html entities to unicode char literal. The > problem is slightly complicated, involving a few questions about speed > in emacs. e.g. string vs buffer, and much more... i spent several > hours on this but it's probably too boring to detail (but i'll do so > if anyone wishes). But anyway, while digging these questions that's > not clear in my mind, i thought of why not generate a regex or > construct and do it in one shot, and wondered if that'd be faster. But > afterwards, i realized this wouldn't be applicable to my problem > because for my problem each string needs to be changed to a unique > string, not all to the same string. > > ?Xah From rosuav at gmail.com Wed Sep 28 09:19:32 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:19:32 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: > each string needs to be changed to a unique > string, not all to the same string. And you'll find that this is, by and large, the most normal situation. Folding many strings down to one string is a lot less common. So, let's have some real-world use cases and then we can talk recommendations. ChrisA From neilc at norwich.edu Wed Sep 28 09:22:41 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 28 Sep 2011 13:22:41 GMT Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <9egld1F385U1@mid.individual.net> On 2011-09-28, Chris Angelico wrote: > On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: >> each string needs to be changed to a unique string, not all to >> the same string. > > And you'll find that this is, by and large, the most normal > situation. Folding many strings down to one string is a lot > less common. So, let's have some real-world use cases and then > we can talk recommendations. I'd like to know what "string replacement" is supposed to mean in the context of Python. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From rosuav at gmail.com Wed Sep 28 09:26:37 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:26:37 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <2b90e8b7-2f1e-4f24-9413-56a3fafa897b@z12g2000yqz.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 11:14 PM, Xah Lee wrote: > (while (< ii (length pairs)) > ? ? ?(setq mystr (replace-regexp-in-string > ? ? ? ? ? ? ? ? ? (elt tempMapPoints ii) > ? ? ? ? ? ? ? ? ? (elt (elt pairs ii) 1) > ? ? ? ? ? ? ? ? ? mystr t t)) > ? ? ?(setq ii (1+ ii)) > ? ? ?) from __future__ import lisp_syntax There, that makes it on-topic for the Python list... I guess. ChrisA From __peter__ at web.de Wed Sep 28 09:29:19 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Sep 2011 15:29:19 +0200 Subject: how to run in xp? References: Message-ID: =?gbk?B?ytjW6rT9zcM=?= wrote: > it can run ,but there is still a problem ,nothing in my file. > please run the code in xp+python32 > import urllib.request, urllib.parse, urllib.error > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > print (file) > what you get is: > >>>> > b'' > b'' > b'' >>>> > > how to fix it? I get the expected output, but I'm on Linux. Are you using the latest bugfix release (Python 3.2.2)? Can you download the data with your browser? From roy at panix.com Wed Sep 28 09:29:57 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 09:29:57 -0400 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <9egld1F385U1@mid.individual.net> Message-ID: In article <9egld1F385U1 at mid.individual.net>, Neil Cerutti wrote: > On 2011-09-28, Chris Angelico wrote: > > On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee wrote: > >> each string needs to be changed to a unique string, not all to > >> the same string. > > > > And you'll find that this is, by and large, the most normal > > situation. Folding many strings down to one string is a lot > > less common. So, let's have some real-world use cases and then > > we can talk recommendations. > > I'd like to know what "string replacement" is supposed to mean in > the context of Python. You just need to use "string" in the more generic computer-sciency sense, not in the python-data-type sense. s = "I am an immutable string" l = list(s) # now you can pretend strings are mutable do_stuff_to_string(l) s = ''.join(l) From rosuav at gmail.com Wed Sep 28 09:32:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 28 Sep 2011 23:32:49 +1000 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <9egld1F385U1@mid.individual.net> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> <9egld1F385U1@mid.individual.net> Message-ID: On Wed, Sep 28, 2011 at 11:22 PM, Neil Cerutti wrote: > I'd like to know what "string replacement" is supposed to mean in > the context of Python. > Substring replacement, such as: >>> "Hello, world!".replace(", "," -- ") 'Hello -- world!' The str method doesn't accept a list, though, so it won't do simultaneous replaces. (At least, I don't think it can. Tried it only in Python 3.2 on Windows.) ChrisA From python.list at tim.thechases.com Wed Sep 28 10:16:59 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Sep 2011 09:16:59 -0500 Subject: Unittest testing assert*() calls rather than methods? Message-ID: <4E832C5B.1080007@tim.thechases.com> While I asked this on the Django list as it happened to be with some Django testing code, this might be a more generic Python question so I'll ask here too. When performing unittest tests, I have a number of methods of the form def test_foo(self): data = ( (item1, result1), ... #bunch of tests for fence-post errors ) for test, result in data: self.assertEqual(process(test), result) When I run my tests, I only get a tick for running one the one test (test_foo), not the len(data) tests that were actually performed. Is there a way for unittesting to report the number of passed-assertions rather than the number of test-methods run? -tkc From ben+python at benfinney.id.au Wed Sep 28 10:17:57 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:17:57 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <87oby4zr6y.fsf@benfinney.id.au> DevPlayer writes: > Calling the Bible a joke is used to hurt people, not enlighten them. How do you know that? > Those words show bitter arrogance, not constructive critism How do you know that? > as it ignores how others feel about that book. That strikes me as a good thing; how people feel about a book should not in any way restrain our criticism of the book. > What benefit to others is gained by calling someones belief a joke? To > put the "believers" minds straight? I think not. I can't speak for the person who wrote that. But when I call a religious belief a joke, it is to point out the folly of the belief in the pursuit of convincing people not to hold beliefs I consider to be foolish. > I think the unsensitive person who attackes others beliefs, even if > illogical or unrealistic, is after some kind of self grandizement or > to illude themself into thinking "they know the truth of the universe" > and should attack others to prove they do. You are wrong to conflate ?attack others's beliefs? with ?attack others?. You are not your beliefs. If your beliefs are shown to be false ? even ridiculous ? you can distance yourself from those beliefs. It is even virtuous to do so. We must always be free to attack any belief, and encourage everyone to stop taking it as any kind of personal attack. > Although this is not the place to defend about such things it is also > not the place to attack those same things (that being someone's > faith). I will join you in deploring any attack on a person. But that's not what you're doing, and I deny your attempt to shield any idea from ridicule, in any forum. Ideas don't have feelings, and you don't get to put people in front of them as human shields against attacking those ideas. Any idea is and must be open to attack in any forum; those that can't survive ridicule deserve to go. -- \ ?Ridicule is the only weapon which can be used against | `\ unintelligible propositions.? ?Thomas Jefferson, 1816-07-30 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 10:29:18 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:29:18 +1000 Subject: Unittest testing assert*() calls rather than methods? References: Message-ID: <87k48szqo1.fsf@benfinney.id.au> Tim Chase writes: > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) The sets of data for running the same test we might call ?scenarios?. > When I run my tests, I only get a tick for running one the one test > (test_foo), not the len(data) tests that were actually performed. Worse, if one of the scenarios causes the test to fail, the loop will end and you won't get the results for the remaining scenarios. > Is there a way for unittesting to report the number of > passed-assertions rather than the number of test-methods run? You can use the third-party ?testscenarios? library to generate test cases at run time, one for each combination of scenarios with test cases on the class. They will all be run and reported as distinct test cases. There is even another library integrating this with Django . -- \ ?Books and opinions, no matter from whom they came, if they are | `\ in opposition to human rights, are nothing but dead letters.? | _o__) ?Ernestine Rose | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 10:53:40 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 00:53:40 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <87fwjgzpjf.fsf@benfinney.id.au> Ben Finney writes: > You can use the third-party ?testscenarios? library The URL got a bit mangled. The proper PyPI URL for that library is . > to generate test cases at run time, one for each combination of > scenarios with test cases on the class. They will all be run and > reported as distinct test cases. > > There is even another library integrating this with Django > . -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From drobinow at gmail.com Wed Sep 28 12:17:05 2011 From: drobinow at gmail.com (David Robinow) Date: Wed, 28 Sep 2011 12:17:05 -0400 Subject: how to run in xp? In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 9:29 AM, Peter Otten <__peter__ at web.de> wrote: > =?gbk?B?ytjW6rT9zcM=?= wrote: > >> it can run ,but there is still a problem ,nothing in my file. >> please run the code in xp+python32 >> import urllib.request, urllib.parse, urllib.error >> exchange=['NASDAQ','NYSE','AMEX'] >> for down in exchange: >> ? ? url='http://www.nasdaq.com/screening/companies-by- > industry.aspx?exchange='+down+'&render=download' >> ? ? file=urllib.request.urlopen(url).read() >> ? ? print (file) >> what you get is: >> >>>>> >> b'' >> b'' >> b'' >>>>> >> >> how to fix it? > > I get the expected output, but I'm on Linux. Are you using the latest bugfix > release (Python 3.2.2)? Can you download the data with your browser? I get the expected output, but I'm on Windows (Vista, Python 3.2.2.) From alec.taylor6 at gmail.com Wed Sep 28 12:19:32 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 29 Sep 2011 02:19:32 +1000 Subject: Python 2.5 zlib trouble In-Reply-To: References: <9ad79d78-e283-40bd-b234-1cdc6558a9ab@v18g2000yqj.googlegroups.com> <4e7c3f18$0$29986$c3e8da3$5496439d@news.astraweb.com> <308367fd-15e4-4133-9fbe-6a919103ce3f@hb5g2000vbb.googlegroups.com> <78c0c680-1abc-424d-a608-f14ce81ed7e8@t11g2000yqa.googlegroups.com> <2ebd0289-5c38-499f-a984-b1e2b669c4c3@gd10g2000vbb.googlegroups.com> <16b3f911-b0bd-4893-a338-5caae441daf8@18g2000yqz.googlegroups.com> Message-ID: Fix: http://lipyrary.blogspot.com/2011/05/how-to-compile-python-on-ubuntu-1104.html On Tue, Sep 27, 2011 at 5:04 AM, Benjamin Kaplan wrote: > On Mon, Sep 26, 2011 at 2:16 PM, Jesramz wrote: >> >> I appreciate all the help, but I am still a little confused. Sorry, >> I'm a lay person. >> >> Should I download zlib1g-dev and install it to get the zlib module? >> >> and Alter the configure script to avoid future issues? >> >> Also about getting zlib I found the following: >> >> "I was able to recompile zlib >> >> $./configure --shared >> >> then recompile Python 2.5.1; I am now able to import the zlib module. >> >> cheers >> >> -sg" >> >> Does this mean that while in the zlib folder run ./configure shared >> and then install python? >> -- > > Not quite. This person was talking about configuring zlib, not Python. > Just about every Linux program out there has a ./configure file- it's > part of GNU Autotools, which many programs use as an easy way to > compile and install their software. Since the version of zlib on > Ubuntu Natty doesn't work for Python 2.5, this person just compiled > their own zlib (calling ./configure --shared; make; make install from > the zlib *source* folder that they downloaded) and then compiled their > own Python version (from the Python source folder that they > downloaded) > > >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From willem at toad.stack.nl Wed Sep 28 13:00:51 2011 From: willem at toad.stack.nl (Willem) Date: Wed, 28 Sep 2011 17:00:51 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: Xah Lee wrote: ) the question originally came from when i was coding elisp of a ) function that changes html entities to unicode char literal. The ) problem is slightly complicated, involving a few questions about speed ) in emacs. e.g. string vs buffer, and much more... i spent several ) hours on this but it's probably too boring to detail (but i'll do so ) if anyone wishes). But anyway, while digging these questions that's ) not clear in my mind, i thought of why not generate a regex or ) construct and do it in one shot, and wondered if that'd be faster. But ) afterwards, i realized this wouldn't be applicable to my problem ) because for my problem each string needs to be changed to a unique ) string, not all to the same string. In Perl, it would be applicable. You see, in Perl, you can call a function in the replacement of the regex substitution, which can then look up the html entity and return the wanted unicode literal. I think you can do that in some other languages as well. SaSW, Willem -- Disclaimer: I am in no way responsible for any of the statements made in the above text. For all I know I might be drugged or something.. No I'm not paranoid. You all think I'm paranoid, don't you ! #EOT From python at mrabarnett.plus.com Wed Sep 28 13:11:33 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 28 Sep 2011 18:11:33 +0100 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <4E835545.9010802@mrabarnett.plus.com> On 28/09/2011 18:00, Willem wrote: > Xah Lee wrote: > ) the question originally came from when i was coding elisp of a > ) function that changes html entities to unicode char literal. The > ) problem is slightly complicated, involving a few questions about speed > ) in emacs. e.g. string vs buffer, and much more... i spent several > ) hours on this but it's probably too boring to detail (but i'll do so > ) if anyone wishes). But anyway, while digging these questions that's > ) not clear in my mind, i thought of why not generate a regex or > ) construct and do it in one shot, and wondered if that'd be faster. But > ) afterwards, i realized this wouldn't be applicable to my problem > ) because for my problem each string needs to be changed to a unique > ) string, not all to the same string. > > In Perl, it would be applicable. You see, in Perl, you can call a function > in the replacement of the regex substitution, which can then look up the > html entity and return the wanted unicode literal. > > I think you can do that in some other languages as well. > Including Python... From ian.g.kelly at gmail.com Wed Sep 28 13:48:48 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 28 Sep 2011 11:48:48 -0600 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On Wed, Sep 28, 2011 at 3:28 AM, Xah Lee wrote: > curious question. > > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially (i.e. replace first > string to aaa, then do the 2nd, 3rd,...) > , or is it faster to use a regex with ?or? them all and do replace one > shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) > > let's say the sourceString this replacement to be done on is 500k > chars. > > Anyone? i suppose the answer will be similar for perl, python, ruby. > > btw, the origin of this question is about writing a emacs lisp > function that replace ~250 html named entities to unicode char. I haven't timed it at the scale you're talking about, but for Python I expect regex will be your best bet: # Python 3.2: Supposing the match strings and replacements are # in a dict stored as `repls`... import re pattern = '|'.join(map(re.escape, repls.keys())) new_str = re.sub(pattern, lambda m: repls[m.group()], old_str) The problem with doing 300 str.replace calls is the 300 intermediate strings that would be created and then collected. Cheers, Ian From * at eli.users.panix.com Wed Sep 28 15:08:21 2011 From: * at eli.users.panix.com (Eli the Bearded) Date: Wed, 28 Sep 2011 19:08:21 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: In comp.lang.perl.misc, Willem wrote: > In Perl, it would be applicable. You see, in Perl, you can call a function > in the replacement of the regex substitution, which can then look up the > html entity and return the wanted unicode literal. A function? I'd use a hash. > I think you can do that in some other languages as well. Hash / array type substitutions indexed by $1 (or language equivilent) are probably easy to implement in many languages. Elijah ------ for really fast, write code to generate a C lexer to do it From willem at toad.stack.nl Wed Sep 28 15:11:27 2011 From: willem at toad.stack.nl (Willem) Date: Wed, 28 Sep 2011 19:11:27 +0000 (UTC) Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: Eli the Bearded wrote: ) In comp.lang.perl.misc, Willem wrote: )> In Perl, it would be applicable. You see, in Perl, you can call a function )> in the replacement of the regex substitution, which can then look up the )> html entity and return the wanted unicode literal. ) ) A function? I'd use a hash. A function can return a sensible value for unknown substitutions. In the case where you prebuild a giant regex or-list, that is not an issue, but I would match html entities generically. SaSW, Willem -- Disclaimer: I am in no way responsible for any of the statements made in the above text. For all I know I might be drugged or something.. No I'm not paranoid. You all think I'm paranoid, don't you ! #EOT From john at castleamber.com Wed Sep 28 16:14:51 2011 From: john at castleamber.com (John Bokma) Date: Wed, 28 Sep 2011 15:14:51 -0500 Subject: question about speed of sequential string replacement vs regex or References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> <86bou553yv.fsf@red.stonehenge.com> <4f37d1f2-699a-4646-a243-cbb3558989c2@j1g2000yqj.googlegroups.com> Message-ID: <8739fgjuf8.fsf@castleamber.com> Willem writes: > Eli the Bearded wrote: > ) In comp.lang.perl.misc, Willem wrote: > )> In Perl, it would be applicable. You see, in Perl, you can call a function > )> in the replacement of the regex substitution, which can then look up the > )> html entity and return the wanted unicode literal. > ) > ) A function? I'd use a hash. > > A function can return a sensible value for unknown substitutions. You can do that also in the RHS of the substitution and still keep it readable if you use something like s{..}{ your code goes here }ge; However, a function can be easier on the eye: s{...}{ some_good_name( ... ) }ge; -- John Bokma j3b Blog: http://johnbokma.com/ Perl Consultancy: http://castleamber.com/ Perl for books: http://johnbokma.com/perl/help-in-exchange-for-books.html From theg33k at gmail.com Wed Sep 28 17:06:23 2011 From: theg33k at gmail.com (The Geek) Date: Wed, 28 Sep 2011 17:06:23 -0400 Subject: new to python question Message-ID: I'm clearly not understanding something about scope in python... Any help is appreciated In the following script I'm attempting to create 2 Foo objects, for each Foo object I create 2 Bars and add them to Foo's bar array Something hokey is occurring with the "foo.bars.append(bar)" line such that Foo.bars is treated as a "static" (I know python doesn't have statics) I have a workaround using encapsulation for the bars array but I prefer would also like to understand the issue. TIA, Brad [SCRIPT] foos = [] class Foo: id = 0 bars = [] class Bar: id = 0 for j in range(0, 2): foo = Foo() for i in range(0, 2): bar = Bar() bar.id = i foo.bars.append(bar) foos.append(foo) for myFoo in foos: print("foo id: ", myFoo.id) for myBar in myFoo.bars: print ("\tbar id: ", myBar.id) [/SCRIPT] [OUTPUT] python test.py foo id: 0 bar id: 0 bar id: 1 bar id: 0 bar id: 1 foo id: 0 bar id: 0 bar id: 1 bar id: 0 bar id: 1 [/OUTPUT] -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Wed Sep 28 17:12:13 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 28 Sep 2011 17:12:13 -0400 Subject: new to python question In-Reply-To: References: Message-ID: On Wed, Sep 28, 2011 at 5:06 PM, The Geek wrote: > I'm clearly not understanding something about scope in python... ?Any help > is appreciated > In the following script I'm attempting to create 2 Foo objects, for each Foo > object I create 2 Bars and add them to Foo's bar array > Something hokey is?occurring?with the "foo.bars.append(bar)" line such that > Foo.bars is treated as a "static" (I know python doesn't have statics) > I have a workaround using encapsulation for the bars array but I prefer > would also like to understand the issue. > TIA, > Brad > [SCRIPT] > foos = [] > class Foo: > id = 0 > bars = [] > class Bar: > id = 0 > for j in range(0, 2): > foo = Foo() > for i in range(0, 2): > bar = Bar() > bar.id = i > foo.bars.append(bar) > foos.append(foo) > for myFoo in foos: > print("foo id: ", myFoo.id) > for myBar in myFoo.bars: > print ("\tbar id: ", myBar.id) > [/SCRIPT] It's a pretty common gotcha for people coming from other languages. Everything declared in the class scope becomes an attribute of the class. >>> class Foo(object) : ... a = 3 ... def b() : pass ... >>> dir(Foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_ _weakref__', 'a', 'b'] Mutating those objects mutates the attribute of the class, which is visible to all instances of the class. In order to get an instance of a class, you have to add the field to the instance of the class instead of to the class itself. class Bar(object) : def ___init__(self) : self.a = 3 From tjreedy at udel.edu Wed Sep 28 17:23:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 17:23:50 -0400 Subject: question about speed of sequential string replacement vs regex or In-Reply-To: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> References: <0062679d-6cde-4e61-baff-3a7289ac5090@t11g2000yqa.googlegroups.com> Message-ID: On 9/28/2011 5:28 AM, Xah Lee wrote: > curious question. > > suppose you have 300 different strings and they need all be replaced > to say "aaa". > > is it faster to replace each one sequentially (i.e. replace first > string to aaa, then do the 2nd, 3rd,...) > , or is it faster to use a regex with ?or? them all and do replace one > shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa) Here the problem is replace multiple random substrings with one random substring that could create new matches. I would start with the re 'or' solution. > btw, the origin of this question is about writing a emacs lisp > function that replace ~250 html named entities to unicode char. As you noted this is a different problem in that there is a different replacement for each. Also, the substrings being searched for are not random but have a distinct and easily recognized structure. The replacement cannot create a new match. So the multiple scan approach *could* work. Unspecified is whether the input is unicode or ascii bytes. If the latter I might copy to a bytearray (mutable), scan forward, replace entity defs with utf-8 encoding of the corresponding unicode (with a dict lookup, and which I assume are *always* fewer chars), and shift other chars to close any gaps created. If the input is unicode, I might do the same with array.array (which is where bytearray came from). Or I might use the standard idiom of constructing a list of pieces of the original, with replacements, and ''.join() at the end. -- Terry Jan Reedy From ethan at stoneleaf.us Wed Sep 28 17:26:09 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 28 Sep 2011 14:26:09 -0700 Subject: syntactic sugar for def? Message-ID: <4E8390F1.9060207@stoneleaf.us> I remember that 'class' is sugar for type(....). I don't remember if 'def' is sugar for something besides lambda. Any clues for me? Heck, I'll even be grateful for outright answers! ~Ethan~ From ian.g.kelly at gmail.com Wed Sep 28 17:36:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 28 Sep 2011 15:36:08 -0600 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. > > Any clues for me? ?Heck, I'll even be grateful for outright answers! If you mean is there a way to create functions using reflection, you can use types.FunctionType. Like type() requires a dict, FunctionType() requires a code object that must first be compiled. Cheers, Ian From arnodel at gmail.com Wed Sep 28 17:37:12 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Wed, 28 Sep 2011 22:37:12 +0100 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On 28 September 2011 22:26, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. > > Any clues for me? ?Heck, I'll even be grateful for outright answers! It's not really sugar. But I think you mean something like this: >>> class A: pass ... >>> type(A) >>> type is type(A) True So the closest you get for functions will be: >>> def f(): pass ... >>> type(f) Try help(type(f)) to see how to use it to create a function object. The problem is that you need to provide a code object, and the easiest way to create a code object is to use a def statement :) HTH -- Arnaud From tayfun92_kayhan at yahoo.com Wed Sep 28 17:49:21 2011 From: tayfun92_kayhan at yahoo.com (Tayfun Kayhan) Date: Wed, 28 Sep 2011 14:49:21 -0700 (PDT) Subject: A trivial question Message-ID: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> I accidentally wrote such a code (below) while trying to write sth else for my application but i am now just wondering much how to run the class Foo, if it is possible. Is not it weird that Python does not give any error when I run it ? Sorry for that it's pretty unimportant question according to the other questions being asked here :D def trial(): class Foo(object): def __init__(self): print("Hello, world!") trial() # not worked, as expected. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ckaynor at zindagigames.com Wed Sep 28 17:51:00 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 28 Sep 2011 14:51:00 -0700 Subject: syntactic sugar for def? In-Reply-To: References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle wrote: > On 28 September 2011 22:26, Ethan Furman wrote: >> I remember that 'class' is sugar for type(....). >> >> I don't remember if 'def' is sugar for something besides lambda. >> >> Any clues for me? ?Heck, I'll even be grateful for outright answers! > > It's not really sugar. ?But I think you mean something like this: > > >>>> class A: pass > ... >>>> type(A) > >>>> type is type(A) > True > > So the closest you get for functions will be: > >>>> def f(): pass > ... >>>> type(f) > > > Try help(type(f)) to see how to use it to create a function object. > The problem is that you need to provide a code object, and the easiest > way to create a code object is to use a def statement :) I would say compile isn't too much harder to use: >>> c = compile('a = 123', 'test', 'exec') >>> d = {} >>> f = types.FunctionType(c, d, 'test') >>> f() >>> print d {'a': 123} Although it appears you get all of the variables defined as global apparently (try "f = types.FunctionType(c, globals(), 'test')" instead). > > HTH > > -- > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > From tayfun92_kayhan at yahoo.com Wed Sep 28 17:53:59 2011 From: tayfun92_kayhan at yahoo.com (Tayfun Kayhan) Date: Wed, 28 Sep 2011 14:53:59 -0700 (PDT) Subject: A Trivial Question Message-ID: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> I accidentally wrote such a code (below) while trying to write sth else for my application but i am now just wondering much how to run the class Foo, if it is possible. Is not it weird that Python does not give any error when I run it ? Sorry for that it's pretty unimportant question according to the other questions being asked here :D def trial(): class Foo(object): def __init__(self): print("Hello, world!") trial() # not worked, as expected. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Sep 28 18:03:48 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 18:03:48 -0400 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: <4E832C5B.1080007@tim.thechases.com> References: <4E832C5B.1080007@tim.thechases.com> Message-ID: On 9/28/2011 10:16 AM, Tim Chase wrote: > When performing unittest tests, I have a number of methods of the form > > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) > > When I run my tests, I only get a tick for running one the one test > (test_foo), not the len(data) tests that were actually performed. Is > there a way for unittesting to report the number of passed-assertions > rather than the number of test-methods run? In my view, unittest, based on JUnit from Java, is both overkill and inadequate for simple function testing of multiple input-output pairs. So I wrote my own short function test function that does just what I want, and which I can change if I change what I want. Ben has described the combinatorial explosion solution. But if I were using unittest, I might do something like the following: def test_foo(self): data = ( (item1, result1), ... #bunch of tests for fence-post errors ) errors = [] for input, expected in data: try: actual = process(input) if actual != expected: errors.append(input, expected, actual) except Exception as e: errors.append(input, expected, actual) self.assertEqual((0,[]), (len(errors),errors)) except that I would write a functest(func, iopairs) that returned the error pair. (This is essentially what I have done for for myself.) I am presuming that one can run unittest so that it prints the unequal items. -- Terry Jan Reedy From clp2 at rebertia.com Wed Sep 28 18:06:14 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 28 Sep 2011 15:06:14 -0700 Subject: A Trivial Question In-Reply-To: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: On Wed, Sep 28, 2011 at 2:53 PM, Tayfun Kayhan wrote: > I accidentally wrote such a code (below) while trying to write sth else for > my application but i am now just wondering much how to run the class Foo, if > it is possible. Is not it weird that Python does not give any error when I > run it ? Sorry for that it's pretty unimportant question according to the > other questions being asked here :D > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. Right now, you've merely defined a class in the local scope of a function, which is perfectly valid, although you don't take advantage of this, so there's no particular reason to put the class definition inside trial(). Foo.__init__() only gets called when you create an instance of Foo, which you aren't doing currently, hence why "Hello, world!" isn't printed. Try this: def trial(): class Foo(object): def __init__(self): print("Hello, world!") Foo() trial() Or this: class Foo(object): def __init__(self): print("Hello, world!") def trial(): Foo() trial() Cheers, Chris -- http://rebertia.com From nad at acm.org Wed Sep 28 18:21:25 2011 From: nad at acm.org (Ned Deily) Date: Wed, 28 Sep 2011 15:21:25 -0700 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e82a1a1$0$29965$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > On Tue, 27 Sep 2011 14:32:43 -0700, Wanderer wrote: > > I need to stay in sink with the rest of the company which is still using > > 2.6 flavors. There was some investigation into going to Python 3 but not > > enough of the libraries we use were available. I'll install 2.6.6. I > > don't think the security stuff really effects me. I think it is strange > > to release a security update but not really expect people to use it. > > > More likely the person who builds the Windows installers just hasn't made > a new release yet. > > The Python development team is relatively small and chronically busy: too > much to do and not enough time to do it. As I understand it, most of them > use Linux, so I'm afraid that Windows sometimes takes a back seat. (At > least it's not Mac OS, which is stuck riding in the boot of the car, or > the other semi-supported OSes, which are on a skateboard desperately > hanging onto the bumper trying not to be left behind.) No, it was a deliberate decision. After a release is in security-fix mode only, we don't build Windows or Mac OS X installers for them. The emphasis is on the actively maintained release branches, currently 3.2.x and 2.7.x. If third-party distributors want to support their users with binary installers, that is of course their option. "Python 2.6.7 is a security-fix only source release for Python 2.6.6, fixing several reported security issues. Python 2.6.7 was released on June 3, 2011. Python 2.6 is now in security-fix-only mode; no new features are being added, and no new bug fix releases are planned. We intend to provide source-only security fixes for the Python 2.6 series until October 2013 (five years after the 2.6 final release). For ongoing maintenance releases, please see the Python 2.7 series." http://www.python.org/getit/releases/2.6.7/ (And I think you may be just slightly mischaracterizing the status of both Mac OS X and Windows support.) -- Ned Deily, nad at acm.org From gagsl-py2 at yahoo.com.ar Wed Sep 28 18:30:01 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Sep 2011 19:30:01 -0300 Subject: syntactic sugar for def? References: <4E8390F1.9060207@stoneleaf.us> Message-ID: En Wed, 28 Sep 2011 18:51:00 -0300, Chris Kaynor escribi?: > On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle > wrote: >> On 28 September 2011 22:26, Ethan Furman wrote: >>> I remember that 'class' is sugar for type(....). >>> >>> I don't remember if 'def' is sugar for something besides lambda. >>> >>> Any clues for me? Heck, I'll even be grateful for outright answers! >> >> It's not really sugar. But I think you mean something like this: >> >> >>>>> class A: pass >> ... >>>>> type(A) >> >>>>> type is type(A) >> True >> >> So the closest you get for functions will be: >> >>>>> def f(): pass >> ... >>>>> type(f) >> >> >> Try help(type(f)) to see how to use it to create a function object. >> The problem is that you need to provide a code object, and the easiest >> way to create a code object is to use a def statement :) > > I would say compile isn't too much harder to use: >>>> c = compile('a = 123', 'test', 'exec') >>>> d = {} >>>> f = types.FunctionType(c, d, 'test') >>>> f() >>>> print d > {'a': 123} > > Although it appears you get all of the variables defined as global > apparently (try "f = types.FunctionType(c, globals(), 'test')" > instead). I know no way of compiling a function body alone. Suppose you have this function: def foo(x): print x y = 2*x return y py> compile(" print x\n y = 2*x\n return y", "", "exec") Traceback (most recent call last): File "", line 1, in File "", line 1 print x ^ IndentationError: unexpected indent py> compile("print x\ny = 2*x\nreturn y", "", "exec") Traceback (most recent call last): File "", line 1, in File "", line 3 SyntaxError: 'return' outside function If you include the 'def' statement in the source string, the resulting code object does not represent the function itself, but a "module" defining it: py> f = FunctionType(compile("def foo(x):\n print x\n y = 2*x\n return y\n", ... "", "exec"), globals(), "foo") py> f(3) Traceback (most recent call last): File "", line 1, in TypeError: () takes no arguments (1 given) py> dis.dis(f) 1 0 LOAD_CONST 0 (", line 1>) 3 MAKE_FUNCTION 0 6 STORE_NAME 0 (foo) 9 LOAD_CONST 1 (None) 12 RETURN_VALUE To get at the actual function code, one should use f.func_code.co_consts[0]; this would be the 'code' parameter for types.FunctionType. Very complicated, really; nothing can beat the 'def' statement for defining a function ;) -- Gabriel Genellina From ericsnowcurrently at gmail.com Wed Sep 28 18:38:26 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 28 Sep 2011 16:38:26 -0600 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman wrote: > I remember that 'class' is sugar for type(....). > > I don't remember if 'def' is sugar for something besides lambda. This is something I have thought about a lot since PyCon this year. I apologize in advance. Since 3.0, class statements are syntactic sugar for some extra steps beyond "meta(...)" [1]. In CPython this is facilitated through the "hidden" __build_class__() builtin[2]. We have the __import__() builtin for customizing module creation. But, as you asked, what about functions? Currently there isn't a way to customize function creation. There is no __build_function__() builtin. The best you can do is, like others have said, directly call FunctionType(...) or type(f)(...) where f is an existing function. I expect that if there were a __build_function__, it would wrap the code that is currently run for the MAKE_FUNCTION/MAKE_CLOSURE opcodes[3]. Also, both modules and classes have mechanisms built-in to allow for customization in certain parts of the creation process (PEP 302[4] and metaclasses[5], respectively). Functions lack this as well, though there hasn't been a big clamor for it. :) Nick Coghlan proposed an interesting idea for this in March[6], with some later follow-up[7]. Nothing much came of it though. Definitely an interesting topic, which has led me to learn a lot about Python and CPython. -eric [1] http://www.python.org/dev/peps/pep-3115/ http://mail.python.org/pipermail/python-3000/2007-March/006338.html [2] http://hg.python.org/cpython/file/default/Python/bltinmodule.c#l35 [3] http://hg.python.org/cpython/file/default/Python/ceval.c#l2680 [4] http://www.python.org/dev/peps/pep-0302/ http://docs.python.org/release/2.3.5/whatsnew/section-pep302.html http://docs.python.org/dev/reference/simple_stmts.html#the-import-statement [5] http://docs.python.org/dev/reference/datamodel.html#customizing-class-creation http://www.python.org/doc/essays/metaclasses/ [6] http://mail.python.org/pipermail/python-ideas/2011-March/009391.html [7] http://mail.python.org/pipermail/python-ideas/2011-March/009625.html http://mail.python.org/pipermail/python-ideas/2011-April/009765.html > > Any clues for me? ?Heck, I'll even be grateful for outright answers! > > ~Ethan~ > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed Sep 28 19:01:11 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 28 Sep 2011 19:01:11 -0400 Subject: syntactic sugar for def? In-Reply-To: <4E8390F1.9060207@stoneleaf.us> References: <4E8390F1.9060207@stoneleaf.us> Message-ID: On 9/28/2011 5:26 PM, Ethan Furman wrote: > I don't remember if 'def' is sugar for something besides lambda. That is a bit backwards. lambda x: expr(x) is syntactic sugar for def (x): return expr(x) del ;-) -- Terry Jan Reedy From greg.ewing at canterbury.ac.nz Wed Sep 28 19:01:27 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 29 Sep 2011 12:01:27 +1300 Subject: Wrote a new library - Comments and suggestions please! In-Reply-To: <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> References: <2fdf5f8c-58f1-4708-8856-a52c7233f3e6@v9g2000vbp.googlegroups.com> <13649656.542.1317133453243.JavaMail.geo-discussion-forums@yqnk41> <4e8208da$0$29994$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ehnaaF35hU1@mid.individual.net> Steven D'Aprano wrote: > I googled on "SAS PROC FREQ" and found this: > > http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm > > Documentation like that really makes me appreciate the sterling work done on > Python's docs. I think you have to read it in context. A couple of levels up there is a section called "The FREQ Procedure" which seems to explain more about what's going on, including examples. (I didn't look too closely at it, though, in case my eyes started to bleed...) -- Greg From tim at akwebsoft.com Wed Sep 28 19:26:51 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 28 Sep 2011 15:26:51 -0800 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <20110928232651.GT19422@johnsons-web.com> * DevPlayer [110928 04:31]: > On Sep 27, 10:25?pm, alex23 wrote: > > rantingrick wrote: > > > Since, like the bible > > > the zen is self contradicting, any argument utilizing the zen can be > > > defeated utilizing the zen. > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > taking it too seriously, that's your problem. > > > > > If however you want to learn about the accepted rules for formatting > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > Contradiction is only seen by narrow perspectve. > > Calling the Bible a joke is used to hurt people, not enlighten them. > Those words show bitter arrogance, not constructive critism as it > ignores how others feel about that book. What benefit to others is > gained by calling someones belief a joke? My wife and I are devout christians, but not fundamentalist. We would not take rantingrick too seriously. If _you_ take him seriously, you're just giving him 'street cred'. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From nobody at nowhere.com Wed Sep 28 20:10:38 2011 From: nobody at nowhere.com (Nobody) Date: Thu, 29 Sep 2011 01:10:38 +0100 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > No, it was a deliberate decision. After a release is in security-fix > mode only, we don't build Windows or Mac OS X installers for them. But you continue to offer the installers for the unfixed version. From steve+comp.lang.python at pearwood.info Wed Sep 28 20:16:30 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 10:16:30 +1000 Subject: Unittest testing assert*() calls rather than methods? References: Message-ID: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Tim Chase wrote: > While I asked this on the Django list as it happened to be with > some Django testing code, this might be a more generic Python > question so I'll ask here too. > > When performing unittest tests, I have a number of methods of the > form > > def test_foo(self): > data = ( > (item1, result1), > ... #bunch of tests for fence-post errors > ) > for test, result in data: > self.assertEqual(process(test), result) > > When I run my tests, I only get a tick for running one the one > test (test_foo), not the len(data) tests that were actually > performed. Is there a way for unittesting to report the number > of passed-assertions rather than the number of test-methods run? I used to ask the same question, but then I decided that if I wanted each data point to get its own tick, I should bite the bullet and write an individual test for each. If you really care, you could subclass unittest.TestCase, and then cause each assert* method to count how often it gets called. But really, how much detailed info about *passed* tests do you need? If you are writing loops inside tests, you might find this anecdote useful: http://mail.python.org/pipermail/python-list/2011-April/1270640.html -- Steven From cmpython at gmail.com Wed Sep 28 20:39:52 2011 From: cmpython at gmail.com (CM) Date: Wed, 28 Sep 2011 17:39:52 -0700 (PDT) Subject: options for plotting points on geographic map Message-ID: Recommendations sought for using Python to plot points/custom markers (and maybe other things?) on a map of an area of the U.S. of maybe 100 miles radius. (This would be a "political" map showing towns, such as from Google Maps or Mapquest, and not a "physical" map). I'll need to place markers or something based on zip codes. I see there is pymaps, a Python wrapper for Google Maps. I may try that but it seems to be barely documented and would require making a webpage with javascript to display the map, whereas I'd probably prefer a desktop app for this--though I'd consider a web page (it's probably easier than I think). I already use Matplotlib, but its Basemap seems to be only for physical geography needs. Are there other options one might recommend? (It is a little hard to Google for this given the map() function). Thanks, Che From zzzzysilence at gmail.com Wed Sep 28 20:42:09 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Wed, 28 Sep 2011 17:42:09 -0700 (PDT) Subject: red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/ Message-ID: <8edb383c-c6c7-4bc4-8b54-13c94a5c6493@18g2000yqz.googlegroups.com> Welcome to the www. currenthats.com,. The currenthats.com is a promotional shop from monster energy hats. It was authorized to provide red bull hats?snapback hats?hello kitty hats and the fashionable sports items to meet red bull hats Fans shopping needs. From zzzzysilence at gmail.com Wed Sep 28 20:46:10 2011 From: zzzzysilence at gmail.com (Bertha Jonanna) Date: Wed, 28 Sep 2011 17:46:10 -0700 (PDT) Subject: red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/ Message-ID: Welcome to the www. currenthats.com,. The currenthats.com is a promotional shop from monster energy hats. It was authorized to provide red bull hats?snapback hats?hello kitty hats and the fashionable sports items to meet red bull hats Fans shopping needs. From roy at panix.com Wed Sep 28 20:49:24 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 20:49:24 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e83b8e0$0$29972$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > If you are writing loops inside tests, you might find this anecdote useful: > > http://mail.python.org/pipermail/python-list/2011-April/1270640.html On the other hand, the best test is one that gets written. I will often write tests that I know do not meet the usual standards of purity and wholesomeness. Here's a real-life example: for artist in artists: name = artist['name'] self.assertIsInstance(name, unicode) name = name.lower() # Due to fuzzy matching, it's not strictly guaranteed that the # following assertion is true, but it works in this case. self.assertTrue(name.startswith(term), (name, term)) Could I have written the test without the loop? Probably. Would it have been a better test? I guess, at some level, probably. And, of course, the idea of a "not strictly guaranteed" assertion is probably enough to make me lose my Unit Tester's Guild Secret Decoder Ring forever :-) But, the test was quick and easy to write, and provides value. I could have spent twice as long writing a better test, and it would have provided a little more value, but certainly not double. More importantly, had I spent the extra time writing the better test, I might have not had enough time to write all the other tests I wrote that day. Sometimes good enough is good enough. From jeanpierreda at gmail.com Wed Sep 28 20:50:03 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 28 Sep 2011 20:50:03 -0400 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: > I used to ask the same question, but then I decided that if I wanted each > data point to get its own tick, I should bite the bullet and write an > individual test for each. Nearly the entire re module test suite is a list of tuples. If it was instead a bunch of TestCase classes, there'd be a lot more boilerplate to write. (At a bare minimum, there'd be two times as many lines, and all the extra lines would be identical...) Why is writing boilerplate for a new test a good thing? It discourages the authorship of tests. Make it as easy as possible by e.g. adding a new thing to whatever you're iterating over. This is, for example, why the nose test library has a decorator for generating a test suite from a generator. Devin On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano wrote: > Tim Chase wrote: > >> While I asked this on the Django list as it happened to be with >> some Django testing code, this might be a more generic Python >> question so I'll ask here too. >> >> When performing unittest tests, I have a number of methods of the >> form >> >> ? ?def test_foo(self): >> ? ? ?data = ( >> ? ? ? ?(item1, result1), >> ? ? ? ?... #bunch of tests for fence-post errors >> ? ? ? ?) >> ? ? ?for test, result in data: >> ? ? ? ?self.assertEqual(process(test), result) >> >> When I run my tests, I only get a tick for running one the one >> test (test_foo), not the len(data) tests that were actually >> performed. ?Is there a way for unittesting to report the number >> of passed-assertions rather than the number of test-methods run? > > I used to ask the same question, but then I decided that if I wanted each > data point to get its own tick, I should bite the bullet and write an > individual test for each. > > If you really care, you could subclass unittest.TestCase, and then cause > each assert* method to count how often it gets called. But really, how much > detailed info about *passed* tests do you need? > > If you are writing loops inside tests, you might find this anecdote useful: > > http://mail.python.org/pipermail/python-list/2011-April/1270640.html > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From roy at panix.com Wed Sep 28 20:52:31 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 20:52:31 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: In article <87k48szqo1.fsf at benfinney.id.au>, Ben Finney wrote: > Worse, if one of the scenarios causes the test to fail, the loop will > end and you won't get the results for the remaining scenarios. Which, depending on what you're doing, may or may not be important. In many cases, there's only two states of interest: 1) All tests pass 2) Anything else From steve+comp.lang.python at pearwood.info Wed Sep 28 21:14:04 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 11:14:04 +1000 Subject: [OT] Benefit and belief [was Re: Suggested coding style] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> DevPlayer wrote: > On Sep 27, 10:25?pm, alex23 wrote: >> And like the Bible, the Zen was created by humans as a joke. If you're >> taking it too seriously, that's your problem. [...] > Calling the Bible a joke is used to hurt people, not enlighten them. > Those words show bitter arrogance, not constructive critism as it > ignores how others feel about that book. What benefit to others is > gained by calling someones belief a joke? It is the same benefit as the little boy who pointed out that the Emperor was not wearing any clothes. (In real life, the story was called "The Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got Arrested and Thrown in Prison Together With His Parents for Insulting The Emperor".) > To put the "believers" minds > straight? I think not. I think the unsensitive person who attackes > others beliefs, even if illogical or unrealistic, is after some kind > of self grandizement or to illude themself into thinking "they know > the truth of the universe" and should attack others to prove they do. There is a difference between attacking ideas and attacking people. "The Bible is a joke" attacks the idea. "Insensitive people after self-aggrandisement deluding themselves" attacks the person. We live in a world where religion is privileged, where governments pander to the most sick and twisted, hateful, bigoted beliefs because of religion, where organised conspiracies to support and protect child molesters and sexual predators are nevertheless looked up to as sources of morality. There are some ideas that are simply incompatible with civilization, and the idea that religious beliefs should be beyond criticism is one of them. Forget money, or even the love of money. The idea that one mustn't criticise another person's beliefs is the root of all evil. -- Steven From jeanpierreda at gmail.com Wed Sep 28 21:40:27 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 28 Sep 2011 21:40:27 -0400 Subject: [OT] Benefit and belief [was Re: Suggested coding style] In-Reply-To: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: > Forget money, or even the love of money. The idea that one mustn't > criticise another person's beliefs is the root of all evil. This was a technical discussion, and calling the bible a joke was not necessary at all. It creates a hostile atmosphere. Can't you pick somewhere else to attack Christianity? Devin On Wed, Sep 28, 2011 at 9:14 PM, Steven D'Aprano wrote: > DevPlayer wrote: > >> On Sep 27, 10:25?pm, alex23 wrote: >>> And like the Bible, the Zen was created by humans as a joke. If you're >>> taking it too seriously, that's your problem. > [...] >> Calling the Bible a joke is used to hurt people, not enlighten them. >> Those words show bitter arrogance, not constructive critism as it >> ignores how others feel about that book. What benefit to others is >> gained by calling someones belief a joke? > > It is the same benefit as the little boy who pointed out that the Emperor > was not wearing any clothes. (In real life, the story was called "The > Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got > Arrested and Thrown in Prison Together With His Parents for Insulting The > Emperor".) > > >> To put the "believers" minds >> straight? I think not. I think the unsensitive person who attackes >> others beliefs, even if illogical or unrealistic, is after some kind >> of self grandizement or to illude themself into thinking "they know >> the truth of the universe" and should attack others to prove they do. > > There is a difference between attacking ideas and attacking people. > > "The Bible is a joke" attacks the idea. > > "Insensitive people after self-aggrandisement deluding themselves" attacks > the person. > > We live in a world where religion is privileged, where governments pander to > the most sick and twisted, hateful, bigoted beliefs because of religion, > where organised conspiracies to support and protect child molesters and > sexual predators are nevertheless looked up to as sources of morality. > > There are some ideas that are simply incompatible with civilization, and the > idea that religious beliefs should be beyond criticism is one of them. > Forget money, or even the love of money. The idea that one mustn't > criticise another person's beliefs is the root of all evil. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Sep 28 21:49:25 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 28 Sep 2011 22:49:25 -0300 Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: En Wed, 28 Sep 2011 21:10:38 -0300, Nobody escribi?: > On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > >> No, it was a deliberate decision. After a release is in security-fix >> mode only, we don't build Windows or Mac OS X installers for them. > > But you continue to offer the installers for the unfixed version. As well as all the previous ones back to Python 1.x I can think of several alternatives: * Upgrade to Python 2.7, the current stable and maintained release. * Compile Python 2.6.7 yourself. For the 32 bits version, you may use Microsoft Visual C++ 2008 Express Edition (free/gratis); see PCbuild\readme.txt for details. Obtain the required dependencies using Tools\buildbot\external.bat. It compiles cleanly out of the box. * Obtain the compiled binary somewhere else. Considering that 2.6.7 is just a security patch, I'm not sure if running a precompiled binary from untrusted sources is any better than sticking with the official, previous version. I've built the binaries, in case you're interested. * Compare both source trees and look at their differences. Most of them are in Python modules that you can just drop over an existing 2.6.6 install. Only two C modules have changed, and require rebuilding python26.dll: timemodule.c r87648: Issue #8013: Fixed time.asctime segfault when OS's asctime fails unicodedata.c http://bugs.python.org/issue10254 If you think you're not affected by these, just ignore 2.6.7 (or apply only the .py changes) -- Gabriel Genellina From rantingrick at gmail.com Wed Sep 28 21:59:49 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 28 Sep 2011 18:59:49 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <42df7e77-44ab-405e-9c60-8f394e3e5628@d17g2000yqa.googlegroups.com> On Sep 27, 11:25?pm, Steven D'Aprano wrote: > The Python development team is relatively small and chronically busy: too > much to do and not enough time to do it. If that is the case then why do they snub their noses at anyone who wishes to help? What kind of people would chase off good help just to save ego? I imagine the folks at py dev sort of like a dying man in need of a heart transplant; the man informs the doctor that he would happy to get a transplant but not if the heart came from a jew, asian, african, latin, russian, or canuck. From ericsnowcurrently at gmail.com Wed Sep 28 22:01:14 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Wed, 28 Sep 2011 20:01:14 -0600 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 28, 2011 at 6:50 PM, Devin Jeanpierre wrote: >> I used to ask the same question, but then I decided that if I wanted each >> data point to get its own tick, I should bite the bullet and write an >> individual test for each. > > Nearly the entire re module test suite is a list of tuples. If it was > instead a bunch of TestCase classes, there'd be a lot more boilerplate > to write. (At a bare minimum, there'd be two times as many lines, and > all the extra lines would be identical...) > > Why is writing boilerplate for a new test a good thing? It discourages > the authorship of tests. Make it as easy as possible by e.g. adding a > new thing to whatever you're iterating over. This is, for example, why > the nose test library has a decorator for generating a test suite from > a generator. +1 > > Devin > > On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano > wrote: >> Tim Chase wrote: >> >>> While I asked this on the Django list as it happened to be with >>> some Django testing code, this might be a more generic Python >>> question so I'll ask here too. >>> >>> When performing unittest tests, I have a number of methods of the >>> form >>> >>> ? ?def test_foo(self): >>> ? ? ?data = ( >>> ? ? ? ?(item1, result1), >>> ? ? ? ?... #bunch of tests for fence-post errors >>> ? ? ? ?) >>> ? ? ?for test, result in data: >>> ? ? ? ?self.assertEqual(process(test), result) >>> >>> When I run my tests, I only get a tick for running one the one >>> test (test_foo), not the len(data) tests that were actually >>> performed. ?Is there a way for unittesting to report the number >>> of passed-assertions rather than the number of test-methods run? >> >> I used to ask the same question, but then I decided that if I wanted each >> data point to get its own tick, I should bite the bullet and write an >> individual test for each. >> >> If you really care, you could subclass unittest.TestCase, and then cause >> each assert* method to count how often it gets called. But really, how much >> detailed info about *passed* tests do you need? >> >> If you are writing loops inside tests, you might find this anecdote useful: >> >> http://mail.python.org/pipermail/python-list/2011-April/1270640.html >> >> >> >> -- >> Steven >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > -- > http://mail.python.org/mailman/listinfo/python-list > From rantingrick at gmail.com Wed Sep 28 22:11:08 2011 From: rantingrick at gmail.com (rantingrick) Date: Wed, 28 Sep 2011 19:11:08 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: On Sep 28, 6:26?pm, Tim Johnson wrote: > * DevPlayer [110928 04:31]: > > On Sep 27, 10:25 pm, alex23 wrote: > > > rantingrick wrote: > > > > Since, like the bible > > > > the zen is self contradicting, any argument utilizing the zen can be > > > > defeated utilizing the zen. > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > > taking it too seriously, that's your problem. > > > > > If however you want to learn about the accepted rules for formatting > > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > Contradiction is only seen by narrow perspectve. > > > Calling the Bible a joke is used to hurt people, not enlighten them. > > Those words show bitter arrogance, not constructive critism as it > > ignores how others feel about that book. What benefit to others is > > gained by calling someones belief a joke? > > ?My wife and I are devout christians, but not fundamentalist. We > ?would not take rantingrick too seriously. If _you_ take him > ?seriously, you're just giving him 'street cred'. DevPlayer was not even talking about what i said, he was replying to a statement by Alex23 who said (and i quote) "And like the Bible, the Zen was created by humans as a joke". Maybe you should spend the next fifteen or so minutes catching up to the conversation...(?_?)...of course only *after* you clean that egg from your face. From devplayer at gmail.com Wed Sep 28 22:15:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Wed, 28 Sep 2011 19:15:24 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <088ba6ac-4468-4755-9336-f1ddf1ab2121@k15g2000yqd.googlegroups.com> Oh I was just testing my intellecual-enlightenment-from-ranter- conversation algorithm found in a previous post. I think my OOP model failed as I'm just too tired to finished that pattern test. He had some good points which fit the process I layed out. But the original topic is just so much better: Suggested coding style Options From ben+python at benfinney.id.au Wed Sep 28 22:25:41 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 12:25:41 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <4e83b8e0$0$29972$c3e8da3$5496439d@news.astraweb.com> Message-ID: <878vp83x0a.fsf@benfinney.id.au> Steven D'Aprano writes: > I used to ask the same question, but then I decided that if I wanted > each data point to get its own tick, I should bite the bullet and > write an individual test for each. Hence my advocating the ?testscenarios? library. Have you tried that? It allows the best of both worlds: within the class, you write a collection of data scenarios, and write one test case for each separate behaviour, and that's all that appears in the code; but the test run shows every test case for every scenario. E.g. with a ParrotTestCase class having three test cases and four scenarios, the test run will run the full combination of all of them and report twelve distinct test cases and the result for each. So the ?bite the bullet? you describe isn't necessary to get what you want. > If you really care, you could subclass unittest.TestCase, and then > cause each assert* method to count how often it gets called. But > really, how much detailed info about *passed* tests do you need? The ?testscenarios? library does subclass the standard library ?unittest? module. But as explained elsewhere, it's not the counting which is the issue. The issue is to ensure (and report) that every test case is actually tested in isolation against every relevant scenario. -- \ ?Human reason is snatching everything to itself, leaving | `\ nothing for faith.? ?Bernard of Clairvaux, 1090?1153 | _o__) | Ben Finney From ben+python at benfinney.id.au Wed Sep 28 22:27:27 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 12:27:27 +1000 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <874nzw3wxc.fsf@benfinney.id.au> Roy Smith writes: > In article <87k48szqo1.fsf at benfinney.id.au>, > Ben Finney wrote: > > > Worse, if one of the scenarios causes the test to fail, the loop will > > end and you won't get the results for the remaining scenarios. > > Which, depending on what you're doing, may or may not be important. In > many cases, there's only two states of interest: > > 1) All tests pass > > 2) Anything else For the purpose of debugging, it's always useful to more specifically narrow down the factors leading to failure. -- \ ?A lie can be told in a few words. Debunking that lie can take | `\ pages. That is why my book? is five hundred pages long.? ?Chris | _o__) Rodda, 2011-05-05 | Ben Finney From wuwei23 at gmail.com Wed Sep 28 22:41:51 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 28 Sep 2011 19:41:51 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <22c6d97a-a0f3-43e8-ac23-16787db5da1d@g33g2000yqc.googlegroups.com> On Sep 28, 10:12?pm, DevPlayer wrote: > Calling the Bible a joke is used to hurt people, not enlighten them. Y'know, I wouldn't even bother responding to this if Xianists were as open, forgiving and accepting as their messiah told them to be. It was a *flippant remark*. If you want to establish intent, aggression and religio-politico-philosophy from every throwaway remark made on the internet, you're not really going to have much time for Python. My belief system isn't your's. Hell, my belief system doesn't even require that I have *any respect whatsoever* for your's. If it's okay for Xianists to "suffer not a witch to live", then I'm going to assert my making light jokes about those whose world view is in direct opposition to mine isn't even comparable to that mentality. from attitude import humour (Since we're already fully derailed here, I've always preferred Borges' suggestion that it was actually Judas who carried the full weight of man's sins, given that his betrayal of Christ and inevitable condemnation to hell was a necessity. Then again, I'm able to safely view this as *allegory* and am genuinely interested in the opinions of modern minds over something first begun by nomads millenia ago...) From roy at panix.com Wed Sep 28 22:49:58 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 22:49:58 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> <874nzw3wxc.fsf@benfinney.id.au> Message-ID: In article <874nzw3wxc.fsf at benfinney.id.au>, Ben Finney wrote: > Roy Smith writes: > > > In article <87k48szqo1.fsf at benfinney.id.au>, > > Ben Finney wrote: > > > > > Worse, if one of the scenarios causes the test to fail, the loop will > > > end and you won't get the results for the remaining scenarios. > > > > Which, depending on what you're doing, may or may not be important. In > > many cases, there's only two states of interest: > > > > 1) All tests pass > > > > 2) Anything else > > For the purpose of debugging, it's always useful to more specifically > narrow down the factors leading to failure. Well, sure, but "need to debug" is just a consequence of being in state 2. If a test fails and I can't figure out why, I can always go back and add additional code to the test case to extract additional information. From ben+python at benfinney.id.au Wed Sep 28 23:05:36 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 13:05:36 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87zkho2glb.fsf@benfinney.id.au> Devin Jeanpierre writes: > > Forget money, or even the love of money. The idea that one mustn't > > criticise another person's beliefs is the root of all evil. > > This was a technical discussion, and calling the bible a joke was not > necessary at all. It creates a hostile atmosphere. I disagree. It was not an attack on any person nor group of people. If we are to be required to avoid jokes not directed at people, then *that* is an atmosphere hostile to open friendly discussion. > Can't you pick somewhere else to attack Christianity? The person who wrote the ?bible is a joke? intended it as a flippant remark. Countless other flippant remarks pass through here all the time, making jokes at the expense of some idea or other. Christianity will not be an exception to that. If you find someone attacking people, I'll join you in ostracising the attacker. But no, don't attempt to silence jokes that attack an idea. Off-topic? If we start discussing the content of the ideas being attacked, yeah, I'd say religion is pretty off-topic. But the topic of keeping this forum safe for technical discussion entails that it must be safe for *any* idea to be the butt of a joke, be it a religious text or the Zen of Python, and that is very much on-topic. -- \ ?We demand rigidly defined areas of doubt and uncertainty!? | `\ ?Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | _o__) Adams | Ben Finney From python.list at tim.thechases.com Wed Sep 28 23:13:57 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Sep 2011 22:13:57 -0500 Subject: Unittest testing assert*() calls rather than methods? In-Reply-To: References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: <4E83E275.6060209@tim.thechases.com> On 09/28/11 19:52, Roy Smith wrote: > In many cases, there's only two states of interest: > > 1) All tests pass > > 2) Anything else Whether for better or worse, at some places (such as a previous employer) the number (and accretion) of test-points is a marketing bullet-point for upgrades & new releases. -tkc From roy at panix.com Wed Sep 28 23:20:27 2011 From: roy at panix.com (Roy Smith) Date: Wed, 28 Sep 2011 23:20:27 -0400 Subject: Unittest testing assert*() calls rather than methods? References: <87k48szqo1.fsf@benfinney.id.au> Message-ID: In article , Tim Chase wrote: > On 09/28/11 19:52, Roy Smith wrote: > > In many cases, there's only two states of interest: > > > > 1) All tests pass > > > > 2) Anything else > > Whether for better or worse, at some places (such as a previous > employer) the number (and accretion) of test-points is a > marketing bullet-point for upgrades & new releases. Never attribute to malice that which is adequately explained by the stupidity of the marketing department. From rosuav at gmail.com Thu Sep 29 00:27:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 29 Sep 2011 14:27:31 +1000 Subject: A Trivial Question In-Reply-To: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: On Thu, Sep 29, 2011 at 7:53 AM, Tayfun Kayhan wrote: > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. Python doesn't have "class declarations" in the way that some other languages do. The 'class' statement is an executable statement - it builds a class object and binds it to the name Foo, just like any other assignment. The 'def' command builds a function object in a similar fashion. So in your trial() function, you're defining a class and binding it to the local name Foo; and then doing nothing with it. It's perfectly legal, and as Chris Rebert suggests, you can make it useful by instantiating Foo() objects inside trial(). ChrisA From gaurav.gangalwar at gmail.com Thu Sep 29 01:17:46 2011 From: gaurav.gangalwar at gmail.com (gaurav gangalwar) Date: Thu, 29 Sep 2011 10:47:46 +0530 Subject: UnicodeDecodeError Message-ID: I am getting this error while some testing on Python2.6, File "/usr/lib64/python2.6/httplib.py", line 774, in _send_output #msg = "\r\n".join(self._buffer) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 14: ordinal not in range(128) I tried the change suggested on this link http://web.archiveorange.com/archive/v/PJbOg9pxJoUpQA9AHp3X, its working fine after that. There seems to be some problem in httplib with unicode handling. I am running it on centos5. I am still not sure why its happening and what will be ideal solution for this? Thanks, Gaurav -------------- next part -------------- An HTML attachment was scrubbed... URL: From namenobodywants at gmail.com Thu Sep 29 01:47:49 2011 From: namenobodywants at gmail.com (Sean McIlroy) Date: Wed, 28 Sep 2011 22:47:49 -0700 (PDT) Subject: change text of a Tkinter Button by clicking it Message-ID: hello (how) can you change the text of a Tkinter Button by clicking it? something like def click(index): return lambda: buttons[index].text = 'hello' buttons = [Button(root,command=click(index)) for index in range(numbuttons)] only with an attribute that Buttons actually have. sorry to have to ask such a see-spot-run question. thanks if you can help. peace stm From namenobodywants at gmail.com Thu Sep 29 02:15:20 2011 From: namenobodywants at gmail.com (Sean McIlroy) Date: Wed, 28 Sep 2011 23:15:20 -0700 (PDT) Subject: change text of a Tkinter Button by clicking it References: Message-ID: never mind. i found it. From questions.anon at gmail.com Thu Sep 29 02:16:13 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 29 Sep 2011 16:16:13 +1000 Subject: memory error In-Reply-To: References: Message-ID: Hello All, I am still having trouble with memory errors when I try to process many netcdf files. Originally I would get the memory error as mentioned in the previous post but when I added gc.collect() after each for loop I receive the error: GEOS_ERROR: bad allocation with no additional information! The error use to occur at the point when a new netcdf file was to be opened and plotted but with the things I have 'fixed' thanks to suggestions from this list it seems to happen while processing the second file. I am just trying to plot 3hourly data for each file and each file contains hourly data for a month and I am trying to do this for many months. It seems like I cannot close down the last file properly so the computer has a clean memory to start the next one. Any feedback will be greatly appreciated. My latest version of the code: ###################### from netCDF4 import Dataset import numpy as N import matplotlib.pyplot as plt from numpy import ma as MA from mpl_toolkits.basemap import Basemap from netcdftime import utime from datetime import datetime import os shapefile1="E:/DSE_BushfireClimatologyProject/griddeddatasamples/test_GIS/DSE_REGIONS" OutputFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/OutputsforValidation" def plotrawdata(variable): if variable=='TSFC': ncvariablename='T_SFC' MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/" ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] Title='Surface Temperature' cmap=plt.cm.jet elif variable=='RHSFC': ncvariablename='RH_SFC' MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/RH_SFC/" ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Title='Surface RH' cmap=plt.cm.jet_r fileforlatlon=Dataset("E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/TSFC_1974_01/IDZ00026_VIC_ADFD_T_SFC.nc", 'r+', 'NETCDF4') LAT=fileforlatlon.variables['latitude'][:] LON=fileforlatlon.variables['longitude'][:] startperiod=raw_input("Start slice (e.g. 1 ): ") endperiod=raw_input("End slice (e.g. 2): ") skipperiod=raw_input("skip slice (e.g. 1): ") if startperiod == "": startperiod = None else: startperiod = int(startperiod) if endperiod == "": endperiod = None else: endperiod = int(endperiod) if skipperiod == "": skipperiod = None else: skipperiod= int(skipperiod) for (path, dirs, files) in os.walk(MainFolder): for dir in dirs: print dir path=path+'/' for ncfile in files: if ncfile[-3:]=='.nc': print "dealing with ncfiles:", path+ncfile ncfile=os.path.join(path,ncfile) ncfile=Dataset(ncfile, 'r+', 'NETCDF4') #global TSFC variable=ncfile.variables[ncvariablename][startperiod:endperiod:skipperiod] TIME=ncfile.variables['time'][startperiod:endperiod:skipperiod] fillvalue=ncfile.variables[ncvariablename]._FillValue ncfile.close() for variable, TIME in zip((variable[:]),(TIME[:])): #for variable, TIME in zip((variable[sliceperiod]),(TIME[sliceperiod])): cdftime=utime('seconds since 1970-01-01 00:00:00') ncfiletime=cdftime.num2date(TIME) print ncfiletime timestr=str(ncfiletime) d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') date_string = d.strftime('%Y%m%d_%H%M') #Set up basemap using mercator projection http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') x,y=map(*N.meshgrid(LON,LAT)) map.drawcoastlines(linewidth=0.5) map.readshapefile(shapefile1, 'DSE_REGIONS') map.drawstates() plt.title(Title+' %s UTC'%ncfiletime) CS = map.contourf(x,y,variable, ticks, cmap=cmap) l,b,w,h =0.1,0.1,0.8,0.8 cax = plt.axes([l+w+0.025, b, 0.025, h], ) cbar=plt.colorbar(CS, cax=cax, drawedges=True) #save map as *.png and plot netcdf file plt.savefig((os.path.join(OutputFolder, ncvariablename+date_string+'UTC.png'))) #plt.show() plt.close() ###################### On Wed, Sep 14, 2011 at 4:08 PM, questions anon wrote: > Hello All, > I keep coming across a memory error when processing many netcdf files. I > assume it has something to do with how I loop things and maybe need to close > things off properly. > In the code below I am looping through a bunch of netcdf files (each file > is hourly data for one month) and within each netcdf file I am outputting a > *png file every three hours. > This works for one netcdf file but when it begins to process the next > netcdf file I receive this memory error: > > *Traceback (most recent call last): > File > "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", > line 44, in > TSFC=ncfile.variables['T_SFC'][:] > File "netCDF4.pyx", line 2473, in netCDF4.Variable.__getitem__ > (netCDF4.c:23094) > MemoryError* > > To reduce processing requirements I have tried making the LAT and LON to > only use [0] but I also receive an error: > > *Traceback (most recent call last): > File > "d:/plot_netcdf_merc_multiplot_across_multifolders_mkdirs_memoryerror.py", > line 75, in > x,y=map(*N.meshgrid(LON,LAT)) > File "C:\Python27\lib\site-packages\numpy\lib\function_base.py", line > 3256, in meshgrid > numRows, numCols = len(y), len(x) # yes, reversed > TypeError: len() of unsized object* > > finally I have added gc.collect() in a couple of places but that doesn't > seem to do anything to help. > I am using :*Python 2.7.2 |EPD 7.1-2 (32-bit)| (default, Jul 3 2011, > 15:13:59) [MSC v.1500 32 bit (Intel)] on win32* > Any feedback will be greatly appreciated! > > > from netCDF4 import Dataset > import numpy > import numpy as N > import matplotlib.pyplot as plt > from numpy import ma as MA > from mpl_toolkits.basemap import Basemap > from netcdftime import utime > from datetime import datetime > import os > import gc > > print "start processing...." > > inputpath=r'E:/GriddedData/Input/' > outputpath=r'E:/GriddedData/Validation/' > shapefile1="E:/test_GIS/DSE_REGIONS" > for (path, dirs, files) in os.walk(inputpath): > for dir in dirs: > print dir > sourcepath=os.path.join(path,dir) > relativepath=os.path.relpath(sourcepath,inputpath) > newdir=os.path.join(outputpath,relativepath) > if not os.path.exists(newdir): > os.makedirs(newdir) > > for ncfile in files: > if ncfile[-3:]=='.nc': > print "dealing with ncfiles:", ncfile > ncfile=os.path.join(sourcepath,ncfile) > #print ncfile > ncfile=Dataset(ncfile, 'r+', 'NETCDF4') > TSFC=ncfile.variables['T_SFC'][:,:,:] > TIME=ncfile.variables['time'][:] > LAT=ncfile.variables['latitude'][:] > LON=ncfile.variables['longitude'][:] > fillvalue=ncfile.variables['T_SFC']._FillValue > TSFC=MA.masked_values(TSFC, fillvalue) > ncfile.close() > gc.collect() > print "garbage collected" > > > for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])): > print TSFC, TIME > #convert time from numbers to date and prepare it to have no > symbols for saving to filename > cdftime=utime('seconds since 1970-01-01 00:00:00') > ncfiletime=cdftime.num2date(TIME) > print ncfiletime > timestr=str(ncfiletime) > d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S') > date_string = d.strftime('%Y%m%d_%H%M') > > #Set up basemap using mercator projection > http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html > map = > Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33, > > llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i') > > # compute map projection coordinates for lat/lon grid. > x,y=map(*N.meshgrid(LON,LAT)) > map.drawcoastlines(linewidth=0.5) > map.readshapefile(shapefile1, 'DSE_REGIONS') > map.drawstates() > > plt.title('Surface temperature at %s UTC'%ncfiletime) > ticks=[-5,0,5,10,15,20,25,30,35,40,45,50] > CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet) > l,b,w,h =0.1,0.1,0.8,0.8 > cax = plt.axes([l+w+0.025, b, 0.025, h], ) > cbar=plt.colorbar(CS, cax=cax, drawedges=True) > > #save map as *.png and plot netcdf file > > plt.savefig((os.path.join(newdir,'TSFC'+date_string+'UTC.png'))) > plt.close() > gc.collect() > print "garbage collected again" > print "end of processing" > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Thu Sep 29 02:21:21 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 28 Sep 2011 23:21:21 -0700 Subject: syntactic sugar for def? In-Reply-To: References: <4E8390F1.9060207@stoneleaf.us> Message-ID: <20110929062121.GA10216@Smoke> On Wed, Sep 28, 2011 at 07:01:11PM -0400, Terry Reedy wrote: > On 9/28/2011 5:26 PM, Ethan Furman wrote: > > >I don't remember if 'def' is sugar for something besides lambda. > > That is a bit backwards. > lambda x: expr(x) > is syntactic sugar for > def (x): return expr(x) > del > ;-) > lambda is less sugar and more of just a def as an expression. From anikom15 at gmail.com Thu Sep 29 02:24:13 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 28 Sep 2011 23:24:13 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <20110929062413.GB10216@Smoke> On Wed, Sep 28, 2011 at 07:11:08PM -0700, rantingrick wrote: > On Sep 28, 6:26?pm, Tim Johnson wrote: > > * DevPlayer [110928 04:31]: > > > On Sep 27, 10:25 pm, alex23 wrote: > > > > rantingrick wrote: > > > > > Since, like the bible > > > > > the zen is self contradicting, any argument utilizing the zen can be > > > > > defeated utilizing the zen. > > > > > > And like the Bible, the Zen was created by humans as a joke. If you're > > > > taking it too seriously, that's your problem. > > > > > > > If however you want to learn about the accepted rules for formatting > > > > > code then you need to read "PEP-8"! PEP 8 is our style guide. > > > > > Contradiction is only seen by narrow perspectve. > > > > > Calling the Bible a joke is used to hurt people, not enlighten them. > > > Those words show bitter arrogance, not constructive critism as it > > > ignores how others feel about that book. What benefit to others is > > > gained by calling someones belief a joke? > > > > ?My wife and I are devout christians, but not fundamentalist. We > > ?would not take rantingrick too seriously. If _you_ take him > > ?seriously, you're just giving him 'street cred'. > > DevPlayer was not even talking about what i said, he was replying to a > statement by Alex23 who said (and i quote) "And like the Bible, the > Zen was created by humans as a joke". Maybe you should spend the next > fifteen or so minutes catching up to the conversation...(?_?)...of > course only *after* you clean that egg from your face Perhaps you should spend a little less time on the mailing list and a little more time in church. From __peter__ at web.de Thu Sep 29 02:27:00 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 Sep 2011 08:27 +0200 Subject: change text of a Tkinter Button by clicking it References: Message-ID: Sean McIlroy wrote: > hello > > (how) can you change the text of a Tkinter Button by clicking it? > something like > > def click(index): return lambda: buttons[index].text = 'hello' > buttons = [Button(root,command=click(index)) for index in > range(numbuttons)] > > only with an attribute that Buttons actually have. sorry to have to > ask such a see-spot-run question. thanks if you can help. See http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html You can set the text of a Button widget with button["text"] = ... or button.configure(text=...) From ian.g.kelly at gmail.com Thu Sep 29 02:57:21 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 00:57:21 -0600 Subject: Suggested coding style In-Reply-To: <20110929062413.GB10216@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <20110929062413.GB10216@Smoke> Message-ID: On Thu, Sep 29, 2011 at 12:24 AM, Westley Mart?nez wrote: > Perhaps you should spend a little less time on the mailing list and a > little more time in church. You must not like churchgoers very much if you want to inflict rantingrick on them... From ian.g.kelly at gmail.com Thu Sep 29 03:08:13 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 01:08:13 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <20110929062413.GB10216@Smoke> Message-ID: On Thu, Sep 29, 2011 at 12:57 AM, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 12:24 AM, Westley Mart?nez wrote: >> Perhaps you should spend a little less time on the mailing list and a >> little more time in church. > > You must not like churchgoers very much if you want to inflict > rantingrick on them... Although come to think of it, I bet he could deliver a pretty mean sermon. ;-) From jitu.icfai at gmail.com Thu Sep 29 03:41:29 2011 From: jitu.icfai at gmail.com (jitendra gupta) Date: Thu, 29 Sep 2011 13:11:29 +0530 Subject: A trivial question In-Reply-To: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> References: <1317246561.85326.YahooMailNeo@web120310.mail.ne1.yahoo.com> Message-ID: HI The class Foo you have defined is local NameSpace for trial functioon, for details http://docs.python.org/tutorial/classes.html def trial(): class Foo(object): def __init__(self): print("Hello, world!") lacalClass = Foo() >>>trial "Hello, world!" Thanks Jitendra On Thu, Sep 29, 2011 at 3:19 AM, Tayfun Kayhan wrote: > I accidentally wrote such a code (below) while trying to write sth else for > my application but i am now just wondering much how to run the class Foo, if > it is possible. Is not it weird that Python does not give any error when I > run it ? Sorry for that it's pretty unimportant question according to the > other questions being asked here :D > > def trial(): > class Foo(object): > def __init__(self): > print("Hello, world!") > trial() # not worked, as expected. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Thu Sep 29 05:21:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Sep 2011 09:21:16 GMT Subject: Python without a tty Message-ID: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> I have a Python script which I would like to test without a tty attached to the process. I could run it as a cron job, but is there an easier way? I am running Linux. -- Steven From redbullhats123 at gmail.com Thu Sep 29 05:36:29 2011 From: redbullhats123 at gmail.com (red bull hats red bull hats) Date: Thu, 29 Sep 2011 02:36:29 -0700 (PDT) Subject: red bull hats, monster energy hats, red bull t shirts, monster energy t shirts, snapback hats on www.theworldhats.com Message-ID: www.theworldhats.com are promoting the products: red bull hats:http://www.theworldhats.com/category-130-b0-Red-Bull- Hats.html snapback hats: http://www.theworldhats.com/category-230-b0-Snapback-Hats.html monster energy hats: http://www.theworldhats.com/category-128-b0-Monster-Energy-Hats.html red bull t shirts:http://www.theworldhats.com/category-227-b0-Red-Bull- T-shirts.html monster energy t shirts:http://www.theworldhats.com/category-203-b0- Monster-Energy-T-shirts.html website: www.theworldhats.com From t at jollybox.de Thu Sep 29 05:45:40 2011 From: t at jollybox.de (Thomas Jollans) Date: Thu, 29 Sep 2011 11:45:40 +0200 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E843E44.7040008@jollybox.de> On 29/09/11 11:21, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > ./program /dev/null 2>&1 From alain at dpt-info.u-strasbg.fr Thu Sep 29 05:53:12 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 29 Sep 2011 11:53:12 +0200 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Steven D'Aprano writes: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. Isn't os.setsid() what you're looking for? It makes the calling process have no controlling terminal. There's also a user command called setsid that should have the same effect. -- Alain. From passiday at gmail.com Thu Sep 29 06:37:39 2011 From: passiday at gmail.com (Passiday) Date: Thu, 29 Sep 2011 03:37:39 -0700 (PDT) Subject: Suggested coding style In-Reply-To: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> Message-ID: <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Oh, my. Who could expect this topic would iterate to some whining about religion (please don't respond on this remark of mine). Here's a summary of what I take from this longwinded thread: Read the Zen of Pthon for some fun: http://www.python.org/dev/peps/pep-0020 Read the PEP-8 for some good guidelines: http://www.python.org/dev/peps/pep-0008 My topic was "Suggested coding style" because I hoped there is some common understanding which of the ancient methods/functions are so not where they should be that the use of them should be depreciated. I can fully understand that when the language evolves, it might implement some ugly methods. Perhaps it was some quick itching need to format some numbers that drove some antique Python programmer so mad that he decided this belongs to the string class, instead of some number/date/string formatting class that attempts to build on existing well established standards. And so, the str.zfill() was born. But I'd expect that there exists some leadership who are brave enough to admit some bad decisions and lead the people by announcing that using certain methods is "bad style". No need to take them out of the implementation, that might unnecessary break some code in obscure places. However, guiding programmers for better coding practice and avoid ugly bloating of nice scripting language should be considered a holy (please don't rant on use of this word) mission. Passiday From steve+comp.lang.python at pearwood.info Thu Sep 29 06:37:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 20:37:53 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> Message-ID: <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > Perhaps you should spend a little less time on the mailing list and a > little more time in church. Is that meant as punishment for Rick or for the churchgoers? -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 29 06:52:22 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 29 Sep 2011 20:52:22 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Alain Ketterlin wrote: > Steven D'Aprano writes: > >> I have a Python script which I would like to test without a tty attached >> to the process. I could run it as a cron job, but is there an easier way? >> >> I am running Linux. > > Isn't os.setsid() what you're looking for? It makes the calling process > have no controlling terminal. There's also a user command called setsid > that should have the same effect. It doesn't appear so to me. [steve at sylar ~]$ tty /dev/pts/16 [steve at sylar ~]$ setsid tty /dev/pts/16 [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" True [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" True If I run the same Python command (without the setsid) as a cron job, I get False emailed to me. That's the effect I'm looking for. -- Steven From hansmu at xs4all.nl Thu Sep 29 07:39:25 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 29 Sep 2011 13:39:25 +0200 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8458ed$0$2486$e4fe514c@news2.news.xs4all.nl> On 29/09/11 11:21:16, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? There is module on Pypi called python-daemon; it implements PEP-3143. This module detaches the process from the tty and resets a number of process attributes that are normally inherited. You could start by reading the PEP to determine which of its features are relevant to your situation. It would provide you with a complete list of aspects you'd need to think about. If a third of what the module does is relevant to your situation and the other two thirds do not hurt, then using the module is likely to be less work than rolling your own. Hope this helps, -- HansM From alain at dpt-info.u-strasbg.fr Thu Sep 29 07:50:18 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 29 Sep 2011 13:50:18 +0200 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <877h4rwosl.fsf@dpt-info.u-strasbg.fr> Steven D'Aprano writes: > Alain Ketterlin wrote: >>> I have a Python script which I would like to test without a tty attached >>> to the process. I could run it as a cron job, but is there an easier way? >> Isn't os.setsid() what you're looking for?[...] > It doesn't appear so to me. [...] > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. If that's what you mean by "without a tty attached", simply redirecting standard channels should work, no? -- Alain. From hansmu at xs4all.nl Thu Sep 29 07:50:29 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 29 Sep 2011 13:50:29 +0200 Subject: Python without a tty In-Reply-To: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e845b85$0$2486$e4fe514c@news2.news.xs4all.nl> On 29/09/11 12:52:22, Steven D'Aprano wrote: > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. In that case, all you need to do is redirect stdout: $ python -c "import sys, os > print os.isatty(sys.stdout.fileno())" >/tmp/xxx $ cat /tmp/xxx False You'll probably want to redirect to /dev/null and maybe you want to redirect stdin and stderr as well. -- HansM From rantingrick at gmail.com Thu Sep 29 08:23:30 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 05:23:30 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 5:37?am, Passiday wrote: > Here's a summary of what I take from this longwinded thread: > Read the Zen of Pthon for some fun:http://www.python.org/dev/peps/pep-0020 > Read the PEP-8 for some good guidelines:http://www.python.org/dev/peps/pep-0008 That's the point of all this, yes. You see, around here, once the point is made there is an unwritten rule that the thread must then descend into chaos. However, it seems you "may" have brought this train wreck back to reality below... whether the trolls will allow that happen remains to be seen...? > My topic was "Suggested coding style" because I hoped > there is some common understanding which of the ancient > methods/functions are so not where they should be that the > use of them should be depreciated. I agree. Whilst zfill is useful, and probably should be a part of the stlib somewhere, the string module is no place for it. The only way zfill WOULD work as a string method is if it were changed to accept a user defined fill char. Even then i don't like it as a string method; too specific! A specific method for padding a string with ONLY zeros is ludicrous and exposes the narrow mindedness of the creator. The only thing worse than "zfill" as a string method is making zfill into built-in function! The ONLY proper place for zfill is as an option in the str.format() method. py> "{0:zf10}".format(1234) -> "00000000001234" When are they going to see that I am the best API designer this community has ever had the privilege to work with! GvR should be texting me every night in hopes that some of my API genius will rub off on him. > I can fully understand > that when the language evolves, it might implement some > ugly methods. Perhaps it was some quick itching need to > format some numbers that drove some antique Python > programmer so mad that he decided this belongs to the > string class, instead of some number/date/string > formatting class that attempts to build on existing well > established standards. And so, the str.zfill() was born. zfills foster home placement is akin to the missing Path object we still don't have. Both are a result of poor planning. Now zfill is like some red headed step child that nobody wants, but nobody has the balls to return the abortion to it's rightful place. > But I'd expect that there exists some leadership who are > brave enough to admit some bad decisions and lead the > people by announcing that using certain methods is "bad > style". Ha! I would not hold my breath waiting for "leadership" to admit wrong doings; these people think they are beyond reproach. > No need to take them out of the implementation, > that might unnecessary break some code in obscure places. What is so bad about breaking code in obscure places? We changed print to a function which broke just about every piece of code every written in this language. (BTW, print should ALWAYS have been a function!) What is so bad then about breaking some very obscure code? We could always have a lengthy deprecation period. > However, guiding programmers for better coding practice > and avoid ugly bloating of nice scripting language should > be considered a holy (please don't rant on use of this > word) mission. I agree. I think you'll agree also with me in the fact that Mr Van Rossum has created the cleanest, most simplistically elegant, and no nonsense language this world has ever seen. However. He is not immune to the wicked influence of a few high ranking people within this community who have "hidden agendas" and want to mutate Python into a clone of some other nasty languages. I believe GvR had a "mid-dev-crisis" and realized the err of his ways. He attempted to turn back the clock with Python 3000, HOWEVER he did not go far enough! Much more cleanup is in order to get this language back on track to what it should be, and COULD be! From ben+python at benfinney.id.au Thu Sep 29 08:32:37 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 29 Sep 2011 22:32:37 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87vcsb34wq.fsf@benfinney.id.au> Steven D'Aprano writes: > I have a Python script which I would like to test without a tty > attached to the process. I could run it as a cron job, but is there an > easier way? > > I am running Linux. You could crib from the ?python-daemon? library implementation . Part of its job involves detaching the current program from the terminal. Or maybe you could simply invoke the library for its main purpose, if that would be sufficient to do what you need. -- \ ?Sane people have an appropriate perspective on the relative | `\ importance of foodstuffs and human beings. Crazy people can't | _o__) tell the difference.? ?Paul Z. Myers, 2010-04-18 | Ben Finney From rantingrick at gmail.com Thu Sep 29 09:21:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 06:21:36 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <1c731ba2-7104-44bb-a5d4-5798ce56bfc8@z12g2000yqz.googlegroups.com> On Sep 29, 7:23?am, rantingrick wrote: > A specific method for padding a string with ONLY zeros is ludicrous > and exposes the narrow mindedness of the creator. The only thing worse > than "zfill" as a string method is making zfill into built-in > function! The ONLY proper place for zfill is as an option in the > str.format() method. > > py> "{0:zf10}".format(1234) -> "00000000001234" If something like "zfill" where to be included as a string method, it should be more general like this: class String: def pad(self, char, count, side='left') => str py> "".pad(0, 10) '00000000001234' However the same can be accomplished with: py> '{0}1234'.format("0"*10) '00000000001234' py> "0"*10+'1234' '00000000001234' Seems like pollution either way you go. Best to just let the programmer handle it. Python IS NOT a 100% OOP language (and for good reason!) so we don't need methods to scratch every little itch -- and this itch seems to have originated in the "nether regions" instead of the "Netherlands". From roy at panix.com Thu Sep 29 09:28:35 2011 From: roy at panix.com (Roy Smith) Date: Thu, 29 Sep 2011 09:28:35 -0400 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <4e84388c$0$29965$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? I'm not sure what you mean by "without a tty attached to the process". If you mean no file descriptors attached to your control terminal, then some variation on foo.py < /dev/null > /dev/null (as others has suggested) might be good enough. Or, are you talking about control terminals in the process control sense? In that case, you might want to look at the "at" or "batch" commands, which do very much the same thing as cron, but without the overhead of having to edit the cron file to get things going. From python at mrabarnett.plus.com Thu Sep 29 10:02:55 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 29 Sep 2011 15:02:55 +0100 Subject: [OT] Benefit and belief In-Reply-To: <87zkho2glb.fsf@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <4E847A8F.3070401@mrabarnett.plus.com> On 29/09/2011 04:05, Ben Finney wrote: > Devin Jeanpierre writes: > >>> Forget money, or even the love of money. The idea that one mustn't >>> criticise another person's beliefs is the root of all evil. >> >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. > >> Can't you pick somewhere else to attack Christianity? > > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. > > If you find someone attacking people, I'll join you in ostracising the > attacker. But no, don't attempt to silence jokes that attack an idea. > > Off-topic? If we start discussing the content of the ideas being > attacked, yeah, I'd say religion is pretty off-topic. > > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. > Even if it offends Python worshippers? http://www.youtube.com/watch?v=asUyK6JWt9U From martin.hellwig at gmail.com Thu Sep 29 10:25:40 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 29 Sep 2011 15:25:40 +0100 Subject: Python without a tty In-Reply-To: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 29/09/2011 10:21, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > > > Well you could double fork and drop the parent, that would lose the tty which is the same effect what you get when you want a daemon. -- mph From brandtrade08 at 126.com Thu Sep 29 10:26:15 2011 From: brandtrade08 at 126.com (jerser-2009) Date: Thu, 29 Sep 2011 07:26:15 -0700 (PDT) Subject: Nike Air Max LeBron VIII Message-ID: <81a0b983-ea36-45ff-b482-450d07eed5ed@g23g2000vbz.googlegroups.com> Published late last year for the first time Nike Air Max LeBron VIII that caused a large response, follow-up and then released LeBron VIII P2 and LeBron 8PS versions, LeBron is so loyal fans surprises. Back to {1}{/1}Nike for the first time this exposure will open the second half of LeBron 9 flagship shoe figure. Mystery photo from the body of the shoe can be seen a lot of reference material of carbon fiber, and also impressively hidden Hyperfuse material which is easy to understand Nike LeBron on the court to strong demand torque and light weighthttp://www.cheap-nbabasketballshoes.com/ under the foot pains. Wei is currently not yet fully revealed Nike LeBron 9 picture, ladies shoes andgentlemens, friends, fans, please wait.it will come update in http://www.cheap-nbabasketballshoes.com/ From brian.curtin at gmail.com Thu Sep 29 10:27:43 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Thu, 29 Sep 2011 09:27:43 -0500 Subject: Installing Python 2.6.7 on Windows In-Reply-To: References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Sep 28, 2011 at 19:10, Nobody wrote: > On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote: > > > No, it was a deliberate decision. After a release is in security-fix > > mode only, we don't build Windows or Mac OS X installers for them. > > But you continue to offer the installers for the unfixed version. No one would use Python if we literally forced everyone to upgrade based on our schedule by removing any trace of previous installers. Also, "unfixed" is relative. You're only vulnerable if you're using urllib to request resources which may end up being 302 redirected. I personally don't need that fix, so 2.6.6 would be alright with me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcloete at gmail.com Thu Sep 29 10:45:53 2011 From: bcloete at gmail.com (Bradley Cloete) Date: Thu, 29 Sep 2011 16:45:53 +0200 Subject: Python without a tty In-Reply-To: <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: > It doesn't appear so to me. > > [steve at sylar ~]$ tty > /dev/pts/16 > [steve at sylar ~]$ setsid tty > /dev/pts/16 > > [steve at sylar ~]$ python -c "import sys,os; print > os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print > os.isatty(sys.stdout.fileno())" > True > > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. > > Maybe nohup is what you looking for? >From the info pages... "`nohup' runs the given COMMAND with hangup signals ignored, so that the command can continue running in the background after you log out. Synopsis: nohup COMMAND [ARG]... If standard output is a terminal, it is redirected so that it is appended to the file `nohup.out'; if that cannot be written to, it is appended to the file `$HOME/nohup.out'. If that cannot be written to, the command is not run. If standard output is not a terminal, then the standard output of COMMAND will be the same as that of `nohup'. " Regards Bradley -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhagurgaon2011 at gmail.com Thu Sep 29 12:11:41 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 09:11:41 -0700 (PDT) Subject: Question on Manipulating List and on Python Message-ID: Dear Group, I have two questions one on list manipulation and other on Python. (i) I have a file of lists. Now, the first digit starts with a number or index, like, [001, "Obama", "USA", "President"] [002 "Major", "UK", "PM"] [003 "Singh", "INDIA", "PM"] Initially, I am reading the file and taking as for line in file: line_word=line.split print line_word I am getting the above result. But, my problem is if I read the array position 0, which is a number then it should give me reciprocal words like if word1=line_word[0] if word1==001: I should get line_word[1], line_word[2] reciprocating the value. Predefining it solves the problem, but I want to capture and do as it iterates. If any one can help? (ii) My second question is posted by one of my colleagues, what makes Python so fast? Regards, Subhabrata Banerjee. From gordon at panix.com Thu Sep 29 12:27:49 2011 From: gordon at panix.com (John Gordon) Date: Thu, 29 Sep 2011 16:27:49 +0000 (UTC) Subject: Question on Manipulating List and on Python References: Message-ID: In Subhabrata Banerjee writes: > (i) I have a file of lists. Now, the first digit starts with a number > or index, like, > [001, "Obama", "USA", "President"] > [002 "Major", "UK", "PM"] > [003 "Singh", "INDIA", "PM"] > Initially, I am reading the file and taking as > for line in file: > line_word=line.split > print line_word This isn't your actual code. Please show us your real code, along with a sample of your input file. > (ii) My second question is posted by one of my colleagues, what makes > Python so fast? Fast compared to what? Why does your colleague believe it should be slower? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From dwblas at gmail.com Thu Sep 29 12:34:00 2011 From: dwblas at gmail.com (David) Date: Thu, 29 Sep 2011 09:34:00 -0700 (PDT) Subject: Question on Manipulating List and on Python References: Message-ID: <12c2b6e4-5fa4-44ed-83f4-2a969ae4076b@8g2000yqm.googlegroups.com> > word1=line_word[0] > if word1==001: You are comparing a string and an integer assuming you are reading a text file. integers word1=int(line_word[0]) if word1=1: strings word1=line_word[0] if word1=="001:" From anikom15 at gmail.com Thu Sep 29 12:34:25 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 09:34:25 -0700 Subject: Suggested coding style In-Reply-To: <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e844a83$0$29982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20110929163425.GA10980@Smoke> On Thu, Sep 29, 2011 at 08:37:53PM +1000, Steven D'Aprano wrote: > Westley Mart?nez wrote: > > > Perhaps you should spend a little less time on the mailing list and a > > little more time in church. > > Is that meant as punishment for Rick or for the churchgoers? > > Hopefully neither, probably both. From subhagurgaon2011 at gmail.com Thu Sep 29 12:36:29 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 09:36:29 -0700 (PDT) Subject: Question on Manipulating List and on Python References: Message-ID: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> On Sep 29, 9:27?pm, John Gordon wrote: > In Subhabrata Banerjee writes: > > > (i) I have a file of lists. Now, the first digit starts with a number > > or index, like, > > [001, "Obama", "USA", "President"] > > [002 ?"Major", "UK", "PM"] > > [003 ?"Singh", "INDIA", "PM"] > > Initially, I am reading the file and taking as > > for line in file: > > ? ? line_word=line.split > > ? ? print line_word > > This isn't your actual code. ?Please show us your real code, along with > a sample of your input file. > > > (ii) My second question is posted by one of my colleagues, what makes > > Python so fast? > > Fast compared to what? ?Why does your colleague believe it should be > slower? > > -- > John Gordon ? ? ? ? ? ? ? ? ? A is for Amy, who fell down the stairs > gor... at panix.com ? ? ? ? ? ? ?B is for Basil, assaulted by bears > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -- Edward Gorey, "The Gashlycrumb Tinies" Hi John, The actual code is till now is: def name_debugger(n): open_file=open("/python27/name1.txt") for line in open_file: line_word=line.split() #print line_word word1=line_word[0] print word1 And Python seems faster than C++/Java. It is indeed. I also experience it. Regards, Subhabrata Banerjee. From clp2 at rebertia.com Thu Sep 29 12:37:28 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 09:37:28 -0700 Subject: Question on Manipulating List and on Python In-Reply-To: References: Message-ID: On Thu, Sep 29, 2011 at 9:11 AM, Subhabrata Banerjee wrote: > Dear Group, > > I have two questions one on list manipulation and other on Python. > > (i) I have a file of lists. Now, the first digit starts with a number > or index, like, > > [001, "Obama", "USA", "President"] > [002 ?"Major", "UK", "PM"] > [003 ?"Singh", "INDIA", "PM"] > > Initially, I am reading the file and taking as > for line in file: > ? ?line_word=line.split > ? ?print line_word > > I am getting the above result. But, my problem is if I read the array > position 0, which is a number then it should give me reciprocal words > like > if > word1=line_word[0] > if word1==001: > ? ?I should get line_word[1], line_word[2] reciprocating the value. > > Predefining it solves the problem, but I want to capture and do as it > iterates. If any one can help? I'm not really clear what you mean by "reciprocal", so this is just a guess: Perhaps you want list slicing? >>> line_word = ["001", "Obama", "USA", "President"] >>> print(line_word[1:]) ['Obama', 'USA', 'President'] >>> Details: http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation > (ii) My second question is posted by one of my colleagues, what makes > Python so fast? CPython is actually relatively slow compared to the primary implementations of other languages since Python highly dynamic, and interpreted rather than compiled to machine code (normally). There are currently some promising efforts (like PyPy) to produce a faster implementation however. Cheers, Chris -- http://rebertia.com From moky.math at gmail.com Thu Sep 29 12:39:51 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 29 Sep 2011 18:39:51 +0200 Subject: Question on Manipulating List and on Python In-Reply-To: References: Message-ID: <4E849F57.4010101@gmail.com> Le 29/09/2011 18:27, John Gordon a ?crit : > In Subhabrata Banerjee writes: > >> (i) I have a file of lists. Now, the first digit starts with a number >> or index, like, > >> [001, "Obama", "USA", "President"] >> [002 "Major", "UK", "PM"] >> [003 "Singh", "INDIA", "PM"] What about creating a dictionary ? dic = {1:["Obama","USA","President"],2:[etc.]] >> (ii) My second question is posted by one of my colleagues, what makes >> Python so fast? If your colleague is used to program inside Word macros, I guess the answer ;) If he is used to program in C, I'm less sure. It really depends on the context of the question. Laurent From anikom15 at gmail.com Thu Sep 29 12:42:11 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 09:42:11 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <20110929164211.GA11016@Smoke> On Thu, Sep 29, 2011 at 05:23:30AM -0700, rantingrick wrote: > On Sep 29, 5:37?am, Passiday wrote: > > What is so bad about breaking code in obscure places? We changed print > to a function which broke just about every piece of code every written > in this language. (BTW, print should ALWAYS have been a function!) > What is so bad then about breaking some very obscure code? We could > always have a lengthy deprecation period. > Well, I once thought that a print function made a lot of sense. In C, printf is a function, however then I think why print is a function. In C, just about every function has side effects (the return values are more often than not either pointers or status codes). In Python functions are encouraged to not have side-effects, so the implementation of print as a statement or a method makes far more sense than as a function. But maybe I'm just batty as you all think I am. From rosuav at gmail.com Thu Sep 29 12:50:49 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 02:50:49 +1000 Subject: Question on Manipulating List and on Python In-Reply-To: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee wrote: > And Python seems faster than C++/Java. It is indeed. I also experience > it. > Python compared to Java? Difficult to compare. Python to C++? Impossible to compare. But performance depends MASSIVELY on algorithmic quality; if you code the exact same thing in Python and in C++, you would probably find that the C++ one is faster, but chances are you're implementing approximately the same thing in two quite different ways. Or possibly you're using a slow and inefficient library or third-party function. I've sometimes written code in one language and directly ported it to another, and then run both on the same hardware. With most such experiments, CPython generally doesn't perform all that well, and C or C++ rocks. But frequently, the C/C++ code is more verbose and more error-prone than the Python - because Python's biggest boast is not that it's fast, but that it's *fast enough*, while being easy to work with. (And every once in a while there's something where I want to use a pointer to some other variable, and that's a concept that just plain doesn't work in Python. You have references to objects, but you can't from one place change another variable, without using some kind of mutable object that they both reference.) ChrisA From miki.tebeka at gmail.com Thu Sep 29 12:52:07 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 29 Sep 2011 09:52:07 -0700 (PDT) Subject: options for plotting points on geographic map In-Reply-To: References: Message-ID: <28071425.854.1317315127547.JavaMail.geo-discussion-forums@prfb12> Probably the google maps routes will be faster (maybe using embedded webkit window). However it requires internet connection. See also http://www.scipy.org/Cookbook/Matplotlib/Maps HTH -- Miki Tebeka http://pythonwise.blogspot.com From gordon at panix.com Thu Sep 29 12:52:53 2011 From: gordon at panix.com (John Gordon) Date: Thu, 29 Sep 2011 16:52:53 +0000 (UTC) Subject: Question on Manipulating List and on Python References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: In <71c71a9d-928d-4ebe-af64-674c31bc1c09 at e9g2000vby.googlegroups.com> Subhabrata Banerjee writes: > Hi John, > The actual code is till now is: > def name_debugger(n): > open_file=3Dopen("/python27/name1.txt") > for line in open_file: > line_word=3Dline.split() > #print line_word > word1=3Dline_word[0] > print word1 Can you give us some sample lines from /python27/name1.txt ? > And Python seems faster than C++/Java. It is indeed. I also experience > it. It shouldn't be inherently faster than C++ or Java. If it is, it's because the C++ or Java code is doing more work. Do you have a sample Python program and a sample C++ or Java program to demonstrate the speed difference? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rosuav at gmail.com Thu Sep 29 13:02:29 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:02:29 +1000 Subject: Suggested coding style In-Reply-To: <20110929164211.GA11016@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <20110929164211.GA11016@Smoke> Message-ID: On Fri, Sep 30, 2011 at 2:42 AM, Westley Mart?nez wrote: > But maybe I'm just batty as you all think I am. Yes, I'm afraid so. Bonkers. Off your head. But let me tell you a secret... All the best people are. > Well, I once thought that a print function made a lot of sense. ?In C, > printf is a function, however then I think why print is a function. ?In > C, just about every function has side effects (the return values are > more often than not either pointers or status codes). ?In Python > functions are encouraged to not have side-effects, so the implementation > of print as a statement or a method makes far more sense than as a > function. Since functions and methods in Python are practically the same thing, I don't know that there really need be any difference in policy. But I do like any reduction in the number of "special features" of a language. If screen output can be done as an ordinary function taking ordinary arguments, that's better than having a special language construct. Also, it's just plain stupid and yet just plain cool to be able to: print = sys.stderr.write and smoothly redirect all your prints to stderr. (Unfortunately this doesn't quite work, as it means you don't get your newlines put in for you, but there's sure to be an equally stupid/cool reassignment available.) ChrisA From moky.math at gmail.com Thu Sep 29 13:08:52 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 29 Sep 2011 19:08:52 +0200 Subject: Counting the number of call of a function Message-ID: Hello Is it possible to count the number of time a function is called ? Of course, if I've access to the source code, it's easy. I tried the following : def foo(): print "foo !" class wraper(object): def __init__(self,fun): globals()[fun]=self.replacement def replacement(*args): print "I'm replaced" foo() X=wraper(foo) foo() I was hoping that globals()[foo] would be replaced by my X.replacement and thus the second call to foo() was expected to print "I'm replaced". Instead nothing is done. By the way, I tried to print globals() inside __init__() to see what happens. It turns out that the entry 'foo' is never modified. Any idea ? I fact what I have to do is to add a decorator _a posteriori_ ... Have a good night Laurent From rosuav at gmail.com Thu Sep 29 13:20:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:20:30 +1000 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens wrote: > def foo(): > ? ?print "foo !" > > > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() Are you able to change the call structure to: foo() # unchanged foo=wrapper(foo) # this changes it foo() # should now be changed perhaps? That would be a lot easier to manage. Then you could write the wrapper thus: class wrapper(object): def __init__(self,func): self.func=func def __call__(self,*args,**kwargs): print("I'm replaced!") # if you want to be noisy self.count+=1 self.func(*args,**kwargs) Tested in Python 3; should also work in Python 2, which you appear to be using. Effectively, I've written something that could actually be a decorator, and then done the same sort of thing that a decorator does by rebinding the name. ChrisA From rosuav at gmail.com Thu Sep 29 13:22:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 03:22:12 +1000 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 3:08 AM, Laurent Claessens wrote: > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement and > thus the second call to foo() was expected to print "I'm replaced". Actually, I've just realized what your problem might be. Try: X = wraper("foo") You're indexing globals() with the actual function object, but you want to index it with the function _name_. I do think that the decorator technique will be a lot cleaner, though. ChrisA From python at mrabarnett.plus.com Thu Sep 29 13:26:18 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 29 Sep 2011 18:26:18 +0100 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E84AA3A.7040209@mrabarnett.plus.com> On 29/09/2011 18:08, Laurent Claessens wrote: > Hello > > > Is it possible to count the number of time a function is called ? > Of course, if I've access to the source code, it's easy. > > I tried the following : > > def foo(): > print "foo !" > > > class wraper(object): > def __init__(self,fun): > globals()[fun]=self.replacement > def replacement(*args): > print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement > and thus the second call to foo() was expected to print "I'm replaced". > > Instead nothing is done. > > By the way, I tried to print globals() inside __init__() to see what > happens. It turns out that the entry 'foo' is never modified. > > Any idea ? > I fact what I have to do is to add a decorator _a posteriori_ ... > The keys of globals() are the _names_. You're giving it the function itself. Try this: class wraper(object): def __init__(self,fun): globals()[fun.__name__]=self.replacement def replacement(*args): print("I'm replaced") A decorator would be better. From clp2 at rebertia.com Thu Sep 29 13:27:35 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 10:27:35 -0700 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: On Thu, Sep 29, 2011 at 10:08 AM, Laurent Claessens wrote: > ? Hello > > > ? Is it possible to count the number of time a function is called ? > Of course, if I've access to the source code, it's easy. > > I tried the following : > > def foo(): > ? ?print "foo !" > > > class wraper(object): > ? ?def __init__(self,fun): > ? ? ? ?globals()[fun]=self.replacement > ? ?def replacement(*args): > ? ? ? ?print "I'm replaced" > > foo() > X=wraper(foo) > foo() > > I was hoping that globals()[foo] would be replaced by my X.replacement and > thus the second call to foo() was expected to print "I'm replaced". > > Instead nothing is done. That's because globals() maps names (i.e. strings) to values, whereas in this case `fun` is a function object, not a string. Trying to subscript globals() with a non-string arguably ought to be an error. By way of example (with irrelevant stuff elided): Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00) Type "help", "copyright", "credits" or "license" for more information. >>> def foo(): ... pass ... >>> globals() {..., 'foo': } >>> globals()[foo] = 42 >>> globals() {..., : 42, 'foo': } >>> globals()["foo"] = 99 >>> globals() {..., 'foo': 99, : 42} Note that you can get the name of a function using its __name__ attribute. That is to say: foo.__name__ == "foo" > By the way, I tried to print globals() inside __init__() to see what > happens. It turns out that the entry 'foo' is never modified. > > Any idea ? > I fact what I have to do is to add a decorator _a posteriori_ ... Recall that the decorator syntax: @bar def qux(): pass is basically equivalent to: def qux(): pass qux = bar(qux) Therefore, you want something like: def wrapped(func): def replacement(*args, **kwargs): print "I'm replaced" return replacement foo = wrapped(foo) foo() # => I'm replaced Cheers, Chris -- http://rebertia.com From jeanpierreda at gmail.com Thu Sep 29 14:49:05 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 14:49:05 -0400 Subject: [OT] Benefit and belief In-Reply-To: <87zkho2glb.fsf@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. Well. It wasn't directly an attack on people exactly. It did mention believers directly. It could certainly be _interpreted_ as an attack (and was interpreted that way), and that's really all that's necessary for a hostile environment. I'm not saying we should censor ourselves exactly. I've always been opposed to harsh _rules_ about what's appropriate and what isn't. But I do think it's important to consider others' feelings. Just because it isn't an attack, doesn't mean it can't hurt peoples' feelings, and I think hurting peoples' feelings is something worth going out of your way to avoid. Anyway, if it was a joke before, it isn't when somebody starts calling some "group of people" "organised conspiracies to support and protect child molesters". > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. That doesn't make it right. Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. It seems, again, hurtful. Especially when the idea is totally unrelated. It's like we're having a discussion about dynamic typing and somebody blurts out "Hahaha, static typing is almost as dumb as Cartesian Dualism". The best case outcome is that nobody cares. The worse case outcomes go down to hurt feelings and flame wars from dualists. > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. It obviously isn't "safe" to joke about any topic, seeing as it caused a derailment and new thread. Devin On Wed, Sep 28, 2011 at 11:05 PM, Ben Finney wrote: > Devin Jeanpierre writes: > >> > Forget money, or even the love of money. The idea that one mustn't >> > criticise another person's beliefs is the root of all evil. >> >> This was a technical discussion, and calling the bible a joke was not >> necessary at all. It creates a hostile atmosphere. > > I disagree. It was not an attack on any person nor group of people. If > we are to be required to avoid jokes not directed at people, then *that* > is an atmosphere hostile to open friendly discussion. > >> Can't you pick somewhere else to attack Christianity? > > The person who wrote the ?bible is a joke? intended it as a flippant > remark. Countless other flippant remarks pass through here all the time, > making jokes at the expense of some idea or other. Christianity will not > be an exception to that. > > If you find someone attacking people, I'll join you in ostracising the > attacker. But no, don't attempt to silence jokes that attack an idea. > > Off-topic? If we start discussing the content of the ideas being > attacked, yeah, I'd say religion is pretty off-topic. > > But the topic of keeping this forum safe for technical discussion > entails that it must be safe for *any* idea to be the butt of a joke, be > it a religious text or the Zen of Python, and that is very much > on-topic. > > -- > ?\ ? ? ? ? ?We demand rigidly defined areas of doubt and uncertainty!? | > ?`\ ? ??Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Adams | > Ben Finney > -- > http://mail.python.org/mailman/listinfo/python-list > From petite.abeille at gmail.com Thu Sep 29 15:32:20 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 29 Sep 2011 21:32:20 +0200 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > It could certainly be _interpreted_ as an attack > (and was interpreted that way), and that's really all that's necessary > for a hostile environment. In other news: http://alt.textdrive.com/assets/public/non/nq050616.gif -- Tout le monde il est beau, tout le monde il est gentil From navkirat.py at gmail.com Thu Sep 29 15:37:34 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Fri, 30 Sep 2011 01:07:34 +0530 Subject: [OT] Benefit and belief In-Reply-To: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: Hi, I am looking for the python mailing list. . ? Have you guys seen it somewhere? I think I accidently reached the cry-me-a-river list? Regards, Nav On Sep 30, 2011 1:03 AM, "Petite Abeille" wrote: > > On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > >> It could certainly be _interpreted_ as an attack >> (and was interpreted that way), and that's really all that's necessary >> for a hostile environment. > > In other news: > > http://alt.textdrive.com/assets/public/non/nq050616.gif > > -- > Tout le monde il est beau, tout le monde il est gentil > > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Sep 29 15:39:48 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 15:39:48 -0400 Subject: options for plotting points on geographic map In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B1B@EMARC112VS01.exchad.jpmchase.net> >I see there is pymaps, a Python wrapper for Google Maps. I may try >that but it seems to be barely documented and would require making a >webpage with javascript to display the map, whereas I'd probably >prefer a desktop app for this--though I'd consider a web page (it's >probably easier than I think). You could create the webpage and then render it in your desktop app. I have seen plenty of apps like that. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Thu Sep 29 15:52:23 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 12:52:23 -0700 Subject: [OT] Benefit and belief In-Reply-To: <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: <4E84CC77.7060804@stoneleaf.us> Petite Abeille wrote: > On Sep 29, 2011, at 8:49 PM, Devin Jeanpierre wrote: > >> It could certainly be _interpreted_ as an attack >> (and was interpreted that way), and that's really all that's necessary >> for a hostile environment. > > In other news: > > http://alt.textdrive.com/assets/public/non/nq050616.gif Okay, now that's funny. ~Ethan~ From ramit.prasad at jpmorgan.com Thu Sep 29 15:52:52 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 29 Sep 2011 15:52:52 -0400 Subject: Question on Manipulating List and on Python In-Reply-To: References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F66B77@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Chris Angelico Sent: Thursday, September 29, 2011 11:51 AM To: python-list at python.org Subject: Re: Question on Manipulating List and on Python On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee wrote: > And Python seems faster than C++/Java. It is indeed. I also experience > it. > Python compared to Java? Difficult to compare. Python to C++? Impossible to compare. But performance depends MASSIVELY on algorithmic quality; if you code the exact same thing in Python and in C++, you would probably find that the C++ one is faster, but chances are you're implementing approximately the same thing in two quite different ways. Or possibly you're using a slow and inefficient library or third-party function. I've sometimes written code in one language and directly ported it to another, and then run both on the same hardware. With most such experiments, CPython generally doesn't perform all that well, and C or C++ rocks. But frequently, the C/C++ code is more verbose and more error-prone than the Python - because Python's biggest boast is not that it's fast, but that it's *fast enough*, while being easy to work with. (And every once in a while there's something where I want to use a pointer to some other variable, and that's a concept that just plain doesn't work in Python. You have references to objects, but you can't from one place change another variable, without using some kind of mutable object that they both reference.) ----------------------------------------------------------------------- I think Steven D'Aprano had an excellent post on this a week or so ago (on the tutor list, not this one). See: http://mail.python.org/pipermail/tutor/2011-September/085573.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 ChrisA -- http://mail.python.org/mailman/listinfo/python-list This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From petite.abeille at gmail.com Thu Sep 29 15:54:54 2011 From: petite.abeille at gmail.com (Petite Abeille) Date: Thu, 29 Sep 2011 21:54:54 +0200 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <2B0B7132-9E4B-41E7-8710-959B03A89F24@gmail.com> Message-ID: <3D981489-D106-459B-91C1-73DE3A45B79C@gmail.com> On Sep 29, 2011, at 9:37 PM, Navkirat Singh wrote: > I am looking for the python mailing list. . ? Have you guys seen it > somewhere? I think I accidently reached the cry-me-a-river list? The portal can be reactivated by intoning Bobby Brown Goes Down in unison. From chris at simplistix.co.uk Thu Sep 29 17:00:58 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 29 Sep 2011 22:00:58 +0100 Subject: TestFixtures 2.1.0 Released! Message-ID: <4E84DC8A.4040508@simplistix.co.uk> Hi All, Another release of TestFixtures, getting things closer to where I want them to be. The only change was: - Add a "strict mode" to `compare`. When used, it ensures that the values compared are not only equal but also of the same type. This mode is not used by default, and the default mode restores the more commonly useful functionality where values of similar types but that aren't equal give useful feedback about differences. For details, read: http://packages.python.org/testfixtures/comparing.html#strict-comparison The full list of changes can be found here: http://packages.python.org/testfixtures/changes.html The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From anikom15 at gmail.com Thu Sep 29 17:20:15 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 14:20:15 -0700 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <20110929212015.GA11663@Smoke> On Thu, Sep 29, 2011 at 02:49:05PM -0400, Devin Jeanpierre wrote: > >> This was a technical discussion, and calling the bible a joke was not > >> necessary at all. It creates a hostile atmosphere. > > > > I disagree. It was not an attack on any person nor group of people. If > > we are to be required to avoid jokes not directed at people, then *that* > > is an atmosphere hostile to open friendly discussion. > > Well. It wasn't directly an attack on people exactly. It did mention > believers directly. It could certainly be _interpreted_ as an attack > (and was interpreted that way), and that's really all that's necessary > for a hostile environment. > > I'm not saying we should censor ourselves exactly. I've always been > opposed to harsh _rules_ about what's appropriate and what > isn't. But I do think it's important to consider others' feelings. > Just because it isn't an attack, doesn't mean it can't hurt peoples' > feelings, and I think hurting peoples' feelings is something worth > going out of your way to avoid. > > Anyway, if it was a joke before, it isn't when somebody starts calling > some "group of people" "organised conspiracies to support and protect > child molesters". > > > The person who wrote the ?bible is a joke? intended it as a flippant > > remark. Countless other flippant remarks pass through here all the time, > > making jokes at the expense of some idea or other. Christianity will not > > be an exception to that. > > That doesn't make it right. Is it OK to make fun of arbitrary ideas as > "jokes"? I don't think so. It seems, again, hurtful. Especially when > the idea is totally unrelated. It's like we're having a discussion > about dynamic typing and somebody blurts out "Hahaha, static typing is > almost as dumb as Cartesian Dualism". The best case outcome is that > nobody cares. The worse case outcomes go down to hurt feelings and > flame wars from dualists. > > > But the topic of keeping this forum safe for technical discussion > > entails that it must be safe for *any* idea to be the butt of a joke, be > > it a religious text or the Zen of Python, and that is very much > > on-topic. > > It obviously isn't "safe" to joke about any topic, seeing as it caused > a derailment and new thread. > Sometimes it's just not appropriate to joke. Save them for the dates. From ben+python at benfinney.id.au Thu Sep 29 17:24:15 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 07:24:15 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <87r52z2gao.fsf@benfinney.id.au> Passiday writes: > Oh, my. Who could expect this topic would iterate to some whining > about religion (please don't respond on this remark of mine). That's an unreasonable request. If you make a provocative remark (I doubt you chose to use ?whining? without knowing how dismissive it is), it's disingenuous to then ask that people please not respond. -- \ ?If nothing changes, everything will remain the same.? ?Barne's | `\ Law | _o__) | Ben Finney From ben+python at benfinney.id.au Thu Sep 29 17:32:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 07:32:42 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <87mxdn2fwl.fsf@benfinney.id.au> MRAB writes: > On 29/09/2011 04:05, Ben Finney wrote: > > But the topic of keeping this forum safe for technical discussion > > entails that it must be safe for *any* idea to be the butt of a > > joke, be it a religious text or the Zen of Python, and that is very > > much on-topic. > > Even if it offends Python worshippers? > http://www.youtube.com/watch?v=asUyK6JWt9U Even then. People who remain attached to ideas are being unreasonable if they take a joke about that idea personally. No idea, certainly not any religion, gets any special exemption. -- \ ?On the other hand, you have different fingers.? ?Steven Wright | `\ | _o__) | Ben Finney From anikom15 at gmail.com Thu Sep 29 17:33:34 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 14:33:34 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4E847A8F.3070401@mrabarnett.plus.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <20110929213334.GB11663@Smoke> I'm kind of new to the whole mailing list thing, but they seem to be a lot more lenient than internet forums about most things. I've noticed that sometimes Off-topic posts can get a little out of hand. I guess it's not really a big deal, but it bothers me, and the trolls just love to feed on it. I mean, as programmers, we should devote our time to improving computer systems. On this mailing list, we're programmers, nothing else, and so we shouldn't mingle other things into the list. Think of it as using global variables or even a goto. That's essentially what OT is. It just serves to obfuscate valuable answers to good programming questions. From rosuav at gmail.com Thu Sep 29 17:40:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 07:40:13 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <20110929213334.GB11663@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <20110929213334.GB11663@Smoke> Message-ID: On Fri, Sep 30, 2011 at 7:33 AM, Westley Mart?nez wrote: > On this mailing list, we're programmers, > nothing else, and so we shouldn't mingle other things into the list. > Think of it as using global variables or even a goto. ?That's > essentially what OT is. Not a bad analogy, that... but I accept it in perhaps not the same way as you intended it. I don't mind using a global variable once in a while. I don't object to a well-placed goto, especially when it's clear and obvious what it's doing. And the occasional off-topic post or thread on a mailing list isn't the end of the world either. ChrisA From ben+python at benfinney.id.au Thu Sep 29 18:01:32 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 08:01:32 +1000 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> Message-ID: <20110929220132.GD2715@benfinney.id.au> On 29-Sep-2011, Devin Jeanpierre wrote: > >> This was a technical discussion, and calling the bible a joke was not > >> necessary at all. It creates a hostile atmosphere. > > > > I disagree. It was not an attack on any person nor group of people. If > > we are to be required to avoid jokes not directed at people, then *that* > > is an atmosphere hostile to open friendly discussion. > > Well. It wasn't directly an attack on people exactly. It did mention > believers directly. It did not. It mentioned only a pair of texts: the bible, and the Zen of Python. Texts are not people, and we should not go out of our way to protect them from jokes or criticism. > It could certainly be _interpreted_ as an attack (and was interpreted > that way), and that's really all that's necessary for a hostile > environment. Nonsense. *Any* joke could be interpreted as an attack; the issue is whether it's reasonable to do so. Anyone who is so confused as to take a joke about a book as an attack on people is being quite unreasonable, and we should not restrain our jokes for the sake of that. > I'm not saying we should censor ourselves exactly. I've always been > opposed to harsh _rules_ about what's appropriate and what > isn't. But I do think it's important to consider others' feelings. Agreed. But only to the extent that attacks *on those people* are concerned. Peoples feelings about ideas are not a consideration when discussing ideas, and certainly not when joking about ideas. > Just because it isn't an attack, doesn't mean it can't hurt peoples' > feelings, and I think hurting peoples' feelings is something worth > going out of your way to avoid. There we disagree. The hurt feelings of someone who attaches their identity to a text should not restrain our discourse. > Anyway, if it was a joke before, it isn't when somebody starts calling > some "group of people" "organised conspiracies to support and protect > child molesters". The group of people to whom that refers, the administrative hierarchy of the Catholic Church, have been doing exactly what the quotation says. I agree that's not a joke; it's a matter of fact, and relevant in the context where it was mentioned. > Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. Yes, a thousand times yes. Ideas are not people, have no rights, and get no exemption from criticism or dismissal or attack or ridicule. > It seems, again, hurtful. Especially when the idea is totally unrelated. That would eliminate just about every joke: a huge range of jokes *depend* for their humour on connecting seemingly-unrelated ideas. So by your logic, we don't get to make those jokes here. > It's like we're having a discussion about dynamic typing and somebody > blurts out "Hahaha, static typing is almost as dumb as Cartesian > Dualism". The best case outcome is that nobody cares. The worse case > outcomes go down to hurt feelings and flame wars from dualists. And the joke would still be okay, and it would be silly for anyone to take it as hurtful. You can call such a joke off-topic, and I'd agree. You can say it's not very funny, and I'd agree. You can say it's undeserving of a flame war, and I'd agree wholeheartedly. But whoever takes that joke and says it's deliberately hurtful is being presumptuous and censorious and unreasonable. If they then castigate the joker for supposedly hurting someone's feelings, it's at that point the atmosphere turns hostile to discussion. -- \ ?The most dangerous man to any government is the man who is | `\ able to think things out for himself, without regard to the | _o__) prevailing superstitions and taboos.? ?Henry L. Mencken | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From ian.g.kelly at gmail.com Thu Sep 29 18:12:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 16:12:51 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > A specific method for padding a string with ONLY zeros is ludicrous > and exposes the narrow mindedness of the creator. The only thing worse > than "zfill" as a string method is making zfill into built-in > function! The ONLY proper place for zfill is as an option in the > str.format() method. > > py> "{0:zf10}".format(1234) -> "00000000001234" Agree that zfill seems to be redundant with str.format, although your suggested syntax is atrocious, especially since a syntax already exists that fits better in the already-complicated format specifier syntax. "{0:=010d}".format(1234) -> "0000001234" There are a couple of warts with the existing implementation, however: 1) str.zfill() operates on strings; the .format() syntax operates on numeric types. I would suggest that the "=" fill alignment in format specifiers should be extended to do the same thing as zfill when given a string. 2) It seems to not behave as documented for floats. I expect: "{0:=010f}".format(-32.7) -> "-0000032.7" I get: "{0:=010f}".format(-32.7) -> "-32.700000" On the other hand, I can't imagine why I would ever actually want the expected result, so maybe it's not a big deal. From clp2 at rebertia.com Thu Sep 29 18:16:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 29 Sep 2011 15:16:43 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <20110929213334.GB11663@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <20110929213334.GB11663@Smoke> Message-ID: On Thu, Sep 29, 2011 at 2:33 PM, Westley Mart?nez wrote: > I'm kind of new to the whole mailing list thing, but they seem to be a > lot more lenient than internet forums about most things. ?I've noticed > that sometimes Off-topic posts can get a little out of hand. ?I guess > it's not really a big deal, but it bothers me, and the trolls just love > to feed on it. ?I mean, as programmers, we should devote our time to > improving computer systems. This is why good mail clients have a "Mute" or equivalent function to ignore an entire thread and not let it waste any more of your time. You may want to plonk Xah and the ranter who goes by Rick while you're at it. :) Cheers, Chris From rantingrick at gmail.com Thu Sep 29 18:56:57 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 15:56:57 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 5:12?pm, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > > A specific method for padding a string with ONLY zeros is ludicrous > > and exposes the narrow mindedness of the creator. The only thing worse > > than "zfill" as a string method is making zfill into built-in > > function! The ONLY proper place for zfill is as an option in the > > str.format() method. > > > py> "{0:zf10}".format(1234) -> "00000000001234" > > Agree that zfill seems to be redundant with str.format, although your > suggested syntax is atrocious, especially since a syntax already > exists that fits better in the already-complicated format specifier > syntax. It's interesting that you find the format specifier "complicated". I will admit that upon first glance i lamented the new format method spec and attempted to cling to the old string interpolation crap. However, as you use the new format method you will come to appreciate it. It's an adult beverage with an acquired taste. ;-) One thing that may help format noobs is to look at the spec as two parts; the part before the colon and the part after the colon. If you break it down in this manner the meaning starts to shine through. I will agree, it is a lot of cryptic info squeezed into a small space HOWEVER you would no want a verbose format specification. But i wholeheartedly agree with you points and i would say the zfill method has no future uses in the stdlib except for historical reasons. We should deprecate it now. > "{0:=010d}".format(1234) -> "0000001234" > > There are a couple of warts with the existing implementation, however: > > 1) str.zfill() operates on strings; the .format() syntax operates on > numeric types. ?I would suggest that the "=" fill alignment in format > specifiers should be extended to do the same thing as zfill when given > a string. EXACTLY! PS: Has anyone noticed all the off topic chatter about religion and feelings? Since the main subject of this thread is about zfill i can't help but wonder if the minions where sent out to present a distraction with "scripted" pseudo arguments. Just an observation. From jeanpierreda at gmail.com Thu Sep 29 19:03:24 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 19:03:24 -0400 Subject: [OT] Benefit and belief In-Reply-To: <20110929220132.GD2715@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: > There we disagree. The hurt feelings of someone who attaches their identity > to a text should not restrain our discourse. Yes, we do. > That would eliminate just about every joke: a huge range of jokes *depend* > for their humour on connecting seemingly-unrelated ideas. So by your logic, > we don't get to make those jokes here. I didn't have much logic. I just don't think it's nice to do things that hurt other people, and if we can, we should avoid those things. Avoiding them is pretty easy here. > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. I don't really care about the "joke". I honestly I didn't understand it as a joke, which would drive most of my disagrement. I don't think it should have been made, yes. I take major issue with the anti-Christian rant that appeared afterward, but I haven't really taken much opportunity to attack it because it doesn't matter. All I'd like is for people to be a little more friendly, if you please. I also didn't reprimand anyone, except maybe Steven. But anyway, no, we don't agree on what it means to be friendly or what a hostile atmosphere is. I've noticed that people tend to be a lot harsher here than what I'm used to, so perhaps your attitude to it is more common on mailing-lists and I should just adapt. Devin On Thu, Sep 29, 2011 at 6:01 PM, Ben Finney wrote: > On 29-Sep-2011, Devin Jeanpierre wrote: >> >> This was a technical discussion, and calling the bible a joke was not >> >> necessary at all. It creates a hostile atmosphere. >> > >> > I disagree. It was not an attack on any person nor group of people. If >> > we are to be required to avoid jokes not directed at people, then *that* >> > is an atmosphere hostile to open friendly discussion. >> >> Well. It wasn't directly an attack on people exactly. It did mention >> believers directly. > > It did not. It mentioned only a pair of texts: the bible, and the Zen of > Python. Texts are not people, and we should not go out of our way to > protect them from jokes or criticism. > >> It could certainly be _interpreted_ as an attack (and was interpreted >> that way), and that's really all that's necessary for a hostile >> environment. > > Nonsense. *Any* joke could be interpreted as an attack; the issue is > whether it's reasonable to do so. Anyone who is so confused as to take a > joke about a book as an attack on people is being quite unreasonable, and > we should not restrain our jokes for the sake of that. > >> I'm not saying we should censor ourselves exactly. I've always been >> opposed to harsh _rules_ about what's appropriate and what >> isn't. But I do think it's important to consider others' feelings. > > Agreed. But only to the extent that attacks *on those people* are > concerned. Peoples feelings about ideas are not a consideration when > discussing ideas, and certainly not when joking about ideas. > >> Just because it isn't an attack, doesn't mean it can't hurt peoples' >> feelings, and I think hurting peoples' feelings is something worth >> going out of your way to avoid. > > There we disagree. The hurt feelings of someone who attaches their identity > to a text should not restrain our discourse. > >> Anyway, if it was a joke before, it isn't when somebody starts calling >> some "group of people" "organised conspiracies to support and protect >> child molesters". > > The group of people to whom that refers, the administrative hierarchy of > the Catholic Church, have been doing exactly what the quotation says. > > I agree that's not a joke; it's a matter of fact, and relevant in the > context where it was mentioned. > >> Is it OK to make fun of arbitrary ideas as "jokes"? I don't think so. > > Yes, a thousand times yes. Ideas are not people, have no rights, and get no > exemption from criticism or dismissal or attack or ridicule. > >> It seems, again, hurtful. Especially when the idea is totally unrelated. > > That would eliminate just about every joke: a huge range of jokes *depend* > for their humour on connecting seemingly-unrelated ideas. So by your logic, > we don't get to make those jokes here. > >> It's like we're having a discussion about dynamic typing and somebody >> blurts out "Hahaha, static typing is almost as dumb as Cartesian >> Dualism". The best case outcome is that nobody cares. The worse case >> outcomes go down to hurt feelings and flame wars from dualists. > > And the joke would still be okay, and it would be silly for anyone to take > it as hurtful. > > You can call such a joke off-topic, and I'd agree. You can say it's not > very funny, and I'd agree. You can say it's undeserving of a flame war, and > I'd agree wholeheartedly. > > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. > > -- > ?\ ? ? ? ? ?The most dangerous man to any government is the man who is | > ?`\ ? ? ? able to think things out for himself, without regard to the | > _o__) ? ? ? ? ?prevailing superstitions and taboos.? ?Henry L. Mencken | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > > From jeanpierreda at gmail.com Thu Sep 29 19:07:28 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 29 Sep 2011 19:07:28 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) Yeah. It's a much more difficult to read thing, but once you learn how to write it it flows faster. Of course, I never managed to learn how to write it... I would suggest that rather than being "complicated" it is "dense". > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. May I suggest a email client that can group mailing list threads? Also, not accusing others of conspiracies. Devin On Thu, Sep 29, 2011 at 6:56 PM, rantingrick wrote: > On Sep 29, 5:12?pm, Ian Kelly wrote: >> On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: >> > A specific method for padding a string with ONLY zeros is ludicrous >> > and exposes the narrow mindedness of the creator. The only thing worse >> > than "zfill" as a string method is making zfill into built-in >> > function! The ONLY proper place for zfill is as an option in the >> > str.format() method. >> >> > py> "{0:zf10}".format(1234) -> "00000000001234" >> >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) > > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. > > But i wholeheartedly agree with you points and i would say the zfill > method has no future uses in the stdlib except for historical reasons. > We should deprecate it now. > > >> "{0:=010d}".format(1234) -> "0000001234" >> >> There are a couple of warts with the existing implementation, however: >> >> 1) str.zfill() operates on strings; the .format() syntax operates on >> numeric types. ?I would suggest that the "=" fill alignment in format >> specifiers should be extended to do the same thing as zfill when given >> a string. > > EXACTLY! > > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. > -- > http://mail.python.org/mailman/listinfo/python-list > From vacorama at gmail.com Thu Sep 29 19:11:02 2011 From: vacorama at gmail.com (ron) Date: Thu, 29 Sep 2011 16:11:02 -0700 (PDT) Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0acaf956-3285-4d0c-98ea-61f7ce88a3ba@x19g2000vbl.googlegroups.com> On Sep 29, 5:21?am, Steven D'Aprano wrote: > I have a Python script which I would like to test without a tty attached > to the process. I could run it as a cron job, but is there an easier way? > > I am running Linux. > > -- > Steven Have you tried GNU Screen? It let's you run processes under virtual terminals, which can then be backgrounded, reconnected to, etc. I think it comes with most linux distros. From rosuav at gmail.com Thu Sep 29 19:12:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 09:12:50 +1000 Subject: [OT] Benefit and belief In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: On Fri, Sep 30, 2011 at 9:03 AM, Devin Jeanpierre wrote: > But anyway, no, we don't agree on what it means to be friendly or what > a hostile atmosphere is. I've noticed that people tend to be a lot > harsher here than what I'm used to, so perhaps your attitude to it is > more common on mailing-lists and I should just adapt. > I'm told that there are other mailing lists / newsgroups that are far, FAR more hostile than this. Haven't explored though, as I don't feel like torturing myself :) As to the original offensiveness, though: I'm a fundamentalist Christian (not Catholic though), and I water-off-a-duck's-backed the insult. If it's true, it's allowed to be offensive; if it's not true, I can distance myself from it. (In this case, the latter; the inner issues of the Catholic church are unconnected to the core of Christianity.) Chris Angelico From ethan at stoneleaf.us Thu Sep 29 19:21:25 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 16:21:25 -0700 Subject: [OT] Benefit and belief In-Reply-To: <20110929220132.GD2715@benfinney.id.au> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <4E84FD75.5050907@stoneleaf.us> Ben Finney wrote: > But whoever takes that joke and says it's deliberately hurtful is being > presumptuous and censorious and unreasonable. If they then castigate the > joker for supposedly hurting someone's feelings, it's at that point the > atmosphere turns hostile to discussion. Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe he /wasn't/ trying to be offensive? ~Ethan~ From python at mrabarnett.plus.com Thu Sep 29 19:37:08 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 30 Sep 2011 00:37:08 +0100 Subject: [OT] Benefit and belief In-Reply-To: <4E84FD75.5050907@stoneleaf.us> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <4E850124.8070508@mrabarnett.plus.com> On 30/09/2011 00:21, Ethan Furman wrote: > Ben Finney wrote: >> But whoever takes that joke and says it's deliberately hurtful is being >> presumptuous and censorious and unreasonable. If they then castigate the >> joker for supposedly hurting someone's feelings, it's at that point the >> atmosphere turns hostile to discussion. > > Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe > he /wasn't/ trying to be offensive? > rantingrick: """Since, like the bible the zen is self contradicting, any argument utilizing the zen can be defeated utilizing the zen.""" alex23: """And like the Bible, the Zen was created by humans as a joke. If you're taking it too seriously, that's your problem.""" From ethan at stoneleaf.us Thu Sep 29 19:40:59 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 29 Sep 2011 16:40:59 -0700 Subject: [OT] Benefit and belief In-Reply-To: <4E84FD75.5050907@stoneleaf.us> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <4E85020B.30207@stoneleaf.us> Ethan Furman wrote: > Ben Finney wrote: >> But whoever takes that joke and says it's deliberately hurtful is being >> presumptuous and censorious and unreasonable. If they then castigate the >> joker for supposedly hurting someone's feelings, it's at that point the >> atmosphere turns hostile to discussion. > > Um, wasn't it RantingRick who made this 'joke'? Do you honestly believe > he /wasn't/ trying to be offensive? Okay, that's what I get for skimming -- it was alex23, not rr. My apologies, rr, for the misattribution. ~Ethan~ From rantingrick at gmail.com Thu Sep 29 19:41:34 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 16:41:34 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <30b05df7-6f16-45fd-bbe8-7f6c09d2e6e1@i28g2000yqn.googlegroups.com> On Sep 29, 6:07?pm, Devin Jeanpierre wrote: > > However, as you use the new format method you will come to appreciate > > it. It's an adult beverage with an acquired taste. ;-) > > Yeah. It's a much more difficult to read thing, but once you learn how > to write it it flows faster. > > Of course, I never managed to learn how to write it... A good way to start out is to just use the positional arguments. py> name = "Bob" py> "Hello my name is {0}".format(name) Hello my name is Bob py> "Hello my name is {name}".format(name=name) Hello my name is Bob py> "Hello my name is {0}. My named spelled backwards is: {0}".format(name) Hello my name is Bob. My named spelled backwards is: Bob py> "A small fry cost {0:0.2f}".format(1.6666666) A small fry cost 1.67 py> "A small car cost {0:,.2f}".format(11666.6666) A small car cost 11,666.67 # Python 2.7+ you can omit the index. py> "{} = {}".format("value",2) value = 2 Start with the small stuff and then diversify! You'll be glad you made the change. From rantingrick at gmail.com Thu Sep 29 19:47:40 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 16:47:40 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> On Sep 29, 5:12?pm, Ian Kelly wrote: > On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: > > A specific method for padding a string with ONLY zeros is ludicrous > > and exposes the narrow mindedness of the creator. The only thing worse > > than "zfill" as a string method is making zfill into built-in > > function! The ONLY proper place for zfill is as an option in the > > str.format() method. > > > py> "{0:zf10}".format(1234) -> "00000000001234" > > Agree that zfill seems to be redundant with str.format, although your > suggested syntax is atrocious, especially since a syntax already > exists that fits better in the already-complicated format specifier > syntax. > > "{0:=010d}".format(1234) -> "0000001234" > > There are a couple of warts with the existing implementation, however: > > 1) str.zfill() operates on strings; the .format() syntax operates on > numeric types. ?I would suggest that the "=" fill alignment in format > specifiers should be extended to do the same thing as zfill when given > a string. Ah ha! Found the answer! py> "{0:010d}".format(1234) 0000001234 py> "{0:0>10}".format(1234) 0000001234 py> "{0:0>10}".format("1234") 0000001234 py> "{0:@>10}".format("1234") @@@@@@1234 I would skip using the "{int}{repeat}d" syntax and just use the string padding since you won't need to worry about the input data type. I hate specificity types in string formats. With the old interpolation i ALWAYS used %s for everything. From rantingrick at gmail.com Thu Sep 29 20:04:40 2011 From: rantingrick at gmail.com (rantingrick) Date: Thu, 29 Sep 2011 17:04:40 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: On Sep 29, 6:40?pm, Ethan Furman wrote: > Okay, that's what I get for skimming -- it was alex23, not rr. ?My > apologies, rr, for the misattribution. Oh don't worry Ethan, this is not the first time I've been falsely accused, misquoted, and kicked in the testicles, and i'm quite sure with this fine group of folks it won't be the last either. From ben+python at benfinney.id.au Thu Sep 29 22:06:56 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 12:06:56 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <87bou23hrz.fsf@benfinney.id.au> Westley Mart?nez writes: > I'm kind of new to the whole mailing list thing, but they seem to be a > lot more lenient than internet forums about most things. Note that a mailing list *is* an internet forum: it is a forum for discussion, conducted on the internet. Mailing lists have been internet forums long before any web application came along. > I've noticed that sometimes Off-topic posts can get a little out of > hand. I guess it's not really a big deal, but it bothers me, and the > trolls just love to feed on it. Yes, these are hazards of an unmoderated discussion forum like this. The overall quality of discussion here, and the signal-to-noise ratio, makes it very worthwhile I think. > I mean, as programmers, we should devote our time to improving > computer systems. On this mailing list, we're programmers, nothing > else, and so we shouldn't mingle other things into the list. What counts as ?mingle other things in?? What sparked this latest outcry was a flippant remark at the expense of an ancient text and the Zen of Python. That outcry was, I have argued, not reasonable. I am firmly committed to allowing flippant remarks which are not at the expense of people. It's highly inappropriate to ask that such remarks not be made simply because some people might take undue offense. Are they off-topic? Maybe, but there's no compulsion to respond to them since flippant remarks, by definition, aren't meant seriously. Are they not funny? That doesn't matter. If the obligation is that people should not make unfunny jokes, we'd all be guilty. Are they poking fun at something? That *definitely* shouldn't matter; if a thing (not a person) is worth defending, then do so or not as you choose. If you like it but can't defend it adequately, that's your problem not anyone else's. If the ridicule works because it's true, then the target thing is perhaps not worth defending. We draw the line, IMO rightly so, at personal attacks on people or groups of people. I have many times spoken out against those in this forum. But books and ideas, no matter who likes them, are fair game for flippant remarks in this and any forum, and I resist efforts to quash such expression. -- \ ?What I have to do is see, at any rate, that I do not lend | `\ myself to the wrong which I condemn.? ?Henry Thoreau, _Civil | _o__) Disobedience_ | Ben Finney From ben+python at benfinney.id.au Thu Sep 29 22:10:16 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 12:10:16 +1000 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <0acaf956-3285-4d0c-98ea-61f7ce88a3ba@x19g2000vbl.googlegroups.com> Message-ID: <877h4q3hmf.fsf@benfinney.id.au> ron writes: > On Sep 29, 5:21?am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > > I have a Python script which I would like to test without a tty attached > > to the process. I could run it as a cron job, but is there an easier way? > > Have you tried GNU Screen? It let's you run processes under virtual > terminals, which can then be backgrounded, reconnected to, etc. I > think it comes with most linux distros. That would not satisfy the ?without a TTY attached? requirement. GNU Screen's main goal is to *provide* an attached TTY to multiple processes when the TTY isn't interacting with the user. I don't know whether Screen can *remove* a TTY from a process, and it would be strange to me if it did so. -- \ ?I have yet to see any problem, however complicated, which, | `\ when you looked at it in the right way, did not become still | _o__) more complicated.? ?Paul Anderson | Ben Finney From derek at simkowiak.net Thu Sep 29 22:16:52 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Thu, 29 Sep 2011 19:16:52 -0700 Subject: Motion Tracking with Python Message-ID: <4E852694.4080303@simkowiak.net> Hello, I have a neat Python project I'd like to share. It does real-time motion tracking, using the Python bindings to the OpenCV library: http://derek.simkowiak.net/motion-tracking-with-python/ There is a YouTube video showing the script in action. It's especially neat because my daughter and I worked together on this project. We used it to track her two pet gerbils, as part of her science fair project. She wrote her own (separate) Python script to read the motion tracking log files, compute distance and velocity, and then export those values in a CSV file. Like I say on the web page: "I?m convinced that Python is the best language currently available for teaching kids how to program." I also use Python professionally, and it's worked out great every time. There's no job Python can't handle. Thanks, Derek Simkowiak http://derek.simkowiak.net From steve+comp.lang.python at pearwood.info Thu Sep 29 22:38:01 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 12:38:01 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> Message-ID: <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Westley Mart?nez wrote: > On this mailing list, we're programmers, nothing else, Speak for yourself. -- Steven From rosuav at gmail.com Thu Sep 29 22:48:17 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 12:48:17 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Sep 30, 2011 at 12:38 PM, Steven D'Aprano wrote: > Westley Mart?nez wrote: > >> On this mailing list, we're programmers, nothing else, > > Speak for yourself. > I don't think he meant that the populace here is exclusively programmers, but that *on this list* we are here because we're programmers. We may happen to have coincidental interest in (say) music, but just because some group of us (or even all of us) all enjoy music does not mean that it'd be on-topic to have a discussion of the tetrachord of Mercury. ChrisA From wuwei23 at gmail.com Thu Sep 29 22:50:27 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 19:50:27 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Sep 29, 10:23?pm, rantingrick wrote: > What is so bad about breaking code in obscure places? Try coding in PHP across minor release versions and see how you feel about deprecating core functions on a whim. > We changed print > to a function which broke just about every piece of code every written > in this language. In a well declared _break_ with backwards compatibility. Not on a whim between minor releases. > (BTW, print should ALWAYS have been a function!) Unfortunately, not everyone is as infallible as you. Or as intractable. Coding styles change over time: this is a concept known as "progress", although it's not as obvious in monocultures, so you may not have heard of it. > What is so bad then about breaking some very obscure code? Because while you say "some very obscure code", what you really mean is "code that isn't mine". > GvR should be texting me every night in hopes that some of my API genius will rub > off on him. Are you off your medication again? > I believe GvR had a "mid-dev-crisis"[...] You seem to believe a lot of absolute garbage. As you have no access to the inner states of _any_ of the people you regularly condemn here with your hypocritical attacks, I've no idea why you consider yourself to be an expert on their desires and opinions. From wuwei23 at gmail.com Thu Sep 29 23:05:26 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:05:26 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> Message-ID: <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> On Sep 30, 9:37?am, MRAB wrote: > rantingrick: > """Since, like the bible the zen is self contradicting, any argument > utilizing > the zen can be defeated utilizing the zen.""" > > alex23: > """And like the Bible, the Zen was created by humans as a joke. If you're > taking it too seriously, that's your problem.""" Strangely, calling the bible self-contradictory wasn't seen as inflammatory... Seeing the quotes again, I'm pretty sure I was intending to be flippant _in reference to rantrantrantrick's comment_. Given that it was a response to someone else referring to the bible _and_ it made a point about the zen, I'm not entirely sure why my comment was OT. Again, if you want to disagree with my remark, knock yourself out. If you want to take it as a personal attack, then there's nothing I can do to stop you. But do realise that it is _you_ who is interpreting it as such, and then recall the provision your very own Christ stated about judging the actions of others: within your own belief system _it's not your right to do so_. That never seems to reduce the moral outrage though... From steve+comp.lang.python at pearwood.info Thu Sep 29 23:10:07 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 13:10:07 +1000 Subject: [OT] Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> Devin Jeanpierre wrote: > I also didn't reprimand anyone, except maybe Steven. If you are more upset at my describing the Catholic Church as protecting child molesters than you are at the Church for actually protecting child molesters, then your priorities are completely screwed up and your reprimand means less than nothing to me. I wear it as a badge of honour. -- Steven From steve+comp.lang.python at pearwood.info Thu Sep 29 23:19:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 13:19:28 +1000 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Fri, Sep 30, 2011 at 12:38 PM, Steven D'Aprano > wrote: >> Westley Mart?nez wrote: >> >>> On this mailing list, we're programmers, nothing else, >> >> Speak for yourself. >> > > I don't think he meant that the populace here is exclusively > programmers, but that *on this list* we are here because we're > programmers. We may happen to have coincidental interest in (say) > music, but just because some group of us (or even all of us) all enjoy > music does not mean that it'd be on-topic to have a discussion of the > tetrachord of Mercury. I didn't say it would be on-topic. But we don't cease to be well-rounded human beings with concerns beyond the narrow world of Python programming just because we are writing on a programming forum. -- Steven From wuwei23 at gmail.com Thu Sep 29 23:29:51 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:29:51 -0700 (PDT) Subject: A Trivial Question References: <1317246839.73013.YahooMailNeo@web120313.mail.ne1.yahoo.com> Message-ID: <65588c04-eea5-4a7a-b7ba-52dbcded227d@c1g2000yql.googlegroups.com> On Sep 29, 8:06?am, Chris Rebert wrote: > Try this: > > def trial(): > ? ? class Foo(object): > ? ? ? ? def __init__(self): > ? ? ? ? ? ? print("Hello, world!") > ? ? Foo() > trial() While this will display "Hello, world!" in the way required, with a slight adjustment you end up with something potentially a little more useful: def trial(): class Foo(object): def __init__(self): print("Hello, world!") return Foo() myfoo = trial() You'll see the same behaviour, but now myfoo refers to the Foo() object that was created inside trial. This makes trial an object factory. If you return an uninstantiated Foo instead: def trial(): class Foo(object): def __init__(self): print("Hello, world!") return Foo MyFoo = trial() foo = MyFoo() Then trial is a class factory, creating and returning a class. Factories can be handy if you're wanting to create dynamic classes based on run time information. def reader_factory(format='json'): class Reader(object): def __init__(self, file): self.file = file if format == 'json': def process(self): print 'json processing goes here' elif format == 'html': def process(self): print 'html processing goes here' return Reader >>> JSONReader = reader_factory('json') >>> j = JSONReader('file1') >>> j.process() json processing goes here This is a trivial example which would probably be better handled by subclasses, but is meant to be indicative of what's possible. From rosuav at gmail.com Thu Sep 29 23:41:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 13:41:31 +1000 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Fri, Sep 30, 2011 at 12:50 PM, alex23 wrote: >> GvR should be texting me every night in hopes that some of my API genius will rub >> off on him. > > Are you off your medication again? > He's very much like jimontrack (aka Tranzit Jim - google him if you're curious), whose username people frequently referred to with the t replaced with a c. Everyone thought he lived in April 1st. ChrisA From wuwei23 at gmail.com Thu Sep 29 23:49:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:49:56 -0700 (PDT) Subject: Off-Topic Posts and Threads on the Python Mailing List References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> Chris Angelico wrote: > We may happen to have coincidental interest in (say) > music, but just because some group of us (or even all of us) all enjoy > music does not mean that it'd be on-topic to have a discussion of the > tetrachord of Mercury. As general discussion it would be, sure, but I don't think there's anything that can be readily dismissed as 'not relevant' in terms of providing abstract concepts to programmers. I've tried explaining encapsulation to non-programmers using Reason's hardware rack metaphor. I'm slowly seeing more and more interest in applying hermeneutics to computer science, a discipline that arose out of the study of religious texts. We don't always know what we don't know. For that alone, I'd rather we were more inclusive of topics of discussion than exclusionary. From wuwei23 at gmail.com Thu Sep 29 23:57:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 20:57:56 -0700 (PDT) Subject: Benefit and belief [was Re: Suggested coding style] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ba4842c-9043-4674-a0d5-5beb915e436b@k10g2000vbn.googlegroups.com> Dennis Lee Bieber wrote: > ? ? ? ? Well... We could try for equality in offense -- the Torah or the > Koran? Maybe the Tripitaka or Sutras? I always enjoyed the possibly apocryphal claim that the design of VRML was influenced by the story of Indra's Net. Maybe some religious tomes are just better? :) From steve+comp.lang.python at pearwood.info Fri Sep 30 00:34:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 14:34:26 +1000 Subject: Hermeneutics and computer science [was off-topic, now back on] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> Message-ID: <4e8546d3$0$29984$c3e8da3$5496439d@news.astraweb.com> alex23 wrote: > I'm slowly seeing more and more interest in applying > a discipline that arose out of the > study of religious texts. Tell us more, please. -- Steven From ian.g.kelly at gmail.com Fri Sep 30 00:36:29 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 22:36:29 -0600 Subject: Benefit and belief In-Reply-To: <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> Message-ID: On Thu, Sep 29, 2011 at 9:05 PM, alex23 wrote: > Strangely, calling the bible self-contradictory wasn't seen as > inflammatory... Well, that part is factual. Whether that makes it a joke is subjective. From mickyhulse.lists at gmail.com Fri Sep 30 00:48:30 2011 From: mickyhulse.lists at gmail.com (Micky Hulse) Date: Thu, 29 Sep 2011 21:48:30 -0700 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: That's really cool! Thanks for sharing! :) From ian.g.kelly at gmail.com Fri Sep 30 00:49:43 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 22:49:43 -0600 Subject: Suggested coding style In-Reply-To: <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> Message-ID: On Thu, Sep 29, 2011 at 5:47 PM, rantingrick wrote: > Ah ha! Found the answer! > > py> "{0:010d}".format(1234) > 0000001234 > > py> "{0:0>10}".format(1234) > 0000001234 > > py> "{0:0>10}".format("1234") > 0000001234 > > py> "{0:@>10}".format("1234") > @@@@@@1234 > > I would skip using the "{int}{repeat}d" syntax and just use the string > padding since you won't need to worry about the input data type. I > hate specificity types in string formats. With the old interpolation i > ALWAYS used %s for everything. Nope, that doesn't work. >>> "{0:0>10}".format("-1234") '00000-1234' The whole point of zfill is that it handles signs correctly. From colinphaedrus at yahoo.com Fri Sep 30 01:02:48 2011 From: colinphaedrus at yahoo.com (crazycga) Date: Fri, 30 Sep 2011 05:02:48 GMT Subject: Motion Tracking with Python References: Message-ID: On Thu, 29 Sep 2011 19:16:52 -0700, Derek Simkowiak wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion > tracking, using the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for > teaching kids how to program." > > I also use Python professionally, and it's worked out great every time. > There's no job Python can't handle. > > > Thanks, > Derek Simkowiak > http://derek.simkowiak.net That is excessively cool dude! You've given me some inspiration for my own programming as a result! Thank you! From ian.g.kelly at gmail.com Fri Sep 30 01:06:27 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 29 Sep 2011 23:06:27 -0600 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: On Thu, Sep 29, 2011 at 4:56 PM, rantingrick wrote: >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) I find it interesting that a self-proclaimed API expert like yourself suggests that it isn't complicated. The documentation on the format specifiers is around 6 1/2 printed pages long, and that's not even including the docs for the string.Formatter API. Devin is right, though, in that a better word for it would be "dense". "Complicated" is not a bad thing here, because with that complexity comes expressiveness. It just means that care needs to be taken when adding new options to ensure that they integrate well with the existing syntax. > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. What makes you think I'm a "format noob"? The details may have evolved over the years, but the format specifiers are fundamentally still the same old printf syntax that we've all been using for decades. From ben+python at benfinney.id.au Fri Sep 30 01:14:27 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 15:14:27 +1000 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <8739fe393g.fsf@benfinney.id.au> alex23 writes: > On Sep 29, 10:23?pm, rantingrick wrote: > > GvR should be texting me every night in hopes that some of my API > > genius will rub off on him. > > Are you off your medication again? Please don't make personal attacks. If you don't feel like addressing the content of his message, don't switch to implying he has a mental illness. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but Tuesday Weld isn't a complete sentence.? ?_Pinky and | _o__) The Brain_ | Ben Finney From ben+python at benfinney.id.au Fri Sep 30 01:22:03 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 30 Sep 2011 15:22:03 +1000 Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <4ba4842c-9043-4674-a0d5-5beb915e436b@k10g2000vbn.googlegroups.com> Message-ID: <87y5x61u6c.fsf@benfinney.id.au> alex23 writes: > I always enjoyed the possibly apocryphal claim that the design of VRML > was influenced by the story of Indra's Net. You see, folks? It's by ?mingling in? other aspects of life with technical discussion that we can improve the technical discussion :-) > Maybe some religious tomes are just better? :) They're all flawed, of course, as is any text. But some are wholly dreadful while others have parts worth keeping. -- \ ?Nature hath given men one tongue but two ears, that we may | `\ hear from others twice as much as we speak.? ?Epictetus, | _o__) _Fragments_ | Ben Finney From wuwei23 at gmail.com Fri Sep 30 01:24:44 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 22:24:44 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <8739fe393g.fsf@benfinney.id.au> Message-ID: <4b295504-3fbe-4d9a-b566-d12afad058c5@dd6g2000vbb.googlegroups.com> On Sep 30, 3:14?pm, Ben Finney wrote: > alex23 writes: > > On Sep 29, 10:23?pm, rantingrick wrote: > > > GvR should be texting me every night in hopes that some of my API > > > genius will rub off on him. > > > Are you off your medication again? > > Please don't make personal attacks. If you don't feel like addressing > the content of his message, don't switch to implying he has a mental > illness. Fair enough. It was intended more as a ludicrous accusation to his ridiculous claim. Lord knows there's enough in his posts to focus on without the ad hominems :) From rosuav at gmail.com Fri Sep 30 01:31:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 15:31:24 +1000 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: On Fri, Sep 30, 2011 at 12:16 PM, Derek Simkowiak wrote: > Like I say on the web page: "I?m convinced that Python is the best language > currently available for teaching kids how to program." Agreed. > There's no job Python can't handle. Ehhh... Not agreed. Not quite. Yes it's true in that Python is Turing-complete, but there are a lot of jobs that it can't handle _well_. (Unless someone's seriously considering porting the Linux kernel to Python... or writing a device driver in Python... or writing a MS Word virus in Python...) Right tool for the job! But certainly Python is excellent at many tasks, and it's easy to work with. I wholeheartedly support the sentiment behind your statement, even if I quibble slightly - your statement has accuracy, it merely wants precision :) I'll watch your vid once I'm home from work - it promises to be some pretty cool stuff! ChrisA From wuwei23 at gmail.com Fri Sep 30 01:54:43 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 22:54:43 -0700 (PDT) Subject: Hermeneutics and computer science [was off-topic, now back on] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <5d04e455-3d9f-4727-bbe1-e7e22e3b27a0@i28g2000yqn.googlegroups.com> <4e8546d3$0$29984$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1e8a3553-75fb-45cc-ab71-998a5406fbcd@m37g2000yqc.googlegroups.com> On Sep 30, 2:34?pm, Steven D'Aprano wrote: > alex23 wrote: > > I'm slowly seeing more and more interest in applying > > a discipline that arose out of the > > study of religious texts. > > Tell us more, please. Well, it's mostly from real world discussions and may actually be an artefact of my holding degrees in both philosophy & computer science :) But googling "hermeneutics computer science" does bring up a heap of entries, although the highest ranked is from 1979, so I may have oversold the idea of it being a growing interest. Amazon also shows that there have been a number of publications dealing with this: http://www.amazon.com/s?ie=UTF8&keywords=Hermeneutics.&rh=n%3A3508%2Ck%3AHermeneutics. For me, the main aspect of hermeneutics that could apply here - to programming especially - is the concept that reading a text informs you for subsequently reinterpreting the text (the "hermeneutic circle" of Heidegger). No philosophical notion of truth is needed to explain this, I see much in common with iterative development processes. Multiplicity of perspective is similarly important in interpretation: again, computer systems are developed with many user roles and thus many 'views' of what is happening. In the interest of fair play, if anyone still smarting at my flippancy wants to take a swing at my belief system, it's mostly cobbled together from Nietzsche, Wittgenstein & Crowley. Personal email preferably, let's keep it off the list unless its particularly witty :) From thebiggestbangtheory at gmail.com Fri Sep 30 02:02:55 2011 From: thebiggestbangtheory at gmail.com (bingbang) Date: Thu, 29 Sep 2011 23:02:55 -0700 (PDT) Subject: Modifying external running process using python Message-ID: <086bd803-ddc5-4913-b1f1-5fb6cb5848bb@i28g2000yqn.googlegroups.com> Hi all, Beginner here. I am trying to figure out how to modify a running process on a linux system using Python. Example: I have a python program that takes in as an argument a PID. My goal is to use this PID and get info about the running process with that PID. (1) Find where it is located in memory (2) Where is the instruction pointer (3) Modify the program such that the next executed instruction is something else (4) Return the pointer back to the next legitimate instruction (5) Let the original process execute as it should have I am trying to develop a POC to show how a small piece of code can be injected into a running process to just print 'hello' to stdout and not disturb the rest of the process. Before you tear you hair out. The program I want to "infect" will be an infinite loop with a sleep in it and the "malware" will be a " print 'infected' " kind of program. Not looking to do anything malicious, just trying to learn. I looked up trace and some other modules but they all seem to do with following the currently executing python process. Also looked at pyhook, but its mainly to trap signals from keyboards etc.. Looked at gray hat python - tuned towards windows. Can anyone please point me to some modules that might be useful, or some code samples. I tried googling for "python inspect process PID" etc.. did not get anything very useful. I know I can run gdb -a pid from within python and such but I am looking for a non os.popen ish kind of a way. Is there a module that will be helpful. Let's assume I have sudo/root privileges and that the POC code "only needs to work in linux". Any help is very appreciated. [Also posted on StackOverflow] - no real good leads from there Thanks! From anikom15 at gmail.com Fri Sep 30 02:14:21 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 29 Sep 2011 23:14:21 -0700 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <20110930061421.GA12929@Smoke> On Thu, Sep 29, 2011 at 07:07:28PM -0400, Devin Jeanpierre wrote: > > However, as you use the new format method you will come to appreciate > > it. It's an adult beverage with an acquired taste. ;-) > > Yeah. It's a much more difficult to read thing, but once you learn how > to write it it flows faster. > > Of course, I never managed to learn how to write it... > > I would suggest that rather than being "complicated" it is "dense". > I'm one of the weirdos who is absolutely hostile to the format method and continues to use % formatting. I'm pretty sure it is because of my C background (actually I learned Python before C, and thus learned % formatting in Python). However, I'm not so opposed to it that I've not learned it. It is quite "dense", almost feels like something in a scripting language like Perl. Indeed, I did try it for some time, but it was just too "heavy" and slow for me. Well someday I'll probably be forced to use it, but for anyone else who agrees with me, always know there's at least one Python programmer out there with some (or no) sense. From wuwei23 at gmail.com Fri Sep 30 02:31:50 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 23:31:50 -0700 (PDT) Subject: Motion Tracking with Python References: Message-ID: <75e59668-9002-4614-9fe8-9605e6ecf924@dm9g2000vbb.googlegroups.com> On Sep 30, 12:16?pm, Derek Simkowiak wrote: > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Thank you for sharing this. My daughter is only 20 months at the moment but I definitely hope to teach her coding as she gets older. Cheers. From rosuav at gmail.com Fri Sep 30 02:35:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 16:35:02 +1000 Subject: Suggested coding style In-Reply-To: <20110930061421.GA12929@Smoke> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <20110930061421.GA12929@Smoke> Message-ID: On Fri, Sep 30, 2011 at 4:14 PM, Westley Mart?nez wrote: > I'm one of the weirdos who is absolutely hostile to the format method > and continues to use % formatting. ?I'm pretty sure it is because of my > C background (actually I learned Python before C, and thus learned % > formatting in Python). I quite like printf-style formatting. It's well known, well defined, and compact. When I write C++ programs, I often still use printf/sprintf extensively - it just "feels nicer" than iostream (and the main downside of printf, the lack of argument checking, is largely solved in recent gcc). So when I work with Python, it makes sense to use the same thing there. Dense syntax results in easy-to-read format strings, imho. ChrisA From wuwei23 at gmail.com Fri Sep 30 02:39:29 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 Sep 2011 23:39:29 -0700 (PDT) Subject: Motion Tracking with Python References: <4E852694.4080303@simkowiak.net> Message-ID: On Sep 30, 3:31?pm, Chris Angelico wrote: > Unless someone's seriously considering porting the Linux > kernel to Python... Well, they've certainly asked: http://bytes.com/topic/python/answers/37048-reimplenting-linux-kernel-python And while not Linux kernels, there are two projects attempting to develop Python-implemented OSes: http://code.google.com/p/cleese/ http://unununium.org > or writing a device driver in Python... http://www.stealth-x.com/programming/driver-writing-with-python.php > or writing a MS Word virus in Python... Now that's just crazy talk. From subhagurgaon2011 at gmail.com Fri Sep 30 02:43:13 2011 From: subhagurgaon2011 at gmail.com (Subhabrata Banerjee) Date: Thu, 29 Sep 2011 23:43:13 -0700 (PDT) Subject: Question on Manipulating List and on Python References: <71c71a9d-928d-4ebe-af64-674c31bc1c09@e9g2000vby.googlegroups.com> Message-ID: On Sep 30, 12:52?am, "Prasad, Ramit" wrote: > -----Original Message----- > From: python-list-bounces+ramit.prasad=jpmorgan.... at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.... at python.org] On Behalf Of Chris Angelico > Sent: Thursday, September 29, 2011 11:51 AM > To: python-l... at python.org > Subject: Re: Question on Manipulating List and on Python > > On Fri, Sep 30, 2011 at 2:36 AM, Subhabrata Banerjee > wrote: > > And Python seems faster than C++/Java. It is indeed. I also experience > > it. > > Python compared to Java? Difficult to compare. Python to C++? > Impossible to compare. But performance depends MASSIVELY on > algorithmic quality; if you code the exact same thing in Python and in > C++, you would probably find that the C++ one is faster, but chances > are you're implementing approximately the same thing in two quite > different ways. Or possibly you're using a slow and inefficient > library or third-party function. > > I've sometimes written code in one language and directly ported it to > another, and then run both on the same hardware. With most such > experiments, CPython generally doesn't perform all that well, and C or > C++ rocks. But frequently, the C/C++ code is more verbose and more > error-prone than the Python - because Python's biggest boast is not > that it's fast, but that it's *fast enough*, while being easy to work > with. (And every once in a while there's something where I want to use > a pointer to some other variable, and that's a concept that just plain > doesn't work in Python. You have references to objects, but you can't > from one place change another variable, without using some kind of > mutable object that they both reference.) > ----------------------------------------------------------------------- > > I think Steven D'Aprano had an excellent post on this a week or so ago (on the tutor list, not this one). > > See:http://mail.python.org/pipermail/tutor/2011-September/085573.html > > Ramit > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > ChrisA > --http://mail.python.org/mailman/listinfo/python-list > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available athttp://www.jpmorgan.com/pages/disclosures/email. ? > > Dear Group, Thanks for your suggestions. I'll check if these work. Converting to dictionary I was thinking but others I have to test. Without patting my own back(I do not write algorithms that good), I can say Python is indeed damn fast. A reason many of my friends are shifting fast to Python and I was suggested by a reputed person of MIT CogLab to use Python instead of C++ and it worked just fabulous for me. To my collegue I would find out an answer. Regards, Subhabrata. From rustompmody at gmail.com Fri Sep 30 03:24:30 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 00:24:30 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> Message-ID: <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> On Sep 30, 4:03?am, Devin Jeanpierre wrote: > > But anyway, no, we don't agree on what it means to be friendly or what > a hostile atmosphere is. I've noticed that people tend to be a lot > harsher here than what I'm used to, so perhaps your attitude to it is > more common on mailing-lists and I should just adapt. A Mulla Nasruddin story comes to mind: The judge in a village court had gone on vacation. Nasrudin was asked to be temporary judge for a day. Mulla sat on the Judge's chair and ordered the first case to be brought up for hearing. "You are right," said Nasrudin after carefully hearing one side. "You are right," he said after carefully hearing the other side. "But both cannot be right!" said the court clerk bewildered. After profound thought said the Mulla: "You are right" From rosuav at gmail.com Fri Sep 30 03:52:42 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 17:52:42 +1000 Subject: Benefit and belief In-Reply-To: <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 5:24 PM, rusi wrote: > "You are right," said Nasrudin after carefully hearing one side. > "You are right," he said after carefully hearing the other side. > "But both cannot be right!" said the court clerk bewildered. > After profound thought said the Mulla: > > ?"You are right" > And I am right, and you are right, and all is right as right can be! -- Pish-Tush, a Japanese nobleman in service of /The Mikado/ Chris Angelico From rosuav at gmail.com Fri Sep 30 03:57:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 17:57:12 +1000 Subject: Motion Tracking with Python In-Reply-To: References: <4E852694.4080303@simkowiak.net> Message-ID: On Fri, Sep 30, 2011 at 4:39 PM, alex23 wrote: >> or writing a MS Word virus in Python... > > Now that's just crazy talk. > ... and I thought all three were. You know what they say - truth is stranger than fiction, because fiction has to make sense! Although the device driver example you cite is still ring-3 code, and the Linux kernel is still in C. I like the idea of a special OS written in Python though; it wouldn't be Linux, but it could well be an excellent embedded-device OS. It'd probably end up having to reinvent all sorts of facilities like process isolation and such, though. ChrisA From ovidiudeac at gmail.com Fri Sep 30 05:10:48 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:10:48 +0300 Subject: regexp compilation error Message-ID: I have the following regexp which fails to compile. Can somebody explain why? >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat Is this a bug or a feature? Thanks, Ovidiu From moky.math at gmail.com Fri Sep 30 05:13:14 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 30 Sep 2011 11:13:14 +0200 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E85882A.6010602@gmail.com> > The keys of globals() are the _names_. You're giving it the function > itself. Ow, ok. I didn't caught it. I understand now. > A decorator would be better. Yes. I keep the solution with foo=Wraper(foo) Thanks a lot all ! Laurent From moky.math at gmail.com Fri Sep 30 05:13:14 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 30 Sep 2011 11:13:14 +0200 Subject: Counting the number of call of a function In-Reply-To: References: Message-ID: <4E85882A.6010602@gmail.com> > The keys of globals() are the _names_. You're giving it the function > itself. Ow, ok. I didn't caught it. I understand now. > A decorator would be better. Yes. I keep the solution with foo=Wraper(foo) Thanks a lot all ! Laurent From rosuav at gmail.com Fri Sep 30 05:18:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 19:18:43 +1000 Subject: regexp compilation error In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 7:10 PM, Ovidiu Deac wrote: > I have the following regexp which fails to compile. Can somebody explain why? > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.6/re.py", line 190, in compile > ? ?return _compile(pattern, flags) > ?File "/usr/lib/python2.6/re.py", line 245, in _compile > ? ?raise error, v # invalid expression > sre_constants.error: nothing to repeat > > Is this a bug or a feature? What version of Python are you using? It looks like you're running in a Python 3 interpreter, and loading a Python 2 module (as shown by the python2.6 in the path and the Python 2 error-raise syntax). You may have a problem with your module path. Running that line of code in Python 3.2 for Windows produces this error: >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in re.compile(r"""^(?: [^y]* )*""", re.X) File "C:\Python32\lib\re.py", line 206, in compile return _compile(pattern, flags) File "C:\Python32\lib\re.py", line 256, in _compile return _compile_typed(type(pattern), pattern, flags) File "C:\Python32\lib\functools.py", line 180, in wrapper result = user_function(*args, **kwds) File "C:\Python32\lib\re.py", line 268, in _compile_typed return sre_compile.compile(pattern, flags) File "C:\Python32\lib\sre_compile.py", line 495, in compile code = _code(p, flags) File "C:\Python32\lib\sre_compile.py", line 480, in _code _compile(code, p.data, flags) File "C:\Python32\lib\sre_compile.py", line 74, in _compile elif _simple(av) and op is not REPEAT: File "C:\Python32\lib\sre_compile.py", line 359, in _simple raise error("nothing to repeat") sre_constants.error: nothing to repeat Does that help at all? ChrisA From ovidiudeac at gmail.com Fri Sep 30 05:26:52 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:26:52 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: $ python --version Python 2.6.6 On Fri, Sep 30, 2011 at 12:18 PM, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 7:10 PM, Ovidiu Deac wrote: >> I have the following regexp which fails to compile. Can somebody explain why? >> >>>>> re.compile(r"""^(?: [^y]* )*""", re.X) >> Traceback (most recent call last): >> ?File "", line 1, in >> ?File "/usr/lib/python2.6/re.py", line 190, in compile >> ? ?return _compile(pattern, flags) >> ?File "/usr/lib/python2.6/re.py", line 245, in _compile >> ? ?raise error, v # invalid expression >> sre_constants.error: nothing to repeat >> >> Is this a bug or a feature? > > What version of Python are you using? It looks like you're running in > a Python 3 interpreter, and loading a Python 2 module (as shown by the > python2.6 in the path and the Python 2 error-raise syntax). You may > have a problem with your module path. > > Running that line of code in Python 3.2 for Windows produces this error: > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ? ?re.compile(r"""^(?: [^y]* )*""", re.X) > ?File "C:\Python32\lib\re.py", line 206, in compile > ? ?return _compile(pattern, flags) > ?File "C:\Python32\lib\re.py", line 256, in _compile > ? ?return _compile_typed(type(pattern), pattern, flags) > ?File "C:\Python32\lib\functools.py", line 180, in wrapper > ? ?result = user_function(*args, **kwds) > ?File "C:\Python32\lib\re.py", line 268, in _compile_typed > ? ?return sre_compile.compile(pattern, flags) > ?File "C:\Python32\lib\sre_compile.py", line 495, in compile > ? ?code = _code(p, flags) > ?File "C:\Python32\lib\sre_compile.py", line 480, in _code > ? ?_compile(code, p.data, flags) > ?File "C:\Python32\lib\sre_compile.py", line 74, in _compile > ? ?elif _simple(av) and op is not REPEAT: > ?File "C:\Python32\lib\sre_compile.py", line 359, in _simple > ? ?raise error("nothing to repeat") > sre_constants.error: nothing to repeat > > Does that help at all? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From rosuav at gmail.com Fri Sep 30 05:29:50 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 30 Sep 2011 19:29:50 +1000 Subject: regexp compilation error In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: > $ python --version > Python 2.6.6 Ah, I think I was misinterpreting the traceback. You do actually have a useful message there; it's the same error that my Py3.2 produced: sre_constants.error: nothing to repeat I'm not sure what your regex is trying to do, but the problem seems to be connected with the * at the end of the pattern. ChrisA From 1248283536 at qq.com Fri Sep 30 05:35:37 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 30 Sep 2011 17:35:37 +0800 Subject: =?gbk?B?u9i4tKO6IGhvdyB0byBydW4gaW4geHA/?= Message-ID: the command : 2to3-3.2 getcode3.py -w can run in linux it can't run in window xp,can i make it in window xp? ------------------ ???? ------------------ ???: "1248283536"<1248283536 at qq.com>; ????: 2011?9?28?(???) ??7:50 ???: "Peter Otten"<__peter__ at web.de>; "python-list"; ??: Re: how to run in xp? it can run ,but there is still a problem ,nothing in my file. please run the code in xp+python32 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() print (file) what you get is: >>> b'' b'' b'' >>> how to fix it? ------------------ Original ------------------ From: "Peter Otten"<__peter__ at web.de>; Date: Wed, Sep 28, 2011 04:04 PM To: "python-list"; Subject: Re: how to run in xp? =?gbk?B?ytjW6rT9zcM=?= wrote: > #coding:utf-8 > import urllib > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies- \ > by-industry.aspx?exchange='+down+'&render=download' > file=urllib.urlopen(url).read() myfile.write(file) > print ('ok',down) > myfile.close() > > it can run in ubuntu+python2.6 ,when it run in window xp+python32,the > output is Traceback (most recent call last): > File "C:\Python32\getcode.py", line 8, in > file=urllib.urlopen(url).read() > AttributeError: 'module' object has no attribute 'urlopen' > > i change it into: > #coding:utf-8 > import urllib.request > exchange=['NASDAQ','NYSE','AMEX'] > for down in exchange: > myfile=open('./'+down,'w') > url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' > file=urllib.request.urlopen(url).read() > myfile.write(file) > print ('ok',down) > myfile.close() > > the output is : > Traceback (most recent call last): > File "C:\Python32\getcode.py", line 9, in > myfile.write(file) > TypeError: must be str, not bytes > > how to make it run in xp+python32? The problem here is the switch from Python 2 to 3. Python 3 has some backwards-incompatible Syntax changes along with changes to classes and library organisation. The good news is that there's a tool, 2to3, that can handle most of these changes: $ cat getcode.py #coding:utf-8 import urllib exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.urlopen(url).read() myfile.write(file) print 'ok', down myfile.close() $ cp getcode.py getcode3.py $ 2to3-3.2 getcode3.py -w RefactoringTool: Skipping implicit fixer: buffer RefactoringTool: Skipping implicit fixer: idioms RefactoringTool: Skipping implicit fixer: set_literal RefactoringTool: Skipping implicit fixer: ws_comma RefactoringTool: Refactored getcode3.py --- getcode3.py (original) +++ getcode3.py (refactored) @@ -1,10 +1,10 @@ #coding:utf-8 -import urllib +import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' - file=urllib.urlopen(url).read() + file=urllib.request.urlopen(url).read() myfile.write(file) - print 'ok', down + print('ok', down) myfile.close() RefactoringTool: Files that were modified: RefactoringTool: getcode3.py $ cat getcode3.py #coding:utf-8 import urllib.request, urllib.parse, urllib.error exchange=['NASDAQ','NYSE','AMEX'] for down in exchange: myfile=open('./'+down,'wb') url='http://www.nasdaq.com/screening/companies-by- industry.aspx?exchange='+down+'&render=download' file=urllib.request.urlopen(url).read() myfile.write(file) print('ok', down) myfile.close() $ python3.2 getcode3.py ok NASDAQ ok NYSE ok AMEX -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ovidiudeac at gmail.com Fri Sep 30 05:57:25 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Fri, 30 Sep 2011 12:57:25 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: This is only part of a regex taken from an old perl application which we are trying to understand/port to our new Python implementation. The original regex was considerably more complex and it didn't compile in python so I removed all the parts I could in order to isolate the problem such that I can ask help here. So the problem is that this regex doesn't compile. On the other hand I'm not really sure it should. It's an anchor on which you apply *. I'm not sure if this is legal. On the other hand if I remove one of the * it compiles. >>> re.compile(r"""^(?: [^y]* )*""", re.X) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat >>> re.compile(r"""^(?: [^y] )*""", re.X) <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>> re.compile(r"""^(?: [^y]* )""", re.X) <_sre.SRE_Pattern object at 0x7f4069cc3730> Is this a bug in python regex engine? Or maybe some incompatibility with Perl? On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >> $ python --version >> Python 2.6.6 > > Ah, I think I was misinterpreting the traceback. You do actually have > a useful message there; it's the same error that my Py3.2 produced: > > sre_constants.error: nothing to repeat > > I'm not sure what your regex is trying to do, but the problem seems to > be connected with the * at the end of the pattern. > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Fri Sep 30 08:06:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 30 Sep 2011 22:06:43 +1000 Subject: regexp compilation error References: Message-ID: <4e85b0d3$0$29975$c3e8da3$5496439d@news.astraweb.com> Ovidiu Deac wrote: >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.6/re.py", line 190, in compile > return _compile(pattern, flags) > File "/usr/lib/python2.6/re.py", line 245, in _compile > raise error, v # invalid expression > sre_constants.error: nothing to repeat >>>> re.compile(r"""^(?: [^y] )*""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>> re.compile(r"""^(?: [^y]* )""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc3730> > > Is this a bug in python regex engine? Or maybe some incompatibility with > Perl? Before asking whether it is a bug, perhaps you should consider what (if anything) that regex is supposed to actually do. Perhaps you should post the Perl equivalent, and some examples of it in use. -- Steven From hansmu at xs4all.nl Fri Sep 30 08:12:12 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 30 Sep 2011 14:12:12 +0200 Subject: regexp compilation error In-Reply-To: References: Message-ID: <4e85b21c$0$2444$e4fe514c@news2.news.xs4all.nl> On 30/09/11 11:10:48, Ovidiu Deac wrote: > I have the following regexp which fails to compile. Can somebody explain why? > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) [...] > sre_constants.error: nothing to repeat > > Is this a bug or a feature? A feature: the message explains why this pattern is not allowed. The sub-pattern (?: [^y]* ) matches zero or more non-'y's, so it potentially matches the empty string. It you were allowed to apply '*' to such a sub-pattern, the matcher could go into an infinite loop, finding billions of matching empty strings, one after the other. I'm not sure what you are trying to match, but for zero-or-more not-'y's, you could write r"^[^y]*". This is guaranteed to always match, since there are always at least zero of them. You might as well write r"^", that is also guaranteed to always match. What are you trying to achieve? -- HansM From neilc at norwich.edu Fri Sep 30 08:15:33 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 12:15:33 GMT Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <73379d6f-7a22-4906-874c-0d87a861a4b8@j10g2000vbb.googlegroups.com> Message-ID: <9elq75Fh5cU1@mid.individual.net> On 2011-09-30, Chris Angelico wrote: > On Fri, Sep 30, 2011 at 5:24 PM, rusi wrote: >> "You are right," said Nasrudin after carefully hearing one side. >> "You are right," he said after carefully hearing the other side. >> "But both cannot be right!" said the court clerk bewildered. >> After profound thought said the Mulla: >> >> ?"You are right" >> > > And I am right, and you are right, and all is right as right can be! > -- Pish-Tush, a Japanese nobleman in service of /The Mikado/ Never has being right, proper and correct been so thoroughly celebrated. Except perhaps when my C++ program compiles without warnings. That's pretty good, too. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From 1248283536 at qq.com Fri Sep 30 08:36:57 2011 From: 1248283536 at qq.com (=?gbk?B?ytjW6rT9zcM=?=) Date: Fri, 30 Sep 2011 20:36:57 +0800 Subject: parse xml Message-ID: please click the http://www.secinfo.com/d14qfp.q9j.htm then ,click the following: 44: XML IDEA: Condensed Consolidating Statements of Income XML 5.11M (Details)--R158 there is the citigroup's annual financial report --statements of income,xml file. how can i get a table of statements of income in python ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Fri Sep 30 08:40:33 2011 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Fri, 30 Sep 2011 08:40:33 -0400 Subject: [OT] Benefit and belief In-Reply-To: <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4e853310$0$29996$c3e8da3$5496439d@news.astraweb.com> Message-ID: > If you are more upset at my describing the Catholic Church as protecting > child molesters than you are at the Church for actually protecting child > molesters I'm not, and your rhetoric is ridiculous. Devin On Thu, Sep 29, 2011 at 11:10 PM, Steven D'Aprano wrote: > Devin Jeanpierre wrote: > >> I also didn't reprimand anyone, except maybe Steven. > > If you are more upset at my describing the Catholic Church as protecting > child molesters than you are at the Church for actually protecting child > molesters, then your priorities are completely screwed up and your > reprimand means less than nothing to me. I wear it as a badge of honour. > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From rantingrick at gmail.com Fri Sep 30 09:54:25 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 06:54:25 -0700 (PDT) Subject: Suggested coding style References: Message-ID: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Note: I am quoting "Passiday" to get this thread back on subject however my reply is for "alex23" the philosopher" On Sep 29, 9:50?pm, alex23 wrote: > On Sep 29, 10:23?pm, rantingrick wrote: > > > What is so bad about breaking code in obscure places? > > Try coding in PHP across minor release versions and see how you feel > about deprecating core functions on a whim. I never said we should remove it now, i said we should deprecate it now. > > We changed print > > to a function which broke just about every piece of code every written > > in this language. > > In a well declared _break_ with backwards compatibility. Not on a whim > between minor releases. Please Google deprecate. > > What is so bad then about breaking some very obscure code? > > Because while you say "some very obscure code", what you really mean > is "code that isn't mine". Well "alex" i can't see a mob approaching with pitchforks because we deprecate a misplaced and rarely used functionality of the stdlib. > As you have no access > to the inner states of _any_ of the people you regularly condemn here > with your hypocritical attacks, I've no idea why you consider yourself > to be an expert on their desires and opinions. Well "alex", like yourself, i hold expertise in many fields BESIDES programming. One of which being psychology. From vlastimil.brom at gmail.com Fri Sep 30 09:56:20 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 30 Sep 2011 15:56:20 +0200 Subject: regexp compilation error In-Reply-To: References: Message-ID: 2011/9/30 Ovidiu Deac : > This is only part of a regex taken from an old perl application which > we are trying to understand/port to our new Python implementation. > > The original regex was considerably more complex and it didn't compile > in python so I removed all the parts I could in order to isolate the > problem such that I can ask help here. > > So the problem is that this regex doesn't compile. On the other hand > I'm not really sure it should. It's an anchor on which you apply *. > I'm not sure if this is legal. > > On the other hand if I remove one of the * it compiles. > >>>> re.compile(r"""^(?: [^y]* )*""", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.6/re.py", line 190, in compile > ? ?return _compile(pattern, flags) > ?File "/usr/lib/python2.6/re.py", line 245, in _compile > ? ?raise error, v # invalid expression > sre_constants.error: nothing to repeat >>>> re.compile(r"""^(?: [^y] )*""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>> re.compile(r"""^(?: [^y]* )""", re.X) > <_sre.SRE_Pattern object at 0x7f4069cc3730> > > Is this a bug in python regex engine? Or maybe some incompatibility with Perl? > > On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: >> On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >>> $ python --version >>> Python 2.6.6 >> >> Ah, I think I was misinterpreting the traceback. You do actually have >> a useful message there; it's the same error that my Py3.2 produced: >> >> sre_constants.error: nothing to repeat >> >> I'm not sure what your regex is trying to do, but the problem seems to >> be connected with the * at the end of the pattern. >> >> ChrisA >> -- I believe, this is a limitation of the builtin re engine concerning nested infinite quantifiers - (...*)* - in your pattern. You can try a more powerful recent regex implementation, which appears to handle it: http://pypi.python.org/pypi/regex using the VERBOSE flag - re.X all (unescaped) whitespace outside of character classes is ignored, http://docs.python.org/library/re.html#re.VERBOSE the pattern should be equivalent to: r"^(?:[^y]*)*" ie. you are not actually gaining anything with double quantifier, as there isn't anything "real" in the pattern outside [^y]* It appears, that you have oversimplified the pattern (if it had worked in the original app), however, you may simply try with import regex as re and see, if it helps. Cf: >>> >>> regex.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) ['a bcd e'] >>> re.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) Traceback (most recent call last): File "", line 1, in File "re.pyc", line 177, in findall File "re.pyc", line 244, in _compile error: nothing to repeat >>> >>> re.findall(r"^(?:[^y]*)*", "a bcd e") Traceback (most recent call last): File "", line 1, in File "re.pyc", line 177, in findall File "re.pyc", line 244, in _compile error: nothing to repeat >>> regex.findall(r"^(?:[^y]*)*", "a bcd e") ['a bcd e'] >>> regex.findall(r"^[^y]*", "a bcd e") ['a bcd e'] >>> hth, vbr From devplayer at gmail.com Fri Sep 30 09:57:17 2011 From: devplayer at gmail.com (DevPlayer) Date: Fri, 30 Sep 2011 06:57:17 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <87mxdn2fwl.fsf@benfinney.id.au> Message-ID: <60c608a5-5f56-4949-806f-f68ff2510fb0@j1g2000yqj.googlegroups.com> from attitude import humour Funny. url link to gif. Funny. Youtube video. Funny. True Pythonees do not speak in English they speak in Python. Shame, this discussion will be sent to the Pearly gates or the Flaming Iron Bars in 5 days. Well, not so much a shame. From rantingrick at gmail.com Fri Sep 30 09:58:36 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 06:58:36 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> Message-ID: <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> On Sep 29, 10:05?pm, alex23 wrote: > On Sep 30, 9:37?am, MRAB wrote: > > alex23: > > """And like the Bible, the Zen was created by humans as a joke. If you're > > taking it too seriously, that's your problem.""" > > Strangely, calling the bible self-contradictory wasn't seen as > inflammatory... For the same reason that telling the truth is not slander. The fact is that the Bible IS contradictory with itself. However, your opinion unlike my facts, were full of vile hatred. Nice try attempting to shift the mob against me. From rick.mansilla at gmail.com Fri Sep 30 10:06:42 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Fri, 30 Sep 2011 09:06:42 -0500 Subject: Motion Tracking with Python In-Reply-To: <4E852694.4080303@simkowiak.net> References: <4E852694.4080303@simkowiak.net> Message-ID: <201109300906.43128.rick.mansilla@gmail.com> On Thursday 29 September 2011 21:16:52 you wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion > tracking, using the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this > project. We used it to track her two pet gerbils, as part of her science > fair project. She wrote her own (separate) Python script to read the > motion tracking log files, compute distance and velocity, and then > export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for > teaching kids how to program." > > I also use Python professionally, and it's worked out great every time. > There's no job Python can't handle. > > > Thanks, > Derek Simkowiak > http://derek.simkowiak.net Hi, this is awesome!! I'm currently working in something similar, but I am having problems with getting data from the CCD (basically i don't know how to do it :), can you give me a tip for doing this? Or explain how you did it please? I not a newbie at python but not as experienced as evidently you are. Thanks a lot in advance. -- (...)Also, since that same law states that any system able to prove its consistency to itself must be inconsistent; any mind that believes it can prove its own sanity is, therefore, insane.(...) Kurt G?del. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Fri Sep 30 10:19:20 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 07:19:20 -0700 (PDT) Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <1139d178-3a74-4234-b458-4005ca426750@i28g2000yqn.googlegroups.com> Message-ID: <7d5a7284-6f73-42f7-9386-14cb5e6e69b2@z8g2000yqb.googlegroups.com> On Sep 29, 11:49?pm, Ian Kelly wrote: > Nope, that doesn't work. > > >>> "{0:0>10}".format("-1234") > > '00000-1234' > > The whole point of zfill is that it handles signs correctly. py> "{0:-010d}".format(-1234) '-000001234' My point was: Use the {char}{repeat}d format for integers and the {char}{<|>|=}{repeat} for strings. Problem solved. No more need for zfill. py> "{0:0>10}".format(-1234) '00000-1234' What result would you expect from that string argument? I think it behaves as anyone would expect. If you have a str and you want it interpreted as a negative integer then cast it. py> "{0:010d}".format(int("-1234")) '-000001234' If you would like for the spec to handle the case of integers and strings transparently then you need to lobby to have the API changed. Maybe they could add a !i like the !s and !r which would be explicit. However, i don't think implicit coercion of strings to integers is a good idea. Using the int function or !i removes and ambiguities. For me, the spec works just fine as is. From rosuav at gmail.com Fri Sep 30 10:43:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 00:43:15 +1000 Subject: Suggested coding style In-Reply-To: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: On Fri, Sep 30, 2011 at 11:54 PM, rantingrick wrote: > Well "alex", like yourself, i hold expertise in many fields BESIDES > programming. One of which being psychology. > I *knew* it! We're all part of a huge experiment to see how much the human psyche can withstand. If we succeed on the Rick test, do we "level up" and get a second troll to deal with, or is this MST3K-style eternity? ChrisA From devplayer at gmail.com Fri Sep 30 10:59:27 2011 From: devplayer at gmail.com (DevPlayer) Date: Fri, 30 Sep 2011 07:59:27 -0700 (PDT) Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: I still assert that contradiction is caused by narrow perspective. By that I mean: just because an objects scope may not see a certain condition, doesn't mean that condition is non-existant. I also propose that just because something seems to contradict doesn't mean it is false. Take for instance: Look out your window. Is it daylight or night time? You may say it is daylight or you may say it is night time. I would disagree that only one of those conditions are true. Both conditions are true. Always. It is only day (or night) for YOU. But the opposite DOES in fact exist on the other side of the world at the same time. I call this Duality of Nature (and I believe there was some religion somewhere in some time that has the same notion, Budism I think but I could be mistaken). I see such "contradictions" in what appears to be most truths. If I am correct; not sure here; but I think that is part of the new math Choas theory. (The notion that not all variables are known and the results of well defined functions may result in completely different actual outcomes) [Missing variables in such data sets and functions, to me is basically a narrow(er) perspective of the all the revelent factors for such computations.] You could think of this in terms of classes and attributes if you want. Just because an object does not see an attribute, like "has_ connection", doesn't mean the app doesn't have a connection to the server, just that that object doesn't have access to the existance of that attribute, because it is not in scope (ie narrow perspective). I propose that if something seems to contradict itself, that that doesnt' invalidate its value outright. It -could- invalidate its value, but doesn't guarentee no value. How this matters to coding style? No connection visible. It's just a proposed notion. From breamoreboy at yahoo.co.uk Fri Sep 30 11:51:37 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 30 Sep 2011 08:51:37 -0700 (PDT) Subject: Installing Python 2.6.7 on Windows References: <52b1c0e2-7b6b-4623-bc70-040a792bc7dc@k6g2000yql.googlegroups.com> <42e816bf-c433-472a-b21e-229bd092c57a@n12g2000yqh.googlegroups.com> <1e8d7957-3462-4f00-bae5-09989e4d9ad7@i30g2000yqd.googlegroups.com> <4e82a1a1$0$29965$c3e8da3$5496439d@news.astraweb.com> <42df7e77-44ab-405e-9c60-8f394e3e5628@d17g2000yqa.googlegroups.com> Message-ID: <9b034444-a387-4f73-9c0c-08c159cd3017@dm9g2000vbb.googlegroups.com> On Sep 29, 2:59?am, rantingrick wrote: > On Sep 27, 11:25?pm, Steven D'Aprano > +comp.lang.pyt... at pearwood.info> wrote: > > The Python development team is relatively small and chronically busy: too > > much to do and not enough time to do it. > > If that is the case then why do they snub their noses at anyone who > wishes to help? What kind of people would chase off good help just to > save ego? I imagine the folks at py dev sort of like a dying man in > need of a heart transplant; the man informs the doctor that he would > happy to get a transplant but not if the heart came from a jew, asian, > african, latin, russian, or canuck. For the uninitiated, rr is to Python what King Herod was to baby sitting. (With apologies to Tommy Docherty) From neilc at norwich.edu Fri Sep 30 11:58:24 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 15:58:24 GMT Subject: Benefit and belief References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <9em790Fnj9U1@mid.individual.net> On 2011-09-30, DevPlayer wrote: > I still assert that contradiction is caused by narrow perspective. > > By that I mean: just because an objects scope may not see a certain > condition, doesn't mean that condition is non-existant. > > I also propose that just because something seems to contradict doesn't > mean it is false. Take for instance: > > Look out your window. Is it daylight or night time? You may say > it is daylight or you may say it is night time. I would > disagree that only one of those conditions are true. Both > conditions are true. Always. It is only day (or night) for YOU. > But the opposite DOES in fact exist on the other side of the > world at the same time. > > I call this Duality of Nature (and I believe there was some > religion somewhere in some time that has the same notion, > Budism I think but I could be mistaken). I see such > "contradictions" in what appears to be most truths. You are not alone. Many ancient philosophers, fathers of religious and scientific thought, thought the same. They thought that contradictory qualities could exist in objects simultaneously. For example, they thought that a cat was both big and small, because it was big compared to a mouse and small compared to a house. They didn't notice that big and small were not poperties of the cat, at all but were instead statements about how a cat relates to another object. When you say, "It is night," you are making an assertion about a position on the surface of the earth and its relationship to the sun. If you are not discussing a specific a position on the Earth, then you cannot make a meaningful assertion about night or day at all. Night and Day are not qualities of the entire Earth, but only of positions on the Earth. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From ramit.prasad at jpmorgan.com Fri Sep 30 12:06:19 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 12:06:19 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> >May I suggest a[n] email client that can group mailing list threads? Please do. Bonus points if it handles threading in a Gmail-like style. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Devin Jeanpierre Sent: Thursday, September 29, 2011 6:07 PM To: rantingrick Cc: python-list at python.org Subject: Re: Suggested coding style > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) Yeah. It's a much more difficult to read thing, but once you learn how to write it it flows faster. Of course, I never managed to learn how to write it... I would suggest that rather than being "complicated" it is "dense". > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. Devin On Thu, Sep 29, 2011 at 6:56 PM, rantingrick wrote: > On Sep 29, 5:12?pm, Ian Kelly wrote: >> On Thu, Sep 29, 2011 at 6:23 AM, rantingrick wrote: >> > A specific method for padding a string with ONLY zeros is ludicrous >> > and exposes the narrow mindedness of the creator. The only thing worse >> > than "zfill" as a string method is making zfill into built-in >> > function! The ONLY proper place for zfill is as an option in the >> > str.format() method. >> >> > py> "{0:zf10}".format(1234) -> "00000000001234" >> >> Agree that zfill seems to be redundant with str.format, although your >> suggested syntax is atrocious, especially since a syntax already >> exists that fits better in the already-complicated format specifier >> syntax. > > It's interesting that you find the format specifier "complicated". I > will admit that upon first glance i lamented the new format method > spec and attempted to cling to the old string interpolation crap. > However, as you use the new format method you will come to appreciate > it. It's an adult beverage with an acquired taste. ;-) > > One thing that may help format noobs is to look at the spec as two > parts; the part before the colon and the part after the colon. If you > break it down in this manner the meaning starts to shine through. I > will agree, it is a lot of cryptic info squeezed into a small space > HOWEVER you would no want a verbose format specification. > > But i wholeheartedly agree with you points and i would say the zfill > method has no future uses in the stdlib except for historical reasons. > We should deprecate it now. > > >> "{0:=010d}".format(1234) -> "0000001234" >> >> There are a couple of warts with the existing implementation, however: >> >> 1) str.zfill() operates on strings; the .format() syntax operates on >> numeric types. ?I would suggest that the "=" fill alignment in format >> specifiers should be extended to do the same thing as zfill when given >> a string. > > EXACTLY! > > PS: Has anyone noticed all the off topic chatter about religion and > feelings? Since the main subject of this thread is about zfill i can't > help but wonder if the minions where sent out to present a distraction > with "scripted" pseudo arguments. Just an observation. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rustompmody at gmail.com Fri Sep 30 12:22:59 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 09:22:59 -0700 (PDT) Subject: Benefit and belief References: <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> Message-ID: <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> On Sep 30, 8:58?pm, Neil Cerutti wrote: > On 2011-09-30, DevPlayer wrote: > > > > > I still assert that contradiction is caused by narrow perspective. > > > By that I mean: just because an objects scope may not see a certain > > condition, doesn't mean that condition is non-existant. > > > I also propose that just because something seems to contradict doesn't > > mean it is false. Take for instance: > > > Look out your window. Is it daylight or night time? You may say > > it is daylight or you may say it is night time. I would > > disagree that only one of those conditions are true. Both > > conditions are true. Always. It is only day (or night) for YOU. > > But the opposite DOES in fact exist on the other side of the > > world at the same time. > > > I call this Duality of Nature (and I believe there was some > > religion somewhere in some time that has the same notion, > > Budism I think but I could be mistaken). I see such > > "contradictions" in what appears to be most truths. > > You are not alone. Many ancient philosophers, fathers of > religious and scientific thought, thought the same. > > They thought that contradictory qualities could exist in objects > simultaneously. For example, they thought that a cat was both big > and small, because it was big compared to a mouse and small > compared to a house. They didn't notice that big and small were > not poperties of the cat, at all but were instead statements > about how a cat relates to another object. > > When you say, "It is night," you are making an assertion about a > position on the surface of the earth and its relationship to the > sun. > > If you are not discussing a specific a position on the Earth, > then you cannot make a meaningful assertion about night or day at > all. Night and Day are not qualities of the entire Earth, but > only of positions on the Earth. But just imagine that we were all pre-galiliean savages -- knowing nothing about the roundness of the earth, the earth going round and so on and somehow you and I get on the phone and we start arguing: Rusi: Its 9:30 pm Neil: No its 12 noon How many cases are there? We both may be right, I may be wrong (my watch may have stopped) or we both etc ie conflicting data may get resolved within a larger world view (which is what devplayer is probably saying). Until then it is wiser to assume that that larger world view exists (and I dont yet know it) than to assume that since I dont know it it does not exist. For me (admittedly an oriental) such agnosticism (literally "I-do-not- know-ness") is as much a foundation for true religiosity as effective science. From anikom15 at gmail.com Fri Sep 30 12:36:38 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 30 Sep 2011 09:36:38 -0700 Subject: Benefit and belief In-Reply-To: <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: <20110930163638.GA13519@Smoke> On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > On Sep 30, 8:58?pm, Neil Cerutti wrote: > > On 2011-09-30, DevPlayer wrote: > > > > > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > By that I mean: just because an objects scope may not see a certain > > > condition, doesn't mean that condition is non-existant. > > > > > I also propose that just because something seems to contradict doesn't > > > mean it is false. Take for instance: > > > > > Look out your window. Is it daylight or night time? You may say > > > it is daylight or you may say it is night time. I would > > > disagree that only one of those conditions are true. Both > > > conditions are true. Always. It is only day (or night) for YOU. > > > But the opposite DOES in fact exist on the other side of the > > > world at the same time. > > > > > I call this Duality of Nature (and I believe there was some > > > religion somewhere in some time that has the same notion, > > > Budism I think but I could be mistaken). I see such > > > "contradictions" in what appears to be most truths. > > > > You are not alone. Many ancient philosophers, fathers of > > religious and scientific thought, thought the same. > > > > They thought that contradictory qualities could exist in objects > > simultaneously. For example, they thought that a cat was both big > > and small, because it was big compared to a mouse and small > > compared to a house. They didn't notice that big and small were > > not poperties of the cat, at all but were instead statements > > about how a cat relates to another object. > > > > When you say, "It is night," you are making an assertion about a > > position on the surface of the earth and its relationship to the > > sun. > > > > If you are not discussing a specific a position on the Earth, > > then you cannot make a meaningful assertion about night or day at > > all. Night and Day are not qualities of the entire Earth, but > > only of positions on the Earth. > > But just imagine that we were all pre-galiliean savages -- knowing > nothing about the roundness of the earth, the earth going round and so > on and somehow you and I get on the phone and we start arguing: > Rusi: Its 9:30 pm > Neil: No its 12 noon > > How many cases are there? > We both may be right, I may be wrong (my watch may have stopped) or we > both etc > > ie conflicting data may get resolved within a larger world view (which > is what devplayer is probably saying). > > Until then it is wiser to assume that that larger world view exists > (and I dont yet know it) > than to assume that since I dont know it it does not exist. > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > know-ness") is as much a foundation for true religiosity as effective > science I.e. humility? From irmen.NOSPAM at xs4all.nl Fri Sep 30 12:40:32 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 30 Sep 2011 18:40:32 +0200 Subject: Motion Tracking with Python In-Reply-To: References: Message-ID: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> On 30-9-2011 4:16, Derek Simkowiak wrote: > Hello, > I have a neat Python project I'd like to share. It does real-time motion tracking, using > the Python bindings to the OpenCV library: > > http://derek.simkowiak.net/motion-tracking-with-python/ > > There is a YouTube video showing the script in action. > > It's especially neat because my daughter and I worked together on this project. We used > it to track her two pet gerbils, as part of her science fair project. She wrote her own > (separate) Python script to read the motion tracking log files, compute distance and > velocity, and then export those values in a CSV file. Like I say on the web page: "I?m > convinced that Python is the best language currently available for teaching kids how to > program." Wow. Very impressive and very enjoyable to read about it. How was her project received at school? Thanks a lot for sharing this. Irmen de Jong From ladasky at my-deja.com Fri Sep 30 12:40:46 2011 From: ladasky at my-deja.com (John Ladasky) Date: Fri, 30 Sep 2011 09:40:46 -0700 (PDT) Subject: Simplest way to resize an image-like array Message-ID: Hi folks, I have 500 x 500 arrays of floats, representing 2D "grayscale" images, that I need to resample at a lower spatial resolution, say, 120 x 120 (details to follow, if you feel they are relevant). I've got the numpy, and scipy, and matplotlib. All of these packages hint at the fact that they have the capability to resample an image- like array. But after reading the documentation for all of these packages, none of them make it straightforward, which surprises me. For example, there are several spline and interpolation methods in scipy.interpolate. They seem to return interpolator classes rather than arrays. Is there no simple method which then calls the interpolator, and builds the resampled array? Yes, I can do this myself if I must -- but over the years, I've come to learn that a lot of the code I want is already written, and that sometimes I just have to know where to look for it. Thanks! From rosuav at gmail.com Fri Sep 30 12:41:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 02:41:30 +1000 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: > ? ? ? ?And I would argue that by starting with "Look out your window..." > you have explicitly excluded the rest of the world from consideration in > answering; you have narrowed the focus to only the region visible from > "my window". > But what if I'm a great windowing magnate, owning windows all over the world? (Is anyone else amused by this thread and its ridiculosity?) ChrisA From rustompmody at gmail.com Fri Sep 30 12:49:21 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 30 Sep 2011 09:49:21 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: On Sep 30, 9:41?pm, Chris Angelico wrote: > On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: > > > ? ? ? ?And I would argue that by starting with "Look out your window..." > > you have explicitly excluded the rest of the world from consideration in > > answering; you have narrowed the focus to only the region visible from > > "my window". > > But what if I'm a great windowing magnate, owning windows all over the world? > > (Is anyone else amused by this thread and its ridiculosity?) > > ChrisA Not more ridiculous than people getting religious over not just about silly (man-made) languages but even over the editors they use From ramit.prasad at jpmorgan.com Fri Sep 30 12:56:46 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 12:56:46 -0400 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <4E847A8F.3070401@mrabarnett.plus.com> <4e852b8a$0$29979$c3e8da3$5496439d@news.astraweb.com> <4e853541$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677B6@EMARC112VS01.exchad.jpmchase.net> >I didn't say it would be on-topic. But we don't cease to be well-rounded >human beings with concerns beyond the narrow world of Python programming >just because we are writing on a programming forum. Everything is on topic to programmers! To (mis)quote Sheldon Cooper: "I'm a [programmer]. I have a working knowledge of the entire universe and everything it contains." Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rosuav at gmail.com Fri Sep 30 12:59:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 02:59:31 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Sat, Oct 1, 2011 at 2:06 AM, Prasad, Ramit wrote: >>May I suggest a[n] email client that can group mailing list threads? > > Please do. Bonus points if it handles threading in a Gmail-like style. > May I suggest Gmail? It handles threading in a very Gmail-like style. ChrisA running and ducking From ramit.prasad at jpmorgan.com Fri Sep 30 13:05:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:05:27 -0400 Subject: Suggested coding style In-Reply-To: References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> >> Please do. Bonus points if it handles threading in a Gmail-like style. >> > >May I suggest Gmail? It handles threading in a very Gmail-like style. Curses, foiled by my lack of specificity! I meant desktop client. Although...if another website does similar threading it would be good to know. Never know when I will want to start avoiding Gmail :) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ethan at stoneleaf.us Fri Sep 30 13:10:32 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 30 Sep 2011 10:10:32 -0700 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <4E85F808.9040100@stoneleaf.us> rusi wrote: > On Sep 30, 9:41 pm, Chris Angelico wrote: >> On Sat, Oct 1, 2011 at 2:38 AM, Dennis Lee Bieber wrote: >> >>> And I would argue that by starting with "Look out your window..." >>> you have explicitly excluded the rest of the world from consideration in >>> answering; you have narrowed the focus to only the region visible from >>> "my window". >> But what if I'm a great windowing magnate, owning windows all over the world? >> >> (Is anyone else amused by this thread and its ridiculosity?) >> >> ChrisA > > Not more ridiculous than people getting religious over not just about > silly (man-made) languages but even over the editors they use No kidding! Vim is *obviously* the best one out there! *ducks and runs* ~Ethan~ From paul.nospam at rudin.co.uk Fri Sep 30 13:11:36 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 30 Sep 2011 18:11:36 +0100 Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> Message-ID: <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> "Prasad, Ramit" writes: >>May I suggest a[n] email client that can group mailing list threads? > > Please do. Bonus points if it handles threading in a Gmail-like style. The answer to any news/mail client with feature X type question is normally "gnus" - although I don't know what "Gmail-like style" is. From rosuav at gmail.com Fri Sep 30 13:12:02 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Oct 2011 03:12:02 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Sat, Oct 1, 2011 at 3:05 AM, Prasad, Ramit wrote: > Curses, foiled by my lack of specificity! I meant desktop client. Although...if another website does similar threading it would be good to know. Never know when I will want to start avoiding Gmail :) > Ah, *desktop* client! Hm. I actually can't advise there; since I'm constantly mobile, I use webmail for everything - installed Squirrel Mail and RoundCube on my server for remote access. Neither does threading though afaik; nor does PMMail (which is a desktop client). ChrisA From neilc at norwich.edu Fri Sep 30 13:12:26 2011 From: neilc at norwich.edu (Neil Cerutti) Date: 30 Sep 2011 17:12:26 GMT Subject: Suggested coding style References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <9embjqFb8uU1@mid.individual.net> On 2011-09-30, Paul Rudin wrote: > "Prasad, Ramit" writes: > >>>May I suggest a[n] email client that can group mailing list threads? >> >> Please do. Bonus points if it handles threading in a Gmail-like style. > > The answer to any news/mail client with feature X type question is > normally "gnus" - although I don't know what "Gmail-like style" is. slrn. Is good. -- Neil Cerutti "A politician is an arse upon which everyone has sat except a man." e. e. cummings From alec.taylor6 at gmail.com Fri Sep 30 13:19:20 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 03:19:20 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F67661@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F677EE@EMARC112VS01.exchad.jpmchase.net> Message-ID: Maybe one Apache's Buzz? On 10/1/11, Prasad, Ramit wrote: >>> Please do. Bonus points if it handles threading in a Gmail-like style. >>> >> >>May I suggest Gmail? It handles threading in a very Gmail-like style. > > Curses, foiled by my lack of specificity! I meant desktop client. > Although...if another website does similar threading it would be good to > know. Never know when I will want to start avoiding Gmail :) > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Fri Sep 30 13:26:00 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 03:26:00 +1000 Subject: Suggested coding style In-Reply-To: <9embjqFb8uU1@mid.individual.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> Message-ID: http://incubator.apache.org/wave/ On 10/1/11, Neil Cerutti wrote: > On 2011-09-30, Paul Rudin wrote: >> "Prasad, Ramit" writes: >> >>>>May I suggest a[n] email client that can group mailing list threads? >>> >>> Please do. Bonus points if it handles threading in a Gmail-like style. >> >> The answer to any news/mail client with feature X type question is >> normally "gnus" - although I don't know what "Gmail-like style" is. > > slrn. Is good. > > -- > Neil Cerutti > "A politician is an arse upon which everyone has sat except a man." > e. e. cummings > -- > http://mail.python.org/mailman/listinfo/python-list > From ramit.prasad at jpmorgan.com Fri Sep 30 13:45:21 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:45:21 -0400 Subject: Suggested coding style In-Reply-To: <9embjqFb8uU1@mid.individual.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> >>>>May I suggest a[n] email client that can group mailing list threads? > The answer to any news/mail client with feature X type question is > normally "gnus" - although I don't know what "Gmail-like style" is. Yeah >slrn. Is good. Unless I am missing something, it does not do email. >http://incubator.apache.org/wave/ Are you suggesting I run my own webserver to aggregate emails, stick them in wave, and then write something that will convert my wave post to email? I suppose it could work, but that is *usually* not what is considered a "desktop app". > Maybe one Apache's Buzz? I think you will have to Google that one for me, as the first results I found were Apache Wicket and Apache Beehive...both which seem not related. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Sep 30 13:48:25 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 30 Sep 2011 13:48:25 -0400 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> >> The answer to any news/mail client with feature X type question is >> normally "gnus" - although I don't know what "Gmail-like style" is. >Yeah Gah, I got distracted mid-email and forgot to finish. What I wanted to say was, "Yeah, not knowing what 'Gmail-like style' makes a big difference ;)". Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rantingrick at gmail.com Fri Sep 30 14:08:16 2011 From: rantingrick at gmail.com (rantingrick) Date: Fri, 30 Sep 2011 11:08:16 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: On Sep 30, 11:36?am, Westley Mart?nez wrote: > On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > > On Sep 30, 8:58???pm, Neil Cerutti wrote: > > > On 2011-09-30, DevPlayer wrote: > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > By that I mean: just because an objects scope may not see a certain > > > > condition, doesn't mean that condition is non-existant. > > > > > I also propose that just because something seems to contradict doesn't > > > > mean it is false. Take for instance: > > > > > Look out your window. Is it daylight or night time? You may say > > > > it is daylight or you may say it is night time. I would > > > > disagree that only one of those conditions are true. Both > > > > conditions are true. Always. It is only day (or night) for YOU. > > > > But the opposite DOES in fact exist on the other side of the > > > > world at the same time. > > > > > I call this Duality of Nature (and I believe there was some > > > > religion somewhere in some time that has the same notion, > > > > Budism I think but I could be mistaken). I see such > > > > "contradictions" in what appears to be most truths. > > > > You are not alone. Many ancient philosophers, fathers of > > > religious and scientific thought, thought the same. > > > > They thought that contradictory qualities could exist in objects > > > simultaneously. For example, they thought that a cat was both big > > > and small, because it was big compared to a mouse and small > > > compared to a house. They didn't notice that big and small were > > > not poperties of the cat, at all but were instead statements > > > about how a cat relates to another object. > > > > When you say, "It is night," you are making an assertion about a > > > position on the surface of the earth and its relationship to the > > > sun. > > > > If you are not discussing a specific a position on the Earth, > > > then you cannot make a meaningful assertion about night or day at > > > all. Night and Day are not qualities of the entire Earth, but > > > only of positions on the Earth. > > > But just imagine that we were all pre-galiliean savages -- knowing > > nothing about the roundness of the earth, the earth going round and so > > on and somehow you and I get on the phone and we start arguing: > > Rusi: Its 9:30 pm > > Neil: No its 12 noon > > > How many cases are there? > > We both may be right, I may be wrong (my watch may have stopped) or we > > both etc > > > ie conflicting data may get resolved within a larger world view (which > > is what devplayer is probably saying). > > > Until then it is wiser to assume that that larger world view exists > > (and I dont yet know it) > > than to assume that since I dont know it it does not exist. > > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > > know-ness") is as much a foundation for true religiosity as effective > > science > > I.e. humility? @DevPlayer, rusi, Neil, Wes, and group Yes, there are two views of reality; that of the absolute and that of the relative. Both are true. It is always daytime and nighttime simultaneously; if you look at things from a global perspective. However, the true nature of "daytime vs nighttime" is purely a relative observation. The fact that both exist does not falsify the validity of the relative view. Recognizing the paradox is important and proves you are not confined to your own selfish view points and are in fact an intelligent being. From rbotting at csusb.edu Fri Sep 30 14:34:37 2011 From: rbotting at csusb.edu (RJB) Date: Fri, 30 Sep 2011 11:34:37 -0700 (PDT) Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sep 29, 3:52?am, Steven D'Aprano wrote: > Alain Ketterlin wrote: > > Steven D'Aprano writes: > > >> I have a Python script which I would like to test without a tty attached > >> to the process. I could run it as a cron job, but is there an easier way? > > >> I am running Linux. > > > Isn't os.setsid() what you're looking for? It makes the calling process > > have no controlling terminal. There's also a user command called setsid > > that should have the same effect. > > It doesn't appear so to me. > > [steve at sylar ~]$ tty > /dev/pts/16 > [steve at sylar ~]$ setsid tty > /dev/pts/16 > > [steve at sylar ~]$ python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > [steve at sylar ~]$ setsid python -c "import sys,os; print os.isatty(sys.stdout.fileno())" > True > > If I run the same Python command (without the setsid) as a cron job, I > get False emailed to me. That's the effect I'm looking for. > > -- > Steven You could try the old UNIX "nohup ... &" technique for running a process in the background (the &) with no HangUP if you log out: $ nohup python -c "import sys,os; print os.isatty(sys.stdout.fileno())" & appending output to nohup.out $ cat nohup.out False But that is over kill I guess. One worrying detail.... the definition of a running process in UNIX implies is that it has standard input/output files open. You'd be wise to make sure that they are connected to things that are safe.... /dev/null. Even so /dev/tty can be opened any way... Hope this helps. From derek at simkowiak.net Fri Sep 30 14:42:57 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Fri, 30 Sep 2011 11:42:57 -0700 Subject: Motion Tracking with Python In-Reply-To: <201109300906.43128.rick.mansilla@gmail.com> References: <4E852694.4080303@simkowiak.net> <201109300906.43128.rick.mansilla@gmail.com> Message-ID: <4E860DB1.202@simkowiak.net> > /I am having problems with getting data from the CCD (basically i don't know how to do it :), can you give me a tip for doing this? Or explain how you did it please?/ I am using the OpenCV library to grab images. Here are the specific lines of code: self.capture = cv.CaptureFromCAM(0)cv.SetCaptureProperty( self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, 320 );cv.SetCaptureProperty( self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 240 );frame = cv.QueryFrame(self.capture) # ...this is done repeatedly in the main loop. These were copied from the examples that came with OpenCV. I don't know if this will work under Windows. The source code to my script is available online; I recommend downloading it and playing with it. Also, check out the OpenCV Python documentation. Thanks, Derek On 09/30/2011 07:06 AM, Ricardo Mansilla wrote: > > On Thursday 29 September 2011 21:16:52 you wrote: > > > Hello, > > > I have a neat Python project I'd like to share. It does real-time motion > > > tracking, using the Python bindings to the OpenCV library: > > > > > > http://derek.simkowiak.net/motion-tracking-with-python/ > > > > > > There is a YouTube video showing the script in action. > > > > > > It's especially neat because my daughter and I worked together on this > > > project. We used it to track her two pet gerbils, as part of her science > > > fair project. She wrote her own (separate) Python script to read the > > > motion tracking log files, compute distance and velocity, and then > > > export those values in a CSV file. Like I say on the web page: "I?m > > > convinced that Python is the best language currently available for > > > teaching kids how to program." > > > > > > I also use Python professionally, and it's worked out great every time. > > > There's no job Python can't handle. > > > > > > > > > Thanks, > > > Derek Simkowiak > > > http://derek.simkowiak.net > > Hi, this is awesome!! > > I'm currently working in something similar, but I am having problems > with getting data from the CCD (basically i don't know how to do it > :), can you give me a tip for doing this? Or explain how you did it > please? > > I not a newbie at python but not as experienced as evidently you are. > > Thanks a lot in advance. > > > -- > > (...)Also, since that same law states that any system able to prove > its consistency to itself must be inconsistent; any mind that believes > it can prove its own sanity is, therefore, insane.(...) > > Kurt G?del. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From derek at simkowiak.net Fri Sep 30 14:48:26 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Fri, 30 Sep 2011 11:48:26 -0700 Subject: Motion Tracking with Python In-Reply-To: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> References: <4e85f0ff$0$2529$e4fe514c@news2.news.xs4all.nl> Message-ID: <4E860EFA.1020807@simkowiak.net> > /How was her project received at school?/ She got an "Outstanding" blue ribbon award. The teachers were impressed. (It was only a mandatory school project; it was not part of a regional competition or anything fancy like that.) --Derek On 09/30/2011 09:40 AM, Irmen de Jong wrote: > On 30-9-2011 4:16, Derek Simkowiak wrote: >> Hello, >> I have a neat Python project I'd like to share. It does real-time motion tracking, using >> the Python bindings to the OpenCV library: >> >> http://derek.simkowiak.net/motion-tracking-with-python/ >> >> There is a YouTube video showing the script in action. >> >> It's especially neat because my daughter and I worked together on this project. We used >> it to track her two pet gerbils, as part of her science fair project. She wrote her own >> (separate) Python script to read the motion tracking log files, compute distance and >> velocity, and then export those values in a CSV file. Like I say on the web page: "I?m >> convinced that Python is the best language currently available for teaching kids how to >> program." > Wow. Very impressive and very enjoyable to read about it. How was her project received > at school? > > Thanks a lot for sharing this. > > Irmen de Jong -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Fri Sep 30 15:27:14 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 30 Sep 2011 12:27:14 -0700 Subject: Benefit and belief In-Reply-To: References: <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <9em790Fnj9U1@mid.individual.net> <55d21fe1-e833-4c8f-b6fb-032dba107244@fx14g2000vbb.googlegroups.com> Message-ID: <20110930192714.GA14314@Smoke> On Fri, Sep 30, 2011 at 11:08:16AM -0700, rantingrick wrote: > On Sep 30, 11:36?am, Westley Mart?nez wrote: > > On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote: > > > On Sep 30, 8:58???pm, Neil Cerutti wrote: > > > > On 2011-09-30, DevPlayer wrote: > > > > > > > I still assert that contradiction is caused by narrow perspective. > > > > > > > By that I mean: just because an objects scope may not see a certain > > > > > condition, doesn't mean that condition is non-existant. > > > > > > > I also propose that just because something seems to contradict doesn't > > > > > mean it is false. Take for instance: > > > > > > > Look out your window. Is it daylight or night time? You may say > > > > > it is daylight or you may say it is night time. I would > > > > > disagree that only one of those conditions are true. Both > > > > > conditions are true. Always. It is only day (or night) for YOU. > > > > > But the opposite DOES in fact exist on the other side of the > > > > > world at the same time. > > > > > > > I call this Duality of Nature (and I believe there was some > > > > > religion somewhere in some time that has the same notion, > > > > > Budism I think but I could be mistaken). I see such > > > > > "contradictions" in what appears to be most truths. > > > > > > You are not alone. Many ancient philosophers, fathers of > > > > religious and scientific thought, thought the same. > > > > > > They thought that contradictory qualities could exist in objects > > > > simultaneously. For example, they thought that a cat was both big > > > > and small, because it was big compared to a mouse and small > > > > compared to a house. They didn't notice that big and small were > > > > not poperties of the cat, at all but were instead statements > > > > about how a cat relates to another object. > > > > > > When you say, "It is night," you are making an assertion about a > > > > position on the surface of the earth and its relationship to the > > > > sun. > > > > > > If you are not discussing a specific a position on the Earth, > > > > then you cannot make a meaningful assertion about night or day at > > > > all. Night and Day are not qualities of the entire Earth, but > > > > only of positions on the Earth. > > > > > But just imagine that we were all pre-galiliean savages -- knowing > > > nothing about the roundness of the earth, the earth going round and so > > > on and somehow you and I get on the phone and we start arguing: > > > Rusi: Its 9:30 pm > > > Neil: No its 12 noon > > > > > How many cases are there? > > > We both may be right, I may be wrong (my watch may have stopped) or we > > > both etc > > > > > ie conflicting data may get resolved within a larger world view (which > > > is what devplayer is probably saying). > > > > > Until then it is wiser to assume that that larger world view exists > > > (and I dont yet know it) > > > than to assume that since I dont know it it does not exist. > > > > > For me (admittedly an oriental) such agnosticism (literally "I-do-not- > > > know-ness") is as much a foundation for true religiosity as effective > > > science > > > > I.e. humility? > > @DevPlayer, rusi, Neil, Wes, and group > > Yes, there are two views of reality; that of the absolute and that of > the relative. Both are true. It is always daytime and nighttime > simultaneously; if you look at things from a global perspective. > > However, the true nature of "daytime vs nighttime" is purely a > relative observation. The fact that both exist does not falsify the > validity of the relative view. Recognizing the paradox is important > and proves you are not confined to your own selfish view points and > are in fact an intelligent being What paradox?. From alec.taylor6 at gmail.com Fri Sep 30 15:57:13 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 1 Oct 2011 05:57:13 +1000 Subject: Suggested coding style In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <16322983.302.1317292659565.JavaMail.geo-discussion-forums@yqlb4> <871uuy0xbr.fsf@no-fixed-abode.cable.virginmedia.net> <9embjqFb8uU1@mid.individual.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678D6@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F20F678F0@EMARC112VS01.exchad.jpmchase.net> Message-ID: Meh, so run your own web-server. If wave isn't right, search on sourceforge for a while. On 10/1/11, Prasad, Ramit wrote: >>> The answer to any news/mail client with feature X type question is >>> normally "gnus" - although I don't know what "Gmail-like style" is. >>Yeah > > Gah, I got distracted mid-email and forgot to finish. What I wanted to say > was, "Yeah, not knowing what 'Gmail-like style' makes a big difference ;)". > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > From nobody at nowhere.com Fri Sep 30 16:09:54 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 30 Sep 2011 21:09:54 +0100 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: >> I have a Python script which I would like to test without a tty attached >> to the process. I could run it as a cron job, but is there an easier way? >> >> I am running Linux. > > Isn't os.setsid() what you're looking for? It makes the calling process > have no controlling terminal. There's also a user command called setsid > that should have the same effect. setsid() requires that the calling process isn't a process group leader; this can be achieved by fork()ing. The setsid command does this automatically. As you say, this ensures that the process has no controlling terminal (i.e. it won't get signals from the tty driver for ^C, ^Z, hangup, etc). It won't detach stdin etc from a terminal. Also, open()ing a tty will result in it becoming the controlling terminal unless O_NOCTTY is used. I suspect that the OP just wants e.g.: script.py &>/dev/null <&- which will redirect stdout and stderr to /dev/null and close stdin. From nobody at nowhere.com Fri Sep 30 16:20:52 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 30 Sep 2011 21:20:52 +0100 Subject: Modifying external running process using python References: <086bd803-ddc5-4913-b1f1-5fb6cb5848bb@i28g2000yqn.googlegroups.com> Message-ID: On Thu, 29 Sep 2011 23:02:55 -0700, bingbang wrote: > Beginner here. I am trying to figure out how to modify a running > process on a linux system using Python. > I looked up trace and some other modules but they all seem to do with > following the currently executing python process. ptrace() is the system call which programs such as gdb, strace, ltrace, etc use to monitor or control another process. You wil probably need to use ctypes to access this function from Python. > Let's assume I have sudo/root privileges and that the POC code "only > needs to work in linux". You don't need root privilege to ptrace() a process which you own and which isn't privileged (a process which starts out setuid/setgid is still treated as privileged even if it reverts to the real user/group IDs). From joncle at googlemail.com Fri Sep 30 16:51:43 2011 From: joncle at googlemail.com (Jon Clements) Date: Fri, 30 Sep 2011 13:51:43 -0700 (PDT) Subject: Simplest way to resize an image-like array References: Message-ID: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> On Sep 30, 5:40?pm, John Ladasky wrote: > Hi folks, > > I have 500 x 500 arrays of floats, representing 2D "grayscale" images, > that I need to resample at a lower spatial resolution, say, 120 x 120 > (details to follow, if you feel they are relevant). > > I've got the numpy, and scipy, and matplotlib. All of these packages > hint at the fact that they have the capability to resample an image- > like array. ?But after reading the documentation for all of these > packages, none of them make it straightforward, which surprises me. > For example, there are several spline and interpolation methods in > scipy.interpolate. ?They seem to return interpolator classes rather > than arrays. ?Is there no simple method which then calls the > interpolator, and builds the resampled array? > > Yes, I can do this myself if I must -- but over the years, I've come > to learn that a lot of the code I want is already written, and that > sometimes I just have to know where to look for it. > > Thanks! Is something like http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html#scipy.misc.imresize any use? From hansmu at xs4all.nl Fri Sep 30 17:09:02 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Fri, 30 Sep 2011 23:09:02 +0200 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e844de7$0$29977$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e862fee$0$2438$e4fe514c@news2.news.xs4all.nl> On 30/09/11 20:34:37, RJB wrote: > You could try the old UNIX "nohup ...&" technique for running a > process in the background (the&) with no HangUP if you log out: > > $ nohup python -c "import sys,os; print > os.isatty(sys.stdout.fileno())"& > appending output to nohup.out > $ cat nohup.out > False > > But that is over kill I guess. > > One worrying detail.... the definition of a running process in > UNIX implies is that it has standard input/output files open. > You'd be wise to make sure that they are connected to things > that are safe.... /dev/null. > > Even so /dev/tty can be opened any way... Not if you really detach from your tty: after you've detached, there is no tty for /dev/tty to connect to and any attempt to open it will raise IOError. -- HansM From navkirat.py at gmail.com Fri Sep 30 23:25:54 2011 From: navkirat.py at gmail.com (Navkirat Singh) Date: Sat, 1 Oct 2011 08:55:54 +0530 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List Message-ID: Lol you all sound like google's angry birds with their feathers ruffled by a comment. You guys should open up another mailing list to extinguish your virtually bruised egos. . . . On Sep 30, 2011 10:27 PM, "Prasad, Ramit" wrote: -------------- next part -------------- An HTML attachment was scrubbed... URL: