itools 0.20.6 released
itools is a Python library, it groups a number of packages into a single meta-package for easier development and deployment: itools.abnf itools.http itools.tmx itools.catalog itools.i18n itools.uri itools.csv itools.ical itools.vfs itools.datatypesitools.odf itools.web itools.gettext itools.pdf itools.workflow itools.git itools.rest itools.xliff itools.handlers itools.rss itools.xml itools.html itools.stl The only feature enhancement in this release is the addition of two new options to the isetup-quality.py script. The --show-lines option to help tracking down the offensive code. And the --graph option, which produces some graphs showing quality information over time. There have been some bugs fixed and other minor changes. The packages concerned include handlers, csv, stl, vfs and xml. The required version of the Glib has been dropt from 2.14 to 2.12. Resources - Download http://download.ikaaro.org/itools/itools-0.20.6.tar.gz http://download.ikaaro.org/itools/itools-0.20.6.win32-py2.5.exe http://download.ikaaro.org/itools/itools-0.20.6.win32-py2.4.exe Home http://www.ikaaro.org/itools Mailing list http://www.ikaaro.org/community/ http://archives.ikaaro.org/index.cgi?list=itools Bug Tracker http://bugs.ikaaro.org/ -- J. David Ibáñez Itaapy http://www.itaapy.com Tel +33 (0)1 42 23 67 45 9 rue Darwin, 75018 Paris Fax +33 (0)1 53 28 27 88 -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Vilnius/Post EuroPython PyPy Sprint 10-12th of July
Vilnius/Post EuroPython PyPy Sprint 10-12th of July The PyPy team is sprinting at EuroPython again and we invite you to participate in our 3 day long sprint at the conference hotel - Reval Hotel Lietuva. If you plan to attend the sprint we recommend you to listen to the PyPy technical talks (`EuroPython schedule`_) during the conference since it will give you a good overview of the status of development. On the morning of the first sprint day (10th) we will also have a tutorial session for those new to PyPy development. As 3 days is relatively short for a PyPy sprint we suggest to travel back home on the 13th if possible (but it is ok to attend less than 3 days too). -- Goals and topics of the sprint -- There are many possible and interesting sprint topics to work on - here we list some possible task areas: * try out Python programs and fix them or fix PyPy or fix performance bottlenecks * some JIT improvement work * port the stackless transform to ootypesystem * other interesting stuff that you would like to work on ...;-) Registration If you'd like to come, please subscribe to the `pypy-sprint mailing list`_ and drop a note about your interests and post any questions. More organisational information will be sent to that list. Please register by adding yourself on the following list (via svn): http://codespeak.net/svn/pypy/extradoc/sprintinfo/post-ep2008/people.txt or on the pypy-sprint mailing list if you do not yet have check-in rights: http://codespeak.net/mailman/listinfo/pypy-sprint --- Preparation (if you feel it is needed): --- * read the `getting-started`_ pages on http://codespeak.net/pypy * for inspiration, overview and technical status you are welcome to read `the technical reports available and other relevant documentation`_ * please direct any technical and/or development oriented questions to pypy-dev at codespeak.net and any sprint organizing/logistical questions to pypy-sprint at codespeak.net * if you need information about the conference, potential hotels, directions etc we recommend to look at http://www.europython.org. We are looking forward to meet you at the Vilnius Post EuroPython PyPy sprint! The PyPy team .. See also .. .. _getting-started: http://codespeak.net/pypy/dist/pypy/doc/getting-started.html .. _`pypy-sprint mailing list`: http://codespeak.net/mailman/listinfo/pypy-sprint .. _`the technical reports available and other relevant documentation`: http://codespeak.net/pypy/dist/pypy/doc/index.html .. _`EuroPython schedule`: http://europython.org/timetable -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: pymunk 0.8 released
Hi everyone, Im glad to announce that pymunk 0.8 have been released, a library wrapping the 2d physics engine Chipmunk. You can find it here: http://code.google.com/p/pymunk/ What is pymunk? === pymunk is a wrapper around the 2d rigid body physics library Chipmunk, http://wiki.slembcke.net/main/published/Chipmunk It puts a pythonic layer above chipmunk to make it easy to use for python programmers. The main goal with pymunk is to make 2d physics easy to include in your game/project. It is (or striving to be): * Easy to use It should be easy to use, no complicated stuff should be needed to add physics to your game/program. * Pythonic It should not be visible that a c-library (chipmunk) is in the bottom, it should feel like a python library (no strange naming, OO, no memory handling and more) * Simple to build install You shouldnt need to have a zillion of libraries installed to make it install, or do a lot of command line trixs. * Multiplatform Should work on both windows, nix and OSX. * Non-intrusive It should not put restrictions on how you structure your progam and not force you to use a special game loop, it should be possible to use with other libraries like pygame and pyglet. Its licensed under MIT just as Chipmunk, so everyone should be able to use it. What is new? This is the first release I actively promote, and the latest additions made up to this release is a better build script, automatic vector conversion and a number of small improvements here and there. /Victor - main pymunk developer ([EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Pattern Matching Over Python Lists
Is anyone aware of any prior work done with searching or matching a pattern over nested Python lists? I have this problem where I have a list like: [1, 2, [1, 2, [1, 7], 9, 9], 10] and I'd like to search for the pattern [1, 2, ANY] so that is returns: [1, 2, [1, 2, [6, 7], 9, 9], 10] [1, 2, [6, 7], 9, 9] -- http://mail.python.org/mailman/listinfo/python-list
Re: String Concatenation O(n^2) (was: Re: Explaining Implementing a Binary Search Tree.)
En Mon, 16 Jun 2008 07:34:06 -0300, Bart Kastermans [EMAIL PROTECTED] escribió: Summary: can't verify big O claim, how to properly time this? This is interesting. I had never attempted to verify a big O statement before, and decided that it would be worth trying. So I wrote some code to collect data, and I can't find that it goes quadratic. In your test code, you're concatenating only two strings, that's a *single* operation, and takes time proportional to the total length. The quadratic behavior appears when you do *several* concatenations in a row (like in your original code, where += was used several times to build a result). If you want to verify it, try joining N strings of size M (for varying values of N and M), and plot total time vs. N (for a given M value), and total time vs. M (for a given N value) and finally total time vs. (N*M), see what happens and post your findings again. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to catch StopIteration?
On Jun 17, 12:36 pm, Lie [EMAIL PROTECTED] wrote: On Jun 17, 10:50 am, [EMAIL PROTECTED] wrote: I'm writing to see calcuration process. And so, I can't catch StopIteration... What is mistake? (snip) In a for-loop, StopIteration is caught by the for-loop for your convenience (so you don't need to set up try-except of your own) (snip) To clarify, when the for-loop catches StopIteration, the for-loop quits and stop looping, continuing to the next statement after the loop block. To be more accurate, in your case, the StopIteration is caught by the enumerate() when it is enumerating collatz. The for-loop then loops the generator expression returned by enumerate, when enumerate runs out of things to return (i.e. when enumerate caught StopIteration raised by collatz), enumerate raise StopIteration which is caught by the for-loop. PS: btw, you can't write 'print last.append(1)' because list operations like append doesn't return itself. To clarify, list append returns 'None' which, in python, means it is a method/sub. In actuality, python doesn't recognize the difference between method and function. -- http://mail.python.org/mailman/listinfo/python-list
print problem
I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ., time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
On Jun 17, 12:28 am, Martin v. Löwis [EMAIL PROTECTED] wrote: My guess is that the two main memory allocate/deallocate cases are 1) appending a new item to the end, and 2) GC'ing the entire data structure. I would optimize these 2 at the expense of all others. Does that include dictionary lookups? Regards, Martin Well, I did (try to) qualify my guess as pertaining specifically to memory allocate/deallocate cases, the other topics in the nearby posts were talking about updates to the odict, so I hope I can be forgiven this oversight. But you're right, the keyed access is one of the main reasons this is being done with an odict instead of just a list of tuples. The point I was trying to make was that sometimes, the GC case occurs far more frequently than other update methods, yet is overlooked because it happens invisibly to most Python users. I worked on a project a while ago where there was a huge performance penalty in releasing a list structure, because each node was freed individually, causing surrounding freelist entries to be updated for every node. In typical worst-case scenario fashion, a second list was built at the same time as the first, and the default system memory allocator interleaved the list nodes. The truly frustrating part was that at this point in the program, we were trying to free *all* the nodes in *both* lists, and would have preferred to just release the whole chunk of memory, if it had just been allocated in a large chunk instead of a node at a time. I implemented a zone-based memory allocator, so that nodes were allocated within a memory zone, but when we were done, we just released the entire zone, with tremendous improvement in system performance. But what kind of keyed access is likely to be used on an odict? For those cases where all of the items are desired, then I would recommend that the odict iterator be preferred, for this type of retrieval: for k,v in odictvar.iteritems(): # do something with key k and value v and discourage this usage: for k in odictvar.keys(): # or iterkeys() # do something with key k and value odictvar[k] How about this as a simple first approach? Let's assume that the nominal usage pattern for an odict is 1) create all entries in the odict, probably using append, 2) access some or all of the entries, either by iterating over the keys or values, or by keyed access to specific values, and 3) delete the odict. Have the odict keep an internal dict representing the keyed lookups, and have this internal dict set to null whenever the odict is updated. When the odict is accessed by specific key, the internal dict is used - if it null, it is built using dict(odict.iteritems()). In the nominal usage, this dict will only be built once, since the keyed accesses wont begin until after all of the key-value pairs have been added to the odict. Or as a first-first approach (to avoid premature optimization), just implement the odict as a list of tuples, and do linear search for matching key if accessed by key. I would bias any performance choices about keyed access toward cases where the queried key exists in the odict - I think that in those cases where odicts are used, such as ORMs and XML, the keys for a particular odict are known and expected to exist. Those applications where the keys are not known are likely to be meta-type apps, like debuggers and introspection GUIs. I contend that the meat-and- potatoes production apps will be those like database queries - when I get an odict back after querying an EMPLOYEES table, I really should reasonably expect odictvar[EMPNO] to exist. And what would be the conditions of an abusive form of odict? How about an application log kept in an odict, keyed by timestamp? This could have many 1000's of entries, and yet, I would guess that an odict would be the wrong data structure for this, and that a list of tuples or LogMessage objects would be more appropriate. But someone is likely to do it - if they do, what will happen? Perhaps trying to anticipate abusive or degenerate uses of an odict might shed some light on ways to avoid, discourage, or maybe even accommodate these uses in odict. Well, this has become something of a rant, and a speculative one at that, but I think the delete the entire data structure memory case should be given reasonably high design attention. (And maybe this is already the norm in Python development - I'm really quite ignorant of this process, not being in the Python development circle.) Always nice to hear from you Martin - cheers! -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
En Mon, 16 Jun 2008 21:21:35 -0300, John Salerno [EMAIL PROTECTED] escribió: I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: -- from socket import * host = '' port = 51567 address = (host, port) buffer_size = 1024 server_socket = socket(AF_INET, SOCK_STREAM) server_socket.bind(address) server_socket.listen(5) while True: print 'waiting for connection...' client_socket, client_address = server_socket.accept() print '...connected from:', client_address while True: data = client_socket.recv(buffer_size) if not data: break client_socket.send('%s %s' % ('You typed:', data)) client_socket.close() server_socket.close() from socket import * host = 'localhost' port = 51567 address = (host, port) buffer_size = 1024 client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(address) while True: data = raw_input(' ') if not data: break client_socket.send(data) data = client_socket.recv(buffer_size) if not data: break print data client_socket.close() --- I tried changing buffer_size to 10 and I got this output: [EMAIL PROTECTED]:~$ python myclient.py hello You typed: something hello this is a long string You typed: why doesn't this work right something [EMAIL PROTECTED]:~$ My first question is, isn't buffer_size the number of bytes being sent at one time? If so, why doesn't 'hello' get printed after the server returns the data to the client? Isn't 'hello' just 5 bytes? Both programs say recv(buffer_size) - buffer_size is the maximum number of bytes to be RECEIVED, that is, READ. recv will return at most buffer_size bytes. It may return less than that, even if the other side sent the data in a single operation. Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. http://docs.python.org/lib/socket-objects.html Secondly, how is it working that once I type in a new string (e.g. 'something') and then the server returns data to the client, it prints the *previous* string, (i.e. 'hello')? Wouldn't the data variable get overwritten with the value, or is the value being stored somewhere else at this point? Yes, it is stored in an intermediate buffer until you read it. You typed hello and sent it, the server replied with the string You typed: hello; the OS stores it. You read only 10 bytes You typed:, the remaining are still in the buffer. Next round: you type something, the server replies, you read the remaining bytes from the original reply, and so on... (Note that in this particular configuration, the client will fill its buffer at some time: because the server sends at least 11 bytes each round, but the client reads at most 10 bytes, so the client is always behind the server...) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to catch StopIteration?
On Jun 17, 5:50 am, [EMAIL PROTECTED] wrote: I'm writing to see calcuration process. And so, I can't catch StopIteration... What is mistake? def collatz(n): r=[] while n1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): try: last = x[:i+1] print x[:i+1] except StopIteration: print last.appnd(1) Output: [13] [13, 40] [13, 40, 20] [13, 40, 20, 10] [13, 40, 20, 10, 5] [13, 40, 20, 10, 5, 16] [13, 40, 20, 10, 5, 16, 8] [13, 40, 20, 10, 5, 16, 8, 4] [13, 40, 20, 10, 5, 16, 8, 4, 2] last.appnd(1) = [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] # i want this list def collatz(n): r=[] while n1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r i = 1 while 1: try: last = x[:i] print x[:i] i += 1 except StopIteration last.append(1) break You will have to control the for loop yourself otherwise the StopIteration is handled for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to catch StopIteration?
On Jun 17, 8:43 am, Chris [EMAIL PROTECTED] wrote: On Jun 17, 5:50 am, [EMAIL PROTECTED] wrote: I'm writing to see calcuration process. And so, I can't catch StopIteration... What is mistake? def collatz(n): r=[] while n1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): try: last = x[:i+1] print x[:i+1] except StopIteration: print last.appnd(1) Output: [13] [13, 40] [13, 40, 20] [13, 40, 20, 10] [13, 40, 20, 10, 5] [13, 40, 20, 10, 5, 16] [13, 40, 20, 10, 5, 16, 8] [13, 40, 20, 10, 5, 16, 8, 4] [13, 40, 20, 10, 5, 16, 8, 4, 2] last.appnd(1) = [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] # i want this list def collatz(n): r=[] while n1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r i = 1 while 1: try: last = x[:i] print x[:i] i += 1 except StopIteration last.append(1) break You will have to control the for loop yourself otherwise the StopIteration is handled for you. forgot to put x = collatz(13) before the while loop starts and a x.next() inside the while, but hopefully you get the point :p -- http://mail.python.org/mailman/listinfo/python-list
Re: print problem
En Tue, 17 Jun 2008 03:15:11 -0300, pirata [EMAIL PROTECTED] escribió: I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ., time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): python -u your_script.py -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How to request data from a lazily-created tree structure ?
Yes, I need to make sure my requests are properly written so that the generic XPath engine does not need all the structure in memory. There are quite a few cases where you really don't need to load everything at all. /a/b/*/c/d is an example. But even with an example like /x/z[last()]/t, you don't need to load everything under the every /x/z nodes. You just need to check for the latest one, and make sure there is a t node under it. Anyway, if I need to make requests that need all the data... that means that the need for lazy instantiation of nodes disappears, right ? Yes. And unless you have memory-constraints I have to admit that I really doubt that the parsing overhead isn't by far exceeded by the network latency. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: print problem
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Gabriel Genellina wrote: En Tue, 17 Jun 2008 03:15:11 -0300, pirata [EMAIL PROTECTED] escribió: I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ., time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): python -u your_script.py Or just write to sys.stdout without the print wrapper.. - -- Rich Healey - [EMAIL PROTECTED] Developer / Systems Admin - OpenPGP: 0x8C8147807 MSN: [EMAIL PROTECTED] AIM: richohealey33 irc.psych0tik.net- #hbh #admins richohealey irc.freenode.org - #hbh #debian PythonNinja -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIV2NxLeTfO4yBSAcRAkunAJ9w5lavHK4TIUbexX+pSYmPla9oOQCfT8tM tzOhQgcpO7dEG7WhE6FNZ4w= =IqJ1 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: String Concatenation O(n^2)
Ian Kelly [EMAIL PROTECTED] writes: On Mon, Jun 16, 2008 at 11:09 AM, Jean-Paul Calderone [EMAIL PROTECTED] wrote: It will depend what version of Python you're using and the *exact* details of the code in question. An optimization was introduced where, if the string being concatenated to is not referred to anywhere else, it will be re-sized in place. This means you'll probably see sub-quadratic behavior, but only with a version of Python where this optimization exists and only if the code can manage to trigger it. AFAICT, PyString_Concat never calls _PyString_Resize. Am I looking in the wrong place? Take a look at ceval.c:string_concatenate. As Jean-Paul says, note that the optimization doesn't work in many circumstances. For example, change local variable to instance attribute, and it goes away. Other python implementations don't have it at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError: 'ascii' codec can't decode byte
Gilles Ganault wrote: It seems like I have Unicode data in a CSV file but Python is using a different code page, so isn't happy when I'm trying to read and put this data into an SQLite database with APSW: My guess is that you have non-ascii characters in a bytestring. What should I do so Python doesn't raise this error? Should I convert data in the CVS file, or is there some function that I should call before APSW's executemany()? You cannot have unicode data in a file, only unicode converted to bytestrings using some encoding. Assuming that encoding is UTF-8 and that apsw can cope with unicode, try to convert your data to unicode before feeding it to the database api: sql = INSERT INTO mytable (col1,col2) VALUES (?,?) rows = ([col.decode(utf-8) for col in row] for row in records(test.tsv)) cursor.executemany(sql, rows) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
En Tue, 17 Jun 2008 02:25:42 -0300, Lie [EMAIL PROTECTED] escribió: On Jun 17, 11:07 am, Leo Jay [EMAIL PROTECTED] wrote: On Tue, Jun 17, 2008 at 11:29 AM, pirata [EMAIL PROTECTED] wrote: What's the difference between is not and != or they are the same thing? The 'is' is used to test do they point to the exactly same object. The '==' is used to test are their values equal. and be very careful to the dirty corner of python: [example with 5 is 5 but 10 is not 10] No you don't have to be careful, you should never rely on it in the first place. Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' and 'not(id(a) == id(b))' No. You use 'is' when you want to test whether two variable/names are actually the same thing (whether they actually refers to the same spot on memory). The '==' equality comparison just test whether two objects' values can be considered equal. Yes, *that* is true. The above statement is not. A counterexample: py [] is [] False py id([])==id([]) True Even dissimilar objects may have the same id: py class A: pass ... py class B: pass ... py A() is B() False py A() == B() False py id(A())==id(B()) True Comparing id(a) with id(b) is only meaningful when a and b are both alive at the same time. If their lifetimes don't overlap, id(a) and id(b) are not related in any way. So I think that trying to explain object identity in terms of the id function is a mistake. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: for loop within for loop confusion
En Mon, 16 Jun 2008 22:51:30 -0300, John Salerno [EMAIL PROTECTED] escribió: takayuki wrote: I'm early on in my python adventure so I'm not there yet on the strip command nuances.I'm reading How to think like a python programmer first. It's great. Then Learning python. I've read parts of Dive into Python and will work through it fully when I'm a little farther along. Yeah, I really recommend Learning Python for getting the basics first. It's very thorough in that regard. Dive Into Python is *not* for beginners. I'm sorry if people disagree, but it's just not. Sure, the author himself says so at the very beginning in http://www.diveintopython.org Dive Into Python is a Python book for experienced programmers. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing inheritance (decorator pattern ?)
Maric Michaud wrote: Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez écrit : On Jun 16, 1:49 pm, Gerard flanagan [EMAIL PROTECTED] wrote: [...] variation of your toy code. I was thinking the Strategy pattern, different classes have different initialisation strategies? But then you could end up with as many Strategy classes as subclasses, I don't know. [...] This doesn't solve the original problem, the combinatorial explosion of empty subclasses. [...] Yes, and it fails to implement the strategy pattern as well... which would have solved the problem as it is intended exactly for this purpose. Ok, better would have been 'my made-up strategy pattern, any resemblance to other patterns, either living or dead, is purely coincidental' :-) Non-canonically, G. -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Terry Reedy wrote: Cédric Lucantis wrote: I don't see any string method to do that 'abcde'.translate(str.maketrans('','','bcd')) 'ae' I do not claim this to be better than all the other methods, but this pair can also translate while deleting, which others cannot. You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be uabcde.translate(dict.fromkeys(map(ord, ubcd))) u'ae' Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: print problem
En Tue, 17 Jun 2008 04:10:41 -0300, Rich Healey [EMAIL PROTECTED] escribió: Gabriel Genellina wrote: En Tue, 17 Jun 2008 03:15:11 -0300, pirata [EMAIL PROTECTED] escribió: I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ., time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? Very probably, altough I can't reproduce it on Windows. Try invoking the script with python -u (unbuffered input/output): python -u your_script.py Or just write to sys.stdout without the print wrapper.. I think the output is still buffered, even if you write directly to sys.stdout, but I don't have a Linux box to test right now. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: print problem
On Jun 17, 8:15 am, pirata [EMAIL PROTECTED] wrote: I was trying to print a dot on console every second to indicates running process, so I wrote, for example: for i in xrange(10): print ., time.sleep(1) Idealy, a dot will be printed out each second. But there is nothing print out until after 10 seconds, all 10 dots come out together. I've tried lose the comma in the print statement, and it works. Is that because of the print statement buffer the characters until there is a new line character? Thanks import sys for i in xrange(10): sys.stdout.write('.') sys.stdout.flush() -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
Leo Jay [EMAIL PROTECTED] wrote: same objects are equal, but equal don't have to be the same object. same objects are often equal, but not always: inf = 2e200*2e200 ind = inf/inf ind==ind False ind is ind True -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: get keys with the same values
You could use my mseqdict implementation of a sorted dict. http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html swap: This method can only be applied when all values of the dictionary are immutable. The Python dictionary cannot hold mutable keys! So swap doesn't work if only one of the values has the type list or dictionary. Tuples and instances of classes are save as long as they don't emulate lists or dictionaries. from http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Mseqdict.html: x=seqdict.mseqdict(dict) x['Bild']='painting' x['Ziel']='goal' x['Tor'] ='goal' x # A small German - English dictionary mseqdict( ['gewinnen', 'deshalb', 'Abend', 'aber', 'Bild', 'Erkennung', 'Fl\366te', 'Ziel', 'Tor'], {'Tor': ['goal'], 'Ziel': ['goal'], 'gewinnen': ['gain'], 'deshalb': ['therefore'], 'Abend': ['evening'], 'aber': ['but'], 'Bild': ['picture', 'painting'], 'Erkennung': ['recognition'], 'Fl\366te': ['flute']}) x.swap() x # A small English - German dictionary mseqdict( ['gain', 'therefore', 'evening', 'but', 'picture', 'painting', 'recognition', 'flute', 'goal'], {'but': ['aber'], 'recognition': ['Erkennung'], 'painting': ['Bild'], 'flute': ['Fl\366te'], 'gain': ['gewinnen'], 'goal': ['Ziel', 'Tor'], 'evening': ['Abend'], 'therefore': ['deshalb'], 'picture': ['Bild']}) Best regards Wolfgang Nader schrieb: Hello, I have a dictionary and will get all keys which have the same values. d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} I will something as : d.keys(where their values are the same) With this statement I can get two lists for this example: l1= ['a','e'] l2=['b','d'] Would somebody tell me how I can do it? Regards, Nader -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing a point in Gnuploy.py
On 2008-06-16, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello. Could some1 tell me how i could display a specific point in gnuplot.py. Supposingly if i have a point of intersection (2,3). How can i show this on the graph? As in how can i write near the point of intersection the value :(2,3). Thnx 1. Find out in the Gnuplot manual what command to enter 2. Send the command to Gnuplot using g() function-call -- http://mail.python.org/mailman/listinfo/python-list
gtk.gdk.Pixbuf.scale() unexpected behavior when offset != 0
Hi! I'm developing a pygtk application where I need to show images zoomed in so that the user can see individual pixels. gtk.gdk.Pixbuf.scale() seemed ideal for this, but if I set offset_x and offset_y to anything other than 0, the resulting image is heavily distorted and the offset is wrong. I've searched the internet for any snippet of code that uses this function with nonzero offset, but even after several hours of searching I've still come up blank. I think this may be a bug, but since it seems so fundamental I think it's way more likely that I've misunderstood something, so I thought I'd pass this by c.l.p first. Any help is greatly appreciated. I wrote a test program to show off this behavior. Please find attached an image of David Hasselhoff with some puppies to help facilitate this demonstration. (feel free to use any image, but who doesn't like Hasselhoff and puppies?) show_hasselhoff.py #--- import gtk original = gtk.gdk.pixbuf_new_from_file('hasselhoff.jpeg') w = original.get_width() h = original.get_height() interp = gtk.gdk.INTERP_NEAREST nice = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h) ugly = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, w, h) original.scale(nice, 0, 0, w, h, 0, 0, 2, 2, interp) original.scale(ugly, 0, 0, w, h, w/2, h/2, 2, 2, interp) outtake = original.subpixbuf(w/4, h/4, w/2, w/2) expected = outtake.scale_simple(w, h, interp) w = gtk.Window() hbox = gtk.HBox() hbox.add(gtk.image_new_from_pixbuf(original)) hbox.add(gtk.image_new_from_pixbuf(nice)) hbox.add(gtk.image_new_from_pixbuf(ugly)) hbox.add(gtk.image_new_from_pixbuf(expected)) w.add(hbox) w.show_all() w.connect('destroy', gtk.main_quit) gtk.main() #--- When you run this, you should see 4 images in a window. From left to right: original, nice, ugly and expected. nice, ugly and expected are scaled/cropped copies of original, but ugly and expected are offset to show less mullet and more face. expected is what I expected ugly to turn out like judging from the pygtk docs. Things to note about ugly: * The topleft pixel of original has been stretched to the area of offset_x * offset_y. * The first offset_x - 1 top pixels of original have been scaled by a factor 2 horizontally and then stretched vertically to the height of offset_y. * Vice versa for the first offset_y - 1 leftmost pixels of original. * The remaining area of ugly is a scaled version of original(1,1,width/2-1,height/2-1). Things to note about the methods: * This behavior is constant for all interpolation methods. * This behavior is identical in gtk.gdk.Pixbuf.compose(). This can't possibly be how this is supposed to work! Have I misunderstood something, or is this a bug? Cheers! /Joel Hedlund inline: hasselhoff.jpeg-- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
In article [EMAIL PROTECTED], Peter Otten [EMAIL PROTECTED] wrote: Terry Reedy wrote: 'abcde'.translate(str.maketrans('','','bcd')) 'ae' You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be uabcde.translate(dict.fromkeys(map(ord, ubcd))) u'ae' Only if you're using Unicode: 'abcde'.translate(string.maketrans('',''), 'bcd') 'ae' sys.version_info (2, 4, 4, 'final', 0) -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ Frankly I have no feelings towards penguins one way or the other -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
go to specific line in text file
Hello NG, I am searching for a way to jump to a specific line in a text file, let's say to line no. 9000. Is there any method like file.seek() which leads me to a given line instead of a given byte? Hope for help Patrick -- http://mail.python.org/mailman/listinfo/python-list
Re: pyinotify issue
On Jun 13, 3:39 pm, AndreH [EMAIL PROTECTED] wrote: Good day, I just installed pyinotify on my gentoo box. When I test the library through pyinotify.pv -v /tmp under root, everything works great, but when I try the same thing under my local user account, I receive the following error: Error: cannot watch . (WD=-1) Not very helpful. I've tried VERBOSE=True mode, but it doens't provide any additional information. I also tried it for a directory in my home folder just to be sure it's not a permission problem, but no luck. Any ideas? Regards, Andre Ok I ended up solving my problem. pyinotify is just a wrapper for the c lib, inotif.h. Installing the inotify-tools package allows one to do better troubleshooting. First, my kernel version was too old and did not allow inotify to be executed at user-level. I bumped my kernel up to 2.6.24 and enabled the user-level execution flag. Then pyinotify worked once and failed for all consecutive retries. inotifwatch said that my maximum number of user watches was maxed out and that I should increase it under /proc/sys/fs/inotify/ max_user_watches. Something must be wrong, since the max_user_watches was set to 8192. I played around with this setting (sysctl -w fs.inotify.max_user_watches=16843), pyinotify.py and inotifywatch, and finally came the conclusion that pyinotify 0.7.0 was buggy. I got hold of 0.7.1 which seems to have fixed this problem. Hopefully, I'm not speaking too soon. -- http://mail.python.org/mailman/listinfo/python-list
New widget
Hello, here's a new casual game that looks interesting. It's called Smilies Invasion and you have to eat as much green smilies as you can: http://www.dolmenent.com/smiliesinvasion/ Greetings from a newbie developer. -- http://mail.python.org/mailman/listinfo/python-list
Re: go to specific line in text file
On Jun 17, 8:10 pm, Patrick David [EMAIL PROTECTED] wrote: Hello NG, I am searching for a way to jump to a specific line in a text file, let's say to line no. 9000. Is there any method like file.seek() which leads me to a given line instead of a given byte? If by jump you mean without reading the preceding 8999 lines, and by text file you mean variable length records without a separate index structure, that method hasn't been implemented yet. AFAIK it hasn't been implemented in any other language either :-) The linecache module may be what you want, depending on how closely your access patterns match those the module was designed for. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Sion Arrowsmith wrote: In article [EMAIL PROTECTED], Peter Otten [EMAIL PROTECTED] wrote: Terry Reedy wrote: 'abcde'.translate(str.maketrans('','','bcd')) 'ae' You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be uabcde.translate(dict.fromkeys(map(ord, ubcd))) u'ae' Only if you're using Unicode: ... which is what you do if you are using the str type in 3.0. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
Martin v. L.: http://wiki.python.org/moin/TimeComplexity Thank you, I think that's not a list of guarantees, while a list of how things are now in CPython. If so, what's the advantage of using that method over d.items[n]? I think I have lost the thread here, sorry. So I explain again what I mean. I think for this data structure it's important to keep all the normal dict operations at the same speed. If you use a C implementation vaguely similar to my pure python recipe you can perform the del in O(1) too, because pairs are joined in (double) linked list. But such data structure is O(n) to find the n-th item inserted into the sequence. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Numeric type conversions
I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. Can anyone point me in the right direction towards a suitable function please? NB I don't know without further checking exactly how the bytes are encoded, but I'm just transcribing some code across from a Windows VB.Net program and these same bytes could be read straight into a standard 2-byte signed short int, so I can be confident that it's a fairly standard Windows-compatible encoding. -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
John Dann wrote: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. Can anyone point me in the right direction towards a suitable function please? see the module struct in the standard-lib. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
try struct.pack -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
On 2008-06-17, John Dann [EMAIL PROTECTED] wrote: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. [snipperdesnip] Can anyone point me in the right direction towards a suitable function please? The ctypes module should be helpful here Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
John Dann wrote: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. [...] Use the unpack() function from the struct module. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: How to request data from a lazily-created tree structure ?
On Jun 17, 9:08 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: Yes, I need to make sure my requests are properly written so that the generic XPath engine does not need all the structure in memory. There are quite a few cases where you really don't need to load everything at all. /a/b/*/c/d is an example. But even with an example like /x/z[last()]/t, you don't need to load everything under the every /x/z nodes. You just need to check for the latest one, and make sure there is a t node under it. Anyway, if I need to make requests that need all the data... that means that the need for lazy instantiation of nodes disappears, right ? Yes. And unless you have memory-constraints I have to admit that I really doubt that the parsing overhead isn't by far exceeded by the network latency. Diez Do you know if there is such XPath engine that can be applied to a DOM- like structure ? One way would be to take an XPath engine from an existing XML engine (ElementTree, or any other), and see what APIs it calls... and see if we cannot create a DOM-like structure that has the same API. Duck typing, really... -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
On Tue, Jun 17, 2008 at 04:33:03AM -0300, Gabriel Genellina wrote: Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)' and 'not(id(a) == id(b))' No. Sure it is... he said similar... not identical. They are not the same, but they are similar. Saying a flat no alone, without qualifying your statement is generally interpreted as rude in English... It's kind of like how you talk to children when they're too young to understand the explanation. Yucky. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D pgpg79fnwMq5d.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
On Jun 17, 9:28 pm, John Dann [EMAIL PROTECTED] wrote: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. Can anyone point me in the right direction towards a suitable function please? NB I don't know without further checking exactly how the bytes are encoded, but I'm just transcribing some code across from a Windows VB.Net program and these same bytes could be read straight into a standard 2-byte signed short int, so I can be confident that it's a fairly standard Windows-compatible encoding. You need the unpack function of the struct module. Supposing you have a four-byte string containing two such short ints, first + 1 then -1 then this will work: import struct two_shorts = '\x01\x00\xff\xff' struct.unpack('hh', two_shorts) (1, -1) In the format string, '' means little-endian (almost universal on PCs running Windows), and 'h' means a signed 'half-word'. See the struct manual section for more options. You can write a function called convert_to_int (take a hint on naming conventions) and use it a slice at a time, or you can use struct.unpack to grab a whole record at once. Here's a real live example of that: ( f.height, option_flags, f.colour_index, f.weight, f.escapement_type, f.underline_type, f.family, f.character_set, ) = unpack('HBBB', data[0:13]) HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
[EMAIL PROTECTED] wrote: On Jun 15, 7:43 pm, Peter Otten [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Jun 15, 6:58 pm, Christian Meesters [EMAIL PROTECTED] wrote: I do need speed. Is there an option? Mind telling us what you *actually* want to achieve? (What do you want to calculate?) Christian Physical simulations of objects with near-lightspeed velocity. How did you determine that standard python floats are not good enough? I have a physical system set up in which a body is supposed to accelerate and to get very close to lightspeed, while never really attaining it. After approx. 680 seconds, Python gets stuck and tells me the object has passed lightspeed. I put the same equations in Mathematica, again I get the same mistake around 680 seconds. So I think, I have a problem with my model! Then I pump up the WorkingPrecision in Mathematica to about 10. I run the same equations again, and it works! At least for the first 10,000 seconds, the object does not pass lightspeed. I concluded that I need Python to work at a higher precision. Everything beyond that is unlikely to be supported by the hardware and will therefore introduce a speed penalty. I have thought of that as well. However I have no choice. I must do these calculations. If you know of any way that is supported by the hardware, it will be terrific, but for now the slower things will have to do. You need to change your representation. Try redoing the algebra using (c-v) as the independent variable, and calculate that. Cheers, Phil Hobbs -- http://mail.python.org/mailman/listinfo/python-list
Mapping a series of Dates to an array of Numbers
Hello. Got a problem here. Ive got a set of points tht id be plotting. Those points would contain the date on which the work was done against its frequency. Supposedly if i did something on the 28th of March one of the points would be (28, respective freq). The next time i did my work on the 1st of April. So my next point would (1,freq). Now how could i map all the dates to another array so that when im plotting them i can plot the points as (day 1, freq), (day2,freq), (day4 , freq) and so on rather than having points like (28, freq), (29,freq), (1,freq) and blah blah blah. Id be needing some help on how to use the time class in python as well. Thnx -- http://mail.python.org/mailman/listinfo/python-list
Re: Mapping a series of Dates to an array of Numbers
Btw dnt forget the solution should also cater to this problem: Supposedly there is a day on which i did not do anything. Than that particular spot in my graph should be left empty. Meaning that if i did something on the 1st March and after it i did something on the 7th March. Then essentially 1st march should be mapped to day1 and 7th march to day 7(not day2)... :P -- http://mail.python.org/mailman/listinfo/python-list
Re: Mapping a series of Dates to an array of Numbers
On Jun 17, 2:15 pm, J-Burns [EMAIL PROTECTED] wrote: Hello. Got a problem here. Ive got a set of points tht id be plotting. Those points would contain the date on which the work was done against its frequency. Supposedly if i did something on the 28th of March one of the points would be (28, respective freq). The next time i did my work on the 1st of April. So my next point would (1,freq). Now how could i map all the dates to another array so that when im plotting them i can plot the points as (day 1, freq), (day2,freq), (day4 , freq) and so on rather than having points like (28, freq), (29,freq), (1,freq) and blah blah blah. Id be needing some help on how to use the time class in python as well. Thnx For every day you could build a timestamp and frequency pair, hell, you don't even need to use the time module if you're capturing data manually. If you build your dataset as (timestamp, frequency) and if frequency is nothing then use None when you extract data to plot you could use a simple list comprehension to retrieve days that actually had items [(timestamp,frequency) for timestamp,frequency in data_structure where frequency != None]. Now you have your own list that is composed just of data pairs where there is a frequency. -- http://mail.python.org/mailman/listinfo/python-list
Re: go to specific line in text file
Patrick David [EMAIL PROTECTED] writes: I am searching for a way to jump to a specific line in a text file, let's say to line no. 9000. Is there any method like file.seek() which leads me to a given line instead of a given byte? You can simulate it fairly easily, but it will internally read the file line by line and will take the time roughly proportional to the size of the file. from itertools import islice def seek_to_line(f, n): for ignored_line in islice(f, n - 1): pass # skip n-1 lines f = open('foo') seek_to_line(f, 9000)# seek to line 9000 # print lines 9000 and later for line in f: print line -- http://mail.python.org/mailman/listinfo/python-list
How do I avoid using HTTPRedirectHandler with urllib2?
Hi, I am new to Python, trying it as an alternative to Perl. I am having problem with python HTTP handling library, urllib2. How do I avoid using the HTTPRedirectHandler while making a HTTP request? For those familiar to Perl-LWP, this is done by using simple_request() on the UserAgent object. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Both programs say recv(buffer_size) - buffer_size is the maximum number of bytes to be RECEIVED, that is, READ. recv will return at most buffer_size bytes. It may return less than that, even if the other side sent the data in a single operation. Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. http://docs.python.org/lib/socket-objects.html I was wondering about sendall(). The examples I've read in two different books are consistent in their use of send() and don't even mention sendall(), so I thought maybe it was for a more specialized situation. Yes, it is stored in an intermediate buffer until you read it. You typed hello and sent it, the server replied with the string You typed: hello; the OS stores it. You read only 10 bytes You typed:, the remaining are still in the buffer. Next round: you type something, the server replies, you read the remaining bytes from the original reply, and so on... Oh I didn't even count You typed: as part of the 10 bytes! And what a coincidence that it happens to be exactly 10 characters! That really helped to hide the problem from me! (Note that in this particular configuration, the client will fill its buffer at some time: because the server sends at least 11 bytes each round, but the client reads at most 10 bytes, so the client is always behind the server...) How is the server sending back 11 bytes? Is it because it's sending at least the 10 characters, plus the extra space? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
John Salerno [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] from socket import * host = 'localhost' port = 51567 address = (host, port) buffer_size = 1024 client_socket = socket(AF_INET, SOCK_STREAM) client_socket.connect(address) while True: data = raw_input(' ') if not data: break client_socket.send(data) data = client_socket.recv(buffer_size) if not data: break print data client_socket.close() Also, is that second if not data: break statement necessary? It seems like once you get past the first if, you don't need the second one. Of course, I guses it's possible that the server could return a False value, but even still, would it make sense to break out of the loop and close the connection because of that? It runs fine without the if statement, but I'm wondering if I just haven't encountered the proper problem situation yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
On Jun 17, 3:13 pm, Phil Hobbs [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Jun 15, 7:43 pm, Peter Otten [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Jun 15, 6:58 pm, Christian Meesters [EMAIL PROTECTED] wrote: I do need speed. Is there an option? Mind telling us what you *actually* want to achieve? (What do you want to calculate?) Christian Physical simulations of objects with near-lightspeed velocity. How did you determine that standard python floats are not good enough? I have a physical system set up in which a body is supposed to accelerate and to get very close to lightspeed, while never really attaining it. After approx. 680 seconds, Python gets stuck and tells me the object has passed lightspeed. I put the same equations in Mathematica, again I get the same mistake around 680 seconds. So I think, I have a problem with my model! Then I pump up the WorkingPrecision in Mathematica to about 10. I run the same equations again, and it works! At least for the first 10,000 seconds, the object does not pass lightspeed. I concluded that I need Python to work at a higher precision. Everything beyond that is unlikely to be supported by the hardware and will therefore introduce a speed penalty. I have thought of that as well. However I have no choice. I must do these calculations. If you know of any way that is supported by the hardware, it will be terrific, but for now the slower things will have to do. You need to change your representation. Try redoing the algebra using (c-v) as the independent variable, and calculate that. Cheers, Phil Hobbs That was suggested. Problem is, that sometimes the velocities are near zero. So this solution, by itself, is not general enough. -- http://mail.python.org/mailman/listinfo/python-list
Re: go to specific line in text file
On Jun 17, 10:46 pm, Hrvoje Niksic [EMAIL PROTECTED] wrote: Patrick David [EMAIL PROTECTED] writes: I am searching for a way to jump to a specific line in a text file, let's say to line no. 9000. Is there any method like file.seek() which leads me to a given line instead of a given byte? You can simulate it fairly easily, but it will internally read the file line by line and will take the time roughly proportional to the size of the file. from itertools import islice def seek_to_line(f, n): The OP gave no impression that he'd restrict himself to one seek_to_line call per open. Perhaps you need f.seek(0) here otherwise seek_to_line(f, 20) seek_to_line(f, 10) will give something unexpected (like jumping forwards instead of backwards). for ignored_line in islice(f, n - 1): pass # skip n-1 lines f = open('foo') seek_to_line(f, 9000)# seek to line 9000 # print lines 9000 and later for line in f: print line -- http://mail.python.org/mailman/listinfo/python-list
Re: 32 bit or 64 bit?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] That was suggested. Problem is, that sometimes the velocities are near zero. So this solution, by itself, is not general enough. Maybe working in p, and delta-p would be more stable. -- http://mail.python.org/mailman/listinfo/python-list
Re: The best way to package a Python module?
Thanks everyone for details. I'll try stealing some of the good bits of python-central of debian for my purpose. On Mon, Jun 16, 2008 at 10:43 AM, Ben Finney [EMAIL PROTECTED] wrote: Jean-Paul Calderone [EMAIL PROTECTED] writes: What has changed is that the tools in common use for Debian packaging of Python libraries have taken on the role of generating those per-version copies at install time. [EMAIL PROTECTED]:~$ ls -l /usr/lib/python2.{4,5}/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.4/site-packages/sqlite/main.py - /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py lrwxrwxrwx 1 root root 63 2007-12-27 15:29 /usr/lib/python2.5/site-packages/sqlite/main.py - /usr/share/pycentral/python-sqlite/site-packages/sqlite/main.py [EMAIL PROTECTED]:~$ That doesn't seem to agree with your statement. Am I missing something? You are missing an inspection of the contents of the actual package file. The package file itself contains only a single copy of the Python module (at /usr/share/pycentral/site-packages/sqlite/main.py). What you see there on your filesystem was created at install time; the installation tool figures out, at install time, which Python versions need to be supported on this particular system, and creates those symlinks. Thus, the change that's occurred is that the user doesn't need to choose between Python SQLite library for Python 2.4 and Python SQLite library for Python 2.5. There is no longer a separation at the package level by Python version, so the user merely needs to choose (given your example) the single Python SQLite library, and the install process takes care of setting it up for all supported versions of Python on the system. -- \ [Freedom of speech] isn't something somebody else gives you. | `\ That's something you give to yourself. —_Hocus Pocus_, | _o__)Kurt Vonnegut | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Authentic Designer Handbags at www. yoyobag.com
Authentic Designer Handbags at www. yoyobag.com -- http://mail.python.org/mailman/listinfo/python-list
Annoying message when interrupting python scripts
Hi all, I find that I semi-frequently get the cryptic message import site failed; use -v for traceback printed on standard error when an arbitrary python script receives SIGINT while the python interpreter is still firing up. If I use -v for traceback I get something along the lines of 'import site' failed; traceback: Traceback (most recent call last): File /usr/lib/python2.4/site.py, line 61, in ? import os File /usr/lib/python2.4/os.py, line 683, in ? import copy_reg as _copy_reg File /usr/lib/python2.4/copy_reg.py, line 5, in ? KeyboardInterrupt Is this a bug? I couldn't find any code, but I imagine something like try: import site except: sys.stderr.write(import site failed; use -v for traceback\n) which should surely allow a KeyboardInterrupt exception through? Regards, Geoff Bache -- http://mail.python.org/mailman/listinfo/python-list
Re: Annoying message when interrupting python scripts
To clarify: this is more serious than an incorrect error message, as the intended interrupt gets swallowed and script execution proceeds. Sometimes I seem to get half-imported modules as well, the script failing later with something like AttributeError: 'module' object has no attribute 'getenv' when trying to call os.getenv Regards, Geoff Bache -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Matching Over Python Lists
At 2008-06-17T05:55:52Z, Chris [EMAIL PROTECTED] writes: Is anyone aware of any prior work done with searching or matching a pattern over nested Python lists? I have this problem where I have a list like: [1, 2, [1, 2, [1, 7], 9, 9], 10] and I'd like to search for the pattern [1, 2, ANY] so that is returns: [1, 2, [1, 2, [6, 7], 9, 9], 10] [1, 2, [6, 7], 9, 9] Hint: recursion. Your general algorithm will be something like: def compare(list, function): if function(list): print list for item in list: if item is a list: compare(item, function) def check(list): if list starts with [1, 2] and length of the list 2: return True else: return False -- Kirk Strauser The Day Companies -- http://mail.python.org/mailman/listinfo/python-list
Re: How to catch StopIteration?
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: I'm writing to see calcuration process. And so, I can't catch StopIteration... What is mistake? def collatz(n): r=[] while n1: r.append(n) n = 3*n+1 if n%2 else n/2 yield r for i, x in enumerate(collatz(13)): try: last = x[:i+1] print x[:i+1] except StopIteration: print last.appnd(1) Output: [13] [13, 40] [13, 40, 20] [13, 40, 20, 10] [13, 40, 20, 10, 5] [13, 40, 20, 10, 5, 16] [13, 40, 20, 10, 5, 16, 8] [13, 40, 20, 10, 5, 16, 8, 4] [13, 40, 20, 10, 5, 16, 8, 4, 2] last.appnd(1) = [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] # i want this list I would have thought you want this... for i, x in enumerate(collatz(13)): ... last = x[:i+1] ... print x[:i+1] ... else: ... last.append(1) ... print last ... [13] [13, 40] [13, 40, 20] [13, 40, 20, 10] [13, 40, 20, 10, 5] [13, 40, 20, 10, 5, 16] [13, 40, 20, 10, 5, 16, 8] [13, 40, 20, 10, 5, 16, 8, 4] [13, 40, 20, 10, 5, 16, 8, 4, 2] [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: 2Q's: How to autocreate instance of class;How to check for membership in a class
asdf [EMAIL PROTECTED] wrote: (Presumably nothing to do with the Common Lisp system-definition utility.) So for example if I know that var1=jsmith. Can I somehow do var1=User(). Something like this might work. class User (object): def __init__(me, name): me.name = name class Users (object): def __getattr__(me, name): try: return object.__getattr__(me, name) except AttributeError: u = me.__dict__[name] = User(name) return u users = Users() alice = users.alice alice.name 'alice' alice is users.alice True Not very nice, though, and not particularly good at defending against typos. My second question is how can I check if object is a member of a class. so let's say I create a=User(), b=User()... The built-in isinstance function seems an obvious choice. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
On Jun 17, 12:28 pm, John Dann [EMAIL PROTECTED] wrote: I'm new to Python and can't readily find the appropriate function for the following situation: I'm reading in a byte stream from a serial port (which I've got working OK with pyserial) and which contains numeric data in a packed binary format. Much of the data content occurs as integers encoded as 2 consecutive bytes, ie a 2-byte integer. I'm guess that there should be a function available whereby I can say something like: My2ByteInt = ConvertToInt(ByteStream[12:13]) to take a random example of the 2 bytes occurring at positions 12 and 13 in the byte stream. [snip] Please note that in slicing the start position is included and the end position is excluded, so that should be ByteStream[12:14]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Debuggers
TheSaint [EMAIL PROTECTED] writes: On 19:21, venerdì 13 giugno 2008 R. Bernstein wrote: I'm not completely sure what you mean, but I gather that in post-mortem debugging you'd like to inspect local variables defined at the place of error. Yes, exactly. This can be seen with pdb, but not pydb. If I'm testing a piece of code and it breaks, then I'd like to see the variables and find which of them doesn't go as expected. Python as a language is a little different than say Ruby. In Python the handler for the exception is called *after* the stack is unwound I'm not doing comparison with other languages. I'm simply curious to know why pydb don't keep variables like pdb. If you are simply curious, then a guess is that the frame from the traceback (t) isn't set by pydb's post_mortem method in calling the Pdb interaction() method, whereas it does get set in the corresponding pdb post_mortem code. It's possible this is a bug -- it's all in the details. But if it is a bug or a feature improvement, probably a better place to to request a change would be in the tracker for the pydb project: http://sourceforge.net/tracker/?group_id=61395 Should you go this route, I'd suggest giving the smallest program and scenario that exhibits the problem but also has a different behavior in pdb. There are programming interfaces to post-mortem debugging in pdb and pydb, namely post_mortem() and pm(); so best is a short self contained program that when run sets up as much of this as possible. And if the bug is accepted and fixed such a short-self contained program would get turned into a test case and incluide to the set regression tests normally run. Final, I agreed the idea to restart the debugger when an exception is trow. It could be feasible to let reload the file and restart. Some time I can re-run the program , as the error is fixed, but sometime pdb doesn't recognize the corrections applied. The restart that I submitted as a patch to pdb two and a half years ago is what I call a warm restart: no Python code is actually reloaded. The reason ti was done way is that is a simple way to maintain the debugger settings such as breakpoints; also it requires saving less knowledge about how the program was initially run so it might be applicable in more contexts. The down side though, in addition to what you've noticed with regards to files which have changed, is that global state may be different going into the program when it is restarted. In the last pydb release, 1.23 a save command was added to so that breakpoints and other debugger state could be saved across debug sessions which includes a cold or exec restart. I mean that after a post-mortem event, the debugger should forget all variables and reload the program, which meanwhile could be debugged. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html -- http://mail.python.org/mailman/listinfo/python-list
text alignment
Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Trying to get pcap working
Hello, I'm fairly new to Python, and have run into dead ends in trying to figure out what is going on. The basic thing I am trying to do is get pylibpcap working on a Python installation. More precisely, I want to get it working on an ActiveState Python installation. I have it working on cygwin (Windows XP). I was hoping to just be able to copy the pcap.py and _pcapmodule.dll file to a directory in the ActiveState install's sys.path (they are both in C:\Python25\Lib\site- packages). When I do this, it finds pcap.py just fine, but then errors with: C:\Python25\Lib\site-packagespython Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import pcap Traceback (most recent call last): File stdin, line 1, in module File C:\Python25\Lib\site-packages\pcap.py, line 7, in module import _pcap ImportError: No module named _pcap (The build and initial install was done under cygwin because I could; the goal is to package this up into a zip file and install it on some more servers.) Getting python to access the _pcapmodule.dll seems to be key; why does the cygwin python installation work and ActiveState does not? Is there some sort of central known-DLL repository somewhere? Thanks for any help you can give. Michael Matthews -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 6:43 pm, Gandalf [EMAIL PROTECTED] wrote: Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Matching Over Python Lists
Kirk Strauser: Hint: recursion. Your general algorithm will be something like: Another solution is to use a better (different) language, that has built-in pattern matching, or allows to create one. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Context manager for files vs garbage collection
Floris Bruynooghe [EMAIL PROTECTED]: I was wondering when it was worthwil to use context managers for file. Consider this example: def foo(): t = False for line in file('/tmp/foo'): if line.startswith('bar'): t = True break return t Using this code inside a jthon web application might hit the resource limits of the underlying operating system. While CPython has a fairly deterministic garbage collector, the JVM gc is non-deterministic, especially inside the server vm. It keeps objects around for quite a long time and only frees them, if available memory runs low or the application is idle. Since file objects don't consume much memory, they might be hanging around for quite some time still claiming resources, which are a rare thing on many restricted server environments. Relying on garbage collection on Python means relying on a non-portable implementation detail. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB [EMAIL PROTECTED] wrote: [snip] Please note that in slicing the start position is included and the end position is excluded, so that should be ByteStream[12:14]. Yes, I just tripped over that, in fact, hence the error in my original post. I suppose there must be some logic in including the start position but excluding the end position, though it does escape me for now. I can understand making a range inclusive or exclusive but not a mixture of the two. Suppose it's just something you have to get used to with Python and, no doubt, much commented on in the past. JGD -- http://mail.python.org/mailman/listinfo/python-list
Re: Buffer size when receiving data through a socket?
Gabriel Genellina [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Note that most of the time you want to use the sendall() method, because send() doesn't guarantee that all the data was actually sent. http://docs.python.org/lib/socket-objects.html If I use sendall(), am I still recv'ing data with a given buffer size? What if I send more data than the buffer size. Is my code as written not prepared to handle that case? It seems like I might need to continue receiving data until there is no more to receive (in a loop?)...is that right? -- http://mail.python.org/mailman/listinfo/python-list
Re: Does '!=' equivelent to 'is not'
pirata wrote: I'm a bit confusing about whether is not equivelent to != 0 is not 0.0 True 0 != 0.0 False -- http://mail.python.org/mailman/listinfo/python-list
Re: Numeric type conversions
John Dann wrote: On Tue, 17 Jun 2008 08:58:11 -0700 (PDT), MRAB [EMAIL PROTECTED] wrote: [snip] Please note that in slicing the start position is included and the end position is excluded, so that should be ByteStream[12:14]. Yes, I just tripped over that, in fact, hence the error in my original post. I suppose there must be some logic in including the start position but excluding the end position, though it does escape me for now. I can understand making a range inclusive or exclusive but not a mixture of the two. http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Making wxPython a standard module?
b = wx.Button(label=Click Me, action=myCallable) Instead you used to have to create a button and then call some utility function in some other object to bind that button to a callable (IIRC this was one place where Window IDs could be used). Now, the button actually has a method you can use. It's still an extra step... That looks quite a lot like the behaviour of PythonForS60's appuifw class. Frex, a menu: appuifw.app.menu = [(u'Octopus', getfish(octopus)), (u'Cuttlefish', getfish(cuttlefish)), (u'Squid', ((u'Humboldt', getfish(humboldt)), (u'Giant', getfish(giantsquid)), (u'Colossal', getfish(colossal)))] gives you a menu with three options, the last of which has three sub- options, all of which call your getfish() function with their value. -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 11:45 am, Gandalf [EMAIL PROTECTED] wrote: On Jun 17, 6:43 pm, Gandalf [EMAIL PROTECTED] wrote: Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) The HtmlWindow widget can only display simple html. So, while you cannot use CSS, you should be able to use the simple html alignment directives. Check out the following site for pointers: http://www.htmlite.com/lite008.php If you want to be able to use CSS and javascript, you'll want to use the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds Internet Explorer. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Peter Otten wrote: Terry Reedy wrote: Cédric Lucantis wrote: I don't see any string method to do that 'abcde'.translate(str.maketrans('','','bcd')) 'ae' I do not claim this to be better than all the other methods, but this pair can also translate while deleting, which others cannot. You should mention that you are using Python 3.0 ;) The 2.5 equivalent would be uabcde.translate(dict.fromkeys(map(ord, ubcd))) u'ae' Sorry. I did not realize that the maketrans function had not then been moved from the string module to the str class object, unlike nearly all other functions from string, including the translate function. I also misremembered that maketrans did not have the new third delete param. What I did do once long ago was something like import string a = 'abcde'.translate(string.maketrans('bd','**')) a.replace('*','') 'ace' which is not very nice. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 7:49 pm, Mike Driscoll [EMAIL PROTECTED] wrote: On Jun 17, 11:45 am, Gandalf [EMAIL PROTECTED] wrote: On Jun 17, 6:43 pm, Gandalf [EMAIL PROTECTED] wrote: Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) The HtmlWindow widget can only display simple html. So, while you cannot use CSS, you should be able to use the simple html alignment directives. Check out the following site for pointers: http://www.htmlite.com/lite008.php If you want to be able to use CSS and javascript, you'll want to use the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds Internet Explorer. Mike well thanks it seems useful... My question is about general items in WX and how to position them inside an element without using CSS. It's only coincidence My item is HtmlWindow -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
since you brought up this issue, please tell me where can I fine menual for this library? can i generate dynamic GUI from it? If not, Is there any way to generate dynamic GUI (one that can change according to the user input) with HTML-CSS- javascript similar environment? -- http://mail.python.org/mailman/listinfo/python-list
Static memory allocation in Python
Hi, I am running a very simple python application and I noted that the memory allocation is something like 4,5M. This is a problem in my case, because I have to run 2 thousand process at the same time. The memory I need is 100k or less. Is there any way to set this for the python process? Regards, Eduardo -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Ethan Furman wrote: Greetings. The strip() method of strings works from both ends towards the middle. Is there a simple, built-in way to remove several characters from a string no matter their location? (besides .replace() ;) For example: .strip -- 'www.example.com'.strip('cmowz.') 'example' .??? -- --- 'www.example.com'.strip('cmowz.') 'exaple' Thanks for all the ideas! -- Ethan -- http://mail.python.org/mailman/listinfo/python-list
Re: 'string'.strip(chars)-like function that removes from the middle?
Peter Otten schreef: Ethan Furman wrote: The strip() method of strings works from both ends towards the middle. Is there a simple, built-in way to remove several characters from a string no matter their location? (besides .replace() ;) identity = .join(map(chr, range(256))) Or identity = string.maketrans('', '') 'www.example.com'.translate(identity, 'cmowz.') 'exaple' -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 12:59 pm, Gandalf [EMAIL PROTECTED] wrote: On Jun 17, 7:49 pm, Mike Driscoll [EMAIL PROTECTED] wrote: On Jun 17, 11:45 am, Gandalf [EMAIL PROTECTED] wrote: On Jun 17, 6:43 pm, Gandalf [EMAIL PROTECTED] wrote: Hi every one. What is the similar python WX style property for CSS text-align? I need this item text to start from the right direction: aaa= html.HtmlWindow(self, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('../../aa.html') Thanks! *right to the left direction... And I'm using pythin 2.5 on XP (I forget to mention...) The HtmlWindow widget can only display simple html. So, while you cannot use CSS, you should be able to use the simple html alignment directives. Check out the following site for pointers: http://www.htmlite.com/lite008.php If you want to be able to use CSS and javascript, you'll want to use the ActiveX_IEHtmlWindow (wx.lib.iewin) widget instead as it embeds Internet Explorer. Mike well thanks it seems useful... My question is about general items in WX and how to position them inside an element without using CSS. It's only coincidence My item is HtmlWindow Positioning the widgets within a container widgets (such as a wx.Window, wx.Panel or wx.Frame) is usually done with sizers. Something like this: mySizer.Add(myWidget, 0, wx.ALIGN_RIGHT) I've written a few tutorials on aligning widgets in various types of sizers. You might find them helpful. There are located here: http://www.blog.pythonlibrary.org You might also find this site useful too: http://www.zetcode.com/wxpython/layout/ Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 1:20 pm, Gandalf [EMAIL PROTECTED] wrote: since you brought up this issue, please tell me where can I fine menual for this library? You want the manual for wxPython? Go to the download page on the Official wxPython page and get the Docs Demos package: http://wxpython.org/download.php That include the wxWidgets Reference. Also see: http://wxpython.org/onlinedocs.php can i generate dynamic GUI from it? Not sure what you mean by this. If you know how to create a dynamic GUI with html/ajax or some such based on the user's interactions with your website, than it should work in the embedded browser just as well as it would in a non-embedded one. If not, Is there any way to generate dynamic GUI (one that can change according to the user input) with HTML-CSS- javascript similar environment? Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing inheritance (decorator pattern ?)
On Jun 16, 11:10 pm, Maric Michaud [EMAIL PROTECTED] wrote: Le Monday 16 June 2008 20:35:22 George Sakkis, vous avez écrit : On Jun 16, 1:49 pm, Gerard flanagan [EMAIL PROTECTED] wrote: George Sakkis wrote: I have a situation where one class can be customized with several orthogonal options. Currently this is implemented with (multiple) inheritance but this leads to combinatorial explosion of subclasses as more orthogonal features are added. Naturally, the decorator pattern [1] comes to mind (not to be confused with the the Python meaning of the term decorator). However, there is a twist. In the standard decorator pattern, the decorator accepts the object to be decorated and adds extra functionality or modifies the object's behavior by overriding one or more methods. It does not affect how the object is created, it takes it as is. My multiple inheritance classes though play a double role: not only they override one or more regular methods, but they may override __init__ as well. Here's a toy example: I don't know if it will map to your actual problem, but here's a variation of your toy code. I was thinking the Strategy pattern, different classes have different initialisation strategies? But then you could end up with as many Strategy classes as subclasses, I don't know. (Also in vaguely similar territory -http://bazaar.launchpad.net/~grflanagan/python-rattlebag/trunk/annota... ) class MetaBase(type): def __init__(cls, name, bases, data): cls.strategies = [] cls.prefixes = [] for base in bases: print base if hasattr(base, 'strategy'): cls.strategies.append(base.strategy) if hasattr(base, 'prefix'): cls.prefixes.append(base.prefix) super(MetaBase, cls).__init__(name, bases, data) class Joinable(object): __metaclass__ = MetaBase strategy = list prefix = '' def __init__(self, words): self._words = words for strategy in self.strategies: self._words = strategy(self._words) def join(self, delim=','): return '%s %s' % (' '.join(self.prefixes), delim.join(self._words)) class Sorted(Joinable): strategy = sorted prefix = '[sorted]' class Reversed(Joinable): strategy = reversed prefix = '[reversed]' class SortedReversed(Sorted, Reversed): pass class ReversedSorted(Reversed, Sorted): pass if __name__ == '__main__': words = 'this is a test'.split() print SortedReversed(words).join() print ReversedSorted(words).join() This doesn't solve the original problem, the combinatorial explosion of empty subclasses. At the end of the day, I'd like a solution that uses a (mostly) flat, single-inheritance, hierarchy, allowing the client say: Yes, and it fails to implement the strategy pattern as well... which would have solved the problem as it is intended exactly for this purpose. As someone in another newsgroup demonstrated, it can be solved with a combination of strategy and decorator: http://tinyurl.com/5ulqh9 George -- http://mail.python.org/mailman/listinfo/python-list
Re: Static memory allocation in Python
On Jun 17, 2008, at 2:34 PM, Eduardo Henrique Tessarioli wrote: Hi, I am running a very simple python application and I noted that the memory allocation is something like 4,5M. This is a problem in my case, because I have to run 2 thousand process at the same time. The memory I need is 100k or less. Is there any way to set this for the python process? The runtime itself isn't as light as, say, the C stdlib. Now, there are a lot of shared libraries here, so you should measure not just a single instance, but how much it actually grows in overall system memory usage as you run more simultaneous python interpreters. Regards, Eduardo -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
2d graphics - drawing a vescica piscis in Python
Hello, I have written a program to draw a vescica piscis http:// en.wikipedia.org/wiki/Vesica_piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color(black) circle(r) color(white) forward(r) color(black) circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. And finally, is turtle the best option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. -- http://mail.python.org/mailman/listinfo/python-list
Re: 2d graphics - drawing a vescica piscis in Python
On Jun 17, 2:45 pm, Terrence Brannon [EMAIL PROTECTED] wrote: Hello, I have written a program to draw a vescica piscis http:// en.wikipedia.org/wiki/Vesica_piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color(black) circle(r) color(white) forward(r) color(black) circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete Because you overwrote that portion of the circle when you changed the color to white. Instead, you should have done up() (which lifts the pen) and then down() after you've moved to the start of the second circle. No need to change the pen color. 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. That would be the fill() command, but it's not documented how to fill with anything other than a solid color. And finally, is turtle the best option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. -- http://mail.python.org/mailman/listinfo/python-list
Is there a standard binary search with overridable comparisons?
I've got an ordered list of MyClasses that I want to be able to do binary searches on, but against a tuple. MyClass has valid __lt__(self, rhs) and __eq__(self, rhs) member functions that work when rhs is a tuple. This works: l = [MyClass(..), MyClass(..), ...] l.find((a,b)) But this doesn't: bisect.bisect(l, (a,b)) I'm assuming this is because inside bisect, it does 'key list[x]' rather than 'list[x] key', so it's the tuple's __lt__ that is called, rather than MyClass's tuple. Is there a way around this? Can I monkeypatch a new __lt__ into the tuple class? Here's some sample code that demonstrates the problem (it uses ints rather than tuples, but the import bisect class MyC: def __init__(self, v): self.v = v def __lt__(self, rhs): return self.v rhs # cant search for int in a list of MyC's l = sorted([MyC(x) for x in range(1000)]) bisect.bisect(l, 40) 1001 # AKA not found # but, I can search for MyC in a list of ints l = sorted(range(1000)) bisect.bisect(l, MyC(40)) 41 -- http://mail.python.org/mailman/listinfo/python-list
Re: 2d graphics - drawing a vescica piscis in Python
On Jun 17, 12:45 pm, Terrence Brannon [EMAIL PROTECTED] wrote: Hello, I have written a program to draw a vescica piscis http:// en.wikipedia.org/wiki/Vesica_piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color(black) circle(r) color(white) forward(r) color(black) circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. And finally, is turtle the best option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. I would just draw on the tk canvas: import Tkinter as tk can = tk.Canvas() can.pack(fill=tk.BOTH, expand=True) c1 = can.create_oval(10,10,110,110) c2 = can.create_oval(60,10,170,110) You can draw cross hatching using can.create_line(...). Have fun, Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError: 'ascii' codec can't decode byte
On Tue, 17 Jun 2008 09:23:28 +0200, Peter Otten [EMAIL PROTECTED] wrote: Assuming that encoding is UTF-8 and that apsw can cope with unicode, try to convert your data to unicode before feeding it to the database api: sql = INSERT INTO mytable (col1,col2) VALUES (?,?) rows = ([col.decode(utf-8) for col in row] for row in records(test.tsv)) cursor.executemany(sql, rows) Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
using the string functions (ex. find()) on a multi-symbol string
How can i use the find() function on a string that is composed of tons of symbols that cause errors... THis is my string: find(htmlheadmeta name=qrichtext content=1 /style type=text/cssp, li { white-space: pre-wrap; }/style/headbody style= font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight: 400; font-style:normal; text-decoration:none;p style= margin-top: 0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block- indent:0; text-indent:0px; font-size:8pt;span style= font-size: 10pt; color:green;Connected!/span/p/body/html,margin) The tough part about this is that the string is dynamically produced. So I can't manually go into the string and eliminate the quote-marks or to literal-character them. -- http://mail.python.org/mailman/listinfo/python-list
Re: 2d graphics - drawing a vescica piscis in Python
On Jun 18, 2:45 am, Terrence Brannon [EMAIL PROTECTED] wrote: Hello, I have written a program to draw a vescica piscis http:// en.wikipedia.org/wiki/Vesica_piscis from turtle import * def main(): setup(width=400, height=400) r = 50 color(black) circle(r) color(white) forward(r) color(black) circle(r) x = raw_input('please enter a string:') if __name__ == '__main__': main() ... but I would like the following: 1 - I dont like how the bottom of the first circle is not complete 2 - I would like for the left circle to be filled with verticle lines and the right circle to be filled with horizontal lines, so that the vescica piscis is cross-hatched. And finally, is turtle the best option for what I'm doing? pyCairo looked a bit hard to get going with, but very powerful. sping looked a bit alpha/beta. For an alternative to turtle, you might want to see PIL (Python Imaging Library) or perhaps pygame. -- http://mail.python.org/mailman/listinfo/python-list
Re: text alignment
On Jun 17, 8:43 pm, Mike Driscoll [EMAIL PROTECTED] wrote: On Jun 17, 1:20 pm, Gandalf [EMAIL PROTECTED] wrote: since you brought up this issue, please tell me where can I fine menual for this library? You want the manual for wxPython? Go to the download page on the Official wxPython page and get the Docs Demos package:http://wxpython.org/download.php That include the wxWidgets Reference. Also see:http://wxpython.org/onlinedocs.php can i generate dynamic GUI from it? Not sure what you mean by this. If you know how to create a dynamic GUI with html/ajax or some such based on the user's interactions with your website, than it should work in the embedded browser just as well as it would in a non-embedded one. If not, Is there any way to generate dynamic GUI (one that can change according to the user input) with HTML-CSS- javascript similar environment? Mike Hi Mike, I was referring to the ActiveX_IEHtmlWindow which you talked about, when I asked you for a tutorial. I have lots of experience on developing web application so if I could implement some of my knowledge for developing none web application it can save me trouble thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: for loop within for loop confusion
Gabriel Genellina wrote: En Mon, 16 Jun 2008 22:51:30 -0300, John Salerno [EMAIL PROTECTED] escribió: takayuki wrote: I'm early on in my python adventure so I'm not there yet on the strip command nuances.I'm reading How to think like a python programmer first. It's great. Then Learning python. I've read parts of Dive into Python and will work through it fully when I'm a little farther along. Yeah, I really recommend Learning Python for getting the basics first. It's very thorough in that regard. Dive Into Python is *not* for beginners. I'm sorry if people disagree, but it's just not. Sure, the author himself says so at the very beginning in http://www.diveintopython.org Dive Into Python is a Python book for experienced programmers. I know, but I just hear so many people recommend that book for people who want to learn the language. -- http://mail.python.org/mailman/listinfo/python-list
Re: using the string functions (ex. find()) on a multi-symbol string
On Jun 18, 7:12 am, korean_dave [EMAIL PROTECTED] wrote: How can i use the find() function on a string that is composed of tons of symbols that cause errors... THis is my string: find(htmlheadmeta name=qrichtext content=1 /style type=text/cssp, li { white-space: pre-wrap; }/style/headbody style= font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight: 400; font-style:normal; text-decoration:none;p style= margin-top: 0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block- indent:0; text-indent:0px; font-size:8pt;span style= font-size: 10pt; color:green;Connected!/span/p/body/html,margin) The tough part about this is that the string is dynamically produced. So I can't manually go into the string and eliminate the quote-marks or to literal-character them. What are you trying to find? What error(s) do you get? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to request data from a lazily-created tree structure ?
Do you know if there is such XPath engine that can be applied to a DOM- like structure ? No. But I toyed with the idea to write one :) One way would be to take an XPath engine from an existing XML engine (ElementTree, or any other), and see what APIs it calls... and see if we cannot create a DOM-like structure that has the same API. Duck typing, really... Why can't you create a *real* DOM? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: [Twisted-Python] Re-working a synchronous iterator to use Twisted
On Tue, 17 Jun 2008 23:10:48 +0200, Terry Jones [EMAIL PROTECTED] wrote: For the record, here's a followup to my own posting, with working code. The earlier untested code was a bit of a mess. The below runs fine. In case it wasn't clear before, you're pulling results (e.g., from a search engine) in off the web. Each results pages comes with an indicator to tell you whether there are more results. I wanted to write a function (see processResults below) that, when called, would call the process function below on each result, all done asynchronously. This solution feels cumbersome, but it does work (aka prints the expected output). Comments welcome (just don't tell me to use version control :-)) I suspect the implementation could be slightly simplified, but it doesn't look too bad as it is now (and I'm feeling slightly too lazy to back that hunch up with code). I did want to point out that you're missing one tiny detail. [snip] # ASYNCHRONOUS calling def processResults(uri): def cb((resultIterator, deferred)): for result in resultIterator: process(result) if deferred is not None: deferred.addCallback(cb) return getResults(uri).addCallback(cb) Here, the returned Deferred will fire as soon as `cb´ has a result. The return value of `cb´ is always `None´ though, so `cb´ will have a result synchronously in all cases. This is incorrect for the case where there are more results coming. Your example produced the correct output anyway, since all of your Deferreds are created already having results. If you had an asynchronous Deferred, you'd see your finished message before process had been called on all results. There are two possible solutions to this. The simpler one is to return `deferred´ from `cb´. The problem this has is that it builds up a chain of unbounded length which may ultimately encounter a limitation in the implementation of Deferred, hitting the Python stack depth limit and then failing with a RuntimeError. The only slightly more complex one is to create a new Deferred in `processResults´ and return it. Then, fire it inside `cb´ when `deferred´ is None. You also need to be slightly careful to hook up the errback chain in this case, so that if there's some problem with getting an iterator the app-facing Deferred gets errbacked. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: using the string functions (ex. find()) on a multi-symbol string
On Jun 18, 7:12 am, korean_dave [EMAIL PROTECTED] wrote: How can i use the find() function on a string that is composed of tons of symbols that cause errors... THis is my string: find(htmlheadmeta name=qrichtext content=1 /style type=text/cssp, li { white-space: pre-wrap; }/style/headbody style= font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight: 400; font-style:normal; text-decoration:none;p style= margin-top: 0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block- indent:0; text-indent:0px; font-size:8pt;span style= font-size: 10pt; color:green;Connected!/span/p/body/html,margin) The tough part about this is that the string is dynamically produced. So I can't manually go into the string and eliminate the quote-marks or to literal-character them. If as you say the string is dynamically created, your script should have a variable name for it e.g. dynstr so all you have to do is: dynstr.find(margin) Note: you should be using str methods (see http://docs.python.org/lib/string-methods.html); almost all functionality in the string module is now deprecated and redirected (slowly) e.g. def find(s, t): return s.find(t) If you really want/need to put such a monster string containing both ' and as a literal in your script, you can use triple quotes ( or '''). I.e. find(htmlheadmeta name=qrichtext ... /span/p/body/ html, margin) See http://docs.python.org/tut/node5.html#SECTION00512 HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Calling pcre with ctypes
Recently I discovered the re module doesn't support POSIX character classes: Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type help, copyright, credits or license for more information. import re r = re.compile('[:alnum:]+') print r.match('123') None So I thought I'd try out pcre through ctypes, to recreate pcredemo.c in python. The c code is at: http://vcs.pcre.org/viewvc/code/trunk/pcredemo.c?view=markup Partial Python code is below I'm stuck, from what I can tell a c array, such as: int ovector[OVECCOUNT]; translates to ovector = ctypes.c_int * OVECOUNT but when I pass ovector to a function I get the traceback $ python pcredemo.py [a-z] fred Traceback (most recent call last): File pcredemo.py, line 65, in module compiled_re, None, subject, len(subject), 0, 0, ovector, OVECOUNT ctypes.ArgumentError: argument 7: type 'exceptions.TypeError': Don't know how to convert parameter 7 What is the correct way to construct and pass ovector? With thanks, Alex # PCRE through ctypes demonstration program import ctypes import getopt import sys import pcre_const OVECOUNT = 30 # Should be a multiple of 3 pcre = ctypes.cdll.LoadLibrary('libpcre.so') compiled_re = None error = ctypes.c_char_p() pattern = '' subject = '' name_table = ctypes.c_ubyte() erroffset = ctypes.c_int() find_all= 0 namecount = 0 name_entry_size = 0 ovector = ctypes.c_int * OVECOUNT options = 0 # First, sort out the command line. There is only one possible option at # the moment, -g to request repeated matching to find all occurrences, # like Perl's /g option. We set the variable find_all to a non-zero value # if the -g option is present. Apart from that, there must be exactly two # arguments. opts, args = getopt.getopt(sys.argv[1:], 'g') for o, v in opts: if o == '-g': find_all = 1 # After the options, we require exactly two arguments, which are the # pattern, and the subject string. if len(args) != 2: print 'Two arguments required: a regex and a subject string' sys.exit(1) pattern = args[0] subject = args[1] subject_length = len(subject) # Now we are going to compile the regular expression pattern, and handle # and errors that are detected. compiled_re = pcre.pcre_compile( pattern, options, ctypes.byref(error), ctypes.byref(erroffset), None ) -- http://mail.python.org/mailman/listinfo/python-list
Execfile issue
I'm having (what I assume is) a simple problem regarding the way import and execfile interact. I apologize in advance for my naivete. Lets say I have the function: def Func1(): print dir() execfile('testfile') print dir() X and the file #file: testfile X = 3 Then, when I run Func1 , I get the output: Func1() [] ['X'] Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in Func1 NameError: global name 'X' is not defined SO, I have three questions: 1) Naively, I would think that the call to execfile in Func1 would act as if the line was replaced with the lines of 'testfile'. But obviously not, in some way that has to do with the subtlety of the python compilation process. Can someone explain exactly what the problem is? 2) Why would something show up in the dir() call, but not be defined (e.g. like 'X' did in the second dir() call in Func1()) ? 3) Is there any way to fix this that does not involved (essentially in one way or another) importing testfile as a py module? I would like to avoid that scenario for a variety of reasons ... Thanks! Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
I think I have lost the thread here, sorry. So I explain again what I mean. I think for this data structure it's important to keep all the normal dict operations at the same speed. If you use a C implementation vaguely similar to my pure python recipe you can perform the del in O(1) too, because pairs are joined in (double) linked list. But such data structure is O(n) to find the n-th item inserted into the sequence. Right. So byindex(n) would be O(n) then, right? If so, what's the purpose of having that method in the first place? The PEP doesn't give a rationale, but just proposes that the method be there. My guess is that it includes it for performance reasons. However, I think the PEP (author) is misguided in assuming that making byindex() a method of odict, you get better performance than directly doing .items()[n] - which, as you say, you won't. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 372 -- Adding an ordered directory to collections
Well, this has become something of a rant, Indeed - and I was only asking about .byindex(n) :-) I don't know why that method is included in the PEP. Speculating myself, I assume that the PEP author wants it to be O(1). As bearophile explains, that's not possible/not a good idea. As for releasing the odict - that will likely have mostly the same cost as releasing a regular dictionary, except that you might have to look at each key twice (once in the regular dict, once in the structure preserving the order). It might be that the odict uses a linked-list style approach, which indeed would nto be so good from a allocation/deallocation overhead point of view. With the approach bearophile suggests (i.e. each slot in the dict has a reference to the predecessor and successor key also), a pure Python implementation would normally allocate additional memory per key, whereas a pure C implementation wouldn't (adding the space for the prev/next pointer right into the slot's struct definition. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a standard binary search with overridable comparisons?
On Jun 18, 6:55 am, markscottwright [EMAIL PROTECTED] wrote: I've got an ordered list of MyClasses that I want to be able to do binary searches on, but against a tuple. MyClass has valid __lt__(self, rhs) and __eq__(self, rhs) member functions that work when rhs is a tuple. This works: l = [MyClass(..), MyClass(..), ...] l.find((a,b)) But this doesn't: bisect.bisect(l, (a,b)) I'm assuming ... Don't. It can be dangerous. this is because inside bisect, it does 'key list[x]' rather than 'list[x] key', so it's the tuple's __lt__ that is called, rather than MyClass's tuple. Actually it appears (extremely gory details in Objects/object.c) that it tries all rich comparison possibilities first: tuple myclass: not defined in tuple type myclass tuple: not defined in MyClass before falling through to the default (which is based on addresses). Is there a way around this? Can I monkeypatch a new __lt__ into the tuple class? Looks like you need to implement MyClass.__gt__ I suspect someone will say that this section of the manual is trying to tell us this: There are no reflected (swapped-argument) versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other's reflection, __le__() and __ge__() are each other's reflection, and __eq__() and __ne__() are their own reflection. ... trying being the operative word :-) Alternatively, do you really need rich comparison? Consider defining __cmp__ instead of 2 to 6 of the __lt__ etc brigade. HTH, John -- http://mail.python.org/mailman/listinfo/python-list