pysensor 0.7 released
PySensor is an environment to work with acceleration sensor data as emitted by mobile devices such as the Nokia N95/N97 or Android G1. Acceleration data and keypress data is sent to a server (PC) where further processing, logging, recording, and visualization of the data is done. The data is then distributed to a client application. Optionally, the client application may send image data at any rate and the device retrieves these images as fast as possible; images may be dropped. Recorded input data can be replayed at original or altered speed. The server software is in Python. For each mobile platform there is a different device software sending the data - currently PyS60, Android, and JavaME/JSR-256. Integration with a client application is provided for Python, pygame, C/C++ or Java. http://code.google.com/p/pysensor/ Have fun -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: How do I Block Events in wxPython
On Wed, Dec 9, 2009 at 10:21 PM, Frank Millman fr...@chagford.com wrote: Wanderer wrote: I have a wxPython program which does some calculations and displays the results. During these calculations if I click the mouse inside the dialog the program locks up. If I leave the dialog alone the process completes fine. I have tried running the function from a separate dialog with Show Modal and I have tried using SetEvtHandlerEnabled all to no avail. The program is long and occupies several files so I won't show the whole thing but here is the calculation part. How do I block events? I also need to block events in my wxPython app, though the time duration is very short. I have a separate thread that sends notification of gui events to a server, and waits for a response. I do not want the user to do anything until the response is received. I don't think blocking events is the right way to think about this. If you need to halt new input for some reason (bearing in mind that its best to run such things in a background task, but yes, sometimes blocking the UI is important), then there's a couple ways to go about it. But trying to mess with the event loop isn't it. First, you always want a visual indicator-- use SetCursor on your top level window to set a busy cursor. You never want any sort of block-ish action to happen without the user being able to see something is going on; if its more then a second or so I /really/ think you should throw up a progress indicator dialog, even if its an infinate one. To actually 'block' the events themselves, you can just call wnd.Enable(False). Just be sure to Enable(True) when you want to process stuff again. Another approach is to use wnd.CaptureMouse() on a particular control which doesn't really respond to anything. Just be sure to ReleaseMouse() later and follow the instructions in the docs about capturing that cancel-capture event. HTH, --S -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
Luis M. González wrote: On Dec 6, 3:21 pm, vsoler vicente.so...@gmail.com wrote: I recently read that many libraries, including Numpy have not been ported to Python 3. When do you think that Python 3 will be fully deployed? Should I stick, so far, to Python 2.6? Regards Vicente Soler You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ I'd argue against using Python 2.6 for production work. Either use Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has some of the features of Python 3.x, but not all of them, and is neither fish nor fowl as a result. 2.6 is really more of a sideline that was used for trying out new features, not something suitable for production. I think the idea is to run your 2.5 code through '2to3 and see if it works in 3.x. Anyway, it will be years, if ever, before Python 3.x gets any real support. Too many major packages still aren't fully supported on it, and some popular packages, like SGMLlib and Feedparser, are being dropped. When a few major Linux distros ship with Python 3.x and enough of the binary packages to run a web site, take a look at it again. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
In article 4b20ac0a$0$1596$742ec...@news.sonic.net, John Nagle na...@animats.com wrote: I'd argue against using Python 2.6 for production work. Either use Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has some of the features of Python 3.x, but not all of them, and is neither fish nor fowl as a result. 2.6 is really more of a sideline that was used for trying out new features, not something suitable for production. I disagree with that advice, strongly. 2.6 not only has new features but it has many bug fixes that have not and will not be applied to 2.5. It is hardly a sideline. See http://www.python.org/download/releases/2.5.4/ for the official policy on 2.5, in particular: Future releases of Python 2.5 [ -- that is, should the need arise -- ] will only contain security patches; no new features are being added, and no 'regular' bugs will be fixed anymore. If you want the latest production version of Python, use Python 2.6.1 or later. [2.6.4 is the latest version]. Then see http://www.python.org/download/releases/2.6.4/ Note that Python 2.6 is considered the stable version and is now in bugfix-only mode; no new features are being added. Per normal python development policy, new features are added to the next major release cycles, now under development: Python 2.7 and Python 3.2. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Parsing html with Beautifulsoup
I am trying to get csv-output from a html-file. With this code I had a little success: = from BeautifulSoup import BeautifulSoup from string import replace, join import re f = open(configuration.html,r) g = open(configuration.csv,'w') soup = BeautifulSoup(f) t = soup.findAll('table') for table in t: rows = table.findAll('tr') for th in rows[0]: t = th.find(text=True) g.write(t) g.write(',') #print(','.join(t)) for tr in rows: cols = tr.findAll('td') for td in cols: try: t = td.find(text=True).replace('nbsp;','') g.write(t) except: g.write ('') g.write(,) g.write(\n) === producing output like this: RULE,SOURCE,DESTINATION,SERVICES,ACTION,TRACK,TIME,INSTALL ON,COMMENTS, 1drop,Log,Any,,, 2,All us...@any,,Any,clientencrypt,Log,Any,,, 3,Any,Any,,drop,None,Any,,, 4drop,None,Any,,, ... It left out all the non-plaintext parts of td/td I then tried using t.renderContents and then got something like this (one line broken into many for the sake of this email): 1,img src=icons/group.pngnbsp;a href=#OBJ_sunetint sunetint/ABR, img src=icons/gateway_cluster.pngnbsp;ahref=#OBJ_Rainwall_Cluster Rainwall_Cluster/A BR, imgsrc=icons/udp.pngnbsp;a href=#SVC_IKE IKE/abr, img src=icons/drop.pngnbsp;drop, img src=icons/log.pngnbsp;Lognbsp;, img src=icons/any.pngnbsp;Anybrnbsp;, img src=icons/gateway_cluster.pngnbsp;a href=#OBJ_Rainwall_Cluster Rainwall_Cluster/A BRnbsp;,nbsp; How do I get Beautifulsoup to render (taking the above line as example) sunentint for img src=icons/group.pngnbsp;a href=#OBJ_sunetintsunetint/ABR and still provide the text-parts in the td's with plain text? I have experimented a little bit with regular expressions, but could so far not find a solution. Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch Lo, children are an heritage of the LORD: and the fruit of the womb is his reward.Psalms 127:3 -- http://mail.python.org/mailman/listinfo/python-list
Connecting to Python COM server from Excel VBA does not work
I ran this script: --- class Example(object): _public_methods_ = ['Add','Mul'] _reg_progid_ = 'MyPython.Example' _reg_clsid_ = '{E39ECD8C-7FAF-48B0-B914-1202319499D4}' def Add(self,a,b): return a+b def Mul(self,a,b): return a*b if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(Example) - connecting to this COM server works with following VBS-script: - Set ex = CreateObject(MyPython.Example) msgbox ex.Add(1, 2) - when i run following VBA script in excel - Sub Testit() Set ex = CreateObject(MyPython.Example) MsgBox ex.Add(1, 2) End Sub - i get the error: Run-time error '-2137024770 (8007007e)': Automation error The specified module could not be found Any ideas what the problem could be? Already searched a long time for solutions but did not find any thanks, diego -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
Michele Simionato wrote: I have just discovered that the syntax with file(name, 'w') as f: do_something(f) does not close the file at the end of the with statement! On the contrary with open(name, 'w') as f: do_something(f) works fine. The docs say When opening a file, it’s preferable to use open() instead of invoking this constructor directly. but perhaps they should mention why :( Are you sure? Python 2.6.4 (r264:75706, Nov 2 2009, 14:44:17) [GCC 4.4.1] on linux2 Type help, copyright, credits or license for more information. with file(tmp.txt, w) as f: ... print f, whatever ... f.write(something) Traceback (most recent call last): File stdin, line 1, in module ValueError: I/O operation on closed file Peter -- http://mail.python.org/mailman/listinfo/python-list
DCT transform (API)? (scipy or otherwise)
I am looking for a 2-D DCT transform function for use in python. Does anyone have any good pointers? I see that one is promised in scipy 0.8.0, but I cannot find any details on how close that is to being released. I am not sure if running bleeding-edge scipy would solve my problem; I should have liked more experience with numerical programming before I tried that, especially since I do not otherwise use the C and fortran libraries it is based on. Are there alternatives to scipy for this particular feature? TIA for any pointers :-- George -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
Michele Simionato wrote: I have just discovered that the syntax with file(name, 'w') as f: do_something(f) does not close the file at the end of the with statement! On the contrary with open(name, 'w') as f: do_something(f) works fine. The docs say When opening a file, it’s preferable to use open() instead of invoking this constructor directly. but perhaps they should mention why :( Are you sure? For me on python2.5, it works as advertised: from __future__ import with_statement def test(outf): with outf: outf.write(test\n) try: outf.write(test\n) assert False, Not closed except ValueError: pass outf = open(/tmp/foo, w) test(outf) outf = file(/tmp/bar, w) test(outf) Which Python do you use? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Graph library for Python
geremy condra: Since that's released under the python license, I'm going to go ahead and commit the version that includes the topo traversal, but if you have any objections you only need to say the word and I'll take it down. No objections :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: relative imports with the __import__ function
Chris Colbert wrote: It seems the relative import level is dependent on the location of the main entry module. I thought the whole idea of relative imports was to make the import independent of the entry point? You don't have to specify it explicitly, so you can move a module containing from .foo import bar into another package without changing its source code (provided there is a foo submodule with a bar attribute). This includes the trivial case of renaming the parent package. Of course Python has to know the importing module's location, just like you cannot meet me one block north and three blocks west unless you know where I currently am. See also http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
On Dec 10, 11:04 am, Diez B. Roggisch de...@nospam.web.de wrote: Are you sure? For me on python2.5, it works as advertised: from __future__ import with_statement def test(outf): with outf: outf.write(test\n) try: outf.write(test\n) assert False, Not closed except ValueError: pass outf = open(/tmp/foo, w) test(outf) outf = file(/tmp/bar, w) test(outf) Which Python do you use? Diez Python 2.5, but it could be an artifact of the way I am looking if a file is closed. I have subclassed the file builtin, added a .close method and it was not called by the with statement. This during debugging, but now I have found another reason to explain why I was running out of file descriptors, (I was opening too many connections to the db). It is entirely possible that the problem was not with the with statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
Michele Simionato wrote: On Dec 10, 11:04 am, Diez B. Roggisch de...@nospam.web.de wrote: Are you sure? For me on python2.5, it works as advertised: from __future__ import with_statement def test(outf): with outf: outf.write(test\n) try: outf.write(test\n) assert False, Not closed except ValueError: pass outf = open(/tmp/foo, w) test(outf) outf = file(/tmp/bar, w) test(outf) Which Python do you use? Diez Python 2.5, but it could be an artifact of the way I am looking if a file is closed. The above ran on python2.5 for me, no hitch. I have subclassed the file builtin, added a .close method and it was not called by the with statement. This during debugging, but now I have found another reason to explain why I was running out of file descriptors, (I was opening too many connections to the db). It is entirely possible that the problem was not with the with statement. Probably. Closing a file through with might not involve calling close() - it might be implemented differently in __exit__. So overload *that*, too. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Python COM server from Excel VBA does not work
Hi ! Warning with lower/uppercases! Try to make two versions of your methods (ex.: add ADD), for study. @+ -- MCI -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
Michele Simionato wrote: Python 2.5, but it could be an artifact of the way I am looking if a file is closed. I have subclassed the file builtin, added a .close method and it was not called by the with statement. This during debugging, but now I have found another reason to explain why I was running out of file descriptors, (I was opening too many connections to the db). It is entirely possible that the problem was not with the with statement. In Python 2.5 you have to implement your own __enter__ and __exit__ methods if you subclass from file. The file.__exit__ function doesn't call f.close(). The minor inconsistency has been fixed in Python 2.6. Python 2.5: static PyObject * file_exit(PyFileObject *f, PyObject *args) { PyObject *ret = file_close(f); if (!ret) /* If error occurred, pass through */ return NULL; Py_DECREF(ret); /* We cannot return the result of close since a true * value will be interpreted as yes, swallow the * exception if one was raised inside the with block. */ Py_RETURN_NONE; } Python 2.6: static PyObject * file_exit(PyObject *f, PyObject *args) { PyObject *ret = PyObject_CallMethod(f, close, NULL); if (!ret) /* If error occurred, pass through */ return NULL; Py_DECREF(ret); /* We cannot return the result of close since a true * value will be interpreted as yes, swallow the * exception if one was raised inside the with block. */ Py_RETURN_NONE; } -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
Michele Simionato wrote: On Dec 10, 11:04 am, Diez B. Roggisch de...@nospam.web.de wrote: Are you sure? For me on python2.5, it works as advertised: from __future__ import with_statement def test(outf): with outf: outf.write(test\n) try: outf.write(test\n) assert False, Not closed except ValueError: pass outf = open(/tmp/foo, w) test(outf) outf = file(/tmp/bar, w) test(outf) Which Python do you use? Diez Python 2.5, but it could be an artifact of the way I am looking if a file is closed. I have subclassed the file builtin, added a .close method and it was not called by the with statement. This during debugging, but now I have found another reason to explain why I was running out of file descriptors, (I was opening too many connections to the db). It is entirely possible that the problem was not with the with statement. Subclassing file doesn't work properly: http://mail.python.org/pipermail/python-list/2005-April/920562.html Peter -- http://mail.python.org/mailman/listinfo/python-list
C to Python
Hello All, I am finding it difficult getting my head around PyObject_CallObject(x,y). I need a gentle and thorough introduction to it. I also need examples. Could someone come to my need? Thanks. Janus. -- http://mail.python.org/mailman/listinfo/python-list
Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?)
Hello, I will re-precise my question: Has anyone ever implemented a script in Python that generates documentation (especially diagrams, in a format such as e.g. Dia, Inkscape SVG or Tikz) for a PostgreSQL database either from an SQL script or by connecting to the database? Postgresql_autodoc is unfortunately written in Perl. ;- TIA, And, btw., please respect my .sig, Sincerely, Wolfgang Keller -- NO Courtesy Copies PLEASE! -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
On Dec 10, 2:00 pm, Carl Banks pavlovevide...@gmail.com wrote: On Dec 9, 5:02 pm, Asun Friere afri...@yahoo.co.uk wrote: On Dec 9, 7:08 pm, Carl Banks pavlovevide...@gmail.com wrote: What if the object is a string you just read from a file? How do you dispatch using polymorphism in that case? This would be a pertinent question, were I advocating that _all_ switch statements should, or even can, be replaced with dispatch using polymorphism. Then why did you claim that a decent OO should never have a switch statement then? The mere fact that it is possible to demonstrate a use of the 'goto' statement, which does not offend against a program's structural integrity, does not mean it's necessarily a good idea to have it lying about given that in the large majority of cases it leads to (encourages?) bad code. Python sagely declined to implement 'goto'. I feel the same considerations apply in regard to the switch/case statement in the context of a true* OO (ie python but not java ;). Imo the decision not to implement a switch statement was wise. This is not to deny that a traditional switch is not in often a sane solution. I just think that if your elifs are getting unwieldy enough to require the application of the proverbial layer of abstraction, then a switch statement fails to deliver sufficient abstraction. You argued that a decent language OO should never have a switch statement because polymorphic dispatch is the right way to handle it in OO languages, which implies that polymorphism can and should take the place of any switch statement. That is a misreading. I wrote, that the case logic is probably symptomatic of poor design. I advocated considering whether an OO solution might be more appropriate. You misunderstand my intent. I'm not here to postulate some ultimate OO truths, but to provide practical advice (aimed here mainly at Hong and Kee). In regard elif chains, this is my advice. If you see too many elifs in your code (or if you find yourself wishing for a switch statement) alarm bells should start to go off. STOP, give serious consideration as to whether applying some patterns or similar will improve the design, and HINT: first consider whether that pattern might be something resembling a dispatch mechanism, it's just downright spooky how in real-life programming situations this turns out to be the answer. Obviously the answers to these questions are not invariably 'yes.' Often enough they are. What if, instead of reading strings from a file, Why don't you answer my question first, Because, as I have already explained, I object to the question. It presupposes my holding a position I don't. But look perhaps I'm being unfair to you Carl. I presumed your question was rhetorical, or at least you supposed it disproved whatever it is you were attacking. If instead you were asking for clarification, the short answer is wrap as you read. A longer answer is in the response to Tim, I'll send in a while. cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?)
Wolfgang Keller wrote: Hello, I will re-precise my question: Has anyone ever implemented a script in Python that generates documentation (especially diagrams, in a format such as e.g. Dia, Inkscape SVG or Tikz) for a PostgreSQL database either from an SQL script or by connecting to the database? I've written a schemadiff-tool for postgres based on SQLAlchemy reflection, which is a branch of SQLAlchemy and which should become part of the upcoming SA 0.6. http://svn.sqlalchemy.org/sqlalchemy/branches/reflection It allows you to extract information about the schema of the DB. This could be the foundation of your tool. Postgresql_autodoc is unfortunately written in Perl. ;- TIA, And, btw., please respect my .sig, Which is supposed to mean what? Never heard the term courtesy copy. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: freeze in python3
Hi Patrick, It's not exactly what you asked, but I've been able to freeze a Python 3 project using cx_Freeze. Almar 2009/12/10 Patrick Stinson patrickstinson.li...@gmail.com: NOTE: This is related but is not a duplicate of my post from yesterday. Has anyone used Tools/freeze/freeze.py in python3? I tried it with a clean source distribution and for some reason freeze.py is generating code that uses the old naming convention for module init functions. I get the following unresolved symbols for the default hello.py: Undefined symbols for architecture i386: _init_codecs, referenced from: __PyImport_Inittab in config.o _init_functools, referenced from: __PyImport_Inittab in config.o _init_thread, referenced from: __PyImport_Inittab in config.o _initerrno, referenced from: __PyImport_Inittab in config.o _initposix, referenced from: __PyImport_Inittab in config.o _initgc, referenced from: __PyImport_Inittab in config.o _init_locale, referenced from: __PyImport_Inittab in config.o _init_io, referenced from: __PyImport_Inittab in config.o _init_sre, referenced from: __PyImport_Inittab in config.o _initimp, referenced from: __PyImport_Inittab in config.o _initpwd, referenced from: __PyImport_Inittab in config.o _init_weakref, referenced from: __PyImport_Inittab in config.o _initsignal, referenced from: __PyImport_Inittab in config.o _initzipimport, referenced from: __PyImport_Inittab in config.o For example, initerrno should now be PyInit_errno. Am I missing something? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: file does not work with the with statement!
On Dec 10, 11:59 am, Christian Heimes li...@cheimes.de wrote: In Python 2.5 you have to implement your own __enter__ and __exit__ methods if you subclass from file. The file.__exit__ function doesn't call f.close(). Yes, that was my problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?)
On Thu, Dec 10, 2009 at 3:48 AM, Diez B. Roggisch de...@nospam.web.de wrote: Wolfgang Keller wrote: Hello, I will re-precise my question: Has anyone ever implemented a script in Python that generates documentation (especially diagrams, in a format such as e.g. Dia, Inkscape SVG or Tikz) for a PostgreSQL database either from an SQL script or by connecting to the database? I've written a schemadiff-tool for postgres based on SQLAlchemy reflection, which is a branch of SQLAlchemy and which should become part of the upcoming SA 0.6. http://svn.sqlalchemy.org/sqlalchemy/branches/reflection It allows you to extract information about the schema of the DB. This could be the foundation of your tool. Postgresql_autodoc is unfortunately written in Perl. ;- TIA, And, btw., please respect my .sig, Which is supposed to mean what? Never heard the term courtesy copy. It appears to be an incorrect expansion of Cc, which is actually Carbon copy. Apparently he means all replies should be directly to the list and not Cc his individual email address. Which seems strange, because usually mailinglists are smart enough not to send the author duplicate copies if they're named in the To or Cc fields. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: plain text parsing to html (newbie problem)
Thanks for the output. akean, I've installed ipython and I'm exploring it. Thanks. Terry, from what I've read stringIO allows us to store strings in a 'virtual' file. Can you please write just 2 lines exemplifying a write to and a read from an OS level file? MRAB, that 'mail' object should've been the os level 'mail' file. But as I'm a beginner I was using it wrong.. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: plain text parsing to html (newbie problem)
Thanks for the output. akean, I've installed ipython and I'm exploring it. Thanks. Terry, from what I've read stringIO allows us to store strings in a 'virtual' file. Can you please write just 2 lines exemplifying a write to and a read from an OS level file? MRAB, that 'mail' object should've been the os level 'mail' file. But as I'm a beginner I was using it wrong.. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Python COM server from Excel VBA does not work
On 10 Dez., 11:52, Michel Claveau - MVPenleverlesx_xx...@xmclavxeaux.com.invalid wrote: Hi ! Warning with lower/uppercases! Try to make two versions of your methods (ex.: add ADD), for study. @+ -- MCI The error comes already at the first line of Excel/VBA code: Set ex = CreateObject(MyPython.Example) rgds,e -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Python COM server from Excel VBA does not work
On 10 Dez., 11:52, Michel Claveau - MVPenleverlesx_xx...@xmclavxeaux.com.invalid wrote: Hi ! Warning with lower/uppercases! Try to make two versions of your methods (ex.: add ADD), for study. @+ -- MCI The error comes already at the first line of Excel/VBA code: Set ex = CreateObject(MyPython.Example) rgds,e -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
On Dec 10, 6:57 am, Tim Chase python.l...@tim.thechases.com wrote: Carl Banks wrote: What if the object is a string you just read from a file? How do you dispatch using polymorphism in that case? This is where I most miss a switch/case statement in Python...I do lots of text-file processing (cellular provider data), so I have lots of code (for each provider's individual format) that looks like phones = {} for row in csv.DictReader(file('data.txt', 'rb')): phonenumber = row['phonenumber'] if phonenumber not in phones: phones[phonenumber] = Phone(phonenumber) phone = phones[phonenumber] rectype = rectype if rectype == '01': phone.international += Decimal(row['internationalcost']) elif rectype == '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) elif rectype == ... ... else: raise WhatTheHeckIsThis() Great example Tim. This is something that many of us must be dealing with on a daily basis. The problem has enough details (bar one), to allow an answer and not so detailed as to be confusing. And for me it's a particularly good example, because your need accommodate mulitple provider formats makes me feel right at home. which would nicely change into something like switch row['recordtype']: case '01': phone.international += Decimal(row['internationalcost']) // optionally a break here depending on // C/C++/Java/PHP syntax vs. Pascal syntax which // doesn't have fall-through case '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) ... default: raise WhatTheHeckIsThis() Cleaner yes. But, with respect, not so clean as to justify the construct. Following my advice you might express that switch statement like so: phone.update_from_record(record) It is, in this context, completely irrelevant observe that 'dispatch' originally referred specifically to the dismissal of ambassadors. It may be slightly more to the point to tap into the wisdom of Henry Ford and turn your design inside out. This switch statement belongs to one guy. One guy who wants to know how to do everything that needs to be done to Phones no matter who asks. Let's install a conveyor belt instead! Standard Disclaimer: Untested (obviously); just a sketch; I don't really know your problem only the code you've posted; etc etc. First some minimal architecture: --- #The first class your already have. We just need one more method class Phone (object) : ... def update_from_record (self, rec) : return rec.updatePhone(self) #and then some data source classes class RecType (dict) : def __init__ (self, row) : ... class RecType_001 (RecType) : def updatePhone(self, phone) : phone.interational += Decimal(self['internationalcost']) class RecType_002 (RecType) : def updatePhone(self, phone) : phone.text_messaging += ( int(self['textmessages sent']) + int(self['pages received']) + ... #and if we must ... rectypes = {'01':RecType_001, '02': RecType_002, ...} # The one thing I'm sure I don't understand from the code is where the original rectypes comes into the process. #I would prefer, if it's possible, just thowing the appropriate class in rather than looking up this dict to instantiate. --- Now the different providor types, previously the bane of your existence, are your staff. Your original code will now read something like: phones = {} for row in csv.DictReader(open('data.txt', 'rb')) : try : record = rectypes[rectype](row) except KeyError : raise WhatTheHeckIsThisError('unknown rectype: %s' % rectype) phonenumber = record.phonenumber if phonenumber not in phones : phones[phonenumber] = Phone(phonenumber) phone = phones[phonenumber] phone.update_from_record(record) I wonder if you agree that it's bit cleaner now? It's an effective solution. I'm making no representation that it's the best. I like think largely because it contains the knowledge accessibly. If you have lots of code that deal with this kind of thing, chances are library of core data source classage could reduce much of it to a simple (and legible!) one liner. A provider enhances their format, or a new provider format is added, code in one class, not in every switch they might be involved in. But sorry, I don't mean to patronise, I'm sure you know the spiel. Asun -- http://mail.python.org/mailman/listinfo/python-list
Re: Graph library for Python
On 12/08/2009 01:27 PM, Robin Becker wrote: I don't want to sound pessimistic, but graph and digraph theory has a lot of history, especially in computer science. There are already very many implementations eg http://code.google.com/p/igraph http://www.boost.org/doc/libs/release/libs/graph http://ernst-schroeder.uni.lu/Digraph/doc/ http://code.google.com/p/python-graph http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html I would like to point out the following two projects as additions to this list: http://graph-tool.forked.de (my own project) http://networkx.lanl.gov The graph-tool module uses the Boost Graph Library internally to achieve good numerical performance, while networkx has a more python-only approach. Cheers, Tiago signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Graph library for Python
On Thu, Dec 10, 2009 at 5:18 AM, Bearophile bearophileh...@lycos.com wrote: geremy condra: Since that's released under the python license, I'm going to go ahead and commit the version that includes the topo traversal, but if you have any objections you only need to say the word and I'll take it down. No objections :-) I appreciate it. I don't seem to be having any luck emailing you offlist, so please feel free to email me privately if you'd rather this not be indexed, but is there a particular way you want your attribution line to read? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
accessing local variables from the pdb debugger
Guys, I have some problem changing method locals with pdb: import pdb def test(): foo = 'foo' pdb.set_trace() test() --Return-- /home/jeanmichel/trunk/tnt/test.py(5)test()-None - pdb.set_trace() (Pdb) print foo foo (Pdb) foo = 'bar' (Pdb) print foo foo (Pdb) I tried using locals() but it returns a copy of the locals. So changing locals['foo'] won't do any good. (Pdb) locals() Out[6]: {'__return__': None, 'foo': 'foo'} Any idea ? I'm starting to wonder if it is possible. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing local variables from the pdb debugger
Jean-Michel Pichavant wrote: Guys, I have some problem changing method locals with pdb: import pdb def test(): foo = 'foo' pdb.set_trace() test() --Return-- /home/jeanmichel/trunk/tnt/test.py(5)test()-None - pdb.set_trace() (Pdb) print foo foo (Pdb) foo = 'bar' (Pdb) print foo foo (Pdb) I tried using locals() but it returns a copy of the locals. So changing locals['foo'] won't do any good. (Pdb) locals() Out[6]: {'__return__': None, 'foo': 'foo'} Any idea ? I'm starting to wonder if it is possible. I recall having some issues with local variables sometimes, but actually your example works fine for me: def test(): foo = foo import pdb; pdb.set_trace() print foo test() And the session: $ python /tmp/test.py /tmp/test.py(9)test() - print foo (Pdb) pp foo 'foo' (Pdb) foo = bar (Pdb) n bar --Return-- /tmp/test.py(9)test()-None - print foo (Pdb) c Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Newbies
On Dec 9, 11:56 pm, geremy condra debat...@gmail.com wrote: The N900 is what I consider the coolest portable device ever: http://temporaryland.wordpress.com/2009/10/09/nokian900-not-just-an-i... http://www.themaemo.com/and-now-for-something-completely-different-th... Dunno if you intended to, but in the last link you imply that you can't run Python on android, when you can do so either via ASE or through the JNI. Geremy Condra The article you mention says: I realize that there is an effort in Android to make Python and other scripting languages available to some degree, but from what I have seen they are relegated to macro like functionality. In other words, you wont be able to create full blown stand alone Python applications in Android. The N900, on the other hand, will allow this. Even the GUI side of the applications can be created with well known Python toolkits like PyGTK and PyQt. That impression came from this blog: http://google-opensource.blogspot.com/2009/06/introducing-android-scripting.html Are you saying that one can write full blown stand alone Android applications in Python, GUI and all. -- http://mail.python.org/mailman/listinfo/python-list
Re: web crawler in python
On Dec 9, 2009, at 7:39 PM, my name wrote: I'm currently planning on writing a web crawler in python but have a question as far as how I should design it. My goal is speed and maximum efficient use of the hardware\bandwidth I have available. As of now I have a Dual 2.4ghz xeon box, 4gb ram, 500gb sata and a 20mbps bandwidth cap (for now) . Running FreeBSD. What would be the best way to design the crawler? Using the thread module? Would I be able to max out this connection with the hardware listed above using python threads? I wrote a web crawler in Python (under FreeBSD, in fact) and I chose to do it using separate processes. Process A would download pages and write them to disk, process B would attempt to convert them to Unicode, process C would evaluate the content, etc. That worked well for me because the processes were very independent of one another so they had very little data to share. Each process had a work queue (Postgres database table); process A would feed B's queue, B would feed C D's queues, etc. I should point out that my crawler spidered one site at a time. As a result the downloading process spent a lot of time waiting (in order to be polite to the remote Web server). This sounds pretty different from what you want to do (an indeed from most crawlers). Figuring out the best design for your crawler depends on a host of factors that you haven't mentioned. (What are you doing with the pages you download? Is the box doing anything else? Are you storing the pages long term or discarding them? etc.) I don't think we can do it for you -- I know *I* can't; I have a day job. ;) But I encourage you to try something out. If you find your code isn't giving what you want, come back to the list with a specific problem. It's always easier to help with specific than with general problems. Good luck Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
On Dec 10, 3:34 am, Asun Friere afri...@yahoo.co.uk wrote: On Dec 10, 2:00 pm, Carl Banks pavlovevide...@gmail.com wrote: [snip most of questionable, verly verbose reply] You argued that a decent language OO should never have a switch statement because polymorphic dispatch is the right way to handle it in OO languages, which implies that polymorphism can and should take the place of any switch statement. That is a misreading. I wrote, that the case logic is probably symptomatic of poor design. I advocated considering whether an OO solution might be more appropriate. You misunderstand my intent. I'm not here to postulate some ultimate OO truths, but to provide practical advice (aimed here mainly at Hong and Kee). In regard elif chains, this is my advice. Even granting that your post wasn't as drastic as it sounded (and enough people reacted to your first post that you should should probably consider whether it came off a little more strongly than you intended), I think you are still overstating it by a lot. OO polymorphic dispatching is good for some stuff, and simpler dispatching such with if...else, a dict, or a hypotheical switch, is good for some stuff. That's it. Having a bunch of if...elses is not probably wrong, and it's not a red flag, unless you're not a good programmer and have already missed a bunch of other more pertinent red flags. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing local variables from the pdb debugger
Diez B. Roggisch wrote: Jean-Michel Pichavant wrote: Guys, I have some problem changing method locals with pdb: import pdb def test(): foo = 'foo' pdb.set_trace() test() --Return-- /home/jeanmichel/trunk/tnt/test.py(5)test()-None - pdb.set_trace() (Pdb) print foo foo (Pdb) foo = 'bar' (Pdb) print foo foo (Pdb) I tried using locals() but it returns a copy of the locals. So changing locals['foo'] won't do any good. (Pdb) locals() Out[6]: {'__return__': None, 'foo': 'foo'} Any idea ? I'm starting to wonder if it is possible. I recall having some issues with local variables sometimes, but actually your example works fine for me: def test(): foo = foo import pdb; pdb.set_trace() print foo test() And the session: $ python /tmp/test.py /tmp/test.py(9)test() - print foo (Pdb) pp foo 'foo' (Pdb) foo = bar (Pdb) n bar --Return-- /tmp/test.py(9)test()-None - print foo (Pdb) c Diez You're right, it can work, eventually... Take a look at sessions below: def test(): foo = 'foo' pdb.set_trace() print 'This is the test method displaying foo:', foo In [3]: test() /home/jeanmichel/trunk/tnt/test.py(6)test() - print 'This is the test method displaying foo:', foo (Pdb) foo='bar' (Pdb) c This is the test method displaying foo: bar In [5]: test() /home/jeanmichel/trunk/tnt/test.py(6)test() - print 'This is the test method displaying foo:', foo (Pdb) foo='bar' (Pdb) print foo foo (Pdb) c This is the test method displaying foo: foo By just inserting the print foo statement right after changing foo's value, I've rolled back the value to 'foo' ??? A hell of a wtf pdb feature ! JM PS : using python 2.5 -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I Block Events in wxPython
Stephen Hansen wrote: On Wed, Dec 9, 2009 at 10:21 PM, Frank Millman fr...@chagford.com wrote: I also need to block events in my wxPython app, though the time duration is very short. I have a separate thread that sends notification of gui events to a server, and waits for a response. I do not want the user to do anything until the response is received. I don't think blocking events is the right way to think about this. If you need to halt new input for some reason (bearing in mind that its best to run such things in a background task, but yes, sometimes blocking the UI is important), then there's a couple ways to go about it. But trying to mess with the event loop isn't it. In fact my method does not work. All that happens is that the events are queued, and as soon as I release the lock the events are processed in a bunch. Not clever :-( First, you always want a visual indicator-- use SetCursor on your top level window to set a busy cursor. You never want any sort of block-ish action to happen without the user being able to see something is going on; if its more then a second or so I /really/ think you should throw up a progress indicator dialog, even if its an infinate one. Agreed. To actually 'block' the events themselves, you can just call wnd.Enable(False). Just be sure to Enable(True) when you want to process stuff again. This may work for the OP, but would not really work for me, because it changes the visual appearance of all the controls. In my case the time duration for blocking is usually very short, so it could result in flicker. Another approach is to use wnd.CaptureMouse() on a particular control which doesn't really respond to anything. Just be sure to ReleaseMouse() later and follow the instructions in the docs about capturing that cancel-capture event. I like this. Unfortunately it does not block keyboard input. However, I have a keyboard event handler on virtually all my controls, so it should be easy to set a flag and tell it to ignore keystrokes while in a 'blocked' state. HTH, It certainly does - thanks. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Graph library for Python
On Thu, Dec 10, 2009 at 7:48 AM, Tiago de Paula Peixoto ti...@forked.de wrote: On 12/08/2009 01:27 PM, Robin Becker wrote: I don't want to sound pessimistic, but graph and digraph theory has a lot of history, especially in computer science. There are already very many implementations eg http://code.google.com/p/igraph http://www.boost.org/doc/libs/release/libs/graph http://ernst-schroeder.uni.lu/Digraph/doc/ http://code.google.com/p/python-graph http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html I would like to point out the following two projects as additions to this list: http://graph-tool.forked.de (my own project) http://networkx.lanl.gov The graph-tool module uses the Boost Graph Library internally to achieve good numerical performance, while networkx has a more python-only approach. Cheers, Tiago Well, we all seem to have reinvented the wheel differently ;) Bearophile, Tiago- any interest in trying to combine the best parts of our libraries, with an eye towards eventual integration into the standard library? Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
Great example Tim. This is something that many of us must be dealing with on a daily basis. The problem has enough details (bar one), to allow an answer and not so detailed as to be confusing. And for me it's a particularly good example, because your need accommodate mulitple provider formats makes me feel right at home. which would nicely change into something like switch row['recordtype']: case '01': phone.international += Decimal(row['internationalcost']) // optionally a break here depending on // C/C++/Java/PHP syntax vs. Pascal syntax which // doesn't have fall-through case '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) ... default: raise WhatTheHeckIsThis() Cleaner yes. But, with respect, not so clean as to justify the construct. Following my advice you might express that switch statement like so: phone.update_from_record(record) This switch statement belongs to one guy. One guy who wants to know how to do everything that needs to be done to Phones no matter who asks This is where you make a false assumption -- the contents and parsing of the switch are provider-specific in this case, mapping to a common ontology of the Phone object: class MonopolyProvider1Parser: ... switch row['recordtype']: case '01': phone.international += Decimal(row['internationalcost']) // optionally a break here depending on // C/C++/Java/PHP syntax vs. Pascal syntax which // doesn't have fall-through case '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) ... default: raise WhatTheHeckIsThis() class MonopolyProvider2Parser: ... switch row['recordtype']: case 'abc': phone.international += ( Decimal(row['canada cost']) + Decimal(row['eu cost']) + Decimal(row['mexico cost']) + Decimal(row['other intl cost']) ) case 'xyz': phone.text_messaging += int(row['textmessages']) ... default: raise WhatTheHeckIsThis() # The one thing I'm sure I don't understand from the code is where the original rectypes comes into the process. From the provider data -- sometimes CSV files, sometimes tab-delimited text files, sometimes MS Access MDB files, sometimes a web service...varies per-provider (and some providers have multiple formats, like Verizon has MyBIZ and IBAS; ATT has their WinCD and Premier; etc). No two formats are the same, so the logic needed to parse the data into our internal homogenized Phone data structure varies per each one. And the logic (or lack thereof) used by many providers in creating their formats require reverse-engineering most of them through trial-and-error, and huge ugly if/elif/else chains. I wonder if you agree that it's bit cleaner now? It's an effective solution. I'm making no representation that it's the best. It's clean if it were the solution to my problem -- however, the mess comes from the profusion of provider formats. simple (and legible!) one liner. A provider enhances their format, or a new provider format is added, code in one class, not in every switch they might be involved in. But sorry, I don't mean to patronise, I'm sure you know the spiel. Yes, having been programming since I was in middle-school (quick calculation yields a boy I'm old estimate of about 20 years...does anybody miss 360k 5.25 floppy disks? :) and have my degree in CS. So it's not my lack of programming skill/knowledge, but rather your misunderstanding of the problem-space. Not to patronize ;-) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect stdout to a buffer [Errno 9]
I tried to replace official Python dll with the one built with MinGW and it works. The problem is, that port is very old and so far it seems that official support for building Python under MinGW is nowhere near. I really don't want to use MSVC, so if there's any other way around this, please, let me know. -- http://mail.python.org/mailman/listinfo/python-list
Re: no module named error
No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into account, and even if it did - _moda.la is a simple archive-file, not a shared library. It can't be dynamically loaded. Something in your build-process is not working. So how should my stuff find these libs? Here's what I've recently learned ... So if I have the dir path of my c libs inside my exported LD_LIBRARY_PATH (which includes the following files), along w/ the dir to the *.la file ... _moda.a _moda.la - ../_moda.la _moda.lai _moda.so - _moda.so.2.0.1 _moda.so.2 - _moda.so.2.0.1 _moda.so.2.0.1 _moda.so.2.0.1T _moda_la-moda_wrap.o I get the 'ImportError: No module named _moda' error as in previous post. But as I think your saying above, this should not work because LD_LIBRARY_PATH doesn't get used. I was at the python command line '' and I did the following command. import sys sys.path.append('/home/me/my/c/libs/path/.libs') # this is the path to the above listed files, and then when I did ... import moda Everything worked just fine. But I'm not quite sure how to fix it in my script or env. -- http://mail.python.org/mailman/listinfo/python-list
Re: no module named error
On Thu, Dec 10, 2009 at 9:56 AM, Joe invalid.e...@at.address wrote: No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into account, and even if it did - _moda.la is a simple archive-file, not a shared library. It can't be dynamically loaded. Something in your build-process is not working. So how should my stuff find these libs? Here's what I've recently learned ... So if I have the dir path of my c libs inside my exported LD_LIBRARY_PATH (which includes the following files), along w/ the dir to the *.la file ... _moda.a _moda.la - ../_moda.la _moda.lai _moda.so - _moda.so.2.0.1 _moda.so.2 - _moda.so.2.0.1 _moda.so.2.0.1 _moda.so.2.0.1T _moda_la-moda_wrap.o I get the 'ImportError: No module named _moda' error as in previous post. But as I think your saying above, this should not work because LD_LIBRARY_PATH doesn't get used. I was at the python command line '' and I did the following command. import sys sys.path.append('/home/me/my/c/libs/path/.libs') # this is the path to the above listed files, and then when I did ... import moda Everything worked just fine. But I'm not quite sure how to fix it in my script or env. -- http://mail.python.org/mailman/listinfo/python-list http://docs.python.org/library/sys.html sys.path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. A program is free to modify this list for its own purposes. Changed in version 2.3: Unicode strings are no longer ignored. Python uses the PYTHONPATH variable to find modules/libraries, not LD_LIBRARY_PATH. -- http://mail.python.org/mailman/listinfo/python-list
Runtime load python modules from memory
Hello! Is it possible to load python module from memory? For example, I can read python .pyc file into memory, preprocess it ( decrypt :-) ), and then import it. Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on Python as career
In article uhleh59csp2u2a5e9ndtvonmc6ht63k...@4ax.com, Tim Roberts t...@probo.com wrote: There are very, very few full-time Python jobs anywhere in the world, although many people use Python as one tool in their toolbox. Depending on how you define Python job, I disagree with you. All my employment in the last decade, including three different full-time jobs at three different companies, has had Python as the primary job skill requirement and is what I spent more time working with than anything else. I don't think I'm particularly unusual. My company has been trying to hire a person with Python and Linux sysadmin experience for more than three months -- in the San Francisco Bay Area -- with little luck. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes / cygwin / django+geos
Oups, i forgot to say that the tests i am excuting are from Django. (django.gis.tests.test_geos, tag 1.0.2) You can have it online here: http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/tests/test_geos.py -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
ctypes / cygwin / django+geos
I am encountering errors with ctypes and geos. The same configuration (geos-3.0 or geos-3.2) runs fine under classical unixes like freebsd, mac or linux but do not pass with cygwin with 'free' function not found. My configuration is 2.6.4 Release, and a little patch for ctypes which lets all its test pass (loading cygpythonxx.dll instead of libpython.dll): Testing package ctypes.test ('2.6.4 (r264:75706, Dec 6 2009, 16:44:34) \n[GCC 4.3.4 20090804 (release) 1]', 'cygwin', 'posix') .. -- Ran 326 tests in 1.671s (0 modules skipped) Unavailable resources: printing, refcount Then, using it by hand with an helloword library makes no problem. However, using it in my real world UseCase [1], make me think that there is a problem with ctypes. Indeed, geos is compiled and its huge test coverage pass. But then, trying to use ctypes over geos do not work. $ cat geos.py from django.contrib.gis.tests import test_geos test_geos.run() $ /minitage/dependencies/python-2.6/parts/part/bin/python bin/djangopy geos.py Testing WKT output. ... ERROR Testing HEX output. ... ERROR Testing KML output. ... ERROR Testing the Error handlers. ... BEGIN - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Expected number but encountered ',' GEOS_ERROR: ParseException: Unknown WKB type 255 END - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Unexpected EOF parsing WKB ok Testing WKB output. ... ERROR Testing creation from HEX. ... ERROR Testing creation from WKB. ... ERROR Testing EWKT. ... ERROR Testing GeoJSON input/output (via GDAL). ... ok Testing equivalence. ... ERROR Testing Point objects. ... ERROR Testing MultiPoint objects. ... ERROR Testing LineString objects. ... ERROR Testing MultiLineString objects. ... ERROR Testing LinearRing objects. ... ERROR Testing Polygon objects. ... ERROR Testing MultiPolygon objects. ... BEGIN - expecting GEOS_NOTICE; safe to ignore. ERROR Testing Geometry __del__() on rings and polygons. ... ERROR Testing Coordinate Sequence objects. ... ok Testing relate() and relate_pattern(). ... ERROR Testing intersects() and intersection(). ... ok Testing union(). ... ok Testing difference(). ... ok Testing sym_difference(). ... ok Testing buffer(). ... ok Testing the SRID property and keyword. ... ERROR Testing the mutability of Polygons and Geometry Collections. ... ERROR Testing three-dimensional geometries. ... ok Testing the distance() function. ... ok Testing the length property. ... ok Testing empty geometries and collections. ... ERROR Testing `ogr` and `srs` properties. ... ok Testing use with the Python `copy` module. ... ok Testing `transform` method. ... ok Testing `extent` method. ... ok Testing pickling and unpickling support. ... ERROR == ERROR: Testing WKT output. -- Traceback (most recent call last): File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/tests/test_geos.py, line 28, in test01a_wkt self.assertEqual(g.ewkt, geom.wkt) File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/base.py, line 378, in wkt return to_wkt(self.ptr) File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/prototypes/errcheck.py, line 67, in check_string libc.free(result) File /minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py, line 366, in __getattr__ func = self.__getitem__(name) File /minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py, line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'free' not found (*�) -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
ctypes / cygwin / django+geos
I am encountering errors with ctypes and geos. The same configuration (geos-3.0 or geos-3.2) runs fine under classical unixes like freebsd, mac or linux but do not pass with cygwin with 'free' function not found. My configuration is 2.6.4 Release, and a little patch for ctypes which lets all its test pass (loading cygpythonxx.dll instead of libpython.dll): Testing package ctypes.test ('2.6.4 (r264:75706, Dec 6 2009, 16:44:34) \n[GCC 4.3.4 20090804 (release) 1]', 'cygwin', 'posix') .. -- Ran 326 tests in 1.671s (0 modules skipped) Unavailable resources: printing, refcount Then, using it by hand with an helloword library makes no problem. However, using it in my real world UseCase [1], make me think that there is a problem with ctypes. Indeed, geos is compiled and its huge test coverage pass. But then, trying to use ctypes over geos do not work. $ cat geos.py from django.contrib.gis.tests import test_geos test_geos.run() $ /minitage/dependencies/python-2.6/parts/part/bin/python bin/djangopy geos.py Testing WKT output. ... ERROR Testing HEX output. ... ERROR Testing KML output. ... ERROR Testing the Error handlers. ... BEGIN - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Expected number but encountered ',' GEOS_ERROR: ParseException: Unknown WKB type 255 END - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Unexpected EOF parsing WKB ok Testing WKB output. ... ERROR Testing creation from HEX. ... ERROR Testing creation from WKB. ... ERROR Testing EWKT. ... ERROR Testing GeoJSON input/output (via GDAL). ... ok Testing equivalence. ... ERROR Testing Point objects. ... ERROR Testing MultiPoint objects. ... ERROR Testing LineString objects. ... ERROR Testing MultiLineString objects. ... ERROR Testing LinearRing objects. ... ERROR Testing Polygon objects. ... ERROR Testing MultiPolygon objects. ... BEGIN - expecting GEOS_NOTICE; safe to ignore. ERROR Testing Geometry __del__() on rings and polygons. ... ERROR Testing Coordinate Sequence objects. ... ok Testing relate() and relate_pattern(). ... ERROR Testing intersects() and intersection(). ... ok Testing union(). ... ok Testing difference(). ... ok Testing sym_difference(). ... ok Testing buffer(). ... ok Testing the SRID property and keyword. ... ERROR Testing the mutability of Polygons and Geometry Collections. ... ERROR Testing three-dimensional geometries. ... ok Testing the distance() function. ... ok Testing the length property. ... ok Testing empty geometries and collections. ... ERROR Testing `ogr` and `srs` properties. ... ok Testing use with the Python `copy` module. ... ok Testing `transform` method. ... ok Testing `extent` method. ... ok Testing pickling and unpickling support. ... ERROR == ERROR: Testing WKT output. -- Traceback (most recent call last): File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/tests/test_geos.py, line 28, in test01a_wkt self.assertEqual(g.ewkt, geom.wkt) File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/base.py, line 378, in wkt return to_wkt(self.ptr) File /cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/prototypes/errcheck.py, line 67, in check_string libc.free(result) File /minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py, line 366, in __getattr__ func = self.__getitem__(name) File /minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py, line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'free' not found (*�) -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: no module named error
Joe wrote: No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into account, and even if it did - _moda.la is a simple archive-file, not a shared library. It can't be dynamically loaded. Something in your build-process is not working. So how should my stuff find these libs? Here's what I've recently learned ... So if I have the dir path of my c libs inside my exported LD_LIBRARY_PATH (which includes the following files), along w/ the dir to the *.la file ... _moda.a _moda.la - ../_moda.la _moda.lai _moda.so - _moda.so.2.0.1 _moda.so.2 - _moda.so.2.0.1 _moda.so.2.0.1 _moda.so.2.0.1T _moda_la-moda_wrap.o I get the 'ImportError: No module named _moda' error as in previous post. But as I think your saying above, this should not work because LD_LIBRARY_PATH doesn't get used. I was at the python command line '' and I did the following command. import sys sys.path.append('/home/me/my/c/libs/path/.libs') # this is the path to the above listed files, and then when I did ... import moda Everything worked just fine. But I'm not quite sure how to fix it in my script or env. Your installation process is botched (no idea why, you don't show us setup.py or anything else I asked for). All that is missing is what I've asked you now several times before: _moda.so is *NOT* alongside moda.py inside your python's site-packages directory. Copy it in there, and the import will work *without* any sys.path-hackery. Of course you shouldn't do this by hand every time you need to, but instead fix the whole package do to this when python setup.py install is invoked. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Connecting to Python COM server from Excel VBA does not work
the problem was that i had never installed python on my workstation. just had a Python25 folder with a batch-file that was adjustin the PATH and executing %PYTHONHOME%python.exe installed Python properly and now everything works fine -- http://mail.python.org/mailman/listinfo/python-list
Re: Graph library for Python
Geremy Condra: is there a particular way you want your attribution line to read? You can just use my nickname (in all lowercase), with the list of parts you have used. Don't worry. Well, we all seem to have reinvented the wheel differently ;) Maybe also because they are designed for different purposes. Bearophile, Tiago- any interest in trying to combine the best parts of our libraries, with an eye towards eventual integration into the standard library? The first thing to do is to ask Guido and Hettinger if they are willing to put a good graph module into the std lib. If their answer is positive for some definition of good, then we can think about doing something. Several years ago I have suggested to put a graph module in the std lib, and the answer was something like: Put the lib online, and if people use it a lot, we'll see to put it into the std lib. In the meantime my lib was used by no one and ten other graph libs are used (networkx seems among the most used), but I think no one of them has shown a strong usage. (In the meantime Hettinger has written and added two or three or four GOOD data structures to the std lib using a fast lane, avoiding the step of popular usage test). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I Block Events in wxPython
On Thu, Dec 10, 2009 at 6:01 AM, Frank Millman fr...@chagford.com wrote: Another approach is to use wnd.CaptureMouse() on a particular control which doesn't really respond to anything. Just be sure to ReleaseMouse() later and follow the instructions in the docs about capturing that cancel-capture event. I like this. Unfortunately it does not block keyboard input. However, I have a keyboard event handler on virtually all my controls, so it should be easy to set a flag and tell it to ignore keystrokes while in a 'blocked' state. Hm, that's a point. Well if you have a legitimate case for pre-empting the event loop with these periodic regular short blocking moments (it seems you may), I think what you want to do is overwrite FilterEvent on your App object. You can then make that flag something you set on the app, and while it's true, returning False (or True, I really don't know the differenced between telling wx 'Ok, I processed this event you can ignore it' and 'Ok, I'm not going to process this event and neither should you'). Otherwise, return -1. --S HTH, It certainly does - thanks. Frank -- http://mail.python.org/mailman/listinfo/python-list --S -- http://mail.python.org/mailman/listinfo/python-list
Re: Immediate Help with python program!
On 2009-12-10, Rhodri James rho...@wildebst.demon.co.uk wrote: Ahem. This is a newsgroup/mailing list, not IM. I happen to have seen this within half an hour of you posting it, but that's just luck. Expecting an immediate response is unrealistic. Furthermore, this is comp.lang.python, a group right up there in pedantry terms with cam.misc. Wandering in and demanding immediate help is just begging for half a dozen replies that give you detailed and mind-boggling versions of exactly what you asked for, especially if it's got nothing to do with the answer you actually need. An exclamation point in a subject line also tends to act as an excellent lighting rod... -- Grant Edwards grante Yow! Gibble, Gobble, we at ACCEPT YOU ... visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
Asun Friere wrote: On Dec 10, 2:00 pm, Carl Banks pavlovevide...@gmail.com wrote: On Dec 9, 5:02 pm, Asun Friere afri...@yahoo.co.uk wrote: On Dec 9, 7:08 pm, Carl Banks pavlovevide...@gmail.com wrote: What if the object is a string you just read from a file? How do you dispatch using polymorphism in that case? This would be a pertinent question, were I advocating that _all_ switch statements should, or even can, be replaced with dispatch using polymorphism. Then why did you claim that a decent OO should never have a switch statement then? You argued that a decent language OO should never have a switch statement because polymorphic dispatch is the right way to handle it in OO languages, which implies that polymorphism can and should take the place of any switch statement. That is a misreading. I wrote... [snip] You wrote, and I quote, For which reason python has no 'case' statement and why *no decent OO language should* . [emphasis added] Just to be clear. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Moving from Python 2 to Python 3: A 4 page cheat sheet
On Dec 3, 12:12 am, Terry Reedy tjre...@udel.edu wrote: At the moment (3.1) there are, unfortunately, library packages that require % for formatting (logging, I believe, for one). There has been discussion on adding a new option for 3.2, but I do not know what will happen. Depends on whether you want to be absolutely complete. I strictly use .format when I can, which so far is always. Logging uses %-style formatting because that was all that was available at the time it was written. A frequent complaint from some quarters is about the overhead of logging, and so I'm not sure it's a good idea to switch over from %-formatting to str.format just for the sake of it, unless a way can be found which avoids the problems of lower performance and backwards compatibility (e.g. a foolproof %- string to {} converter, which I've had a stab at, but which cannot be achieved without changes to the {} code, e.g. to allow old-style octal constants). As far as logging is concerned I'll be periodically looking to see if moving over to the new format without performance/ backwards compatibility compromises is feasible, and when it is I'll adopt the new format. For now, AFAIK, people who are determined to use the {}-format can do so by subclassing logging.Formatter and by passing in message classes which convert format-string and args to final message. It's a one-time cost they'd incur (to write the relevant subclasses) which could be used on multiple projects. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
On Thu, 10 Dec 2009 05:47:19 +, Steven D'Aprano wrote: I string together a bunch of elif statements to simulate a switch if foo == True: blah elif bar == True: blah blah elif bar == False: blarg elif This isn't what would normally be considered a switch (i.e. what C considers a switch). Anyone would think that C was the only programming language in existence... It's the only one I know of which calls such statements switch statements. Most other languages call them case statements. A switch tests the value of an expression against a set of constants. In C. Things may be different in other languages. For example, I recall the so-called 4GL (remember when that was the marketing term of choice for interpreted programming languages?) Hyperscript from Informix. I can't check the exact syntax right now, but it had a switch statement which allowed you to do either C-like tests against a single expression, or if-like multiple independent tests. Interpreted languages generally don't care about the labels being constant, so you can do e.g. (BBC BASIC V): CASE TRUE OF WHEN foo: blah WHEN bar: blah blah WHEN NOT(bar): blarg ENDCASE The test expression is compared against each case expression sequentially until one matches; both the test expression and case expressions are evaluated at run-time. This is essentially just an if/elif chain with different syntax, whereas a C-style switch may be signficiantly more efficient (e.g. using a jump table or a balanced tree). Compiled languages' switch statements typically require constant labels as this enables various optimisations. Pascal, for example, can test against either single values, enumerated values, or a range of values: case n of 0: writeln('zero'); 1, 2: writeln('one or two'); 3...10: writeln('something between three and ten'); else writeln('something different'); end; IOW, identical semantics to C, but with some extra syntax to avoid the need to write multiple consecutive labels. -- http://mail.python.org/mailman/listinfo/python-list
Re: switch
Steven D'Aprano wrote: On Wed, 09 Dec 2009 18:50:29 +, Nobody wrote: On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: I string together a bunch of elif statements to simulate a switch if foo == True: blah elif bar == True: blah blah elif bar == False: blarg elif This isn't what would normally be considered a switch (i.e. what C considers a switch). Anyone would think that C was the only programming language in existence... A switch tests the value of an expression against a set of constants. In C. Things may be different in other languages. For example, I recall the so-called 4GL (remember when that was the marketing term of choice for interpreted programming languages?) Hyperscript from Informix. I can't check the exact syntax right now, but it had a switch statement which allowed you to do either C-like tests against a single expression, or if-like multiple independent tests. Moving away from obsolete languages, we have Ruby which does much the same thing: if you provide a test value, the case expression does a C- like test against that expression, and if you don't, it does if-like multiple tests. http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what- you-can-do-with-it/ If you were writing the above in C, you would need to use a chain of if/else statements; you couldn't use a switch. Compiled languages' switch statements typically require constant labels as this enables various optimisations. Pascal, for example, can test against either single values, enumerated values, or a range of values: case n of 0: writeln('zero'); 1, 2: writeln('one or two'); 3...10: writeln('something between three and ten'); else writeln('something different'); end; Originally the 'case' statement in Pascal didn't support ranges or a default; they started as non-standard extensions in some implementations. Originally, if none of the values matched then that was a runtime error. -- http://mail.python.org/mailman/listinfo/python-list
ANN: Wing IDE 3.2.3 released
Hi, Wingware has released version 3.2.3 of Wing IDE, our integrated development environment for the Python programming language. Wing IDE can be used on Windows, Linux, and OS X to develop Python code for web, GUI, and embedded scripting applications. Wing IDE provides auto-completion, call tips, a powerful debugger, unit testing, version control, search, and many other features. This release introduces the following minor features and improvements: * Show return value types in Source Assistant * Add preference to control folding of trailing white space * Add preference to use ## style comments in comment-out feature * Show number of search and replace matches * Added documentation for using Wing with Autodesk Maya * Correct analysis of Python 3.x builtins * Fix tutorial to work under Python 3.x as well * Turn off mixed indent tab size forcing until time of read or save * Fix issues with debugger API used for embedded debugging * Several other minor features and bug fixes. See the change log for details: http://wingware.com/pub/wingide/3.2.3/CHANGELOG.txt *Wing 3.2 Highlights* Versions 3.2.x of Wing IDE include the following new features not present in Wing IDE 3.1: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) * Improved OS Commands and Bookmarks tools (*) * Support for debugging 64-bit Python on OS X (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.3/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.3http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.3 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.3http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities. These features reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. 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 entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. For more product information see http://wingware.com/products *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license:https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 7, 12:58 pm, Carl Banks pavlovevide...@gmail.com wrote: On Dec 7, 10:53 am, dbd d...@ieee.org wrote: ... You're talking about machine epsilon? I think everyone else here is talking about a number that is small relative to the expected smallest scale of the calculation. Carl Banks When you implement an algorithm supporting floats (per the OP's post), the expected scale of calculation is the range of floating point numbers. For floating point numbers the intrinsic truncation error is proportional to the value represented over the normalized range of the floating point representation. At absolute values smaller than the normalized range, the truncation has a fixed value. These are not necessarily 'machine' characteristics but the characteristics of the floating point format implemented. A useful description of floating point issues can be found: http://dlc.sun.com/pdf/800-7895/800-7895.pdf Dale B. Dalrymple -- http://mail.python.org/mailman/listinfo/python-list
Re: no module named error
Your installation process is botched (no idea why, you don't show us setup.py or anything else I asked for). Sorry, but I do know how it's currently installed is exactly the way I need it to be installed. All that is missing is what I've asked you now several times before: _moda.so is *NOT* alongside moda.py inside your python's site-packages directory. Copy it in there, and the import will work *without* any sys.path-hackery. Yeah, that's something I don't want to do. But you've given me enough info to help me understand what's going on and how to fix it. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl to Python conversion
martin.sch...@gmail.com (Martin Schöön) writes: First off: I am new here and this is my first post after lurking for quite some time. Hi. Second off: I don't know much Python---yet. It's not a very big language. If you have experience programming in other languages, you can probably pick it up in a day or two. Problem: I have come across a small open source application that I find quite useful. It does have one major flaw though. Its output is in imperial units. Converting isn't a big deal for occasional use but if I start to use this stuff on a regular basis... So I down-loaded the source code and found this thing is written in Perl. Should I learn enough Perl to add the conversion? Probably but this may be a nice excuse to get my Python education going and if I do I might as well re-do the user interface. Well you can always call it from Python via subprocess (which basically wraps a shell and has fancy ways putting data in and extracting data out). If I do re-write this thing in Python I might need to learn both Perl and Python... You'll need to know one of them rather well and enough of the other to get by. It's probably easier to know more Perl than Python since Perl is a lot more expressive than Python (in the TMTOWTDI sense). Frankly I learned Perl before Python and find it rather easy to go between the two. YMMV. Hence, are there any Perl to Python converters? So far I have only found bridgekeeper which really is (was?) consultancy. Apart from that I only find people recommending a manual re-write. It depends where the two languages vary from one another. If the script your translating uses basic types or even simple classes and typical control structures and operations then translating from one to the other is a simple matter of copy-pasting the code and translating the syntax and small bits of grammar. However, in areas where there are high variations; you'll probably want to stay away from it. Perl has a lot of freedom to manipulate references and the programmer can modify the language to suit their needs. So just be careful of code that uses these features as they are difficult to translate into Python. Any thoughts/recommendations? Depends: - If you needed it done yesterday to get some work done, wrap the Perl script in a subprocess and buy yourself some time to think it over. - If your purpose is to learn Python, then start from scratch. Use the Perl as a guide if there are any maths or algorithms you are unsure about. - If you're just hacking around to learn stuff, learn a little of both. It will make you smarter if it doesn't confuse the heck out of you and make you quit before you finish. ;) TIA, /Martin HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: C to Python
Emeka emekamicro at gmail.com writes: Hello All, I am finding it difficult getting my head around PyObject_CallObject(x,y). I need a gentle and thorough introduction to it. I also need examples. Could someone come to my need? PyObject_CallFunction is probably easier to use. http://docs.python.org/c-api/object.html#PyObject_CallObject -- http://mail.python.org/mailman/listinfo/python-list
Re: plain text parsing to html (newbie problem)
On 12/10/2009 11:17 PM, João wrote: Thanks for the output. akean, I've installed ipython and I'm exploring it. Thanks. Terry, from what I've read stringIO allows us to store strings in a 'virtual' file. Can you please write just 2 lines exemplifying a write to and a read from an OS level file? MRAB, that 'mail' object should've been the os level 'mail' file. But as I'm a beginner I was using it wrong.. it's actually easier to use real files than creating a virtual file: f = open('mail.txt', 'w') f.write(foo\n) # or print f, foo and, is there any reason why you're not using the email and smtplib? http://docs.python.org/library/email-examples.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl to Python conversion
Thanks all, great response! A little more background: I am not a programmer but I have done some programming in the past. This was all humble number crunching as part of my PhD project using FORTRAN. I also did some Rocky Mountain Basic coding for programs manipulating measurement instruments. And I did a minute amount of Turbo Pascal code, too little and too many years ago to count. Since then I have done some stuff in Matlab and (very basic) UNIX scripts. Does HTML, css and LaTeX count? So why Python? Well, I thought it would be fun to learn a little about GUI programming and a friend who is a real programmer recommended Python + PyQt. I have bought some books and lurked here for about a year but haven't managed to get going yet. I figured I needed some kind of project for that and now I have two. Learning Python and PyQt is spare time killer/brain teaser activity. The thermal contact conductance stuff is something that come in handy at work. So here is what I plan to do based on your kind advice and some thinking of my own. 1) I fix the unit thing by adding a conversion to the results presentation routine. 2) Recreating the functionality of the program in Python and PyQt will be a 'long term' educational project at home. There are various bits and pieces there: data base handling, GUI design, math, logic, error/exception handling... We have long, dark winters where I live :-) All the best, /Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing local variables from the pdb debugger
On 12/11/2009 12:37 AM, Jean-Michel Pichavant wrote: Diez B. Roggisch wrote: By just inserting the print foo statement right after changing foo's value, I've rolled back the value to 'foo' ??? A hell of a wtf pdb feature ! Apparently it's fixed in 2.7 and 3.1 D:\Lie Ryan\Desktoppython27 d.py d:\lie ryan\desktop\d.py(6)test() - print(foo) (Pdb) foo = bar (Pdb) pp foo 'bar' (Pdb) c bar D:\Lie Ryan\Desktoppython27 d.py d:\lie ryan\desktop\d.py(6)test() - print(foo) (Pdb) foo = bar (Pdb) c bar -- http://mail.python.org/mailman/listinfo/python-list
Re: freeze in python3
For example, initerrno should now be PyInit_errno. Am I missing something? No; freeze hasn't been ported to Python 3 yet. Contributions are welcome. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
On Dec 10, 10:46 am, dbd d...@ieee.org wrote: On Dec 7, 12:58 pm, Carl Banks pavlovevide...@gmail.com wrote: On Dec 7, 10:53 am, dbd d...@ieee.org wrote: ... You're talking about machine epsilon? I think everyone else here is talking about a number that is small relative to the expected smallest scale of the calculation. Carl Banks When you implement an algorithm supporting floats (per the OP's post), the expected scale of calculation is the range of floating point numbers. For floating point numbers the intrinsic truncation error is proportional to the value represented over the normalized range of the floating point representation. At absolute values smaller than the normalized range, the truncation has a fixed value. These are not necessarily 'machine' characteristics but the characteristics of the floating point format implemented. I know, and it's irrelevant, because no one, I don't think, is talking about magnitude-specific truncation value either, nor about any other tomfoolery with the floating point's least significant bits. A useful description of floating point issues can be found: [snip] I'm not reading it because I believe I grasp the situation just fine. But you are welcome to convince me otherwise. Here's how: Say I have two numbers, a and b. They are expected to be in the range (-1000,1000). As far as I'm concerned, if they differ by less than 0.1, they might as well be equal. Therefore my test for equality is: abs(a-b) 0.08 Can you give me a case where this test fails? If a and b are too far out of their expected range, all bets are off, but feel free to consider arbitrary values of a and b for extra credit. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
Il Thu, 10 Dec 2009 04:56:33 +, Brad Harms ha scritto: On Thu, 10 Dec 2009 00:29:45 +, mattia wrote: Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: On Dec 9, 11:53 pm, mattia ger...@gmail.com wrote: Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. Ouch, so the simplest solution is just insert in the 'main' function a try/catch? I believed there was the necessity to create a signal and than attach the KeyboardInterrupt to it... KeyboardInterrupt is just an exception that gets raised when CTLR+C (or the OS's equivalent keyboard combo) gets pressed. It can occur at any point in a script since you never know when the user will press it, which is why you put the try: except KeyboardInterrupt: around as much of your script as possible. The signal that the OS sends to the Python interpreter is irrelevant. Ok, so can you tell me why this simple script doesn't work (i.e. I'm not able to catch the keyboard interrupt)? import time import sys from threading import Thread def do_work(): for _ in range(1000): try: time.sleep(1) print(., end=) sys.stdout.flush() except KeyboardInterrupt: sys.exit() def go(): threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() go() -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
On Thu, Dec 10, 2009 at 4:42 PM, mattia ger...@gmail.com wrote: def go(): threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() The KeyboardInterrupt goes to the main thread, which is sitting there in t.join() with no exception handler around it. -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC http://stutzbachenterprises.com -- http://mail.python.org/mailman/listinfo/python-list
umath import error for Numpy builds on OSX 10.6
For the past several weeks, I have been unable to build numpy from source, at least nothing that works. The issue is that symbols appear to be missing from umath. When numpy is imported, I get the following: In [1]: import numpy Traceback (most recent call last): File ipython console, line 1, in module File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/__init__.py, line 132, in module import add_newdocs File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/add_newdocs.py, line 9, in module from numpy.lib import add_newdoc File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/lib/__init__.py, line 4, in module from type_check import * File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/lib/type_check.py, line 8, in module import numpy.core.numeric as _nx File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py, line 6, in module import umath ImportError: dlopen(/Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so, 2): Symbol not found: _npy_cexp Referenced from: /Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so Expected in: flat namespace in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- macosx-10.6-universal.egg/numpy/core/umath.so I think my build script is good, but here it is just incase: #!/bin/sh export MACOSX_DEPLOYMENT_TARGET=10.6 export CFLAGS=-arch x86_64 #export FFLAGS=-arch i386 -arch x86_64 export FFLAGS=-arch x86_64 export LDFLAGS=-Wall -lgfortran -undefined dynamic_lookup -bundle - arch x86_64 rm -rf build python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ fonnesbeck/Code/libpng build python setupegg.py egg_info --tag-date bdist_egg I'm at my wits end with this one, so any help at all is most appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
mattia wrote: Il Thu, 10 Dec 2009 04:56:33 +, Brad Harms ha scritto: On Thu, 10 Dec 2009 00:29:45 +, mattia wrote: Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: On Dec 9, 11:53 pm, mattia ger...@gmail.com wrote: Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. Ouch, so the simplest solution is just insert in the 'main' function a try/catch? I believed there was the necessity to create a signal and than attach the KeyboardInterrupt to it... KeyboardInterrupt is just an exception that gets raised when CTLR+C (or the OS's equivalent keyboard combo) gets pressed. It can occur at any point in a script since you never know when the user will press it, which is why you put the try: except KeyboardInterrupt: around as much of your script as possible. The signal that the OS sends to the Python interpreter is irrelevant. Ok, so can you tell me why this simple script doesn't work (i.e. I'm not able to catch the keyboard interrupt)? import time import sys from threading import Thread def do_work(): for _ in range(1000): try: time.sleep(1) print(., end=) sys.stdout.flush() except KeyboardInterrupt: sys.exit() def go(): threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() go() Only the main thread can receive the keyboard interrupt. -- http://mail.python.org/mailman/listinfo/python-list
Re: umath import error for Numpy builds on OSX 10.6
On 2009-12-10 17:09 PM, hardcoreUFO wrote: For the past several weeks, I have been unable to build numpy from source, at least nothing that works. The issue is that symbols appear to be missing from umath. When numpy is imported, I get the following: You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists In [1]: import numpy Traceback (most recent call last): File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py, line 6, in module import umath ImportError: dlopen(/Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so, 2): Symbol not found: _npy_cexp Referenced from: /Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so Expected in: flat namespace in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- macosx-10.6-universal.egg/numpy/core/umath.so I think my build script is good, but here it is just incase: #!/bin/sh export MACOSX_DEPLOYMENT_TARGET=10.6 export CFLAGS=-arch x86_64 #export FFLAGS=-arch i386 -arch x86_64 export FFLAGS=-arch x86_64 export LDFLAGS=-Wall -lgfortran -undefined dynamic_lookup -bundle - arch x86_64 rm -rf build python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ fonnesbeck/Code/libpng build python setupegg.py egg_info --tag-date bdist_egg I'm at my wits end with this one, so any help at all is most appreciated. Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for the npy_math library that numpy builds internally and tries to link with. -- 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: umath import error for Numpy builds on OSX 10.6
On Dec 11, 12:29 pm, Robert Kern robert.k...@gmail.com wrote: On 2009-12-10 17:09 PM, hardcoreUFO wrote: For the past several weeks, I have been unable to build numpy from source, at least nothing that works. The issue is that symbols appear to be missing from umath. When numpy is imported, I get the following: You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists In [1]: import numpy Traceback (most recent call last): File /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py, line 6, in module import umath ImportError: dlopen(/Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so, 2): Symbol not found: _npy_cexp Referenced from: /Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so Expected in: flat namespace in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- macosx-10.6-universal.egg/numpy/core/umath.so I think my build script is good, but here it is just incase: #!/bin/sh export MACOSX_DEPLOYMENT_TARGET=10.6 export CFLAGS=-arch x86_64 #export FFLAGS=-arch i386 -arch x86_64 export FFLAGS=-arch x86_64 export LDFLAGS=-Wall -lgfortran -undefined dynamic_lookup -bundle - arch x86_64 rm -rf build python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ fonnesbeck/Code/libpng build python setupegg.py egg_info --tag-date bdist_egg I'm at my wits end with this one, so any help at all is most appreciated. Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for the npy_math library that numpy builds internally and tries to link with. Thanks Robert. I was not able to solve the problem on the Numpy list, so I had to broaden the search.Will try what you suggest, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: umath import error for Numpy builds on OSX 10.6
On Dec 11, 12:29 pm, Robert Kern robert.k...@gmail.com wrote: Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for the npy_math library that numpy builds internally and tries to link with. Unfortunately, that did not eliminate the error. I thought it was something that was changed in Numpy, because my first go at building was successful on Snow Leopard; it suddenly stopped working a few weeks ago. -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
Il Thu, 10 Dec 2009 23:10:02 +, Matthew Barnett ha scritto: mattia wrote: Il Thu, 10 Dec 2009 04:56:33 +, Brad Harms ha scritto: On Thu, 10 Dec 2009 00:29:45 +, mattia wrote: Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: On Dec 9, 11:53 pm, mattia ger...@gmail.com wrote: Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. Ouch, so the simplest solution is just insert in the 'main' function a try/catch? I believed there was the necessity to create a signal and than attach the KeyboardInterrupt to it... KeyboardInterrupt is just an exception that gets raised when CTLR+C (or the OS's equivalent keyboard combo) gets pressed. It can occur at any point in a script since you never know when the user will press it, which is why you put the try: except KeyboardInterrupt: around as much of your script as possible. The signal that the OS sends to the Python interpreter is irrelevant. Ok, so can you tell me why this simple script doesn't work (i.e. I'm not able to catch the keyboard interrupt)? import time import sys from threading import Thread def do_work(): for _ in range(1000): try: time.sleep(1) print(., end=) sys.stdout.flush() except KeyboardInterrupt: sys.exit() def go(): threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() go() Only the main thread can receive the keyboard interrupt. Ok, so is there any way to stop all the threads if the keyboard interrupt is received? -- http://mail.python.org/mailman/listinfo/python-list
Issues with multiprocessing
Hi, I have an application that uses multiprocessing pools (multiprocessing.Pool(processes=.)). There are multiple such pools and each pool has configurable number of processes. Once the process is spawned, it keeps on executing and does the needed processing. If there is nothing to process (like ftp'ing files from some source, if the files are not there, the process would sleep for some time, and then again check for files, that way, it is a infinite loop with some sleep), the process 'sleeps' for some time and continues. I am using a T5220, Solaris box with Solaris 10. Problem -there are multiple pools and multiple processes, i am seeing that not all the processes get spawned. They get spawned when the sleep time is increased (say from 0.1 sec to 1 sec). If I further increase the number of processes, again some process do not get spawned. For that, I further need to increase the sleep time (say to 2 sec), then the processes get spawned. Typically, in a multiprocessing I would expect that if a process sleeps for even a small time, other processes should get their chance to execute, but this does not seem to be happening here. Can you please throw some light on it? Thanks and Regards, Yateen V. Joshi This email and any attachments may contain legally privileged and/or confidential information of Starent Networks, Corp. and is intended only for the individual or entity named in the message. The information transmitted may not be used to create or change any contractual obligations of Starent Networks, Corp. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this e-mail and its attachments by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify the sender immediately -- by replying to this message or by sending an email to postmas...@starentnetworks.com -- and destroy all copies of this message and any attachments without reading or disclosing their contents. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Issues with multiprocessing
Hi, I have an application that uses multiprocessing pools (multiprocessing.Pool(processes=.)). There are multiple such pools and each pool has configurable number of processes. Once the process is spawned, it keeps on executing and does the needed processing. If there is nothing to process (like ftp'ing files from some source, if the files are not there, the process would sleep for some time, and then again check for files, that way, it is a infinite loop with some sleep), the process 'sleeps' for some time and continues. I am using a T5220, Solaris box with Solaris 10. Problem -there are multiple pools and multiple processes, i am seeing that not all the processes get spawned. They get spawned when the sleep time is increased (say from 0.1 sec to 1 sec). If I further increase the number of processes, again some process do not get spawned. For that, I further need to increase the sleep time (say to 2 sec), then the processes get spawned. Typically, in a multiprocessing I would expect that if a process sleeps for even a small time, other processes should get their chance to execute, but this does not seem to be happening here. Can you please throw some light on it? Thanks and Regards, Yateen V. Joshi This email and any attachments may contain legally privileged and/or confidential information of Starent Networks, Corp. and is intended only for the individual or entity named in the message. The information transmitted may not be used to create or change any contractual obligations of Starent Networks, Corp. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this e-mail and its attachments by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify the sender immediately -- by replying to this message or by sending an email to postmas...@starentnetworks.com -- and destroy all copies of this message and any attachments without reading or disclosing their contents. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
file does not work with the with statement!
I have just discovered that the syntax with file(name, 'w') as f: do_something(f) does not close the file at the end of the with statement! On the contrary with open(name, 'w') as f: do_something(f) works fine. The docs say When opening a file, it’s preferable to use open() instead of invoking this constructor directly. but perhaps they should mention why :( -- http://mail.python.org/mailman/listinfo/python-list
Implementation suggestions for creating a Hierarchical circuit database
Hi, I am writing a personal software that will read circuit design/ netlist. I will be using the MCNC benchmarks that contain different types of designs in SPICE netlist format. I need some pointers/papers/suggestions on creating a hierarchical netlist database. The netlist database can, at times, be fully flattened, partially flattened or fully hierarchical. I should be able to answer queries like: are there any capacitors connected to node: x1.x2.n1? My program is currently only for analyzing designs for connectivity, types of elements (resistors/capacitors) and figuring out some simple electrical properties. I am just starting, so please bear with me if I haven't thought about corner cases. Regards Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?)
That was a joke in the tree view. You clicked on the science link in the tree hierarchy. I will fix it due to your complaint. Fixed. Now clicking on the same link goes to Scientific American. http://whiffdoc.appspot.com/ Is that humourless enough for you? :) You are now immortalized in the WHIFF repository http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/rev/6d8c650102dd Please let me know if anything else offends your sensibilities. Thanks again, -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -- kliban -- http://mail.python.org/mailman/listinfo/python-list
Re: Brent's variation of a factorization algorithm
PPS The code was successfully tested e.g. here: http://www.spoj.pl/ranks/FACT1/ (see my 2nd and 4th places). They confused versions: the 2nd is in Python 2.5, not 2.6.2. PPPS Funnilly... almost only Python on the 1st page =) -- http://mail.python.org/mailman/listinfo/python-list
Re: Brent's variation of a factorization algorithm
On Dec 10, 1:11 am, Irmen de Jong ir...@-nospam-xs4all.nl wrote: 9 == 27 * 37037037 What gives? Isn't this thing supposed to factor numbers into the product of two primes? -irmen Only if you yield to it a SEMIprime =) 27 * 37037037 Now you can apply brent() to these numbers, and so on -- http://mail.python.org/mailman/listinfo/python-list
Re: Brent's variation of a factorization algorithm
On 12/10/09 12:52 AM, n00m wrote: On Dec 10, 1:11 am, Irmen de Jongir...@-nospam-xs4all.nl wrote: 9 == 27 * 37037037 What gives? Isn't this thing supposed to factor numbers into the product of two primes? -irmen Only if you yield to it a SEMIprime =) A 'semiprime' being a product of 2 prime numbers, I suppose. 27 * 37037037 Now you can apply brent() to these numbers, and so on Right :) I more or less expected it to do that by itself (didn't look at the algorithm) But you wrote that it might run indefinately if you feed it a prime number. There's no safeguard then against getting into an endless loop if you keep applying brent() to the factors it produces? Because in the end one or both factors will be prime... -irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: Brent's variation of a factorization algorithm
On Dec 10, 2:59 am, Irmen de Jong irmen.nos...@xs4all.nl wrote: On 12/10/09 12:52 AM, n00m wrote: On Dec 10, 1:11 am, Irmen de Jongir...@-nospam-xs4all.nl wrote: 9 == 27 * 37037037 What gives? Isn't this thing supposed to factor numbers into the product of two primes? -irmen Only if you yield to it a SEMIprime =) A 'semiprime' being a product of 2 prime numbers, I suppose. 27 * 37037037 Now you can apply brent() to these numbers, and so on Right :) I more or less expected it to do that by itself (didn't look at the algorithm) But you wrote that it might run indefinately if you feed it a prime number. There's no safeguard then against getting into an endless loop if you keep applying brent() to the factors it produces? Because in the end one or both factors will be prime... -irmen Just to use e.g. Rabin-Miller's before supplying a number to brent() A 'semiprime' being a product of 2 prime numbers, I suppose. Aha, exactly. == Also it's worthy to test a num is it a perfect square? But all this is obvious trifles... -- http://mail.python.org/mailman/listinfo/python-list
Re: Implementation suggestions for creating a Hierarchical circuit database
nick freesof...@gmail.com writes: I am writing a personal software that will read circuit design/ netlist. I will be using the MCNC benchmarks that contain different types of designs in SPICE netlist format. [snip] You cross-posted this question to comp.theory, comp.lang.c++, comp.lang.c, comp.lang.python, and sci.math. Since you don't mention anything about any implementation language, I don't see how your question is relevant to any of the comp.lang.* groups. If you have questions about a particular language, feel free to post to comp.lang.whatever. (I won't bother to redirect followups, since that affects only followups to *this* article, but please consider trimming the newsgroups line.) -- Keith Thompson (The_Other_Keith) ks...@mib.org http://www.ghoti.net/~kst Nokia We must do something. This is something. Therefore, we must do this. -- Antony Jay and Jonathan Lynn, Yes Minister -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
On Dec 9, 11:53 pm, mattia ger...@gmail.com wrote: Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: On Dec 9, 11:53 pm, mattia ger...@gmail.com wrote: Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. Ouch, so the simplest solution is just insert in the 'main' function a try/catch? I believed there was the necessity to create a signal and than attach the KeyboardInterrupt to it... -- http://mail.python.org/mailman/listinfo/python-list
Re: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing?
On Dec 9, 11:58 am, Valery khame...@gmail.com wrote: Hi all, Q: how to organize parallel accesses to a huge common read-only Python data structure? Details: I have a huge data structure that takes 50% of RAM. My goal is to have many computational threads (or processes) that can have an efficient read-access to the huge and complex data structure. snip 1. multi-processing = a. child-processes get their own *copies* of huge data structure -- bad and not possible at all in my case; How's the layout of your data, in terms # of objects vs. bytes used? Just to have an idea of the overhead involved in refcount externalization (you know, what I mentioned here: http://groups.google.com/group/unladen-swallow/browse_thread/thread/9d2af1ac3628dc24 ) -- http://mail.python.org/mailman/listinfo/python-list
Re: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing?
Hi Klauss, How's the layout of your data, in terms # of objects vs. bytes used? dict (or list) of 10K-100K objects. The objects are lists or dicts. The whole structure eats up to 2+ Gb RAM Just to have an idea of the overhead involved in refcount externalization (you know, what I mentioned here:http://groups.google.com/group/unladen-swallow/browse_thread/thread/9... ) yes, I've understood the idea explained by you there. regards, Valery -- http://mail.python.org/mailman/listinfo/python-list
Re: freeze in python3
awesome! On Thu, Dec 10, 2009 at 2:17 PM, Martin v. Loewis mar...@v.loewis.de wrote: For example, initerrno should now be PyInit_errno. Am I missing something? No; freeze hasn't been ported to Python 3 yet. Contributions are welcome. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: IndentationError
hong zhang wrote: List, I got error says IndentationError in end of line. I could not figure out why. See following: $ ./cont-mcs File ./cont-mcs, line 264 mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val ^ IndentationError: unindent does not match any outer indentation level Look at previous lines. Make sure you only use tabs or only use spaces and not both. If you still need help, post all code back to last unindented line. -- http://mail.python.org/mailman/listinfo/python-list
Re: Float precision and float equality
[Carl Banks] You're talking about machine epsilon? I think everyone else here is talking about a number that is small relative to the expected smallest scale of the calculation. That was also my reading of the OP's question. The suggestion to use round() was along the lines of performing a quantize or snap-to-grid operation after each step in the calculation. That approach parallels the recommendation for how to use the decimal module for fixed point calculations: http://docs.python.org/library/decimal.html#decimal-faq Raymond -- http://mail.python.org/mailman/listinfo/python-list
urllib post and redirect = fail
I'm trying to do a post to log into a simple admin console. All I get is a simple you need to log in error. I already mapped the form id's to make sure they are correct, but it still seems to deny. I know mechanize would probably do a better job of this than urllib, but their docs for python aren't available online right now. Any help is appreciated. import urllib, urllib2 # build opener with HTTPCookieProcessor o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( o ) # assuming the site expects 'user' and 'pass' as query params #p = urllib.urlencode( { 'j_character_encoding' : 'UTF-8', 'j_username': 'cooduser', 'j_password': 'password' } ) p = urllib.urlencode(dict(j_username='cooduser', j_password='password')) # perform login with params f = o.open( 'http://myserver:5000/login/LoginForm.jsp', p ) data = f.read() f.close() print data Here is the form source: form id=loginData name=loginData method=post action=/console/j_security_check div class=message-row p class=loginFailedimg src=/console/images/message_error.gif alt='Authentication Denied ' Authentication Denied/p pThe username or password has been refused by Server. Please try again./p /div div class=input-row label for=j_username Username:/label span class=ctrl input class=textinput type=text name=j_username id=j_username /span /div div class=input-row label for=j_password Password:/label span class=ctrl input class=textinput type=password name=j_password id=j_password /span /div div class=button-row span class=ctrl input class=formButton type=submit onclick=form.submit();this.disabled=true;document.body.style.cursor = 'wait'; this.className='formButton-disabled'; value='Log In' /span input type=hidden name=j_character_encoding value=UTF-8 /div /form The response code is 200. Here is the header info from f.info() : Cache-Control: no-cache Connection: close Date: Fri, 11 Dec 2009 01:29:40 GMT Pragma: no-cache Content-Length: 3534 Content-Type: text/html; charset=UTF-8 Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: NCONSOLESESSION=QwcDLhgG5NrxJGBQJfpv1dynvpddjT4LJTHnGhYz9ZDl6R9Pzqvh!2016686010; path=/ X-Powered-By: Servlet/2.5 JSP/2.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: IndentationError
En Wed, 09 Dec 2009 16:32:18 -0300, hong zhang henryzhan...@yahoo.com escribió: I got error says IndentationError in end of line. I could not figure out why. See following: $ ./cont-mcs File ./cont-mcs, line 264 mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val ^ IndentationError: unindent does not match any outer indentation level The caret ^ might be misplaced; look at start of line 264, or perhaps the previous line. Remember not to mix tabs and spaces. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
daemon.DaemonContext and logging
I'm finally getting around to trying out the python-daemon module and have hit a wall. I'm trying to set up logging inside of the with daemon.DaemonContext block. But when I try to use a logger inside the block it throws an error: ~~ from __future__ import with_statement import logging import logging.handlers import daemon import daemon.pidlockfile import sys logger = logging.getLogger(DaemonLog) logger.setLevel(logging.INFO) formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s) handler = logging.FileHandler(log.file) logger.addHandler(handler) pid = daemon.pidlockfile.TimeoutPIDLockFile(/var/run/daemontest.pid, 10) with daemon.DaemonContext(pidfile=pid, gid=0, uid=0, stdout=sys.stdout, stderr=sys.stderr): logger.info(POO) ~~ I get the following traceback: ~~ [seans_imac:~/Downloads] halfitalian% Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 753, in emit self.flush() File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 731, in flush self.stream.flush() IOError: [Errno 9] Bad file descriptor Error in atexit._run_exitfuncs: Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 1355, in shutdown h.close() File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 784, in close self.stream.close() IOError: [Errno 9] Bad file descriptor Error in sys.exitfunc: Traceback (most recent call last): File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/atexit.py, line 24, in _run_exitfuncs func(*targs, **kargs) File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 1355, in shutdown h.close() File /Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py, line 784, in close self.stream.close() IOError: [Errno 9] Bad file descriptor ~~~ Any advice? Also, I left in the call to TimeoutPIDLockfile() as well, because the library's documentation is pretty sparse, and I want to know if I'm using it properly. Thanks in advance. ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: using freeze.py with python3
En Wed, 09 Dec 2009 17:04:45 -0300, Patrick Stinson patrickstinson.li...@gmail.com escribió: Has anyone tried using Python-3.1.1/Tools/freeze/freeze.py with the encodings package? It appears that encodings is required to intialize the interpreter, but PyImport_ImportFrozenModule is failing for the encodings module in marshal.c:r_object(), after trying to demarshal an object of type 0. I'd report this at http://bugs.python.org -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Porting pyftpdlib to Python 3.x: question about tarball naming convention
En Wed, 09 Dec 2009 20:13:17 -0300, Giampaolo Rodola' gne...@gmail.com escribió: I've started the (hard) process of porting pyftpdlib [1] to Python 3. In order to do that I'm working on a separate SVN branch and I plan to maintain two different releases of my software, one for 2.x and another one for 3.x. I would not do that. Try to keep a single source (2.x) and use 2to3 to automatically generate the 3.x version. Perhaps including some conditionals checking sys.version_info. Somewhere in the wiki there are porting guidelines. (Try to resist the temptation to alter the 3.x code: it must remain generated by the 2to3 conversion) My doubts are about the naming convention I have to use for the tarball and how it affects the integration with distutils and setuptools. Now that I'm going to have two major releases (pyftpdlib-0.5.2 for Python 2.x and pyftpdlib-0.5.2 for Python 3.x) how am I supposed to deal with that? If you manage to write the code in a way that 2to3 can convert it to 3.x without any problems, then you don't have to distribute the 3.x sources at all. Just run 2to3 on the target system as part of the install process. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
On 12/11/2009 10:43 AM, mattia wrote: Ok, so is there any way to stop all the threads if the keyboard interrupt is received? You can't stop a thread from outside. The thread has to end itself (by ending the function). Usually, in the thread, you will check the value of a variable. If it's false, then it's time to stop and head to the end of the function. # global, or better use a Quit sentinel in a Queue import time, sys from threading import Thread running = True def do_work(): while True: time.sleep(1) print(., end=) sys.stdout.flush() if running == False: break print('thread ended') def go(): global running threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() try: while running: time.sleep(1) running = any(t.is_alive() for t in threads) except KeyboardInterrupt: running = False -- http://mail.python.org/mailman/listinfo/python-list
Re: KeyboardInterrupt
En Thu, 10 Dec 2009 20:43:48 -0300, mattia ger...@gmail.com escribió: Il Thu, 10 Dec 2009 23:10:02 +, Matthew Barnett ha scritto: Only the main thread can receive the keyboard interrupt. Ok, so is there any way to stop all the threads if the keyboard interrupt is received? If all other threads (except the main one) are daemon threads, then the whole process finishes when the main thread exits; all daemon threads are abruptly finished. Note that try/finally blocks are not honored, neither are with statements... If you want an orderly retreat, the other threads must cooperate (e.g. the main thread sets a flag and they periodically check for it). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python 3 be fully deployed
En Thu, 10 Dec 2009 05:18:13 -0300, John Nagle na...@animats.com escribió: Luis M. González wrote: On Dec 6, 3:21 pm, vsoler vicente.so...@gmail.com wrote: I'd argue against using Python 2.6 for production work. Either use Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has some of the features of Python 3.x, but not all of them, and is neither fish nor fowl as a result. 2.6 is really more of a sideline that was used for trying out new features, not something suitable for production. I think the idea is to run your 2.5 code through '2to3 and see if it works in 3.x. In addition to Ned Deily's previous comments, I'd like to note that 2to3 assumes the source is valid 2.6 code - you have to ensure the code runs fine with Python 2.6 before using 2to3 to convert to 3.x -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing html with Beautifulsoup
En Thu, 10 Dec 2009 06:15:19 -0300, Johann Spies jsp...@sun.ac.za escribió: How do I get Beautifulsoup to render (taking the above line as example) sunentint for img src=icons/group.pngnbsp;a href=#OBJ_sunetintsunetint/ABR and still provide the text-parts in the td's with plain text? Hard to tell if we don't see what's inside those td's - please provide at least a few rows of the original HTML table. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list