[ANN] git JSONRPC web service and matching pyjamas front-end
as more than just a proof-of-concept but to get pyjamas out of looking like a nice toy, doesn't do much, great demos, shame about real life, i've created yet another git repository browser. this one, thanks to pyjamas, obviously runs as both a desktop application and also as a web application - same source code. pyjamasgitweb is actually two independent happily small projects. the first is simply a JSONRPC-based git web server (in python, using python-git) and the second is a matching front-end. the front-end is happily bare but functional. a demo is here (please be nice to it) where you will see immediately a total lack of colour or even borders: http://pyjs.org/pygit if anyone wants the source code, or to help contribute, it's at: git clone gitol...@pyjs.org:pyjamasgitweb to start the server, read the README, install the dependencies, then do: $ cd jsonservice $ python srv.py {path to top level of repository} $ cd ../pyjamas $ ./build.sh # requires symlink ~/bin/pyjsbuild to sandbox $ firefox http://127.0.0.1:8000/outputJSONRPCService.html $ python JSONRPCService.py # for the desktop version l. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
RE: Python profiler usage with objects
-Original Message- From: python-list-bounces+bsk16=case@python.org [mailto:python-list- bounces+bsk16=case@python.org] On Behalf Of rik Sent: Tuesday, June 29, 2010 10:52 PM To: python-list@python.org Subject: Re: Python profiler usage with objects harit harit.himanshu at gmail.com writes: Hi, I have a specific question regarding the usage of profiler. I am new to python programming I am trying to profile a function which I want to invoke as a class method, something like this import profile class Class: def doSomething(): do here .. def callMethod(): **self.doSomething()** instead of this I want to use **profile.run(self.doSomething())** but the profile.run expects the string inside it and I get error TypeError: exec: arg 1 must be a string, file, or code object Can somebody please help? Thank you Harit, i am OLD to python, and have used its profiler in the past. but i'm getting your same error: TypeError: exec: arg 1 must be a string, file, or code object on both Ubuntu with Python 2.6 and OSX with 2.4. with both cProfile and profile?! whether or not i specify a file for profile output!?! anybody else having trouble profiling? - rik Let's take this code as an example: def foo() : return None import profile profile.run(foo()) What does the profile.run call do? First thin it does is evaluate foo(), which returns None. So you're calling profile.run(None) There's nothing special about profile.run- you have to hand it something to execute, not something already executed. Try calling Profile.run(doSomething) # no parenthesis for doSomething. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python profiler usage with objects
Ben Kaplan bsk16 at case.edu writes: Let's take this code as an example: def foo() : return None import profile profile.run(foo()) What does the profile.run call do? First thin it does is evaluate foo(), which returns None. So you're calling profile.run(None) There's nothing special about profile.run- you have to hand it something to execute, not something already executed. Try calling Profile.run(doSomething) # no parenthesis for doSomething. -- http://mail.python.org/mailman/listinfo/python-list hi Ben, right: i have a top-level function main() that runs just fine. but i give it as an argument to cProfile.run() or profile.run(), it executes as expected, but then: File /var/folders/lu/luGJNSGwE0mO84R+YbcKpU+++TI/-Tmp-/python-439Ffi.py, line 544, in ? profile.run(main(seedFile),'/Data/tmp/fetchProfile_100629.profile') File /Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/profile.py, line 72, in run prof = prof.run(statement) File /Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/profile.py, line 448, in run return self.runctx(cmd, dict, dict) File /Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/profile.py, line 454, in runctx exec cmd in globals, locals TypeError: exec: arg 1 must be a string, file, or code object this example is from python2.4 on OSX, but the same code generates the same error on python2.6 on Ubuntu?! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python profiler usage with objects
Ben Kaplan bsk16 at case.edu writes: First thin it does is evaluate foo(), which returns None. So you're calling profile.run(None) There's nothing special about profile.run- you have to hand it something to execute, not something already executed. Try calling Profile.run(doSomething) # no parenthesis for doSomething. i'm reading your message more carefully, and so tried calling profile.run(main), without any parens (and absorbing the argument into the function's body for this test). same error!? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python profiler usage with objects
On 2010-06-30 06:39, rik wrote: Ben Kaplan bsk16 at case.edu writes: Let's take this code as an example: def foo() : return None import profile profile.run(foo()) What does the profile.run call do? First thin it does is evaluate foo(), which returns None. So you're calling profile.run(None) There's nothing special about profile.run- you have to hand it something to execute, not something already executed. Try calling Profile.run(doSomething) # no parenthesis for doSomething. -- http://mail.python.org/mailman/listinfo/python-list hi Ben, right: i have a top-level function main() that runs just fine. but i give it as an argument to cProfile.run() or profile.run(), it executes as expected, but then: File /var/folders/lu/luGJNSGwE0mO84R+YbcKpU+++TI/-Tmp-/python-439Ffi.py, line 544, in ? profile.run(main(seedFile),'/Data/tmp/fetchProfile_100629.profile') Looks like the same problem. As Ben pointed out, you need to pass profile.run() an executable (e.g. the main() function itself) and not something that's already been executed. Since you've already called main(seedFile), it's the return value that is being passed to profile.run(), and that's why it's complaining... Perhaps you meant: profile.run('main(seedFile)', '/Data/tmp/whatever') ? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python profiler usage with objects
Ben Kaplan bsk16 at case.edu writes: There's nothing special about profile.run- you have to hand it something to execute, not something already executed. Try calling Profile.run(doSomething) # no parenthesis for doSomething. your hint and REREADING THE DOCUMENTATION made me realize it was the QUOTE MARKS on the function call i was missing: profile.run('main(seedFile)','profileOutFile') Harit, perhaps this was your problem, too? Ben, thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about the posibility of raise-yield in Python
I'm writing this as a complete newbie (on the issue), so don't be surprised if it's the stupidest idea ever. I was wondering if there was ever a discusision in the python community on a 'raise-yield' kind-of combined expression. I'd like to know if it was proposed/rejected/discussed/not-decided yet?? Recently (ok, several hours ago) I've come up to Greenlets [1] and it seems they implement exactly what I was asking for, in a C extension!! It's too bad that Python doesn't support this by default and many libraries won't make use of it by default. Gevent [2] for example, has to monkey-patch Python's socket, time.sleep and other modules so that things like urllib work with it. I'll continue to read now. [1] http://codespeak.net/py/0.9.2/greenlet.html [2] http://www.gevent.org/ A 'raise-yield' expression would break the flow of a program just like an exception, going up the call stack until it would be handled, but also like yield it would be possible to continue the flow of the program from where it was raise-yield-ed. This would be usefull for example in event based frameworks, they could just replace socket.* and similar, normally blocking, modules/functions with it's own 'raise-yield' enabled ones. Then you could just take any normal imperative code that calls normal library networking code (say smtplib, poplib or httplib) nad run it in a event framework. The normal xxxlib calls at some point would get to the now non-blocking, event based socket write/read, break the flow back to the event framework, and when it finishes the event framework would continue the normal flow of the program past the raise-yield. -- дамјан ((( http://damjan.softver.org.mk/ ))) Please remember 43% of statistics are made on the spot. -- http://mail.python.org/mailman/listinfo/python-list
Re: Find slope of function given empirical data.
Thomas wrote: Trying to find slope of function using numpy. Getting close, but results are a bit off. Hope someone out here can help. You don't make it easy to understand your post. In the future please try to rely more on plain english than on lots of numbers and code that doesn't run. import numpy as np def deriv(y): x = list(range(len(y))) x.reverse() # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = np.array(x) #to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] y = np.array(y) # x.reverse() is used to put point 0 at end of list. z = np.polyfit(x, y, 2) print np.poly1d(z) # Returns: # 2 # 3.142 x - 18.85 x + 35.13 # 2 # Should be closer to 3.142 x - 6.283 + 10 To add one more question mark: how did you find that alternative? Anyway, we can put both polynomials to a test: import numpy as np y = np.array([160.796416, 119.95572, 85.398208, 57.12388, 35.132736,19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736]) x = np.arange(len(y), dtype=float)[::-1] p1 = np.poly1d(np.polyfit(x, y, 2)) print p1 2 3.142 x - 18.85 x + 35.13 p2 = np.poly1d([3.142, -6.283, 10.0]) print p2 2 3.142 x - 6.283 x + 10 Now calculate the sum of the squares: np.sum((p1(x)-y)**2) 5.0683524299544787e-26 np.sum((p2(x)-y)**2) 33028.342907811333 Conclusion: numpy's result is much better than what you suggest. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: PDF Generation With Reportlab
Albert Leibbrandt albe...@compuscan.co.ug wrote: I am hoping there is someone out there that knows reportlab quite well. I posted this on the reportlab mailing list but there is not much activity on that list Never the less, that is the correct forum for this question. The ReportLab mailing list is operated and manned by ReportLab employees. They know the code better than anyone. I am currently generating a pdf report using reportlab 2.3 and python 2.5.4. The report has a table that spans multiple pages. My problem is that the portions on the table that continues after the first page, is starting at a point not defined by me, so it creates a layer over the logo which is on each page. How do I specify the starting point of each page the table spans ? Are you talking about something more sophisticated than setting the topMargin property in the SimpleDocTemplate constructor? If you have a logo on each page, you'd want your top margin to exclude that logo. The default top margin is 1 inch. If that's not enough, extend it. If you need different margins on different pages, then you need something more sophisticated than SimpleDocTemplate. Normally I would use pagebreak and spacers but I cannot figure out how to fit this into the table structure. Page breaks and spacers are absolutely the wrong way to handle this. Think about this as a Word document. If you want to exclude the logo, you'd change the top margin to protect it. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: [python] how to ensure item in list or dict bind with an uuid meaning integer type ID?
kee chen keekychen.sha...@gmail.com wrote: I have 2 lists stored in 2 text files may have duplicated records, the raw data looks like this: lfruit lcountry == = orange japan pearchina orange china apple american cherry india lemon china lemon japan strawberry korea banana thailand australia basically, what I want is: 1. all of the duplicated records need to be removed and 2. the unique items need bind with an unique integer ID, something like a PK in database, no sort needed. but before you give answer here, pls also read below. You need a database. What you're talking about here is exactly the kind of thing that an SQL database can provide. Sqlite is simple and lightweight, and can do your unique checks and your join without even breaking a sweat. If you don't like that, there are pure Python SQL engines available that are even simpler. Why reinvent the whell? What you want already exists. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
pyc runtime error
Can anyone explain this unexpected behavior? all files chmod 755, i've compiled x.py with py_compilefiles, also tried within python console with import x system: centos 5.4 32bit This a PATH related problem i think? [r...@centos-14 cgi-bin]# ./x.pyc : command not found ./x.pyc: line 2: syntax error near unexpected token `)' ./x.pyc: line 2: `��)l...@sdghdghdkzeighds(sContent-Type:text/ html' [r...@centos-14 cgi-bin]# python x.pyc Content-Type:text/html python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] x.py file content: #!/usr/bin/env python print Content-Type:text/html\n\n print python import sys print sys.version -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On Wed, Jun 30, 2010 at 1:06 AM, Baris CUHADAR 189...@gmail.com wrote: Can anyone explain this unexpected behavior? all files chmod 755, i've compiled x.py with py_compilefiles, also tried within python console with import x system: centos 5.4 32bit This a PATH related problem i think? Nope. [r...@centos-14 cgi-bin]# ./x.pyc .pyc files are just bytecode, not scripts, so you can't run them as scripts/executables under *nix. Run the .py file instead. Or do `python x.pyc` like you showed. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On 2010-06-30 01:06, Baris CUHADAR wrote: Can anyone explain this unexpected behavior? I'm sorry -- can you let us know what behavior you're expecting? all files chmod 755, i've compiled x.py with py_compilefiles, also tried within python console with import x system: centos 5.4 32bit This a PATH related problem i think? Perhaps I'm misunderstanding what you're trying to do but from what I can see, you are expecting .pyc files to be directly executed by the shell. And as I understand them, they are *not* meant to be directly executed by the shell at all -- they're simply a sometimes-useful shortcut for the Python interpreter. Python scripts like your x.py, however, *are* meant to be executed by the shell. Have you tried: [u...@box cgi-bin]$ ./x.py ? [r...@centos-14 cgi-bin]# ./x.pyc May I ask, as well, why you're doing all of this as root? [r...@centos-14 cgi-bin]# python x.pyc Content-Type:text/html python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] x.py file content: #!/usr/bin/env python print Content-Type:text/html\n\n print python import sys print sys.version -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: git JSONRPC web service and matching pyjamas front-end
On 06/30/10 03:29, CM wrote: On Jun 29, 6:54 pm, Luke Kenneth Casson Leightonl...@lkcl.net wrote: as more than just a proof-of-concept but to get pyjamas out of looking like a nice toy, doesn't do much, great demos, shame about real life, cut If may be generated with pyjamas but I'm not sure how this fulfills your wish to do something that does more than doesn't do much. I would expect a demo to at least have some typical GUI features on it--or am I completely missing the point of what you're doing? I think lkcl wanted to demonstrate that it is more than 'a nice toy' and that there is an actual real world application for it. I am not sure why he seems to have the urge to do that as for me I am already convinced about its usability. -- mph -- http://mail.python.org/mailman/listinfo/python-list
Build unordered list in HTML from a python list
Dear list members I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, ] From that list I want to create the following HTML code: ul id=tree liItem 1/li liItem 2/li liFolder 1 ul liSub Item 1.1/li liSub Item 1.2/li /ul /li liItem 3/li liFolder 2 ul liSub Item 2.1/li liFolder 2.1 ul liSub Item 2.1.1/li liSub Item 2.1.2/li /ul /li /ul /li /ul If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. My problem is: How do I keep track of the closing tags while iterating over the python list? Any help is much appreciated. Regards Nico -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On Jun 30, 11:31 am, Rami Chowdhury rami.chowdh...@gmail.com wrote: On 2010-06-30 01:06, Baris CUHADAR wrote: Can anyone explain this unexpected behavior? I'm sorry -- can you let us know what behavior you're expecting? all files chmod 755, i've compiled x.py with py_compilefiles, also tried within python console with import x system: centos 5.4 32bit This a PATH related problem i think? Perhaps I'm misunderstanding what you're trying to do but from what I can see, you are expecting .pyc files to be directly executed by the shell. And as I understand them, they are *not* meant to be directly executed by the shell at all -- they're simply a sometimes-useful shortcut for the Python interpreter. Python scripts like your x.py, however, *are* meant to be executed by the shell. Have you tried: [u...@box cgi-bin]$ ./x.py ? [r...@centos-14 cgi-bin]# ./x.pyc May I ask, as well, why you're doing all of this as root? [r...@centos-14 cgi-bin]# python x.pyc Content-Type:text/html python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] x.py file content: #!/usr/bin/env python print Content-Type:text/html\n\n print python import sys print sys.version -- http://mail.python.org/mailman/listinfo/python-list Thank you for your replies. This machine is a local virtual test machine so security issues are omitted. Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. On centos 5.4, i think httpd tries to execute it as i did ./x.pyc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python dynamic attribute creation
On 06/29/2010 06:46 PM, WANG Cong wrote: On 06/29/10 17:48, Andre Alexander Bell p...@andre-bell.de wrote: var a a - should raise an variable 'unset' exception Keep in mind that the module you are writing in is just an object as is any function or method. So using local variables therein you are doing exactly what you want to abandon from the OOP part. Hmm, this looks really appealing. I actually very much prefer Python's implementation with direct assignment, just because it's short and comprehensible. Regards Andre -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: Why Is Escaping Data Considered So Magical?
On Wed, 2010-06-30, Michael Torrie wrote: On 06/29/2010 10:17 PM, Michael Torrie wrote: On 06/29/2010 10:05 PM, Michael Torrie wrote: #include stdio.h int main(int argc, char ** argv) { char *buf = malloc(512 * sizeof(char)); const int a = 2, b = 3; snprintf(buf, sizeof buf, %d + %d = %d\n, a, b, a + b); ^^ Make that 512*sizeof(buf) Sigh. Try again. How about 512 * sizeof(char) ? Still doesn't make a different. The code still crashes because the buf is incorrect. I haven't tried to understand the rest ... but never write 'sizeof(char)' unless you might change the type later. 'sizeof(char)' is by definition 1 -- even on odd-ball architectures where a char is e.g. 16 bits. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. It looks like you have the binfmt kernel feature installed and configured on your Ubuntu machines. Do you have some Python related files in /proc/sys/fs/binfmt_misc/ ? Christian -- http://mail.python.org/mailman/listinfo/python-list
Ancient C string conventions (was Re: Why Is Escaping Data Considered So Magical?)
On Wed, 2010-06-30, Carl Banks wrote: On Jun 28, 2:44 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Carl Banks wrote: Indeed, strncpy does not copy that final NUL if it's at or beyond the nth element. Probably the most mind-bogglingly stupid thing about the standard C library, which has lots of mind-boggling stupidity. I don't think it was as stupid as that back when C was designed. Every byte of memory was precious in those days, and if you had, say, 10 bytes allocated for a string, you wanted to be able to use all 10 of them for useful data. So the convention was that a NUL byte was used to mark the end of the string *if it didn't fill all the available space*. I can't think of any function in the standard library that observes that convention, Me neither, except strncpy(), according to above. which inclines me to disbelieve this convention ever really existed. If it did, there would be functions to support it. Maybe others existed, but got killed off early. That would make strncpy() a living fossil, like the Coelacanth ... For that matter, I'm not really inclined to believe bytes were *that* precious in those days. It's somewhat believable. If I handled thousands of student names in a big C array char[30][], I would resent the fact that 1/30 of the memory was wasted on NUL bytes. I'm sure plenty of people have done what Gregory suggests ... but it's not clear that strncpy() was designed to support those people. I suppose it's all lost in history. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
1.5.1 Py_XDECREF Core
Hi, We are using a legacy product which is using 1.5.1 version of Python and we have seen frequent core dumps offlate which is as below #0 0x2b79b0 in list_dealloc (op=0x414b11d0) at listobject.c:220 #1 0x283c48 in dict_dealloc (mp=0x415b8c18) at dictobject.c:491 #2 0x2b4760 in frame_dealloc (f=0x4042ea50) at frameobject.c:116 #3 0x28b938 in eval_code2 (co=0x404a4d28, globals=0x4049bec8, locals=0x0, args=0x404da5dc, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, owner=0x0) at ceval.c:1873 #4 0x28d690 in call_function (func=0x41497958, arg=0x404da5d0, kw=0x0) at ceval.c:2472 Can someone confirm if this is a problem at Python or in the source code, I know that this version is quite old and needs upgarde, but since this in use for long i would need evidence to prove that this is a problem at Python not in the product so that we can upgrade to the latest version. listobject.c for (i = 0; i op-ob_size; i++) { Py_XDECREF(op-ob_item[i]); //Line 220 } Can some one help me out in this, while i belive that the pointer where the derefernece is happening might have got corrupted but this happens rarely and the code is a provisioning script with a command that is successful most times. Regards Sunil -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Is Escaping Data Considered So Magical?
On 29Jun2010 21:49, Carl Banks pavlovevide...@gmail.com wrote: | On Jun 28, 2:44 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: | Carl Banks wrote: | Indeed, strncpy does not copy that final NUL if it's at or beyond the | nth element. Probably the most mind-bogglingly stupid thing about the | standard C library, which has lots of mind-boggling stupidity. | | I don't think it was as stupid as that back when C was | designed. Every byte of memory was precious in those days, | and if you had, say, 10 bytes allocated for a string, you | wanted to be able to use all 10 of them for useful data. | | So the convention was that a NUL byte was used to mark | the end of the string *if it didn't fill all the available | space*. | | I can't think of any function in the standard library that observes | that convention, which inclines me to disbelieve this convention ever | really existed. If it did, there would be functions to support it. | | For that matter, I'm not really inclined to believe bytes were *that* | precious in those days. Jeez. PDP-11s, 16 bit addressing, tiny tiny disc drives! The original V7 (and probably earlier) UNIX filesystem has 16 byte directory entries: 2 bytes for an inode and 14 bytes for the name. You could use 14 bytes of that name, and strncpy makes it effective to work with that data structure. Shortening something already only 14 bytes (the name) _is_ a big ask, and it is well work the unusual convention in play. | The obvious rationale behind strncpy's stupid behavior is that it's | not a string function at all, but a memory block function, that stops | at a NUL in case you don't care what's after the NUL in a block. But | it leads you to believe it's a string function by it's name. Bah. It's for copying a _string_ into a _buffer_! Strangely, since it starts with a string (NUL-terminated byte sequence) it begins with str. And it _is_ copying, but not into another string. It is special purpose but perfectly reasonable for the problem at hand. -- Cameron Simpson c...@zip.com.au DoD#743 http://www.cskk.ezoshosting.com/cs/ If it ain't broken, keep playing with it. -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.5.1 Py_XDECREF Core
On 06/30/2010 11:39 AM, Sunil wrote: Hi, We are using a legacy product which is using 1.5.1 version of Python and we have seen frequent core dumps offlate which is as below #0 0x2b79b0 in list_dealloc (op=0x414b11d0) at listobject.c:220 #1 0x283c48 in dict_dealloc (mp=0x415b8c18) at dictobject.c:491 #2 0x2b4760 in frame_dealloc (f=0x4042ea50) at frameobject.c:116 #3 0x28b938 in eval_code2 (co=0x404a4d28, globals=0x4049bec8, locals=0x0, args=0x404da5dc, argcount=1, kws=0x0, kwcount=0, defs=0x0, defcount=0, owner=0x0) at ceval.c:1873 #4 0x28d690 in call_function (func=0x41497958, arg=0x404da5d0, kw=0x0) at ceval.c:2472 Can someone confirm if this is a problem at Python or in the source code, I know that this version is quite old and needs upgarde, but since this in use for long i would need evidence to prove that this is a problem at Python not in the product so that we can upgrade to the latest version. listobject.c for (i = 0; i op-ob_size; i++) { Py_XDECREF(op-ob_item[i]); //Line 220 } Can some one help me out in this, while i belive that the pointer where the derefernece is happening might have got corrupted but this happens rarely and the code is a provisioning script with a command that is successful most times. I can't really help much as I've never used Python versions that old. Some thoughts: * are you using C extension modules? If you are, double-check their increfs and decrefs. * if you're using pure-Python code, the bug is in Python. Python scripts have no access to memory management and refcounting details (or do they?) and thus can't currupt anything at that level. * see http://www.python.org/download/releases/1.6.1/ : -- What's new in release 1.6.1? - A core dump in the C API function PyList_Reverse() has been fixed. possibly relevant? -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
On Wed, Jun 30, 2010 at 2:04 PM, Nico Grubert nicogrub...@yahoo.de wrote: Dear list members I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, ] From that list I want to create the following HTML code: ul id=tree liItem 1/li liItem 2/li liFolder 1 ul liSub Item 1.1/li liSub Item 1.2/li /ul /li liItem 3/li liFolder 2 ul liSub Item 2.1/li liFolder 2.1 ul liSub Item 2.1.1/li liSub Item 2.1.2/li /ul /li /ul /li /ul If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. My problem is: How do I keep track of the closing tags while iterating over the python list? Use a stack? Whenever you start a new list, push the corresponding closing tag onto a stack. Whenever your indent level decreases, pop the stack and write out the closing tag you get. It's straightforward to use a python list as a stack. -- regards, kushal -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
Nico Grubert, 30.06.2010 10:34: I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, ] From that list I want to create the following HTML code: ul id=tree liItem 1/li liItem 2/li liFolder 1 ul liSub Item 1.1/li liSub Item 1.2/li /ul /li liItem 3/li liFolder 2 ul liSub Item 2.1/li liFolder 2.1 ul liSub Item 2.1.1/li liSub Item 2.1.2/li /ul /li /ul /li /ul If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. My problem is: How do I keep track of the closing tags while iterating over the python list? Don't. Just use a tool for generating the XML, such as ElementTree's builder. http://effbot.org/zone/element-builder.htm http://svn.effbot.org/public/stuff/sandbox/elementlib/builder.py Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
Use a stack? Whenever you start a new list, push the corresponding closing tag onto a stack. Whenever your indent level decreases, pop the stack and write out the closing tag you get. It's straightforward to use a python list as a stack. Thanks for the tip, Kushal. Do you have a short code example for me? Regards Nico -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On Jun 30, 12:06 pm, Christian Heimes li...@cheimes.de wrote: Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. It looks like you have the binfmt kernel feature installed and configured on your Ubuntu machines. Do you have some Python related files in /proc/sys/fs/binfmt_misc/ ? Christian Thanks Christian, before your message i was thinking about writing wrapper to turn round this issue. my wrapper: #!/usr/bin/bash /usr/bin/python m_file.pyc Yes /proc/sys/fs/binfmt_misc/python2.6 is there. enabled interpreter /usr/bin/python2.6 flags: offset 0 magic d1f20d0a How can make it possible in centos? With custom kernel compiling? -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On Jun 30, 2:20 pm, Baris CUHADAR 189...@gmail.com wrote: On Jun 30, 12:06 pm, Christian Heimes li...@cheimes.de wrote: Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. It looks like you have the binfmt kernel feature installed and configured on your Ubuntu machines. Do you have some Python related files in /proc/sys/fs/binfmt_misc/ ? Christian Thanks Christian, before your message i was thinking about writing wrapper to turn round this issue. my wrapper: #!/usr/bin/bash /usr/bin/python m_file.pyc Yes /proc/sys/fs/binfmt_misc/python2.6 is there. enabled interpreter /usr/bin/python2.6 flags: offset 0 magic d1f20d0a How can make it possible in centos? With custom kernel compiling? According to this documentation below, i've solved my problem. http://git.kernel.org/gitweb.cgi?p=linux/kernel/git/torvalds/linux-2.6.git;a=blob;f=Documentation/binfmt_misc.txt;hb=HEAD registered .pyc extension to invoke python interpreter. Done, thank you everybody, especially Christian.. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On 06/30/2010 01:20 PM, Baris CUHADAR wrote: On Jun 30, 12:06 pm, Christian Heimes li...@cheimes.de wrote: Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. It looks like you have the binfmt kernel feature installed and configured on your Ubuntu machines. Do you have some Python related files in /proc/sys/fs/binfmt_misc/ ? Christian Thanks Christian, before your message i was thinking about writing wrapper to turn round this issue. my wrapper: #!/usr/bin/bash /usr/bin/python m_file.pyc Yes /proc/sys/fs/binfmt_misc/python2.6 is there. enabled interpreter /usr/bin/python2.6 flags: offset 0 magic d1f20d0a How can make it possible in centos? With custom kernel compiling? The binfmt_misc module has to be loaded, which is presumably is, if /proc/sys/fs/binfmt_misc exists (not 100% sure on that) It's almost certainly provided by CentOS, even if it's not loaded by default. Assuming file.pyc was actually compiled by python2.6, and not some other version, it should work. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
Dear list members I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. Or you can change your list to a dict with a tree structure and use recursion instead of a stack: tree = [ { 'title': 'Item 1', 'children': [] }, { 'title': 'Item 2', 'children': [] }, { 'title': 'Folder 1', 'children': [ { 'title': 'sub item 1.1', 'children' : [], }, { 'title': 'Folder 1.1', 'children' : [ .. ], }, ] }, ] and something like: def displayListItem(i): print 'li%s' % i['title'] if i['children']: print 'ul' for c in i['children']: displayListItem(c) print '/ul' print /li you might also use recursion with your existing list, by 'pop'ing the first item and passing the rest of the list. Remi -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
On Tue, 29 Jun 2010 08:41:03 -0400, Roy Smith wrote: And what about regular expressions? What about them? As the saying goes: Some people, when confronted with a problem, think I know, I'll use regular expressions. Now they have two problems. That's silly. RE is a good tool. Like all good tools, it is the right tool for some jobs and the wrong tool for others. When all you have is a hammer, everything looks like a nail ;) Except, REs are more like a turbocharged angle grinder: bloody dangerous in the hands of a novice. [I was going to say hole hawg, but then realised that most of my post would be a quotation explaining it. The reference is to Neal Stephenson's essay In the Beginning was the Command Line: http://www.cryptonomicon.com/beginning.html] I've noticed over the years a significant anti-RE sentiment in the Python community. IMHO, the sentiment isn't so much against REs per se, but against excessive or inappropriate use. Apart from making it easy to write illegible code, they also make it easy to write code that mostly sort-of works but somewhat harder to write code which is actually correct. It doesn't help that questions on REs often start out by stating a problem for which REs are inappropriate, e.g. parsing a context-free (or higher) language, and in the same sentence indicate the the poster is already predisposed to using REs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Is Escaping Data Considered So Magical?
In article mailman.14.1277891765.1673.python-l...@python.org, Cameron Simpson c...@zip.com.au wrote: Jeez. PDP-11s, 16 bit addressing, tiny tiny disc drives! What you talking about, tiny? An RK-05 was huge! Why would anybody ever need more than that? The original V7 (and probably earlier) UNIX filesystem has 16 byte directory entries Certainly earlier. I used v6, and it was like that there. I'm reasonably sure it pre-dated v6, however. -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. -- http://mail.python.org/mailman/listinfo/python-list
Re: Find slope of function given empirical data.
On Jun 30, 3:28 am, Peter Otten __pete...@web.de wrote: Thomas wrote: Trying to find slope of function using numpy. Getting close, but results are a bit off. Hope someone out here can help. You don't make it easy to understand your post. In the future please try to rely more on plain english than on lots of numbers and code that doesn't run. import numpy as np def deriv(y): x = list(range(len(y))) x.reverse() # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = np.array(x) # to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] y = np.array(y) # x.reverse() is used to put point 0 at end of list. z = np.polyfit(x, y, 2) print np.poly1d(z) # Returns: # 2 # 3.142 x - 18.85 x + 35.13 # 2 # Should be closer to 3.142 x - 6.283 + 10 To add one more question mark: how did you find that alternative? Anyway, we can put both polynomials to a test: import numpy as np y = np.array([160.796416, 119.95572, 85.398208, 57.12388, 35.132736,19.424776, 10.0, 6.858408, 10.0, 19.424776, 35.132736]) x = np.arange(len(y), dtype=float)[::-1] p1 = np.poly1d(np.polyfit(x, y, 2)) print p1 2 3.142 x - 18.85 x + 35.13 p2 = np.poly1d([3.142, -6.283, 10.0]) print p2 2 3.142 x - 6.283 x + 10 Now calculate the sum of the squares: np.sum((p1(x)-y)**2) 5.0683524299544787e-26 np.sum((p2(x)-y)**2) 33028.342907811333 Conclusion: numpy's result is much better than what you suggest. Peter As usual, thanks to all for putting me on the right track. Kind regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: PDF Generation With Reportlab
On 2010/06/30 10:52 AM, Tim Roberts wrote: Albert Leibbrandtalbe...@compuscan.co.ug wrote: I am hoping there is someone out there that knows reportlab quite well. I posted this on the reportlab mailing list but there is not much activity on that list Never the less, that is the correct forum for this question. The ReportLab mailing list is operated and manned by ReportLab employees. They know the code better than anyone. I am currently generating a pdf report using reportlab 2.3 and python 2.5.4. The report has a table that spans multiple pages. My problem is that the portions on the table that continues after the first page, is starting at a point not defined by me, so it creates a layer over the logo which is on each page. How do I specify the starting point of each page the table spans ? Are you talking about something more sophisticated than setting the topMargin property in the SimpleDocTemplate constructor? If you have a logo on each page, you'd want your top margin to exclude that logo. The default top margin is 1 inch. If that's not enough, extend it. If you need different margins on different pages, then you need something more sophisticated than SimpleDocTemplate. Normally I would use pagebreak and spacers but I cannot figure out how to fit this into the table structure. Page breaks and spacers are absolutely the wrong way to handle this. Think about this as a Word document. If you want to exclude the logo, you'd change the top margin to protect it. Thanks a mil Tim, your reply actually gave me what I was looking for. too little sleep on my part ... Cheers Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
Nico Grubert wrote: Use a stack? Whenever you start a new list, push the corresponding closing tag onto a stack. Whenever your indent level decreases, pop the stack and write out the closing tag you get. It's straightforward to use a python list as a stack. Thanks for the tip, Kushal. Do you have a short code example for me? Regards Nico mylist = [3, 4, 5] mylist.append[42] print mylist3,4,5,42 item = mylist.pop() returns the 42, removing it from the list So, use append as a push, and pop without arguments as a pop. And use len() to decide how big the list currently is. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: pyc runtime error
On Jun 30, 3:10 pm, Thomas Jollans tho...@jollans.com wrote: On 06/30/2010 01:20 PM, Baris CUHADAR wrote: On Jun 30, 12:06 pm, Christian Heimes li...@cheimes.de wrote: Actually i wrote some scripts in python that are working as gateway controlling scripts iptables/tc/squid-proxy, and i want to execute them as cgi. Protection of source code is also important. These scripts works fine with ubuntu 9.10 and ubuntu 10.04, trying to eleminate this execution error and successfully port them to centos 5.4. Or i have to rewrite these scripts in C which is time comsuming. It looks like you have the binfmt kernel feature installed and configured on your Ubuntu machines. Do you have some Python related files in /proc/sys/fs/binfmt_misc/ ? Christian Thanks Christian, before your message i was thinking about writing wrapper to turn round this issue. my wrapper: #!/usr/bin/bash /usr/bin/python m_file.pyc Yes /proc/sys/fs/binfmt_misc/python2.6 is there. enabled interpreter /usr/bin/python2.6 flags: offset 0 magic d1f20d0a How can make it possible in centos? With custom kernel compiling? The binfmt_misc module has to be loaded, which is presumably is, if /proc/sys/fs/binfmt_misc exists (not 100% sure on that) It's almost certainly provided by CentOS, even if it's not loaded by default. Assuming file.pyc was actually compiled by python2.6, and not some other version, it should work. -- Thomas Yes centos5.4 loads it automatically, however little kickstart script in /etc/rc.local is required. is_python=$(ls -l /proc/sys/fs/binfmt_misc/python2.4 | wc -l) if [ $is_python -lt 1 ]; then echo ':python2.4:E::pyc::/usr/bin/python:' /proc/sys/fs/binfmt_misc/ register fi i'm still digging in.. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Re: Why Is Escaping Data Considered So Magical?
On 06/30/2010 03:00 AM, Jorgen Grahn wrote: On Wed, 2010-06-30, Michael Torrie wrote: On 06/29/2010 10:17 PM, Michael Torrie wrote: On 06/29/2010 10:05 PM, Michael Torrie wrote: #include stdio.h int main(int argc, char ** argv) { char *buf = malloc(512 * sizeof(char)); const int a = 2, b = 3; snprintf(buf, sizeof buf, %d + %d = %d\n, a, b, a + b); ^^ Make that 512*sizeof(buf) Sigh. Try again. How about 512 * sizeof(char) ? Still doesn't make a different. The code still crashes because the buf is incorrect. I haven't tried to understand the rest ... but never write 'sizeof(char)' unless you might change the type later. 'sizeof(char)' is by definition 1 -- even on odd-ball architectures where a char is e.g. 16 bits. You're right. I normally don't use sizeof(char). This is obviously a contrived example; I just wanted to make the example such that there's no way the original poster could argue that the crash is caused by something other than buf. Then again, it's always a bad idea in C to make assumptions about anything. If you're on Windows and want to use the unicode versions of everything, you'd need to do sizeof(). So using it here would remind you that when you move to the 16-bit Microsoft unicode versions of snprintf need to change the sizeof(char) lines as well to sizeof(wchar_t). -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
On Tue, 2010-06-29, Stephen Hansen wrote: On 6/29/10 5:41 AM, Roy Smith wrote: Nobodynob...@nowhere.com wrote: And what about regular expressions? What about them? As the saying goes: Some people, when confronted with a problem, think I know, I'll use regular expressions. Now they have two problems. That's silly. RE is a good tool. Like all good tools, it is the right tool for some jobs and the wrong tool for others. There's nothing silly about it. It is an exaggeration though: but it does represent a good thing to keep in mind. Not an exaggeration: it's an absolute. It literally says that any time you try to solve a problem with a regex, (A) it won't solve the problem and (B) it will in itself become a problem. And it doesn't tell you why: you're supposed to accept or reject this without thinking. How can that be a good thing to keep in mind? I wouldn't normally be annoyed by the quote, but it is thrown around a lot in various places, not just here. Yes, re is a tool -- and a useful one at that. But its also a tool which /seems/ like an omnitool capable of tackling everything. That's more like my attitude towards them. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: Find slope of function given empirical data.
On 2010-06-29, Thomas thom1...@gmail.com wrote: Trying to find slope of function using numpy. Getting close, but results are a bit off. Hope someone out here can help. import numpy as np def deriv(y): x = list(range(len(y))) x.reverse() # Change from [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x = np.array(x) #to [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] y = np.array(y) # x.reverse() is used to put point 0 at end of list. z = np.polyfit(x, y, 2) print np.poly1d(z) # Returns: # 2 # 3.142 x - 18.85 x + 35.13 # 2 # Should be closer to 3.142 x - 6.283 + 10 Numpy's answer is correct. I've no idea where you got your answer. Perhaps the commented-out stuff was meant to convey that. If so, it went past me. Here's the least-squares fit done by gnuplot, the resulting fuction f(x) plotted against the data, as well as your should be function plotted against the data. As you can see, your should be function is way off. For prettier results, you can change the gnuplot script to use a different output format -- I just used the dumb terminal so I could post it here. In any case, the values returned by numpy and gnuplot hit the data points pretty much exactly -- far better than your should be results. NB: You might want to grab a copy of gnuplot (or a similar) tool to use when tinkering with data analysis and visualisation. It's very handy. --foo.gp-- #!/usr/bin/gnuplot f(x) = a*x**2 + b*x + c fit f(x) foo.dat via a,b,c set xra[-1:11] set term dumb 120 40 plot f(x), foo.dat plot 3.142*x**2 + 6.283*x + 10, foo.dat --foo.gp-- --foo.dat-- 10 160.796416 9 119.95572 8 85.398208 7 57.12388 6 35.132736 5 19.424776 4 10.0 3 6.858408 2 10.0 1 19.424776 0 35.132736 --foo.dat-- results of running foo.gp Iteration 0 [...] Iteration 1 [...] Iteration 2 [...] Iteration 3 [...] Iteration 4 [...] Iteration 5 [...] Iteration 6 [...] Iteration 7 [...] ** After 8 iterations the fit converged. final sum of squares of residuals : 7.70717e-28 rel. change during last iteration : 0 degrees of freedom(FIT_NDF): 8 rms of residuals (FIT_STDFIT) = sqrt(WSSR/ndf): 9.81528e-15 variance of residuals (reduced chisquare) = WSSR/ndf : 9.63396e-29 Final set of parametersAsymptotic Standard Error ===== a = 3.14159 +/- 3.351e-16(1.067e-14%) b = -18.8496 +/- 3.479e-15(1.846e-14%) c = 35.1327 +/- 7.478e-15(2.128e-14%) [...] 250 ++---+-+-+--+-+-+---++ |+ + + + + f(x) ** | | foo.dat A| | | | | | | | * 200 ++ *+ | * | | *** | | * | | * | | * | | *A| 150 ++ * ++ | * | | **
Re: Build unordered list in HTML from a python list
On Wed, 2010-06-30, Kushal Kumaran wrote: On Wed, Jun 30, 2010 at 2:04 PM, Nico Grubert nicogrub...@yahoo.de wrote: Dear list members I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, ] From that list I want to create the following HTML code: ul id=tree liItem 1/li liItem 2/li liFolder 1 ul liSub Item 1.1/li liSub Item 1.2/li /ul /li liItem 3/li liFolder 2 ul liSub Item 2.1/li liFolder 2.1 ul liSub Item 2.1.1/li liSub Item 2.1.2/li /ul /li /ul /li /ul If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. My problem is: How do I keep track of the closing tags while iterating over the python list? Use a stack? Whenever you start a new list, push the corresponding closing tag onto a stack. Whenever your indent level decreases, pop the stack and write out the closing tag you get. It's straightforward to use a python list as a stack. Or even simpler. You keep track of your current indentation level (0, 1, ...). If level==1 and you come to an indent: 2, you generate an ul and increase level to 2. Similarly for going left. When you reach the end you add /uls to go back up to level 1 (or maybe you want to call it level 0 instead). That probably assumes you use HTML (like you say) rather than XHTML (which your example hints at). In HTML you don't need to supply the /lis. I did all this in Perl earlier today, but in my case it was unsuitable because I skipped levels (had a list of HTML headings, wanted a table-of-contents, but sometimes a h1 was followed by h3 with no h2 inbetween. I'd get invalid stuff like ulul. /Jorgen -- // Jorgen Grahn grahn@ Oo o. . . \X/ snipabacken.se O o . -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
On 6/30/10 7:14 AM, Jorgen Grahn wrote: On Tue, 2010-06-29, Stephen Hansen wrote: On 6/29/10 5:41 AM, Roy Smith wrote: Nobodynob...@nowhere.com wrote: And what about regular expressions? What about them? As the saying goes: Some people, when confronted with a problem, think I know, I'll use regular expressions. Now they have two problems. That's silly. RE is a good tool. Like all good tools, it is the right tool for some jobs and the wrong tool for others. There's nothing silly about it. It is an exaggeration though: but it does represent a good thing to keep in mind. Not an exaggeration: it's an absolute. It literally says that any time you try to solve a problem with a regex, (A) it won't solve the problem and (B) it will in itself become a problem. And it doesn't tell you why: you're supposed to accept or reject this without thinking. How can that be a good thing to keep in mind? That it speaks in absolutes is what makes it an exaggeration. Yes, it literally says something kind of like that (Your 'a' is a mischaracterization). It's still a very good thing to keep in mind. Its a saying -- a proverb, an expression. Since when are the wise remarks of our ancient forefathers literal? Not last I checked. Reading into a saying as not a guide or suggestion or cautionary tale but instead a doctrinal absolute is where we run into problems, not in the repeating of them. -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 6/30/10 5:52 AM, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. I want to stamp a [Citation Needed] claim on that :) Considering all the other things you're likely to do during 'quick and dirty' debugging, an extra set of parens seems terribly unlikely to really be any kind of issue. And if you have an editor worth its salt, it'll take care of a lot of that anyways. That justification sounds like its based on a mountain-out-of-a-mole-hill complaint: print() is really not that significantly more difficult then the print statement. This isn't Ruby or another language which has determined () is an onerous requirement for executing something. -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Jun 30, 2:52 pm, Lie Ryan lie.1...@gmail.com wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. Actually when debugging I use pdb which uses p (no parens) for printing, so having print or print() would not make any difference for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Build unordered list in HTML from a python list
I have this python list that represets a sitemap: tree = [{'indent': 1, 'title':'Item 1', 'hassubfolder':False}, {'indent': 1, 'title':'Item 2', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 1', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 1.1', 'hassubfolder':False}, {'indent': 2, 'title':'Sub Item 1.2', 'hassubfolder':False}, {'indent': 1, 'title':'Item 3', 'hassubfolder':False}, {'indent': 1, 'title':'Folder 2', 'hassubfolder':True}, {'indent': 2, 'title':'Sub Item 2.1', 'hassubfolder':False}, {'indent': 2, 'title':'Folder 2.1', 'hassubfolder':True}, {'indent': 3, 'title':'Sub Item 2.1.1', 'hassubfolder':False}, {'indent': 3, 'title':'Sub Item 2.1.2', 'hassubfolder':False}, ] From that list I want to create the following HTML code: ul id=tree liItem 1/li liItem 2/li liFolder 1 ul liSub Item 1.1/li liSub Item 1.2/li /ul /li liItem 3/li liFolder 2 ul liSub Item 2.1/li liFolder 2.1 ul liSub Item 2.1.1/li liSub Item 2.1.2/li /ul /li /ul /li /ul If an item of the list has 'True' for the 'hassubfolder' key than a new ulli must be created instead of /li after its title. (See Folder 2 node in the HTML code above. My problem is: How do I keep track of the closing tags while iterating over the python list? Elementtree has already been mentioned as a solution, but if you need something more lightweight, give markup.py a try: http://markup.sourceforge.net/ it's a single module and very easy to use for the sort of things you are after. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
numpy - save many arrays into a file object
import numpy data = numpy.array(...) numpy.save(test.np,data) This is very good, but I want to save the data into a file object with a write() method. E.g. not a real file. (My purpose right now is to save many arrays into one binary file, while recording starting positions of the arrays.) How can I do that? Thanks Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: git JSONRPC web service and matching pyjamas front-end
On Jun 30, 4:27 am, Martin P. Hellwig martin.hell...@dcuktec.org wrote: On 06/30/10 03:29, CM wrote: On Jun 29, 6:54 pm, Luke Kenneth Casson Leightonl...@lkcl.net wrote: as more than just a proof-of-concept but to get pyjamas out of looking like a nice toy, doesn't do much, great demos, shame about real life, cut If may be generated with pyjamas but I'm not sure how this fulfills your wish to do something that does more than doesn't do much. I would expect a demo to at least have some typical GUI features on it--or am I completely missing the point of what you're doing? I think lkcl wanted to demonstrate that it is more than 'a nice toy' and that there is an actual real world application for it. I am not sure why he seems to have the urge to do that as for me I am already convinced about its usability. I also already had the impression that pyjamas was a usable and valuable thing, but I felt that if he wanted to show an application it should have showcased the GUI elements like buttons, dropdowns, lists, etc. to make the point about how applications can run either as a desktop GUI app or a web based GUI app. What is shown instead looks like it could have been written w/ just HTML, and has limited interactivity. The pyjamas examples page shows many nice GUI elements that could make it into a non-toy demo app, and I expect this will happen soon, but this demo doesn't quite do it for me, GUI-wise. I only say this because I think pyjamas is a great project and I'm looking forward to see more people using it for dual (desktop/web) apps. Che -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy - save many arrays into a file object
On 6/30/2010 11:48 AM, Laszlo Nagy wrote: import numpy data = numpy.array(...) numpy.save(test.np,data) This is very good, but I want to save the data into a file object with a write() method. E.g. not a real file. (My purpose right now is to save many arrays into one binary file, while recording starting positions of the arrays.) How can I do that? Try the numpy list -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 07/01/10 01:30, Stephen Hansen wrote: On 6/30/10 5:52 AM, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. I want to stamp a [Citation Needed] claim on that :) That's based on my own anecdotal experience. Considering all the other things you're likely to do during 'quick and dirty' debugging, an extra set of parens seems terribly unlikely to really be any kind of issue. You want to focus on doing these other things you're likely to do instead of having to do the function call keyboard dance. That justification sounds like its based on a mountain-out-of-a-mole-hill complaint: print() is really not that significantly more difficult then the print statement. indeed it isn't a major irritant; but it *is* irritating. -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 07/01/10 01:42, Michele Simionato wrote: On Jun 30, 2:52 pm, Lie Ryan lie.1...@gmail.com wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. Actually when debugging I use pdb which uses p (no parens) for printing, so having print or print() would not make any difference for me. You mean I have to start a full-blown debugger to figure out the value of a variable? No thanks, debugger has its use for stepping through program, but not when printing values is sufficient. -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamically modify help text
In article mailman.2338.1277812368.32709.python-l...@python.org, Thomas Jollans tho...@jollans.com wrote: % python2.6 Python 2.6.5+ (release26-maint, Jun 28 2010, 19:46:36) [GCC 4.4.4] on linux2 Type help, copyright, credits or license for more information. class OLD: pass ... class NEW(object): pass ... OLD.__doc__ = foo NEW.__doc__ = bar Traceback (most recent call last): File stdin, line 1, in module AttributeError: attribute '__doc__' of 'type' objects is not writable I'd argue that's a bug -- feel free to file one. I think this might even be fixable in 2.7.1. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you don't know what your program is supposed to do, you'd better not start writing it. --Dijkstra -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about the posibility of raise-yield in Python
On 6/30/2010 12:13 AM, Дамјан Георгиевски wrote: A 'raise-yield' expression would break the flow of a program just like an exception, going up the call stack until it would be handled, but also like yield it would be possible to continue the flow of the program from where it was raise-yield-ed. Bad idea. Continuing after an exception is generally troublesome. This was discussed during the design phase of Ada, and rejected. Since then, it's been accepted that continuing after an exception is a terrible idea. The stack has already been unwound, for example. What you want, in in the situation you describe, is an optional callback, to be called in case of a fixable problem. Then the caller gets control, but without stack unwinding. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: numpy - save many arrays into a file object
Laszlo Nagy wrote: import numpy data = numpy.array(...) numpy.save(test.np,data) This is very good, but I want to save the data into a file object with a write() method. E.g. not a real file. (My purpose right now is to save many arrays into one binary file, while recording starting positions of the arrays.) How can I do that? numpy.save() accepts file(-like) objects, the help is quite clear about that: save(file, arr) Save an array to a binary file in NumPy format. Parameters -- f : file or string File or filename to which the data is saved. If the filename does not already have a ``.npy`` extension, it is added. x : array_like Array data. import numpy from StringIO import StringIO stream = StringIO() a = numpy.array([1,2,3]) b = numpy.array([10, 11]) numpy.save(stream, a) pos = stream.tell() numpy.save(stream, b) stream.seek(0) stream.seek(pos) numpy.load(stream) array([10, 11]) stream.seek(0) numpy.load(stream) array([1, 2, 3]) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
On 6/30/2010 8:22 AM, Nobody wrote: I've noticed over the years a significant anti-RE sentiment in the Python community. IMHO, the sentiment isn't so much against REs per se, but against excessive or inappropriate use. Apart from making it easy to write illegible code, they also make it easy to write code that mostly sort-of works but somewhat harder to write code which is actually correct. It doesn't help that questions on REs often start out by stating a problem for which REs are inappropriate, e.g. parsing a context-free (or higher) language, and in the same sentence indicate the the poster is already predisposed to using REs. They also often start with a problem that is 'sub-relational-grammar' and easily solved with string methods, and again the OP proposes to use the overkill of REs. In other words, people ask How do I do this with an RE rather than What tool should I use for this, and how. If people asked How do I push a pin into a corkboard with a (standard) hammer or How do I break up a concrete sidewalk with a (standard) hammer), it would not be 'anti-hammer sentiment' to suggest another tool, like pliers or a jackhammer. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
Terry Reedy wrote: On 6/30/2010 8:22 AM, Nobody wrote: I've noticed over the years a significant anti-RE sentiment in the Python community. IMHO, the sentiment isn't so much against REs per se, but against excessive or inappropriate use. Apart from making it easy to write illegible code, they also make it easy to write code that mostly sort-of works but somewhat harder to write code which is actually correct. It doesn't help that questions on REs often start out by stating a problem for which REs are inappropriate, e.g. parsing a context-free (or higher) language, and in the same sentence indicate the the poster is already predisposed to using REs. They also often start with a problem that is 'sub-relational-grammar' and easily solved with string methods, and again the OP proposes to use the overkill of REs. In other words, people ask How do I do this with an RE rather than What tool should I use for this, and how. If people asked How do I push a pin into a corkboard with a (standard) hammer or How do I break up a concrete sidewalk with a (standard) hammer), it would not be 'anti-hammer sentiment' to suggest another tool, like pliers or a jackhammer. I took the time to learn REs about a year ago. It was well worth it, even though I've only used REs a handful of times since, because when you need them there is no good substitute. But when you don't, there are plenty. ;) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 6/30/10 9:22 AM, Lie Ryan wrote: On 07/01/10 01:30, Stephen Hansen wrote: On 6/30/10 5:52 AM, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. I want to stamp a [Citation Needed] claim on that :) That's based on my own anecdotal experience. That was meant as a joke. :) Considering all the other things you're likely to do during 'quick and dirty' debugging, an extra set of parens seems terribly unlikely to really be any kind of issue. You want to focus on doing these other things you're likely to do instead of having to do the function call keyboard dance. Function call keyboard dance? Really? That justification sounds like its based on a mountain-out-of-a-mole-hill complaint: print() is really not that significantly more difficult then the print statement. indeed it isn't a major irritant; but it *is* irritating. Ooookay. See, if *this* is irritating to you, I just can't fathom how you get through actually coding anything without going postal. I'm just gonna chalk it up to different strokes and give up :) -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Using Python for web applications
Dear Python-List members, Sorry for asking such a simple (or possibly complicated) question, as I am new to Python programming. Anyways, I have read online that many popular websites use Python for some of their web-based applications (for example, Reddit), and that lead me to wonder how is this done? Thanks in advance! - Wyatt - Beginning Python Programmer -- http://mail.python.org/mailman/listinfo/python-list
Hwy doesn't len(None) return zero ?
hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : So I wonder why len is not allowed on None and if there are objections to extend the len function . thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 6/30/10 11:39 AM, Stef Mientki wrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : Just do: if Result: You don't have to do a length check 1; because if Result has a length of 0, it'll be false too. So the above check will catch both None, and empty sequences. So I wonder why len is not allowed on None and if there are objections to extend the len function . Len is not allowed on None, becaues None is not a sequence, and doesn't have a length. None, *very* much on purpose, is distinct and does not behave like anything else. It's the I'm not anything object. -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for web applications
Sorry for asking such a simple (or possibly complicated) question, as I am new to Python programming. Anyways, I have read online that many popular websites use Python for some of their web-based applications (for example, Reddit), and that lead me to wonder how is this done? There are various options, the simplest is using a full blown web framework which simplifies about 90% of the work and you only need to code the logic related to your app. Two of the most popular frameworks are django [1] and turbogears [2]. You can also go more low level by designing your own framework from scratch which is something the bigger shops are doing like youtube. In any case there is a wiki page that you might find useful [3]. HTH, Daniel [1] http://www.djangoproject.com/ [2] http://www.turbogears.org/ [3] http://wiki.python.org/moin/WebProgramming -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On Thu, Jul 1, 2010 at 12:09 AM, Stef Mientki stef.mien...@gmail.comwrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : use if Result: do something Checking the length would be a bad idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 06/30/2010 11:39 AM, Stef Mientki wrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : So I wonder why len is not allowed on None and if there are objections to extend the len function . thanks, Stef Mientki Because the natural interpretation of len only makes sense for concepts such as a container or collection. The value None is no such thing. Assigning a meaning to len(None) begs the question of meanings for len(True), len(False), len(3.14), len(sys), ... This is a slippery slope, best avoided. But there are solutions: 1. Have your functions return [] or () or whatever.If they are to return a list, and the list may be empty, [] is correct. 2. If you insist on a function returning a list sometimes and other values at other times (such as None), then be prepared to write your code which uses the result with test to determine which type was returned. Fortunately that's not hard, as your one example shows. 3. Create a test function Empty(Result) which does what you want returning a boolean and write your tests as: if Empty(Result): ... Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for web applications
On Wed, Jun 30, 2010 at 11:34 PM, Wyatt Schwartz wyattj...@gmail.comwrote: Dear Python-List members, Sorry for asking such a simple (or possibly complicated) question, as I am new to Python programming. Anyways, I have read online that many popular websites use Python for some of their web-based applications (for example, Reddit), and that lead me to wonder how is this done? Thanks in advance! I would recommend that you check out the various web-frameworks which are out there. Django is the framework I use and love, but there are loads out there. Have fun! Zubin -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
Stef Mientki, 30.06.2010 20:39: I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : So I wonder why len is not allowed on None and if there are objections to extend the len function . Because getting an exception is actually a feature. Imagine a world where None would implement all sorts of protocols, such as len, getitem, getattr, etc., and would always return something that would be useful for, well, someone, maybe even a majority of use cases. In such a world, it would actually be very easy to write buggy code that doesn't handle None values properly, simply because it's easy for programmers to forget to do so. And this would mean that code that would best drop dead early would instead silently ignore all errors and just do, well, something, which may or may not be meaningful, correct and/or useful. That would be very hard to debug code, as it would fail in obscure places that may be completely unrelated to the original problem. The current behaviour, on the other hand, will give you an exception exactly in the place where you treat the None value in an illegal way, so it will be easy for you to see what the problem is and much easier to track it down. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 06/30/2010 01:50 PM, Stephen Hansen wrote: On 6/30/10 11:39 AM, Stef Mientki wrote: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : Just do: if Result: You don't have to do a length check 1; because if Result has a length of 0, it'll be false too. So the above check will catch both None, and empty sequences. Not to counter the rest of your comment below (which is right on), the OP asked about 1, not 0 for which if Result would work...one character vs. more than one character (your test would be 0 vs more-than-0) So I wonder why len is not allowed on None and if there are objections to extend the len function . Len is not allowed on None, becaues None is not a sequence, and doesn't have a length. None, *very* much on purpose, is distinct and does not behave like anything else. It's the I'm not anything object. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Is Escaping Data Considered So Magical?
On Jun 30, 2:55 am, Cameron Simpson c...@zip.com.au wrote: On 29Jun2010 21:49, Carl Banks pavlovevide...@gmail.com wrote: | On Jun 28, 2:44 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: | Carl Banks wrote: | Indeed, strncpy does not copy that final NUL if it's at or beyond the | nth element. Probably the most mind-bogglingly stupid thing about the | standard C library, which has lots of mind-boggling stupidity. | | I don't think it was as stupid as that back when C was | designed. Every byte of memory was precious in those days, | and if you had, say, 10 bytes allocated for a string, you | wanted to be able to use all 10 of them for useful data. | | So the convention was that a NUL byte was used to mark | the end of the string *if it didn't fill all the available | space*. | | I can't think of any function in the standard library that observes | that convention, which inclines me to disbelieve this convention ever | really existed. If it did, there would be functions to support it. | | For that matter, I'm not really inclined to believe bytes were *that* | precious in those days. Jeez. PDP-11s, 16 bit addressing, tiny tiny disc drives! The original V7 (and probably earlier) UNIX filesystem has 16 byte directory entries: 2 bytes for an inode and 14 bytes for the name. You could use 14 bytes of that name, and strncpy makes it effective to work with that data structure. Shortening something already only 14 bytes (the name) _is_ a big ask, and it is well work the unusual convention in play. You are talking about fixed-length memory records, not strings. I'm saying that bytes were not so precious that, when you operate on *actual strings*, that you need to desperately cut off nul terminators to save space. | The obvious rationale behind strncpy's stupid behavior is that it's | not a string function at all, but a memory block function, that stops | at a NUL in case you don't care what's after the NUL in a block. But | it leads you to believe it's a string function by it's name. Bah. It's for copying a _string_ into a _buffer_! Strangely, since it starts with a string (NUL-terminated byte sequence) it begins with str. And it _is_ copying, but not into another string. I'm going to disagree. The input of strncpy can be either a string or a memory block, and the output can only a memory block. In other words, neither the source nor destination has to be a string. This is a memory block function, not a string function. The correct name for this function should have been memcpytonul. Even if you disagree, then you must admit it should have been called strcpytobuf. Nothing about the name strncpy gives the slightest suggestion that the destination is not a string. Based on analogy from other str functions, none of which have any sources or destinations that are memory blocks, one would logically expect that strncpy's destination was a string. It defies common sense. And there should have been an actual, correctly working strncpy in the standard library that copies and truncates actual strings. It is special purpose but perfectly reasonable for the problem at hand. The usefulness of strncpy's behavior for writing fixed-length memory blocks is not in question here. The thing that's mind-bogglingly stupid is that the function that does this is called strncpy. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 6/30/10 12:02 PM, Tim Chase wrote: On 06/30/2010 01:50 PM, Stephen Hansen wrote: On 6/30/10 11:39 AM, Stef Mientki wrote: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : Just do: if Result: You don't have to do a length check 1; because if Result has a length of 0, it'll be false too. So the above check will catch both None, and empty sequences. Not to counter the rest of your comment below (which is right on), the OP asked about 1, not 0 for which if Result would work...one character vs. more than one character (your test would be 0 vs more-than-0) Gah, oops. You're right. I misread, my bad. In that case yes, he's right and needs if Result and len(Result) 1 -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
Stephen Hansen wrote: On 6/30/10 11:39 AM, Stef Mientki wrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : Just do: if Result: You don't have to do a length check 1; because if Result has a length of 0, it'll be false too. So the above check will catch both None, and empty sequences. snip Look closer: the OP wanted len(Result) 1 not len(Result) 0. For that, you need two checks, for example, as for example: if Result and (len(Result)1): . DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Ancient C string conventions
Jorgen Grahn grahn+n...@snipabacken.se writes: It's somewhat believable. If I handled thousands of student names in a big C array char[30][], I would resent the fact that 1/30 of the memory was wasted on NUL bytes. But you'd be wasting even more of the memory on bytes left unused when the student's name is less than 30 chars. If memory is that scarce you need a different representation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Is Escaping Data Considered So Magical?
Cameron Simpson c...@zip.com.au writes: The original V7 (and probably earlier) UNIX filesystem has 16 byte directory entries: 2 bytes for an inode and 14 bytes for the name. You could use 14 bytes of that name, and strncpy makes it effective to work with that data structure. Why not use memcpy for that? -- http://mail.python.org/mailman/listinfo/python-list
Python/C++ timer intermittent bug
I have a problem with threading using the Python/C API. I have an extension that implements a timer, and the C++ timer callback function calls a Python function. The relevant code looks like this: static PyObject *timer_setmodname( PyObject *pSelf, PyObject *pArgs ) { char *b; PyArg_ParseTuple( pArgs, s, b ); mod = PyImport_ImportModule(b); if( mod == NULL ) { printf(Could not import %s\n,b); return Py_None; } modsetFlag = TRUE; return Py_None; } static PyObject *timer_setprocname( PyObject *pSelf, PyObject *pArgs ) { char *b; if( !modsetFlag )return Py_None; PyArg_ParseTuple( pArgs, s, b ); attr = PyObject_GetAttrString(mod,b); if( attr == NULL ) { printf(Could not import %s\n,b); return Py_None; } attrsetFlag = TRUE; return Py_None; } static void CALLBACK PeriodicTimer(UINT wTimerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2) { PyGILState_STATE pgs; pgs = PyGILState_Ensure(); if(attrsetFlag) { pres = PyObject_CallFunction(attr,NULL); if( pres == NULL )printf(CallFunction failed!\n); } PyGILState_Release( pgs ); } The Python code that sets this up looks like this: fetimer.setmodname(Timeslice3) fetimer.setprocname(Timetester) print \n Program Waiting for Time Slice while True: time.sleep(0.010) and the module Timeslice3.py looks like this: #Timeslice3.py def Timetester(): pass When I run this stuff, it works fine for hundreds, often even thousands, of timer ticks (I've been testing with about thirty ticks per second, but it doesn't matter - it still crashes at ten or fewer ticks per second). Sometimes it runs for only a few seconds, sometimes for ten minutes or so. But it always eventually crashes Python. Usually it gives no error message. Sometimes, though, it does give an error message, but not always the same one. I've noted three that it has given in my testing so far: Fatal Python Error: This thread state must be current when releasing Fatal Python Error: PyThreadState_DeleteCurrent: no current tstate Fatal Python Error: PyEval_SaveThread: NULL tstate Can anybody help me make this code stable, so that it works all the time? I'm using Python 2.6.5 under Windows Vista, but it crashes under Windows XP as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python as a scripting language. Alternative to bash script?
Michael Torrie torr...@gmail.com wrote in news:mailman.2313.1277759925.32709.python-l...@python.org: On 06/28/2010 02:06 PM, Mithrandir wrote: I can't see Python as an alt. to bash. (As I recall) Python is much more object-oriented than bash, but also there are many commands (such as apt- get, etc.) that would need Python equivs. However, I can see Python being used as a scripting alt. to C. OO is a plus for most things, in my book. As for commands they have *nothing* to do with Bash. apt-get is not a Bash command. By your logic tcsh or zsh would not be an alternate to bash, but in fact they are. I use python for shell scripting quite often now. Anytime one of my own Bash scripts exceeds 100 lines, I know it's time to switch it to python. Please read that link I posted a while back on how you can use generators in python to replace many of the things that piping to external commands did in Bash. There certainly are a few tasks that Bash is best at (chaining commands together through pipes), but often Python already has support for many of the things I'd use external commands and pipes in Bash for. Bash is designed for working down at the level of files, directories, and processes, but Python works pretty well too, if you make some abstraction modules like my runcmd module that I use extensively. You both are correct. :) (I wrote that before my first cup of coffee, so my wording was way off. That, and I'm new to Python.) :) I think that Python could be a alternative to bash and have some advantages, but it's a long way off from being fully implemented. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On Wed, Jun 30, 2010 at 12:39 PM, Stef Mientki stef.mien...@gmail.com wrote: So I wonder why len is not allowed on None and if there are objections to extend the len function . For the same reason that (None + 42) doesn't return 42, and that (None.upper()) doesn't return NONE. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 6/30/2010 11:39 AM Stef Mientki said... hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: which works fine if beforehand you do Result = presumedFuncCall() or [] particularly if you want to test len subsequently. Emile if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : So I wonder why len is not allowed on None and if there are objections to extend the len function . thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are String Formatted Queries Considered So Magical?
On Wed, 30 Jun 2010 14:14:38 +, Jorgen Grahn wrote: On Tue, 2010-06-29, Stephen Hansen wrote: On 6/29/10 5:41 AM, Roy Smith wrote: Nobodynob...@nowhere.com wrote: And what about regular expressions? What about them? As the saying goes: Some people, when confronted with a problem, think I know, I'll use regular expressions. Now they have two problems. That's silly. RE is a good tool. Like all good tools, it is the right tool for some jobs and the wrong tool for others. There's nothing silly about it. It is an exaggeration though: but it does represent a good thing to keep in mind. Not an exaggeration: it's an absolute. It literally says that any time you try to solve a problem with a regex, (A) it won't solve the problem and (B) it will in itself become a problem. And it doesn't tell you why: you're supposed to accept or reject this without thinking. It's a *two sentence* summary, not a reasoned and nuanced essay on the pros and cons for REs. Sheesh, I can just imagine you as a child, arguing with your teacher on being told not to run with scissors -- but teacher, there may be circumstances where running with scissors is the right thing to do, you are guilty of over-simplifying a complex topic into a single simplified sound-byte, instead of providing a detailed, rich heuristic for analysing each and every situation in full before making the decision whether or not to run with scissors. If you look at the quote carefully, instead of making a knee-jerk reaction, you will see that it is *literally* correct. Given some problem, having decided to solve it with a regex, you DO have two problems: (1) Merely making the decision use REs doesn't actually solve the original problem, any more than use a hammer solves the problem of how do I build a table?. You've decided on an approach and a tool, but your original problem still applies. (2) AND you now have the additional problem of dealing with regular expressions, which are notoriously hard to write, harder to debug, difficult to maintain, often slow, incapable of solving certain common problems (such as parsing nested parentheses). So it might be a short, simplified quip, but it *is* literally correct. How can that be a good thing to keep in mind? Because many people consider REs to be some sort of panacea for solving every text-based problem, and it's a good thing to open their eyes. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Wed, 30 Jun 2010 22:52:06 +1000, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. *rolls eyes* Not as irritating as people who complain about having to type parentheses. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Wed, 30 Jun 2010 13:10:43 -0700 (PDT) garryTX garry5...@gmail.com wrote: On Jun 29, 5:31 pm, nanothermite911fbibustards [...] you ignorant mf. stfu. You shouldn't be calling people ignorant for what they post if you are just going to repost every word again. Everything that applies to him applies to you. I have had it with GG. For the last few months I have been filtering all mail from gmail.com that comes through the news gateway into a separate folder to see where the spam and abuse comes from. Over that time about 99% of all the useless crap has been caught in that filter. It's unfortunate that there are some decent posts as well but I have finally decided that the peace and quiet is worth more than the odd missed gem. So, if you are accessing this list through GG and wonder why I seem to be ignoring your brilliant arguments, this is why. If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null Cheers. -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On 6/30/10 1:55 PM, D'Arcy J.M. Cain wrote: I have had it with GG. For the last few months I have been filtering all mail from gmail.com that comes through the news gateway into a separate folder to see where the spam and abuse comes from. Over that time about 99% of all the useless crap has been caught in that filter. It's unfortunate that there are some decent posts as well but I have finally decided that the peace and quiet is worth more than the odd missed gem. So, if you are accessing this list through GG and wonder why I seem to be ignoring your brilliant arguments, this is why. Gmail and Google Groups are not one and the same. There's a number of people who subscribe to the list directly, use Gmail, and don't go anywhere near Google Groups. If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null Bye. -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Wed, 30 Jun 2010 14:06:05 -0700 Stephen Hansen me+list/pyt...@ixokai.io wrote: Gmail and Google Groups are not one and the same. There's a number of people who subscribe to the list directly, use Gmail, and don't go anywhere near Google Groups. I know that. My filter doesn't catch them. If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null As you can see, to be caught in the filter you need to have a gmail address and be sending through the news gateway. People sending from gmail.com directly to the mailing list don't get picked up. I'm pretty sure that that defines everyone using Google Groups only. I am definitely open to correction though. -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On 6/30/10 2:15 PM, D'Arcy J.M. Cain wrote: If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null As you can see, to be caught in the filter you need to have a gmail address and be sending through the news gateway. People sending from gmail.com directly to the mailing list don't get picked up. I'm pretty sure that that defines everyone using Google Groups only. I am definitely open to correction though. Hmm, my procmail-fu is about a decade out of date, so I'll have to take your word on that. Okay, un-Bye :) -- ... Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Wed, Jun 30, 2010 at 4:34 PM, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Wed, 30 Jun 2010 22:52:06 +1000, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. *rolls eyes* Not as irritating as people who complain about having to type parentheses. http://www.xkcd.net/297/ Actually, I agree with this complaint though- it is much easier to type spaces than parens. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Wed, Jun 30, 2010 at 5:15 PM, D'Arcy J.M. Cain da...@druid.net wrote: On Wed, 30 Jun 2010 14:06:05 -0700 Stephen Hansen me+list/pyt...@ixokai.io wrote: Gmail and Google Groups are not one and the same. There's a number of people who subscribe to the list directly, use Gmail, and don't go anywhere near Google Groups. I know that. My filter doesn't catch them. If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null As you can see, to be caught in the filter you need to have a gmail address and be sending through the news gateway. People sending from gmail.com directly to the mailing list don't get picked up. I'm pretty sure that that defines everyone using Google Groups only. I am definitely open to correction though. If you get this, you get the gmail-but-not-google-groups stuff. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Wed, 30 Jun 2010 17:25:55 -0400 geremy condra debat...@gmail.com wrote: If you get this, you get the gmail-but-not-google-groups stuff. Hello. -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for web applications
Wyatt Schwartz wyattj...@gmail.com wrote in news:mailman.33.1277921551.1673.python-l...@python.org: Dear Python-List members, Sorry for asking such a simple (or possibly complicated) question, as I am new to Python programming. Anyways, I have read online that many popular websites use Python for some of their web-based applications (for example, Reddit), and that lead me to wonder how is this done? Thanks in advance! - Wyatt - Beginning Python Programmer For something more server side see: http://wiki.python.org/moin/WebFrameworks Some nice examples are at: http://wiki.python.org/moin/WebApplications Good luck! :) -- People should read more. https://secure.wikimedia.org/wikipedia/en/wiki/User:MithrandirAgain All that is gold does not glitter, not all those who wander are lost; the old that is strong does not wither, deep roots are not reached by the frost. From the ashes a fire shall be woken, a light from the shadows shall spring; renenwed shall be blade that was broken, the crownless again shall be king. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Jun 30, 3:55 pm, D'Arcy J.M. Cain da...@druid.net wrote: I have had it with GG. For the last few months I have been filtering all mail from gmail.com that comes through the news gateway into a separate folder to see where the spam and abuse comes from. Over that time about 99% of all the useless crap has been caught in that filter. It's unfortunate that there are some decent posts as well but I have finally decided that the peace and quiet is worth more than the odd missed gem. So, if you are accessing this list through GG and wonder why I seem to be ignoring your brilliant arguments, this is why. Just filter out %s and your done with this nitwit. % (''.join(map(chr, [66, 85, 83, 84, 65, 82, 68, 83]))) PS: I really hope the BUSTARDS find this guy soon and shut him up! I would trade this guy for ten xah's right now! At least xah's rants *are* computer related and far less frequent! -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Wed, 30 Jun 2010 14:18:55 -0700 Stephen Hansen me+list/pyt...@ixokai.io wrote: Okay, un-Bye :) Nice to be back. :-) -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On Jun 30, 2010, at 4:55 PM, D'Arcy J.M. Cain wrote: On Wed, 30 Jun 2010 13:10:43 -0700 (PDT) garryTX garry5...@gmail.com wrote: On Jun 29, 5:31 pm, nanothermite911fbibustards [...] you ignorant mf. stfu. You shouldn't be calling people ignorant for what they post if you are just going to repost every word again. Everything that applies to him applies to you. I have had it with GG. For the last few months I have been filtering all mail from gmail.com that comes through the news gateway into a separate folder to see where the spam and abuse comes from. Over that time about 99% of all the useless crap has been caught in that filter. It's unfortunate that there are some decent posts as well but I have finally decided that the peace and quiet is worth more than the odd missed gem. So, if you are accessing this list through GG and wonder why I seem to be ignoring your brilliant arguments, this is why. If anyone is interested in the procmail recipe I will be using, here it is in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null For a few weeks I've been tossing anything sent to the Python list with an Organization header == http://groups.google.com (based on someone else's suggestion) and it's vastly improved the signal/noise ratio for me. HTH P -- http://mail.python.org/mailman/listinfo/python-list
Re: Ignorance and Google Groups (again)
On 06/30/2010 10:55 PM, D'Arcy J.M. Cain wrote: in all it's glory. :0: Hir * ^List-Id:.*python-list.python.org * ^From:@gmail.com * ^Newsgroups: /dev/null * X-Complaints-To: groups-ab...@google.com looks like a nice header to filter on -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
Please pardon me for breaking threading, but Stef's original post has not come through to me. On 6/30/10 11:39 AM, Stef Mientki wrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Well there's your problem right there. If you have a function that returns a list of X, and there are no X to return, you should return an empty list, not None. filter(lambda n: n%2 == 0, [1, 3, 5, 7]) # return even numbers [] There are good use-cases for functions that sometimes return X and sometimes return None, but they're rare. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Wed, 30 Jun 2010 17:21:32 -0400, geremy condra wrote: On Wed, Jun 30, 2010 at 4:34 PM, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Wed, 30 Jun 2010 22:52:06 +1000, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. *rolls eyes* Not as irritating as people who complain about having to type parentheses. http://www.xkcd.net/297/ Actually, I agree with this complaint though- it is much easier to type spaces than parens. Yes. And typing p is easier than typing print. Perhaps we should replace all Python built-ins with one letter names so that we can *really* optimize our typing effort? i m d sin2pi(x): r m.s(x*2*m.p) f n == '__main__': p Sine of 1.3*2*pi is, sin2pi(1.3) Perhaps not. The rule against premature optimization doesn't just apply to *code*. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Jun 30, 2010, at 8:52 , Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. actually, what I find is the following: 1) the parens are a bit more irritating than just a print 2) in my quick-and-dirty scripts, I often want to get rid of all of the prints after it works. 3) being able to redefine print vastly outweighs the irritation caused by the extra parens bb -- Brian Blais bbl...@bryant.edu http://web.bryant.edu/~bblais http://bblais.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Hwy doesn't len(None) return zero ?
On 30-06-2010 20:56, Gary Herron wrote: On 06/30/2010 11:39 AM, Stef Mientki wrote: hello, I've lot of functions that returns their result in some kind of tuple / list / array, and if there is no result, these functions return None. Now I'm often what to do something if I've more than 1 element in the result. So I test: if len ( Result ) 1 : But to prevent exceptions, i've to write ( I often forget) if Result and ( len ( Result ) 1 ) : So I wonder why len is not allowed on None and if there are objections to extend the len function . thanks, Stef Mientki Because the natural interpretation of len only makes sense for concepts such as a container or collection. The value None is no such thing. Assigning a meaning to len(None) begs the question of meanings for len(True), len(False), len(3.14), len(sys), ... This is a slippery slope, best avoided. But there are solutions: 1. Have your functions return [] or () or whatever.If they are to return a list, and the list may be empty, [] is correct. thanks guys, I think that will be the best idea. cheers, Stef 2. If you insist on a function returning a list sometimes and other values at other times (such as None), then be prepared to write your code which uses the result with test to determine which type was returned. Fortunately that's not hard, as your one example shows. 3. Create a test function Empty(Result) which does what you want returning a boolean and write your tests as: if Empty(Result): ... Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Wed, Jun 30, 2010 at 6:30 PM, Steven D'Aprano steve-remove-t...@cybersource.com.au wrote: On Wed, 30 Jun 2010 17:21:32 -0400, geremy condra wrote: On Wed, Jun 30, 2010 at 4:34 PM, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Wed, 30 Jun 2010 22:52:06 +1000, Lie Ryan wrote: On 06/27/10 11:24, Steven D'Aprano wrote: Producing print function takes a little bit more effort than producing a print statement. (1) The main use-cases for print are quick (and usually dirty) scripts, interactive use, and as a debugging aid. That is precisely how the quick-and-dirty syntax of print statement can be justified. While debugging, you'll need to be able to quickly add and delete prints here and there, and the extra parens can quickly become irritating. *rolls eyes* Not as irritating as people who complain about having to type parentheses. http://www.xkcd.net/297/ Actually, I agree with this complaint though- it is much easier to type spaces than parens. Yes. And typing p is easier than typing print. Perhaps we should replace all Python built-ins with one letter names so that we can *really* optimize our typing effort? i m d sin2pi(x): r m.s(x*2*m.p) f n == '__main__': p Sine of 1.3*2*pi is, sin2pi(1.3) Perhaps not. The rule against premature optimization doesn't just apply to *code*. Hypocrite. You just took Jorgen Grahn to task in another thread for slaying exactly this kind of strawman. You're too smart to think that this is what I was advocating. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On 30/06/2010 23:30, Steven D'Aprano wrote: [snips] The rule against premature optimization doesn't just apply to *code*. +1QOTW Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Is Escaping Data Considered So Magical?
On 30Jun2010 12:19, Paul Rubin no.em...@nospam.invalid wrote: | Cameron Simpson c...@zip.com.au writes: | The original V7 (and probably earlier) UNIX filesystem has 16 byte directory | entries: 2 bytes for an inode and 14 bytes for the name. You could use 14 | bytes of that name, and strncpy makes it effective to work with that data | structure. | | Why not use memcpy for that? Because when you've pulled names _out_ of the directory structure they're conventional C strings, ready for conventional C string mucking about: NUL terminated, with no expectation that any memory is allocated beyond the NUL. Think of strncpy as a conversion function. Your source is a conventional C string of unknown size, your destination is a NUL padded buffer of known size. Copy at most n bytes of this string into the buffer, pad with NULs. Cheers, -- Cameron Simpson c...@zip.com.au DoD#743 http://www.cskk.ezoshosting.com/cs/ We had the experience, but missed the meaning. - T.S. Eliot -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about the posibility of raise-yield in Python
On Jun 30, 10:48 am, John Nagle na...@animats.com wrote: On 6/30/2010 12:13 AM, Дамјан Георгиевски wrote: A 'raise-yield' expression would break the flow of a program just like an exception, going up the call stack until it would be handled, but also like yield it would be possible to continue the flow of the program from where it was raise-yield-ed. Bad idea. Continuing after an exception is generally troublesome. This was discussed during the design phase of Ada, and rejected. Since then, it's been accepted that continuing after an exception is a terrible idea. The stack has already been unwound, for example. What you want, in in the situation you describe, is an optional callback, to be called in case of a fixable problem. Then the caller gets control, but without stack unwinding. Strangely I was just thinking about something similar (non-stack the other day. Something like def caller(): try: callee() except SomeError, exc: ... else exclist: ... def callee(): if error: raise SomeError() else raise2: SomeWarning() raise2 would create an exception object but unlike raise, would save in it a list somewhere and when callee() returned normally, the list would be made asvailable to caller, possibly in a parameter to the try/except else clause as shown above. Obviously raise2 is a placeholder for some way to signal that this is a non-stack-unwinding exception. The use case addressed is to note exceptional conditions in a function that aren't exceptional enough to be fatal but which the caller may or may not care about. Siminlar to the Warning module but without the brokenness of doing io. Integrates well with the existing way of handling fatal exceptions. No idea if something like this even remotely feasible. -- http://mail.python.org/mailman/listinfo/python-list
automate minesweeper with python
I would like to create a python script that plays the Windows game minesweeper. The python code logic and running minesweeper are not problems. However, seeing the 1-8 in the minesweeper map and clicking on squares is. I have no idea how to proceed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need instruction on how to use isinstance
alex23 wrote: Stephen Hansen me+list/pyt...@ixokai.io wrote: P.S. The removal of callable is something I don't understand in Python 3: while generally speaking I do really believe and use duck typing, I too have on occassion wanted to dispatch based on 'is callable? do x'. Sometimes its not convenient to do so via duck typing. Its rare. But it is there. That isinstance()/issubclass got a boost in power with the ABC's and registering, while at the same time the ability to introspect about the function-y callable-y ness of a function was removed? Makes no sense to me. But alas! There's always: isinstance(object, collections.Callable) There's also: hasattr(object, '__call__'). It works in both 2.x and 3.x. -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Jun 30, 9:42 am, Michele Simionato michele.simion...@gmail.com wrote: Actually when debugging I use pdb which uses p (no parens) for printing, so having print or print() would not make any difference for me. Perhaps you don't use CJK strings much? p u'\u30d1\u30a4\u30c8\u30f3' give quite a different result than print u'\u30d1\u30a4\u30c8\u30f3' at least in python2. Is this different in python3? -- http://mail.python.org/mailman/listinfo/python-list
Re: I strongly dislike Python 3
On Jun 30, 4:21 pm, geremy condra debat...@gmail.com wrote: Actually, I agree with this complaint though- it is much easier to type spaces than parens. Oh Geremy please. If you're going to whine about something at least find something worth whining about! Yes a few more key strokes are needed. But print should have been a function from day one. The benefits of a print function over a print statement are obvious to those who seek the truth and lost on those who wallow in self pity. If it's that much trouble for you then pick up an editor that auto inserts parenthesis for you, or *gasps* write a routine yourself. Look i know masturbation makes you lazy, but geez! -- http://mail.python.org/mailman/listinfo/python-list