IMDbPY for Symbian
I've released a brand new version of IMDbPY for Symbian mobile phones: http://imdbpy.sf.net/?page=mobile It allows complete access to the IMDb data even to devices with very limited bandwidth and it should also be possible to locally install the whole database, so that no data connection is required. Obviously the code is still in a very early stage, and so I'm here fundamentally searching for someone interested in helping the development, since my skills as Symbian developer are very limited. Any help will be greatly appreciated! -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: image matching algorithms
| The various free tools differ by their chosen optimization paths and | their degree of specialization. My preference would be, | | 1. Doesn't really matter how long it takes to compute the N numbers per image Your problem here is that there is really no such thing as 'general features' and correspondingly, no such thing as 'general similarity of features'. Yes there are! :) Image manipulation experts defined dozens of ways of characterizing what 'similarity' means for images and all I was asking is whether anyone here knew of a simple one. The features extracted have to have a specific definition. The features represent a severe lossy compression of the original. What to keep depends on the application. Yes, and if you know *any* simple but useful (yes, useful, in *any* sense) definition, I'd be happy to hear it. Example: classify each pixel as white, black, red, green, or blue. Will that match your intuitive idea of what matches? Probably not, but thanks for the idea. To be a bit more sophisticated, use more color bins and do the binning separately for multiple areas, such as top, left, center, right, and bottom (or center, upper right, upper left, lower right, and lower left). I suspect Google does something like this to match, for instance, pictures with skin tones in the center, or pictures with blue tops (sky?) and green bottoms (vegetation?). Now this sounds like a simple and good idea. I'll try this and see how far I get. | 2. Lookups should be fast, consequently N should not be too large (I guess) | 3. It should be a generic algorithm working on generic images (everyday photos) Given feature vectors, there are various ways to calculate a distance or similarity coefficient. There have been great debates on what is 'best'. True. As I've said, *any* but concrete and useful example would make me happy. | 4. PIL should be enough for the implementation | | So if anyone knows of a good resource that is close to being pseudo | code I would be very grateful! If you do not have sufficient insight into your own idea of 'matches', try something on a test set of perhaps 20 photos, calculate a 'match matrix', and compare that you your intuition. Yes, this is what I'll do. The second thing I'll try (after trying your suggestion) is based on this paper which I found in the meantime: http://salesin.cs.washington.edu/abstracts.html#MultiresQuery In case anyone is interested, it describes a multiresolution querying algorithm and best of all, it has pseudo code for the various steps. I don't know yet how difficult the implementation will be but so far this looks the most promising. Cheers, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
If all you wanted was some grouping of exceptions why not something like... soft_exception_list = [IndexError, TypeError] hard_exception_list = [ZeroDivision] try: do_something() except Exception, e: if e.__class__ in soft_exception_list: handle_soft_exception() elif e.__class__ in hard_exception_list: handle_hard_exception() else: raise NotImplementedError Granted you're most likely looking for something that does this constantly on every line of code though... -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does my compiler say invalid syntax then highlight...?
On Mar 11, 5:44 am, Nathan Pinno [EMAIL PROTECTED] wrote: Why does my compiler say invalid syntax and then highlight the quotation marks in the following code: # This program is to find primes. primes = [] import math import gmpy while 1: run = int(raw_input(Do you want to calculate primes? 1 = yes and 2 = no. )) if run == 1: y = int(raw_input(What number do you want to use as the final number to calculate with? )) x = int(raw_input(What number do you want to start calculating primes from? )) while x 2: print Number must be at least 2 for math reasons. else: while x y: prime = math.cos(gmpy.pi(0) * gmpy.fac((x-1)) / x) if prime 0: primes.append(x) else: print x is not prime. # highlights the final here x = x + 1 print primes elif run == 2: break else: print Sorry, not a choice. Please enter your choice again. print Goodbye. How do I fix such an invalid syntax? TIA, Nathan Pinno The reason that line is giving you a syntax error is because you have no comma between your variable and the string. Same reason you can do something like 'print a b c' but instead have to use 'print a, b, c' -- http://mail.python.org/mailman/listinfo/python-list
Re: image matching algorithms
The second thing I'll try (after trying your suggestion) is based on this paper which I found in the meantime: http://salesin.cs.washington.edu/abstracts.html#MultiresQuery In case anyone is interested, it describes a multiresolution querying algorithm and best of all, it has pseudo code for the various steps. I don't know yet how difficult the implementation will be but so far this looks the most promising. Actually, the exact same algorithm has already been implemented in ... drum roll python! http://members.tripod.com/~edcjones/pycode.html -- http://mail.python.org/mailman/listinfo/python-list
Re: tcp client socket bind problem
[EMAIL PROTECTED] wrote: On Mar 10, 9:40 am, Marc Christiansen [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: I have a linux box with multiple ip addresses. I want to make my python client connect from one of the ip addresses. Here is my code, no matter what valid information I put in the bind it always comes from the default ip address on the server. Am I doing something wrong? ... help string: Bind the socket to a local address. For IP sockets, the address is a pair (host, port); the host must refer to the local host. docs: Bind the socket to address. Wikipedia: Before a socket may accept incoming connections, it must be bound. PHP.net: Binds the name given in address to the socket described by socket . This has to be done before a connection is be established using socket_connect() or socket_listen(). This function must be used on the socket before socket_connect(). That's all true. So what was your point? How does this help the original poster? -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
Chris schrieb: If all you wanted was some grouping of exceptions why not something like... soft_exception_list = [IndexError, TypeError] hard_exception_list = [ZeroDivision] try: do_something() except Exception, e: if e.__class__ in soft_exception_list: handle_soft_exception() elif e.__class__ in hard_exception_list: handle_hard_exception() else: raise NotImplementedError Granted you're most likely looking for something that does this constantly on every line of code though... It's not about grouping, which would be done better with inheritance by the way. Its about not raising certain exceptions if there is no handler. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Distributed App - C++ with Python for Portability?
in 337600 20080310 222850 [EMAIL PROTECTED] wrote: On Mar 10, 2:21 pm, Bob Martin [EMAIL PROTECTED] wrote: Java is more portable than most other languages, especially if your app needs a gui. The promise of Java portability was one of the biggest scams ever perpetrated on the software industry. There are issues going from OS to OS, VM to VM, DB to DB, app server to app server, etc. Certainly no easier than porting C++ and the appropriate libraries, IMHO. Quite untrue - I have a stack of large java apps which run without change on Linux, OS/2 and Windows. Not many, if any, other languages can match that, and definitely not C++. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Sockets Help
On 10 Mar, 23:58, Mark M Manning [EMAIL PROTECTED] wrote: I need your expertise with a sockets question. Let me preface this by saying I don't have much experience with sockets in general so this question may be simple. I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt All I want to do is edit this script so that it records the IP address. I've seen other examples use the accept() object which returns the data and the IP address it is receiving the data from. I can't use that in this case but I'm wondering if someone could show me how. Here is the socket part of the script: if __name__ == '__main__': ip='192.168.1.1' print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.bind(('',53)) try: while 1: data, addr = udps.recvfrom(1024) p=DNSQuery(data) udps.sendto(p.respuesta(ip), addr) print 'Respuesta: %s - %s' % (p.dominio, ip) except KeyboardInterrupt: print 'Finalizando' udps.close() Thanks to everyone in advance! ~Mark You already have the address of the sender, is in the 'addr' variable, as returned by udps.recvfrom. Change the print statement in sometinmh like: print 'Respuesta (%s): %s - %s' % ( addr, p.dominio, ip) and you will see the sender address in dotted notation printed inside the (). Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: execute python script question
Sam wrote: Hello, I may misunderstand your problem, but it may be related to the execution environment, especially the PYTHONPATH variable. Have a look at the following log: [EMAIL PROTECTED]:/$ pwd / [EMAIL PROTECTED]:/$ cat -n /tmp/test_import.py 1 class A(object): 2 def __init__(self): 3 self.value = 1 4 def show(self): 5 print self.value [EMAIL PROTECTED]:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type help, copyright, credits or license for more information. from test_import import A Traceback (most recent call last): File stdin, line 1, in module ImportError: No module named test_import exit() [EMAIL PROTECTED]:/$ export PYTHONPATH=/tmp [EMAIL PROTECTED]:/$ python Python 2.5.1 (r251:54863, Oct 5 2007, 13:50:07) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type help, copyright, credits or license for more information. from test_import import A a=A() a.show() 1 ++ Sam Hello Sam, Thank you for your reply. I tried that and it works, thanks. I was trying to modify the sys.path in __init__.py and it wasn't working. Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules)
Hi Malcom On Mar 10, 4:27 pm, Malcolm Greene [EMAIL PROTECTED] wrote: I'm new to Python and getting ready to build a small client based application intended to run on Windows and Linux. I was planning on using wxPython until I saw your comment above. We use wxPython and Python internally in the company without any mayor problems or crashes. It seems quite solid. But errors happen in complex systems. And if for example a crash occurs it would be good to know the reason and to track it down. And that is hard in Python with C extensions. That does not only apply to wxPython but to all other (GUI) libraries with C parts, too. At least we will not switch to something else then wxPython. Best regards, Noel -- http://mail.python.org/mailman/listinfo/python-list
Re: execute python script question
Michael Wieher wrote: stupid question: you have myPackage somewhere on sys.path? I mean, module1.py only knows it lives in a directory, it doesn't know anything about anything above it. 2008/3/10, Gabriel Rossetti [EMAIL PROTECTED] mailto:[EMAIL PROTECTED]: Hello, I have been developping something in python that has the following hierarchy : project/src/myPackage/ project/src/myPackage/__init__.py project/src/myPackage/module1.py project/src/myPackage/module2.py project/src/myPackage/test/ project/src/myPackage/test/__init__.py project/src/myPackage/test/test_module1.py project/src/myPackage/test/test_module2.py project/src/myPackage/mySubPackage/__init__.py project/src/myPackage/mySubPackage/module1.py project/src/myPackage/mySubPackage/test/ project/src/myPackage/mySubPackage/test/__init__.py project/src/myPackage/mySubPackage/test/module1.py ... up until now, I had been executing my modules from inside project/src/myPackage/ but I realised that that is wrong (while implementing the test suite) and that since all my modules had relative imports (if module2 needed module1, it would just say : import module1) I changed them to myPackage.module1 for example. Now my test suite is happy, I can say : test.sh myPackage.test and it tests everything. The only problem now is that I can't execute the scripts from inside or outside the myPackage dir, I get this : from outside : Traceback (most recent call last): File myPackage/module1.py, line 15, in module from myPackage import constants, utils ImportError: No module named myPackage or if from inside it : Traceback (most recent call last): File module1.py, line 15, in module from myPackage import constants, utils ImportError: No module named myPackage can anybody please help me? I don't think I understood the whole package/module thing I think... I think some people do some sort of importing in the __init__.py files but I'm not sure this helps in this case. Thanks, Gabriel Hello Michael, not a stupid question, I think that may be it. I tried setting PYTHONPATH like Sam suggested and it worked, but I was unable to do it programmically. I tried putting it in the __init__.py file like a web post suggested but it wasn't run until after I set PYTHONPATH, and once that was done there is no need (that I can see anyways) to set it in __init__.py. Thanks for your help, Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing directory for certain filetypes
On Mar 11, 6:21 am, royG [EMAIL PROTECTED] wrote: On Mar 10, 8:03 pm, Tim Chase wrote: In Python2.5 (or 2.4 if you implement the any() function, ripped from the docs[1]), this could be rewritten to be a little more flexible...something like this (untested): that was quite a good lesson for a beginner like me.. thanks guys in the version using glob() path = os.path.normpath(os.path.join(folder, '*.txt')) lst = glob.glob(path) is it possible to check for more than one file extension? here i will have to create two path variables like path1 = os.path.normpath(os.path.join(folder, '*.txt')) path2 = os.path.normpath(os.path.join(folder, '*.doc')) and then use glob separately.. or is there another way? I don't think you can match multiple patterns directly with glob, but `fnmatch` - the module used by glob to do check for matches - has a `translate` function which will convert a glob pattern to a regular expression (string). So you can do something along the lines of the following: - import os from fnmatch import translate import re d = '/tmp' patt1 = '*.log' patt2 = '*.ini' patterns = [patt1, patt2] rx = '|'.join(translate(p) for p in patterns) patt = re.compile(rx) for f in os.listdir(d): if patt.match(f): print f - hth Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: Distributed App - C++ with Python for Portability?
On Mar 11, 3:03 am, Bob Martin [EMAIL PROTECTED] wrote: in 337600 20080310 222850 [EMAIL PROTECTED] wrote: On Mar 10, 2:21 pm, Bob Martin [EMAIL PROTECTED] wrote: Java is more portable than most other languages, especially if your app needs a gui. The promise of Java portability was one of the biggest scams ever perpetrated on the software industry. There are issues going from OS to OS, VM to VM, DB to DB, app server to app server, etc. Certainly no easier than porting C++ and the appropriate libraries, IMHO. Quite untrue - I have a stack of large java apps which run without change on Linux, OS/2 and Windows. Not many, if any, other languages can match that, and definitely not C++. I'm happy that it's worked for you, but I haven't seen it in my experience. My current client has code that works in 1.4.0, but not higher versions of the JDK without code changes. And other that won't run in later versions of the app server (JBoss) than the one for which it was developed. And upgrading our SQL Server version required an upgrade of DB drivers. Another headache. They have their own JVM requirements as well, as do other packages and libraries. Getting them all to play together hasn't been seamless or easy by any stretch. -- http://mail.python.org/mailman/listinfo/python-list
Re: for-else
On Mar 4, 11:27 pm, [EMAIL PROTECTED] wrote: The meaning is explicit. While else seems to mean little there. So I may like something similar for Python 3.x (or the removal of the else). Consider a loop with the following form: while 1: if while-cond: 0-to-many times code block else: 0-to-1 times code block break A break, return or exception in the 0-to-many times code block will obviously skip over the 'else' part of that if statement - it will only be executed if while-cond evaluates as a false value. The above code is actually equivalent to a normal Python while-loop: while while-cond: 0-to-many times code block else: 0-to-1 times code block For loops aren't quite so straightforward since the termination condition is tied up with the StopIteration exception, but the clause keeps the same name as the corresponding clause on the while loop. Thinking of it as break-else (as someone else posted) probably isn't a bad way to look at the situation. Cheers, Nick. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does my compiler say invalid syntax then highlight...?
Mensanator [EMAIL PROTECTED] wrote: On Mar 10, 10:44¨«pm, Nathan Pinno [EMAIL PROTECTED] wrote: Why does my compiler say invalid syntax and then highlight the quotation marks in the following code: # This program is to find primes. Needs work. Be fair. The OP hadn't managed to figure out why the program wasn't running, so you can't expect him to have got all the bugs out of the code yet. And he only asked about the specific syntax error not the entire solution to his homework. My advice to Nathan would be: 1. If you get a weird syntax error that you don't understand try cutting the code down to just the bit which generates the error. 2. Play around in the interactive interpreter to see what works and what doesn't. 3. If you don't understand why the code doesn't work then get a stuffed toy, cardboard cutout of a person, or the least technical member of your family and explain to them in great detail exactly why the code must (despite error messages to the contrary) be correct. Usually you'll spot the problem half way through the explanation. 4. If you post to this list then post the full error message and traceback. That way we don't have to guess which quotation marks are the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mar 11, 2:18 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: The problem with callbacks is that it works only for a small amount of callbacks, it'd be too messy to have twenty different callbacks. And the ultimate problem with callbacks is that we can't determine from the outside whether the operation should continue or breaks at the point of the callback without some messy trick. We can't always determine whether we want to do this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() or this: def somefunc(argA, argB, callback = DO_NOTHING): if argA == argB: callback() return perhaps we could do this: if argA == argB: if callback() == True: return but that's so much extra codes written and would've been too messy to write. And actually this isn't a rare cases, and in fact is very common. It's just that most cases that can be more cleanly written in SoftException, can usually be handled in different ways, using tricks that range from subtle to messy (like callbacks). I fail to see how your arguments follow. Regarding the number of callbacks: you can as well pass an object that has several methods to call. If you passed an object that has several methods to call (using tuple or list) and you want to handle several softexceptions and ignore some others, you must still pass an empty methods to the one you want to ignore, cluttering the caller's code by significant degree: def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, DO_NOTHING)): if a == 0: raise callback(0) try: a += b except ZeroDivisionError: raise callback(1) if a = 0: raise callback(2) raise callback(3) return a somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, DO_NOTHING)) if instead we use dict, well, we know how inverseconvenient/ inverse dict's syntax is for a lot of manual data entry. ## imagine if we want to handle five or more callbacks somefunc(a, b, {callbackzero:handlerzero, callbacktwo:handlertwo}) And the above example can easily be accomplished with normal exceptions, like this: def toplelevel(): def callback(a, b): if a == b: raise InterruptException() try: work(callback) except InterruptException: pass def work(callback=callback): a = 10 b = 20 callback(a, b) That's why I said most things that can be more cleanly handled by SoftException can usually be handled in other forms, although in a more cluttered way. That could be more cleanly written in SoftException as: def work(): a = 10 b = 20 raise Equal(a, b) def toplevel(): try: work() except Equal, args: a, b = args if a == b: raise InterruptException OR ALTERNATIVELY (Which one's better depends on the purpose, generally the one below is better, but the one in the above is more flexible, yet a bit less convenient to use) def work(): a = 10 b = 20 if a == b: raise Equal def toplevel(): try: work() except Equal: raise InterruptException The reason why SoftException is useful is similar to the reason why for-loop and while condition is useful. AFAIK, all looping cases can be handled only by a blind loopers (a.k.a. while True:) and break, but a blind loopers is very inconvenient to use, and for-loop and while condition simplifies a lot of codes a lot. Exactly the same reason why SoftException is useful. And even more: the callback-approach can do things like this: a, b = callback(a,b) to change values, which makes it superior to SoftExceptions - unless I missed it's ability to capture context. If there is a syntax support, you could also make resume able to transfer values: def somefunc(a, b): if a == b: a, b = raise Equal(a, b) def toplevel(): try: somefunc(10, 20) except Equal, args: a, b = args[0], args[1] + 1 resume a, b On Mar 11, 5:18 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: How would that differ from something like this: with add_soft_handler(SoftException): invoke_something() ... # deep down in code raise_soft(SoftException()) The implementation of add_soft_handler and raise_soft is trivial - a bit of thread-local storage and a stack. Perhaps you meant: raise_soft(SoftException) cause SoftException() may have side effects if called greedily That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: raise_soft(SoftException) break but this makes SoftException must break everytime, which make it lost its original purpose, so you have to add return code to
rmdir problem
hi i am checking if a directory exists and if it does i want to delete it and its contents.then i want to create the directory before creating files in it. def myfolderops(): testdir='..\mytestdir' #if dir exist remove it if isdir(testdir): rmdir(testdir) #again create directory mkdir(testdir) I am working on WinXP and logged in as admin in WinXP. when there is no dir called '..\mytestdir' or an empty dir this code works removing and creating the directory.but if the directory exists with contents already then it causes an error 145 when rmdir is executed.the message says 'directory is not empty' what should i do to correct this? (i need to remove the dir with its contents because each time i will be putting diff files into it and donot want them to be mixed with old files) thanks RG -- http://mail.python.org/mailman/listinfo/python-list
Re: execute python script question
Gabriel Rossetti [EMAIL PROTECTED] (GR) wrote: GR not a stupid question, I think that may be it. I tried setting PYTHONPATH GR like Sam suggested and it worked, but I was unable to do it programmically. GR I tried putting it in the __init__.py file like a web post suggested but it GR wasn't run until after I set PYTHONPATH, and once that was done there is no GR need (that I can see anyways) to set it in __init__.py. The __init__.py is executed during your import statement, thus it is too late to find MyPackage. You will have to change the sys.path before the import, e.g. in your main program. Or do what is usually done: put MyPackage in the site-packages directory. -- Piet van Oostrum [EMAIL PROTECTED] URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: rmdir problem
On Mar 11, 10:35 am, royG [EMAIL PROTECTED] wrote: i am checking if a directory exists and if it does i want to delete it and its contents.then i want to create the directory before creating files in it. Have a look at shutil.rmtree -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list
Re: rmdir problem
royG wrote: hi i am checking if a directory exists and if it does i want to delete it and its contents.then i want to create the directory before creating files in it. def myfolderops(): testdir='..\mytestdir' #if dir exist remove it if isdir(testdir): rmdir(testdir) #again create directory mkdir(testdir) I am working on WinXP and logged in as admin in WinXP. when there is no dir called '..\mytestdir' or an empty dir this code works removing and creating the directory.but if the directory exists with contents already then it causes an error 145 when rmdir is executed.the message says 'directory is not empty' what should i do to correct this? (i need to remove the dir with its contents because each time i will be putting diff files into it and donot want them to be mixed with old files) Two things: 1) Use raw strings (r..\blah) or forward slashes (../blah) when messing with path names under windows. 2) Check out the shutils module: http://docs.python.org/lib/module-shutil.html TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules)
Gilles Ganault wrote: On Mon, 10 Mar 2008 11:27:06 -0400, Malcolm Greene [EMAIL PROTECTED] wrote: Any suggestions on an alternative Python client-side GUI library (pyQT ?) or tips on where I can find out more about wxPython/wxWidget problems? One thing that bothers me is that it seems like there's no ecosystem around it, so the only widgets available are those that come from wxWidgets proper. For instance, I find the grid object a bit poor-featured compared to what's available for VB6, .Net, or Delphi, but I didn't find alternatives. Funny, compared to Delphi-7, I found the grid in wxPython much richer ;-) Very easy to add own in place editors, easy add checkboxes, colorpickers etc into the grid. cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ? (was Re: Quality assurance in Python projects containing C modules)
On Mon, 10 Mar 2008 22:17:16 -0700 (PDT), Frank Millman [EMAIL PROTECTED] wrote: I do not know if this helps, but here is an extract from a recent post to the wxPython mailing list from Robin Dunn, the main developer of wxPython - I'll take a look. Thanks for the info. -- http://mail.python.org/mailman/listinfo/python-list
Python PDF + Pictures
Hi, dear Python Masters! I wanna ask about the Python and PDF creating. I have many photos, and I wanna make some presentation from these photos, a thumbnail like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. Do you knows about a PDF maker library with I can make this thing? Or other technic to simplify the making? Thanks for your help! dd -- http://mail.python.org/mailman/listinfo/python-list
Re: rmdir problem
On Mar 11, 3:37 pm, Paul Have a look at shutil.rmtree thanks Paul RG -- http://mail.python.org/mailman/listinfo/python-list
how to increase the system speed....to improve the proceesssor speed.....
how to increase the system speedto improve the proceesssor speed. http://intelspentium.googlepages.com -- http://mail.python.org/mailman/listinfo/python-list
The stange behaviour of Tkinter.Canvas
I tried to update the rectangle on a canvas to get the visual effect of progressbar. It works all right if I delete the existing objects (rectangle and text) and create a new one. However, if I invoke canvas.itemconfig() to update the existing objects' options, gui just went nuts. I am more than happy to receive any help and advise. My code is provided as follows: Start of Code import Tkinter import threading import time class Progressbar(Tkinter.Frame): def __init__(self, parent=None, color='white', width=200, height=15): Tkinter.Frame.__init__(self, parent) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) canv = Tkinter.Canvas(self, bg=color, relief=Tkinter.SUNKEN) canv.config(width=width, height=height) canv.pack(side=Tkinter.LEFT, expand=Tkinter.YES, fill=Tkinter.BOTH) self.canv = canv self.width = width self.height = height progress = -10 rect = canv.create_rectangle(0, 0, 0, height, fill='beige') text = canv.create_text(width/2, height*2/3, text='0%') self.rect = rect self.text = text self.progress = progress self.parent = parent parent.progressbar = self self.UpdateProgress() def SetProgress(self, progress=0): canv = self.canv width = self.width height = self.height rect = self.rect text = self.text ##canv.delete(rect) ##canv.delete(text) ##rect = canv.create_rectangle(0, 0, progress*width/100, height, ## fill='beige') ##text = canv.create_text(width/2, height*2/3, ##text='%s' %(str(progress)) + '%') canv.itemconfig(rect, width=width*progress/100) ## comment this canv.itemconfig(text, text='%s' %(str(progress)) + '%') ## comment this ##self.rect = rect ##self.text = text def UpdateProgress(self): progress = self.progress progress = progress + 10 self.progress = progress self.SetProgress(progress) if progress 100: self.after(500, self.UpdateProgress) if __name__ == '__main__': root = Tkinter.Tk() Progressbar(parent=root) root.mainloop() End of Code uncomment the lines and comment out the itemconfig() lines to see the difference in gui's behaviours. Thanks, -- This is a UTF-8 formatted mail --- James C.-C.Yu -- http://mail.python.org/mailman/listinfo/python-list
MySQL DB-Api
Good morning list. I'm in the process of learning my way around the DB-API module for MySQL and wanted to come and get some advice on how you all manage your database connections and cursors. Within my applications I'll have many classes which access the database, I'm wondering to what level I should extract the database connection. Should I create a new database connection and close it for every method which calls the database? Should I create the connection/cursor to the DB when I construct the class and place the cursor in the self scope? Or should I create a application wide connection/cursor to the database and inject the cursor into all the classes which require it? All classes within the application access the same database so at the moment I'm leaning towards creating an application wide connection and cursor and then injecting it into classes which require database access, does that sound like a fair plan? I'm just interested to learn how you are managing this. Thanks guys, Rob -- http://mail.python.org/mailman/listinfo/python-list
Check For SELF Variable Existance
Hello Guys, I want to be able to check if a class has a certain property in its 'self' scope, what's the best way to do this? I've seen a few examples of people using a try: block to test if the variable exists but to be honest, this seems a little bit verbose, do we not have a better method of checking for its existence? Cheers, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Python PDF + Pictures
[EMAIL PROTECTED] a écrit : Hi, dear Python Masters! I wanna ask about the Python and PDF creating. I have many photos, and I wanna make some presentation from these photos, a thumbnail like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. Do you knows about a PDF maker library with I can make this thing? Or other technic to simplify the making? Dont know if this will match your needs, but you may want to have a look at pisa: http://www.htmltopdf.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python PDF + Pictures
[EMAIL PROTECTED] wrote: I have many photos, and I wanna make some presentation from these photos, a thumbnail like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. PIL can write PDFs, and it's clearly a good choice for image processing. http://www.pythonware.com/products/pil/ Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python PDF + Pictures
Hi! Bruno Desthuilliers wrote: [EMAIL PROTECTED] a écrit : Hi, dear Python Masters! I wanna ask about the Python and PDF creating. Dont know if this will match your needs, but you may want to have a look at pisa: http://www.htmltopdf.org/ With HTML I have only one problem. The HTML is not page specific language. But I wanna use pages (for example: A4) with diff. orientation to show images correctly. But I try it if possible. Thanks for your help: dd -- http://mail.python.org/mailman/listinfo/python-list
Re: TextWrapper keepking line breaks?
Hi Arnaud, Great. Thanks for your help! On Tue, Mar 11, 2008 at 10:27 AM, Arnaud Delobelle [EMAIL PROTECTED] wrote: On Mar 10, 11:31 pm, js [EMAIL PROTECTED] wrote: Hi list, Can I make TextWrapper keep line breaks in the text? For example, s = spam\nham print wrap(s) spam ham As far as I can tell, there seems no way to do this, but before writing my own solution, I want to know whether the solution already exists or not. Thanks. Don't know but you could write: import textwrap def wraplines(text): ... return '\n'.join(textwrap.fill(line) for line in text.split('\n')) ... s = spam\nham print wraplines(s) spam ham HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
RE: Obtaining the PyObject * of a class
Are there any Python C API experts/SWIG experts out there that can help me with this issue please. Andy -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Cooper, Andrew Sent: 10 March 2008 15:55 To: python-list@python.org Subject: Obtaining the PyObject * of a class I',m currently using SWIG to generate a python interface to a C DLL. I'm new to the Python C API and have a question that has been stumping me for the last week. As part of the wrapper process I want to hide some of the complexity with dealing with handles using a python class. But the problem I have is I don't know how to get the PyObject* that refers to the class Pin that I have defined in the %pythoncode section Here is a cut down version of the interface file %module example typedef long pin; typedef unsigned short ushort; ushort wkDefinePin(char *, char *, pin *OUTPUT); %pythoncode { class Pin(object): def __init__(self, name, tic): self.handle = wkDefinePin(name,tic)[1] return } %typemap(in) (pin tp) { // // TODO: really need to change this to IsInstance type code // if(strcmp($input-ob_type-tp_name,Pin) == 0) { $1 = PyInt_AsLong(PyObject_GetAttrString($input,handle)); } else { PyErr_SetString(PyExc_TypeError,arg must be type Pin); return NULL; } } %typemap(in) (int nCnt_tp, pin *tp) { /* Check if is a list */ if (PyList_Check($input)) { int i; $1 = PyList_Size($input); $2 = (pin *) malloc(($1) * sizeof(pin)); for (i = 0; i $1; i++) { // // TODO: really need to change this to IsInstance type code // PyObject *o = PyList_GetItem($input,i); if (strcmp(o-ob_type-tp_name, Pin) == 0) { $2[i] = PyInt_AsLong(PyObject_GetAttrString(o,handle)); } else { PyErr_SetString(PyExc_TypeError,list must contain Pins); free($2); return NULL; } } $2[i] = 0; } else { PyErr_SetString(PyExc_TypeError,not a list); return NULL; } } -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Sockets Help
That's embarrassingly simple! Thank you very much!! On Mar 11, 4:03 am, [EMAIL PROTECTED] wrote: On 10 Mar, 23:58, Mark M Manning [EMAIL PROTECTED] wrote: I need your expertise with a sockets question. Let me preface this by saying I don't have much experience with sockets in general so this question may be simple. I am playing with the mini dns server from a script I found online:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/491264/index_txt All I want to do is edit this script so that it records the IP address. I've seen other examples use the accept() object which returns the data and the IP address it is receiving the data from. I can't use that in this case but I'm wondering if someone could show me how. Here is the socket part of the script: if __name__ == '__main__': ip='192.168.1.1' print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udps.bind(('',53)) try: while 1: data, addr = udps.recvfrom(1024) p=DNSQuery(data) udps.sendto(p.respuesta(ip), addr) print 'Respuesta: %s - %s' % (p.dominio, ip) except KeyboardInterrupt: print 'Finalizando' udps.close() Thanks to everyone in advance! ~Mark You already have the address of the sender, is in the 'addr' variable, as returned by udps.recvfrom. Change the print statement in sometinmh like: print 'Respuesta (%s): %s - %s' % ( addr, p.dominio, ip) and you will see the sender address in dotted notation printed inside the (). Ciao --- FB -- http://mail.python.org/mailman/listinfo/python-list
Re: Check For SELF Variable Existance
On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins [EMAIL PROTECTED] wrote: I want to be able to check if a class has a certain property in its 'self' scope, what's the best way to do this? class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... spam = Spam() spam.egg() spam.chips = 'beans' spam.egg() got chips! -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing directory for certain filetypes
On Mar 11, 12:21 am, royG [EMAIL PROTECTED] wrote: On Mar 10, 8:03 pm, Tim Chase wrote: in the version using glob() path = os.path.normpath(os.path.join(folder, '*.txt')) lst = glob.glob(path) is it possible to check for more than one file extension? here i will have to create two path variables like path1 = os.path.normpath(os.path.join(folder, '*.txt')) path2 = os.path.normpath(os.path.join(folder, '*.doc')) and then use glob separately.. or is there another way? use a loop. (untested) def parsefolder(folder): lst = [] for pattern in ('*.txt','*.doc'): path = os.path.normpath(os.path.join(folder, pattern)) lst.extend(glob.glob(path)) lst.sort() return lst -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.10.0
Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New == News since 0.9 -- Features Interface * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
RE: Check For SELF Variable Existance
Thank you Simon, I was hoping there would be something as simple as that :-) Rob -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Simon Brunning Sent: 11 March 2008 13:21 To: python-list@python.org Subject: Re: Check For SELF Variable Existance On Tue, Mar 11, 2008 at 11:00 AM, Robert Rawlins [EMAIL PROTECTED] wrote: I want to be able to check if a class has a certain property in its 'self' scope, what's the best way to do this? class Spam(object): ... def egg(self): ... if hasattr(self, 'chips'): print 'got chips!' ... spam = Spam() spam.egg() spam.chips = 'beans' spam.egg() got chips! -- Cheers, Simon B. [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing directory for certain filetypes
royG wrote: On Mar 10, 8:03 pm, Tim Chase wrote: In Python2.5 (or 2.4 if you implement the any() function, ripped from the docs[1]), this could be rewritten to be a little more flexible...something like this (untested): that was quite a good lesson for a beginner like me.. thanks guys in the version using glob() path = os.path.normpath(os.path.join(folder, '*.txt')) lst = glob.glob(path) is it possible to check for more than one file extension? here i will have to create two path variables like path1 = os.path.normpath(os.path.join(folder, '*.txt')) path2 = os.path.normpath(os.path.join(folder, '*.doc')) and then use glob separately.. Though it doesn't use glob, the 2nd solution I gave (the one that uses the any() function you quoted) should be able to handle an arbitrary number of extensions... -tkc -- http://mail.python.org/mailman/listinfo/python-list
RE: SQLObject 0.10.0
Excellent stuff Oleg, I've been looking for an ORM framework for a while and hadn't settled on one, I'll give this a look through later today. Thanks, Robert -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Oleg Broytmann Sent: 11 March 2008 13:40 To: Python Announce Mailing List; Python Mailing List Subject: SQLObject 0.10.0 Hello! I'm pleased to announce version 0.10.0, the first stable release of 0.10 branch of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.0 News and changes: http://sqlobject.org/News.html What's New == News since 0.9 -- Features Interface * Dropped support for Python 2.2. The minimal version of Python for SQLObject is 2.3 now. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.10. * SQLBuilder Select supports the rest of SelectResults options (reversed, distinct, joins, etc.) * SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect() use SQLBuilder Select queries; this make all SELECTs implemented internally via a single mechanism. * SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias) and properly sqlrepr. * Added SQLBuilder ImportProxy. It allows one to ignore the circular import issues with referring to SQLObject classes in other files - it uses the classregistry as the string class names for FK/Joins do, but specifically intended for SQLBuilder expressions. See tests/test_sqlbuilder_importproxy.py. * Added SelectResults.throughTo. It allows one to traverse relationships (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's a simple mechanism for pre-caching/eager-loading of later FK relationships (i.e., going to loop over a select of somePeople and ask for aPerson.group, first call list(somePeople.throughTo.group) to preload those related groups and use 2 db queries instead of N+1). See tests/test_select_through.py. * Added ViewSQLObject. * Added sqlmeta.getColumns() to get all the columns for a class (including parent classes), excluding the column 'childName' and including the column 'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to override it in the inheritable sqlmeta class; this makes asDict() to work properly on inheritable sqlobjects. * Allow MyTable.select(MyTable.q.foreignKey == object) where object is an instance of SQLObject. * Added rich comparison methods; SQLObjects of the same class are considered equal is they have the same id; other methods return NotImplemented. * RowDestroySignal is sent on destroying an SQLObject instance; postfunctions are run after the row has been destroyed. * Changed the implementation type in BoolCol under SQLite from TINYINT to BOOLEAN and made fromDatabase machinery to recognize it. * MySQLConnection (and DB URI) accept a number of SSL-related parameters: ssl_key, ssl_cert, ssl_ca, ssl_capath. * Use sets instead of dicts in tablesUsed. Dropped tablesUsedDict function; instead there is tablesUsedSet that returns a set of strings. * SQLBuilder tablesUsedSet handles sqlrepr'able objects. * Under MySQL, PickleCol no longer uses TEXT column types; the smallest column is now BLOB - it is not possible to create TINYBLOB column. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
difference b/t dictionary{} and anydbm - they seem the same
anydbm and dictionary{} seem like they both have a single key and key value. Can't you put more information into a DBM file or link tables? I just don't see the benefit except for the persistent storage. d= dbm.open('c:\\temp\\mydb.dat','n') It has the following interface (key and data are strings): d[key] = data # store data at key (may override data at # existing key) data = d[key] # retrieve data at key (raise KeyError if no # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) flag = key in d # true if the key exists list = d.keys() # return a list of all existing keys (slow!) -- http://mail.python.org/mailman/listinfo/python-list
Re: difference b/t dictionary{} and anydbm - they seem the same
On Tue, 2008-03-11 at 06:49 -0700, davidj411 wrote: anydbm and dictionary{} seem like they both have a single key and key value. Can't you put more information into a DBM file or link tables? I just don't see the benefit except for the persistent storage. Persistent storage /is/ the benefit. If you want to store relational data, you should use a relational database. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: difference b/t dictionary{} and anydbm - they seem the same
davidj411 wrote: anydbm and dictionary{} seem like they both have a single key and key value. Can't you put more information into a DBM file or link tables? I just don't see the benefit except for the persistent storage. Except for the persistent storage, that insignificant feature... ;) Well I guess that persistent storage must be the reason some people use anydbm sometimes. If you want keys and values of any type (not just strings) and persistent storage, you can use builtin dicts then pickle them. Cheers, RB -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mar 10, 7:32 pm, Nathan Pinno [EMAIL PROTECTED] wrote: Thanks on the factoring bit, but I did mean factorial, not factoring. How do I code that correctly, so that I can figure the following equation out: cos(Pi * (z-1)! / z). Is z an integer in this expression? (Note: it's not an equation--- there's no equality sign.) This looks suspiciously like a formula that's supposed to be valid for real and possibly even complex z, in which case what you're after is the gamma function. (gamma(z) = (z-1)!). The real version of this should certainly be present in numpy/scipy, and possibly the complex version too. If z really is supposed to be an integer then you should be aware that evaluating the expression directly is going to give almost no accuracy, for z greater than 30 or so: the absolute error in the argument to cosine will likely be much larger than 2*pi, so that the result of the cos() evaluation is meaningless. You might be better off computing w = (factorial(z-1) % (2*z)) as an integer; then cos(pi*(z-1)!/z) can be computed as cos(pi * w/z). Also, there are algebraic simplifications possible. If z is an integer greater than 4, and not a prime number, then the value of your expression is always going to be 1. If z is a prime number then Wilson's theorem is going to come in handy. (Google Wilson's theorem prime). Where does the expression come from? Is z a real or an integer? Is this a genuine real-world formula, or something that appeared in an elementary number theory textbook? Mark -- http://mail.python.org/mailman/listinfo/python-list
how to theme/skin pyGtk apps
hi again dear group. what i am interested in is giving my pygtk app some distinct look, a lil childish look coz the app is for children. so, i downloaded a couple of themes from http://art.gnome.org/themes/gtk2/ and for the past 1 hr i have been trying to theme my app but with no results. could anyone please guide me on who to theme pygtk and code samples would be greatly appreciated thanks binary-j -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno [EMAIL PROTECTED] wrote: How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? This should work to do x! (factorial of x). reduce(lambda x,y: x*y, range(1, x+1)) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Tue, Mar 11, 2008 at 10:38 AM, Joe Riopel [EMAIL PROTECTED] wrote: On Mon, Mar 10, 2008 at 1:08 AM, Nathan Pinno [EMAIL PROTECTED] wrote: How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? This should work to do x! (factorial of x). reduce(lambda x,y: x*y, range(1, x+1)) Sorry, the variable naming was confusing in that code. def dofact(x): ... return reduce(lambda a,b: a*b, range(1,x+1)) ... dofact(5) 120 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mar 10, 7:32 pm, Nathan Pinno [EMAIL PROTECTED] wrote: Thanks on the factoring bit, but I did mean factorial, not factoring. How do I code that correctly, so that I can figure the following equation out: cos(Pi * (z-1)! / z). Python returns a invalid syntax error and highlight the !. So it would be nice to find a way to solve such a problem. Aha. I've just found the Is there a mathematical formula that will find prime numbers? thread that you started over on sci.math. It looks like at least one of us has been trolled. I suggest you: (1) Ignore the formula Gerry gave you. It's completely impractical as a way of determining primality, and I'm certain that Gerry knew this. (2) Learn some elementary number theory before trying to crack RSA. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: difference b/t dictionary{} and anydbm - they seem the same
Persistent storage /is/ the benefit. If you want to store relational data, you should use a relational database. Thanks, that makes sense. Are there any local relational databases available to python that don't require a server backend? -- http://mail.python.org/mailman/listinfo/python-list
ZSI and attachments
Hi All, I wonder if the newest ZSI has support for attachments? Last time I checked (about a year ago) this feature was missing. I desperately need it. Alternatively, is there any other SOAP lib for python that can handle attachments? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
Nathan Pinno wrote: How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? Thanks in advance, Nathan P. import os os.system('factor 25') -- http://mail.python.org/mailman/listinfo/python-list
Re: difference b/t dictionary{} and anydbm - they seem the same
On Tue, Mar 11, 2008 at 10:58 AM, davidj411 [EMAIL PROTECTED] wrote: Thanks, that makes sense. Are there any local relational databases available to python that don't require a server backend? sqlite http://www.sqlite.org/ -- http://mail.python.org/mailman/listinfo/python-list
mulithreaded server
import socket import sys import thread p=1 PORT=11000 BUFSIZE=1024 def getData(cSocket): global stdoutlock,cSocketlock while True: cSocketlock.acquire() data=cSocket.recv(BUFSIZE) if data=='q': data='client exited' cSocket.close() p=0 cSocketlock.release() stdoutlock.acquire() stdout.write(data) stdoutlock.release() def sendData(cSocket): global stdoutlock,cSocketlock while True: stdoutlock.acquire() data=raw_input('') cSocketlock.acquire_lock() if data=='q': stdout.write('server exited') stdout.release() p=0 cSocket.close() sSocket.send(data) sSocketlock.release() stdout=sys.stdout host='' sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sSocket.bind((host,PORT,)) sSocket.listen(1) #sSocketlock=thread.allocate_lock() stdoutlock=thread.allocate_lock() print 'waiting for connection' cSocket,addr=sSocket.accept() print 'connection from',addr cSocketlock=thread.allocate_lock() thread.start_new_thread(sendData,(cSocket,)) thread.start_new_thread(getData,(cSocket,)) if p==0: sSocket.close() In the above program, why there is an unhandeled exception ??? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ?
Stefan Behnel [EMAIL PROTECTED] wrote: Just to make this sound a bit less like FUD: my last experience with wxPython dates back a couple of years (2004/5?), but back then, we used BoaConstructor in a project, which crashed a bit too often to do real work with it - and with crashing I mean crashing Python, not just showing us its blank traceback. So this was definitely a problem either in wxWindows or in wxPython. I spent a couple of years maintaining and developing a series of commercial wxPython-based applications (up until about 18 months ago when I changed job), and I would happily describe wxPython itself as stable enough for production code. The biggest problem I had with it was its failure to be anywhere near as transparently cross-platform as one might be lead to expect. And before you blame wx* for crashes: what platform was this on? Because my experience was that wx on GTK was significantly more prone to glitches than on Windows (through to wxglade being unusably crashy) -- if the underlying toolkit has problems, that's going to be reflected in wx. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ Frankly I have no feelings towards penguins one way or the other -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
urllib proxy support confusion
Reading through the doc at http://docs.python.org/lib/module-urllib.html, there are several paragraphs (including code examples) showing how you specify what proxies to use when calling urlopen(): Alternatively, the optional proxies argument may be used to explicitly specify proxies. [...] The explanation of how to specify proxies is followed by this paragraph denying that the ability to do so exists: The urlopen() function does not support explicit proxy specification. If you need to override environmental proxy settings, use URLopener, or a subclass such as FancyURLopener. That seems a bit baffling. If it urlopen doesn't support specifying proxies, why are there examples showing how to do it? If it does support specifying proxies, what is the pragraph quoted above supposed to mean? -- Grant Edwards grante Yow! Am I accompanied by a at PARENT or GUARDIAN? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python PDF + Pictures
On Mar 11, 5:00 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, dear Python Masters! I wanna ask about the Python and PDF creating. I have many photos, and I wanna make some presentation from these photos, a thumbnail like document with one image per one page. If I wanna make one document now I do this: I execute a python script that create a html site with resized pictures, and split this html site to 50 images per one html file. Next I open these files in OpenOffice Writer by hand, and save them as PDF document with poor quality (image compression 95%, image DPI 75). This generates a medium sized PDF documents (2,5 - 5,6 MB for each) that can opened everywhere (because of PDF format). But I wanna automatize this process with python. The technic that I will use is this: 1.) Collect the files in dirs. 2.) I process one dir in one time. 3.) I get the files. 4.) I resize them to max. 1024/768. 5.) I put the actual image file to the PDF document. 6.) After each 50. file I open new numbered PDF. 7.) Every picture placed in one page, and every page orientation set up as the picture orientation (Portrait or Landscape). The PDF must be parameterized to image compression 95%, and 75 or 96 DPI. Do you knows about a PDF maker library with I can make this thing? Or other technic to simplify the making? Thanks for your help! dd You might also want to take a look at ReportLab. Its a PDF library for Python. You can find it at http://www.reportlab.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
If one wants to do serious math using Python, the best bet is to use Sage ( http://www.sagemath.org ). Here are some examples: sage: def f(x, bits=53): : R = RealField(bits); z = R(x) : return cos(R(pi) * factorial(z-1) / z) sage: f(100.00,bits=1000) 0.2343 sage: a = 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 sage: time ecm.factor(a) CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s Wall time: 2.63 [3478697, 49998841, 11927295803, 518069464441, 1858900129817, 161610704597143, 157394131396743433859615518992811454816816449] sage: a = ZZ.random_element(10**100); a 1266081670515546883639925088390407903294616094325617831128683357589913968497538978358203322629420841 sage: a.is_prime() False sage: b = a.next_prime(); b 8975665868645752218769838623717890808871334875974244952657480072373614614471639002293590745490978883 sage: b.is_prime() True --Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: __iter__ yield
On Mar 10, 3:58 am, duccio [EMAIL PROTECTED] wrote: Hello! Someone knows if it's possible to make this __iter__ function with just one 'yield' intead of two? Is there some simpler way to make this __iter__ iter through all nodes? Thanks! class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): return ''+str(self.data)+'' def __iter__(self): yield self #1 for n in self.childs: for nn in n.__iter__(): yield nn #2 n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) for node in n: print node Technically, the root node isn't a child node, and thus it shouldn't show up in the iteration. I think a more semantically correct way for this is to have the __str__() returns the current Node + All Descendants Nodes (like the one you wanted for __iter__) and while __iter__ only yields the child nodes (used by the __str__ to iterate through itself), like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## Returns root node + all descendants return '%s\n' % self.data + ''.join(str(child) for child in self) def __iter__(self): ## yields childrens only for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) ## Note I added the line below for testing branches in ## lower nodes n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n The missing functionality of returning current Node's name can be easily solved by adding it in another function. The main problem with __iter__ behavior you originally wanted is that it doesn't reflect the nesting behavior of the Node class and you could've been equally well served by using flat data structure if you do that. I smell a bad data structure design here, you'd better revise your design. To reflect the nesting, you could do it like this: class Node: def __init__(self, data=None): self.childs=[] self.data=data def appendNode(self, n): node=Node(n) self.childs.append(node) return node def __str__(self): ## This reflects nesting behavior better return '\n%s' % (str(self.data) + ''.join(str(child) for child in self)) ## Uncomment this and Comment the statement above ## for an alternate data structure you might be ## interested in, the format below resembles HTML ##curNode = str(self.data) ##return '\n%s%s\n/%s' % ( ##curNode, ##''.join(str(child) for child in self), ##curNode) def __iter__(self): for n in self.childs: yield n n=Node() n.appendNode(1).appendNode(2).appendNode(3).appendNode(4) n.childs[0].appendNode(222) n.appendNode(11).appendNode(22).appendNode(33).appendNode(44) print n This changes the data structure quite a lot though, but the data structure is bad from the start. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib proxy support confusion
On Mar 11, 11:35 am, Grant Edwards [EMAIL PROTECTED] wrote: That seems a bit baffling. If it urlopen doesn't support specifying proxies, why are there examples showing how to do it? If it does support specifying proxies, what is the pragraph quoted above supposed to mean? Looks like a definite documentation bug to me, and it's still there in the development version of the documentation. I think a bug report should be filed. A little bit of investigation shows that the documentation changes were made in svn revisions 26181 and 26182 ( http://svn.python.org/view?view=revrev=26181 ) as a fix for http://bugs.python.org/issue523415 but this doesn't seem to help much with figuring out what the docs intend to say. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ?
Sion Arrowsmith wrote: And before you blame wx* for crashes: what platform was this on? Because my experience was that wx on GTK was significantly more prone to glitches than on Windows (through to wxglade being unusably crashy) -- if the underlying toolkit has problems, that's going to be reflected in wx. :) Interesting. This was actually on GTK. Although I would still blame at least the wxWidgets-GTK bindings here. I never had any problems with GTK in my life. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: mulithreaded server
On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit [EMAIL PROTECTED] wrote: import socket import sys import thread p=1 PORT=11000 BUFSIZE=1024 def getData(cSocket): global stdoutlock,cSocketlock while True: cSocketlock.acquire() data=cSocket.recv(BUFSIZE) if data=='q': data='client exited' cSocket.close() p=0 cSocketlock.release() stdoutlock.acquire() stdout.write(data) stdoutlock.release() def sendData(cSocket): global stdoutlock,cSocketlock while True: stdoutlock.acquire() data=raw_input('') cSocketlock.acquire_lock() if data=='q': stdout.write('server exited') stdout.release() p=0 cSocket.close() sSocket.send(data) sSocketlock.release() Could it be because `sSocketlock´ here stdout=sys.stdout host='' sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sSocket.bind((host,PORT,)) sSocket.listen(1) #sSocketlock=thread.allocate_lock() is never bound since the line above here is commented out? stdoutlock=thread.allocate_lock() print 'waiting for connection' cSocket,addr=sSocket.accept() print 'connection from',addr cSocketlock=thread.allocate_lock() thread.start_new_thread(sendData,(cSocket,)) thread.start_new_thread(getData,(cSocket,)) if p==0: sSocket.close() In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Python Contract/Job Opportunity
InfoCentrality are a small company who provided a custom Web/Database application for a customer in the Insurance industry. Our customer now wants a number of improvements to this application. To provide these improvements in a timely manner we need an additional programmer. 3 months contract initially - possibly leading to much more. We use Python, PostgreSQL, Html, Javascript and Linux. Suite a recent Computer Science or Programming graduate. Location - just south of Reading, Berks, UK. Must be able to travel to us. Phone Trevor Hennion on 0845 5083766. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython/wxWidgets ok for production use ?
On Tue, Mar 11, 2008 at 11:01 AM, Stefan Behnel [EMAIL PROTECTED] wrote: Sion Arrowsmith wrote: And before you blame wx* for crashes: what platform was this on? Because my experience was that wx on GTK was significantly more prone to glitches than on Windows (through to wxglade being unusably crashy) -- if the underlying toolkit has problems, that's going to be reflected in wx. :) Interesting. This was actually on GTK. Although I would still blame at least the wxWidgets-GTK bindings here. I never had any problems with GTK in my life. Gtk is much more finicky than windows about the timingof when you can and cannot use certain functions. wxPython has checks in place for many of these functions so you get an exception instead of a crash, but not everything is safe (and of course in the past even fewer things were). In particular, you need to have a wxApp object safely constructed before you can use almost any gui object, which is not the case under Windows. wx makes the attempt to make correct code work correctly on platforms, but doesn't necessarily guarantee that incorrect code fails the same (or at all) on all platforms. This is an unavoidable compromise due to the nature of a layering toolkit like this, although figuring out what correct code actually is can take some experience. Stefan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib proxy support confusion
On 2008-03-11, Mark Dickinson [EMAIL PROTECTED] wrote: That seems a bit baffling. If it urlopen doesn't support specifying proxies, why are there examples showing how to do it? If it does support specifying proxies, what is the pragraph quoted above supposed to mean? Looks like a definite documentation bug to me, and it's still there in the development version of the documentation. I think a bug report should be filed. A little bit of investigation shows that the documentation changes were made in svn revisions 26181 and 26182 ( http://svn.python.org/view?view=revrev=26181 ) as a fix for http://bugs.python.org/issue523415 but this doesn't seem to help much with figuring out what the docs intend to say. Before I submit a bug, I'll give it a try to find out if it does support explicit specification of proxys or not. -- Grant Edwards grante Yow! How many retured at bricklayers from FLORIDA visi.comare out purchasing PENCIL SHARPENERS right NOW?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mar 10, 4:16 am, [EMAIL PROTECTED] wrote: On Mar 9, 4:25 am, Lie [EMAIL PROTECTED] wrote: On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote: To Lie: Personally I preferred a code that has chosen good names but have little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's But I much prefer it that the code has good names AND concise comments, not too short and not too long that it becomes obscure. What do you mean? If 'obscure' is the right word, then it's subjective (from metrics import obscurity?), which means that 10% of the people disagree with you, or 90% do. The end-all be-all, there is no such thing. I don't think it's obscure; I do. Is it? No, there is a point where everyone would say obscure. Such as a simple two integer addition function that have thirty pages of documentation and that have names like: def dosomereallyfunkythings(argumentoneissomethingadded, argumentbisaddinga): blah blah blah blah ... 30 or so pages later... ... Ok, that is the end of it, it's a complex function actually return argumentoneissomethingadded + argumentbisaddinga (remember you don't have access to source code, so you have to decipher the documentation for what the function is about) I prefer to see something like this: def add(a, b): return a + b Even without documentation I'd know immediately what it does from the name (add) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mar 10, 12:08 pm, Nathan Pinno [EMAIL PROTECTED] wrote: How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? Thanks in advance, Nathan P. Factorial algorithm is a very simple and common algorithm, and it's one of the most basic of all recursive algorithm def fact(x): return x * fact(x - 1) That recursive function is very close to the basic definition of factorials, that is x! = x * (x - 1)! If however, you expected x to be a real (float) value, you'd better consider the gamma function as Mark Dickinson pointed out. Wikipedia is a good start to create your gamma function: http://en.wikipedia.org/wiki/Factorial http://en.wikipedia.org/wiki/Gamma_function -- http://mail.python.org/mailman/listinfo/python-list
Exctract GIF comment from image
Hi, simple question: The PIL does not support reading the optional description in GIF Images. http://www.pythonware.com/library/pil/handbook/format-gif.htm After some reasearch I could not find a python solution for this, any suggestions? Thanx, Wingi. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
If you passed an object that has several methods to call (using tuple or list) and you want to handle several softexceptions and ignore some others, you must still pass an empty methods to the one you want to ignore, cluttering the caller's code by significant degree: def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, DO_NOTHING)): if a == 0: raise callback(0) try: a += b except ZeroDivisionError: raise callback(1) if a = 0: raise callback(2) raise callback(3) return a somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, DO_NOTHING)) You misunderstood. I'd pass something like a context-object, which wold look like this: def somefunc(a, b, context=NullContext()): if a == b: context.a_equals_b() Not more clutter than with only one callback. And the NullContext-object would actually serve as documentation on what events the code produces. def toplelevel(): def callback(a, b): if a == b: raise InterruptException() try: work(callback) except InterruptException: pass def work(callback=callback): a = 10 b = 20 callback(a, b) That's why I said most things that can be more cleanly handled by SoftException can usually be handled in other forms, although in a more cluttered way. That could be more cleanly written in SoftException as: def work(): a = 10 b = 20 raise Equal(a, b) def toplevel(): try: work() except Equal, args: a, b = args if a == b: raise InterruptException I totally fail to see where raise Equal(a, b) is less cluttered or not than callback(a, b) Actually, the latter is even less cluttered, misses a raise - if pure number of literals is your metric, that is. If there is a syntax support, you could also make resume able to transfer values: def somefunc(a, b): if a == b: a, b = raise Equal(a, b) def toplevel(): try: somefunc(10, 20) except Equal, args: a, b = args[0], args[1] + 1 resume a, b Sure, you can make all kinds of things, but so far you didn't come up with a comprehensive feature description that just _does_ specify what SEs are and what not. Perhaps you meant: raise_soft(SoftException) cause SoftException() may have side effects if called greedily Nope, I didn't, and it's beside the point. That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: raise_soft(SoftException) break but this makes SoftException must break everytime, which make it lost its original purpose, so you have to add return code to raise_soft whether you want to break it or not: You didn't understand my example. If there is a handler registered, it will be invoked. If not, nothing will be raised. The exact same amount of state-keeping and lookups needs to be done by the SE-implementation. That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: if raise_soft(SoftException): break Compare to: def caller(a, b): if a == b: raise SoftException And this also makes it impossible to have state-changing behavior without some other weirder tricks That's not true. The with add_soft_handler(SoftException, handler): approach (I missed the handrel the first time, sorry) can easily throw an exception to interrupt, like this: def handler(e): if some_condition_on_e(e): raise InterruptException() with add_soft_handler(SoftException, handler): try: work(...) except InterruptException: pass You could also introduce a function def interruptable(fun, *args, **kwargs): try: return fun(*args, **kwargs) except InterruptException: pass to make the code look a bit cleaner - if it fits your usecase, that is of course. I don't say that SoftExceptions can't have semantics that go beyond this. I just don't see a oh-so-compelling use-case that makes things so much better than they are reachable now, without actually much programming. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mar 11, 11:47 pm, Lie [EMAIL PROTECTED] wrote: On Mar 10, 12:08 pm, Nathan Pinno [EMAIL PROTECTED] wrote: How do I factor a number? I mean how do I translate x! into proper Python code, so that it will always do the correct math? Thanks in advance, Nathan P. Factorial algorithm is a very simple and common algorithm, and it's one of the most basic of all recursive algorithm def fact(x): return x * fact(x - 1) As an exercise (actually I forget), I'll let you figure out yourself why the above function doesn't work. There is only one simple line to be added and all's done. Hint: There are two important elements in all recursive algorithm, the catch-all return statement (which I've given you) and the conditioned return statement (which you've got to figure out yourself) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
def fact(x): if x == 1: return 1 # don't forget this else: return x * fact(x - 1) print fact(5) Factorial algorithm is a very simple and common algorithm, and it's one of the most basic of all recursive algorithm def fact(x): return x * fact(x - 1) That recursive function is very close to the basic definition of factorials, that is x! = x * (x - 1)! If however, you expected x to be a real (float) value, you'd better consider the gamma function as Mark Dickinson pointed out. Wikipedia is a good start to create your gamma function: http://en.wikipedia.org/wiki/Factorial http://en.wikipedia.org/wiki/Gamma_function -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining the PyObject * of a class
Cooper, Andrew [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. tjr -- http://mail.python.org/mailman/listinfo/python-list
How to make a Tkinter widget always visible?
Hello, I have a simple Tkinter window with [GO] and [Quit] buttons at the bottom. When I resize the window to be shorter, the first thing to disappear are the buttons, however I want these button to be visible at all times. Is there a way to make sure that these buttons are always visible? Thanks, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Check For SELF Variable Existance
Robert Rawlins [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Thank you Simon, | | I was hoping there would be something as simple as that :-) | class Spam(object): | ... def egg(self): | ... if hasattr(self, 'chips'): print 'got chips!' I strongly suggest that you read Library Reference Ch.2 on builtin functions and types. -- http://mail.python.org/mailman/listinfo/python-list
Re: Exctract GIF comment from image
Hello Wingi, simple question: The PIL does not support reading the optional description in GIF Images. http://www.pythonware.com/library/pil/handbook/format-gif.htm After some reasearch I could not find a python solution for this, any suggestions? Use ImageMagick (www.imagemagick.org), identify -verbose image should have the comments somewhere in the output. There also a python binding to ImageMagick but I have no experience with it. HTH, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Exctract GIF comment from image
2008/3/11, [EMAIL PROTECTED] [EMAIL PROTECTED]: Hi, simple question: The PIL does not support reading the optional description in GIF Images. http://www.pythonware.com/library/pil/handbook/format-gif.htm After some reasearch I could not find a python solution for this, any suggestions? Thanx, Wingi. -- http://mail.python.org/mailman/listinfo/python-list I did a quick thing here, try it and check if it solves the problem for you: import os import sys import struct def extract_comments(giffile): fobj = open(giffile, 'rb') giftype = fobj.read(6) pf = struct.unpack('hhBBB', fobj.read(7))[2] if pf 0x80: pallete_size = 2 (pf 0x07) fobj.read(3 * pallete_size) # finished reading header fsize = os.stat(giffile).st_size while fobj.tell() != fsize: mark = ord(fobj.read(1)) if mark == 0x21: # gif extension label = ord(fobj.read(1)) is_comment = label == 254 # read the extension block blocksize = ord(fobj.read(1)) while blocksize: if is_comment: print fobj.read(blocksize) else: fobj.read(blocksize) blocksize = ord(fobj.read(1)) def main(args): if len(args) 2: print Usage: %s gif file ... % args[0] sys.exit(0) for gif in args[1:]: extract_comments(gif) if __name__ == __main__: main(sys.argv) -- -- Guilherme H. Polo Goncalves -- http://mail.python.org/mailman/listinfo/python-list
XML-SAX parser problem
Hello, Can any one help for error in following code. actually i want to map parent element with child element, but i am unable to do so. here is the code which i am trying for please do reply if iam not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes=NULL): #attributes=None if name == emph3: self.buffer1 = self.inTitle1 = 1 # self.id = attributes[None] elif name == year: self.buffer2 = self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == year: self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name ==emph3: self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 #s # #emph3Jose Joaquin Avila/emph3 #year1929/year # #emph3Yiye Avila/emph3 #year1941/year # #/s -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Tue, 11 Mar 2008 03:14:54 -0700, Lie wrote: Regarding the number of callbacks: you can as well pass an object that has several methods to call. If you passed an object that has several methods to call (using tuple or list) and you want to handle several softexceptions and ignore some others, you must still pass an empty methods to the one you want to ignore, cluttering the caller's code by significant degree: def somefunc(a, b, callback = (DO_NOTHING, DO_NOTHING, DO_NOTHING, DO_NOTHING)): if a == 0: raise callback(0) try: a += b except ZeroDivisionError: raise callback(1) if a = 0: raise callback(2) raise callback(3) return a somefunc(a, b, (callbackzero, DO_NOTHING, callbacktwo, DO_NOTHING)) Yes, you are right that this is a bad idea. But it is a bad idea regardless of whether you use callbacks or SoftExceptions. In your example above, you seem to have accidentally written raise callback when you (probably) meant to just call the callback. That's significant because it shows that replacing the callback is still just as cluttered, and still puts a large burden on somefunc() to perform every test that callers might want to perform. This is a bad idea because you are tightly coupling somefunc() to the specific needs of some arbitrary callers. You should aim to have loose coupling between functions, not tight. Tight coupling should be avoided, not encouraged. In most circumstances, the right place to put the various tests is in the caller, not in somefunc(). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a Tkinter widget always visible?
Miki wrote: Hello, I have a simple Tkinter window with [GO] and [Quit] buttons at the bottom. When I resize the window to be shorter, the first thing to disappear are the buttons, however I want these button to be visible at all times. Is there a way to make sure that these buttons are always visible? There are various ways to do this: you can set the window to be non-resizable, or set a minimum size to it, so that it can't be resized below that level. However, if you allow arbitrary resizing of the window, there's no real way to guarantee that the widgets will be visible at all times. -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Time Zone application after strptime?
M.-A. Lemburg mal at egenix.com writes: On 2008-03-07 22:24, Jim Carroll wrote: It's taken me a couple of hours to give up on strptime with %Z for recognizing time zones... but that still leaves me in the wrong zone: How can I use the PST (or any other time zone name) to adjust dt by the correct number of hours to get it into UTC before storing in MySQL? You could try mxDateTime's parser. It will convert most timezones into UTC for you: from mx.DateTime import * DateTimeFrom('10:29:52 PST, Feb 29, 2008') mx.DateTime.DateTime object for '2008-02-29 18:29:52. 00' at 2afdc7078f50 Unfortunately, mx.DateTime also ignores the time zone. If I parse the PST time, and ask for the result's time zone it gives me my local time zone. I have had some luck with dateutil: import dateutil.parse as p p.parse(10:29:52 Feb 29, 2008 PST) datetime.datetime(2008, 2, 29, 10, 29, 52) and if I hand it a list of time zones, it does the right thing zones = {PST: -8*60*60} p.parse(10:29:52 Feb 29, 2008 PST, tzinfos=zones) datetime.datetime(2008, 2, 29, 10, 29, 52, tzinfo=tzoffset('PST', -28800)) But I cannot figure out how to get dateutil to use the zoneinfo file that it includes in its own package. It has a zoneinfo-2007k.tar.gz right in the package, and a class to parse the binary zoneinfo, but no clear way to get it to parse its own file and use those during the parsing. -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
On Mon, 10 Mar 2008 12:14:40 -0700, [EMAIL PROTECTED] wrote: Common Lisp has two ways of raising: functions error and signal. Python's raise is like CL's error: you end up in the debugger if the exception is not handled. Exceptions that are raised by CL's signal don't have to be caught: if there is no matching except clause the raise statement becomes a pass. Or as Wikipedia states nicely: Conditions are a generalization of exceptions. When a condition arises, an appropriate condition handler is searched for and selected, in stack order, to handle the condition. Conditions which do not represent errors may safely go unhandled entirely; their only purpose may be to propagate hints or warnings toward the user. http://en.wikipedia.org/wiki/Exception_handling#Condition_systems If I had come across signals before now, I would have thought that they were a good idea. But after watching Lie repeatedly argue for tightly coupling functions together using signal-like SoftExceptions, all I can see are the disadvantages. I'm afraid that if Lie's arguments are the best available for such a signaling mechanism, then it's probably a good thing Python doesn't have it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
help regarding xml parser modules
Hello, Can any one help for error in following code. actually i want to map the element name with its data between start and end tag , but i am unable to do so. here is the code which i am trying for please do reply if i am not on right track. import xml.sax.handler class BookHandler(xml.sax.handler.ContentHandler): def __init__(self): self.inTitle1 = 0 self.inTitle2 = 0 self.mapping1 = {} self.mapping2 = {} def startElement(self, name, attributes=NULL): #attributes=None if name == emph3: self.buffer1 = self.inTitle1 = 1 # self.id = attributes[None] elif name == year: self.buffer2 = self.inTitle2 = 1 def characters(self,data): if self.inTitle1 == 1: self.buffer1 += data elif self.inTitle2 == 1: self.buffer2 += data def endElement(self,name): if name == year: self.inTitle2 = 0 self.mapping2[self.name] = self.buffer2 elif name ==emph3: self.inTitle1 =0 self.mapping1[self.name] = self.buffer1 this is an xml file an example #s # #emph3Jose Joaquin Avila/emph3 #year1929/year # #emph3Yiye Avila/emph3 #year1941/year # #/s This is main file import xml.sax import try1 import pprint parser = xml.sax.make_parser() handler = try1.BookHandler() parser.setContentHandler(handler) parser.parse(tp.xml) pprint.pprint(handler.mapping1) pprint.pprint(handler.mapping2) -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining the PyObject * of a class
On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy [EMAIL PROTECTED] wrote: Cooper, Andrew [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining the PyObject * of a class
2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the boilerplate code, but honestly, copy paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon [EMAIL PROTECTED]: On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy [EMAIL PROTECTED] wrote: Cooper, Andrew [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] ... | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a Tkinter widget always visible?
Hello Kevin, Is there a way to make sure that these buttons are always visible? There are various ways to do this: you can set the window to be non-resizable, or set a minimum size to it, so that it can't be resized below that level. However, if you allow arbitrary resizing of the window, there's no real way to guarantee that the widgets will be visible at all times. Thanks. I've set a minimal size to the window. However when I resize it to be shorter, the buttons are hidden while the top frame stays visible. Thanks, -- Miki [EMAIL PROTECTED] http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make a Tkinter widget always visible?
Miki wrote: Hello Kevin, Is there a way to make sure that these buttons are always visible? There are various ways to do this: you can set the window to be non-resizable, or set a minimum size to it, so that it can't be resized below that level. However, if you allow arbitrary resizing of the window, there's no real way to guarantee that the widgets will be visible at all times. Thanks. I've set a minimal size to the window. However when I resize it to be shorter, the buttons are hidden while the top frame stays visible. Please post the code you're using--it will be easier to help if we can see exactly what you are trying. --K -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does my compiler say invalid syntax then highlight...?
On Mar 11, 3:36 am, Duncan Booth [EMAIL PROTECTED] wrote: Mensanator [EMAIL PROTECTED] wrote: On Mar 10, 10:44‹¨«pm, Nathan Pinno [EMAIL PROTECTED] wrote: Why does my compiler say invalid syntax and then highlight the quotation marks in the following code: # This program is to find primes. Needs work. Be fair. Being helpful isn't fair? The OP hadn't managed to figure out why the program wasn't running, so you can't expect him to have got all the bugs out of the code yet. The bug had already been answered. If you fail to implement your premise correctly, you have a bug. It doesn't matter if the code is bug-free if the premise is false. In this case, the premise that he can determine primes this way is false. He will have to abandon the cos() thing, for although it works in theory, he'll never get it to work in practice. Besides, the cos() is a red herring (hint: cos(pi*n)). The problem can be made to work EXACTLY (at least up to z=1) by using rationals (which gmpy supports). His problem is going to take much more than fixing a syntax error. And he only asked about the specific syntax error not the entire solution to his homework. If this is indeed homework, and he's supposed to come up with a factorial algorithm, I seriously doubt the teacher would accept gmpy.fac(z-1), so I assume it isn't. My advice to Nathan would be: 1. If you get a weird syntax error that you don't understand try cutting the code down to just the bit which generates the error. 2. Play around in the interactive interpreter to see what works and what doesn't. 3. If you don't understand why the code doesn't work then get a stuffed toy, cardboard cutout of a person, or the least technical member of your family and explain to them in great detail exactly why the code must (despite error messages to the contrary) be correct. Usually you'll spot the problem half way through the explanation. 4. If you post to this list then post the full error message and traceback. That way we don't have to guess which quotation marks are the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: mulithreaded server
On Mar 11, 9:10 pm, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit [EMAIL PROTECTED] wrote: import socket import sys import thread p=1 PORT=11000 BUFSIZE=1024 def getData(cSocket): global stdoutlock,cSocketlock while True: cSocketlock.acquire() data=cSocket.recv(BUFSIZE) if data=='q': data='client exited' cSocket.close() p=0 cSocketlock.release() stdoutlock.acquire() stdout.write(data) stdoutlock.release() def sendData(cSocket): global stdoutlock,cSocketlock while True: stdoutlock.acquire() data=raw_input('') cSocketlock.acquire_lock() if data=='q': stdout.write('server exited') stdout.release() p=0 cSocket.close() sSocket.send(data) sSocketlock.release() Could it be because `sSocketlock´ here stdout=sys.stdout host='' sSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sSocket.bind((host,PORT,)) sSocket.listen(1) #sSocketlock=thread.allocate_lock() is never bound since the line above here is commented out? stdoutlock=thread.allocate_lock() print 'waiting for connection' cSocket,addr=sSocket.accept() print 'connection from',addr cSocketlock=thread.allocate_lock() thread.start_new_thread(sendData,(cSocket,)) thread.start_new_thread(getData,(cSocket,)) if p==0: sSocket.close() In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. Jean-Paul It's not a traceback error. It's an unhandeled exception..please help -- http://mail.python.org/mailman/listinfo/python-list
Re: What c.l.py's opinions about Soft Exception?
(If there is anything weird that I say, please ignore it since I'm writing this half-sleeping) On Mar 12, 12:00 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: (snip) I totally fail to see where raise Equal(a, b) is less cluttered or not than callback(a, b) Actually, the latter is even less cluttered, misses a raise - if pure number of literals is your metric, that is. You don't just compare by the calling code, you've got to compare also by the surrounding codes. The calling codes in SE might be a little bit messy, but it worths by making the code surrounding it more clean and structured. And anyway, if you used Context Object callback, they will be as messy as each other. If there is a syntax support, you could also make resume able to transfer values: def somefunc(a, b): if a == b: a, b = raise Equal(a, b) def toplevel(): try: somefunc(10, 20) except Equal, args: a, b = args[0], args[1] + 1 resume a, b Sure, you can make all kinds of things, but so far you didn't come up with a comprehensive feature description that just _does_ specify what SEs are and what not. - Exception that aren't handled when no handler exists for it. - It's not a way for notifying errors - It's a way to describe status changes to higher codes - Everything described in the first post Perhaps you meant: raise_soft(SoftException) cause SoftException() may have side effects if called greedily Nope, I didn't, and it's beside the point. Then what happen when SoftException is called? And a side-effect occurs? That could be done, but when raise_soft() returns, it returns to the code that raises it so it must be 'break'en: def caller(a, b): if a == b: raise_soft(SoftException) break but this makes SoftException must break everytime, which make it lost its original purpose, so you have to add return code to raise_soft whether you want to break it or not: You didn't understand my example. If there is a handler registered, it will be invoked. If not, nothing will be raised. The exact same amount of state-keeping and lookups needs to be done by the SE-implementation. I do understand your example. And even if I misunderstood you about passing context object, the same problem still exists in context object based solution, i.e. functions can't make the called function break automatically, it must be 'break' manually or the program will go astray (break == return, sorry I confused it with break for loops). And if you used InterruptException to break, it doesn't play well with multiple SoftExceptions. The final, resulting code by function passing below is extremely messy, see if you can make it cleaner and with the same functionalities and all to the SE version. def called(a, b, cont_obj = Null_CO): if a == b: a, b = cont_obj.a_equal_b(a, b) cont_obj.addition(a, b) return a + b def caller(): class cont_obj(object): def a_equal_b(a, b): if a 0 and b 0: return a + 1, b # resume raise InterruptException(('a_e_b',)) # break def addition(a, b): if a b: return raise InterruptException(('addit', (a, b))) # break try: called(10, 10, cont_obj) except InterruptException, args: # if breaken ret, arg = args if ret == 'a_e_b': return -1 a, b = arg if ret == 'addit': return a ** b # by adding try clauses, and you've really equalize the biggest overhead of SE. # And I don't think you could create a less messy InterruptException handler, # the other solution to it would be to create a handler for each unique returns # but that would make it exceed the second SE overhead, the Exception Declaration # In other words, the tricks that is used to emulate the SoftException would all # have higher code overhead compared to using the clean, structured SEs # * Overheads means garbage code that's important to make something work # The code is separated into three parts, try except, and cont_obj, and called. Worse, the cont_obj can't determine what happen if they got unresumed errors, without using some tricky part. Compare that code above with: def called(a, b): if a == b: a, b = raise a_equal_b(a, b) raise addition(a, b) return a + b def caller(): class a_equal_b(Exception): pass class addition(Exception): pass try: ret = called(10, 10) except a_equal_b(a, b): if a 0 and b 0: resume a + 1, b return -1 except addition(a, b): if a b: resume return a ** b # The code is separated into two parts, the trys and excepts and the called code. That
Re: mulithreaded server
In article [EMAIL PROTECTED], asit [EMAIL PROTECTED] wrote: On Mar 11, 9:10 pm, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On Tue, 11 Mar 2008 08:24:54 -0700 (PDT), asit [EMAIL PROTECTED] wrote: In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. It's not a traceback error. It's an unhandeled exception..please help http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mar 11, 11:31 am, Lie [EMAIL PROTECTED] wrote: On Mar 10, 4:16 am, [EMAIL PROTECTED] wrote: On Mar 9, 4:25 am, Lie [EMAIL PROTECTED] wrote: On Mar 9, 3:27 am, [EMAIL PROTECTED] wrote: To Lie: Personally I preferred a code that has chosen good names but have little or no comments compared to codes that makes bad names and have Personally I don't. Show me a good one. Until you do, it's not that I won't like it, it's that I can't. You know, in linguistics, there's But I much prefer it that the code has good names AND concise comments, not too short and not too long that it becomes obscure. What do you mean? If 'obscure' is the right word, then it's subjective (from metrics import obscurity?), which means that 10% of the people disagree with you, or 90% do. The end-all be-all, there is no such thing. I don't think it's obscure; I do. Is it? No, there is a point where everyone would say obscure. But not on all code. Comments can obscure code, and code can too. Here's a snip from the docs: # p2cwrite ---stdin--- p2cread # c2pread--stdout--- c2pwrite # errread--stderr--- errwrite Is c2pread more or less obscure than c2pr or chi2parread? If there's an objective metric of the degree of something's obscurity (obscured- ity), then that has an answer. Is it a scalar, or if not, is there abs( answer )? Does that comment obscure the later code? Are 'in' and 'out' more or less obscure than those? (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) Information design can get (*subjective) breathtaking, but if you see a potential improvement, you should always be able to make it. Tell me what you think of this simile: Sometimes Steve Chessmaster reads board positions, sometimes prose. Some of the prose is less obscure, -to- -him-, than board states. To someone with a different speciality, as in bishops vs. knights, endgame vs. openings, certain forks, the states are less obscure than the corresponding prose. To my fmr. A.I. professor, The minimax A*, and The beaten path A* are plenty clear. He can say what they do. Can you? (remember you don't have access to source code, so you have to decipher the documentation for what the function is about) But you're still calling it? I prefer to see something like this: def add(a, b): return a + b Even without documentation I'd know immediately what it does from the name (add). What if the word is generic? Do you know if it has a return value? -- http://mail.python.org/mailman/listinfo/python-list
Re: mulithreaded server
In the above program, why there is an unhandeled exception ??? Just a guess. You should really include the traceback when you ask a question like this. It's not a traceback error. It's an unhandeled exception. Have a look at this: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5cbf90133a6ffaca/ It gives you a console with several threads running that you send functions to call to. Then it connects to a socket on one of them, serving on the other. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to factor using Python?
On Mar 11, 10:57 am, Mike Hansen [EMAIL PROTECTED] wrote: If one wants to do serious math using Python, the best bet is to use Sage (http://www.sagemath.org). Here are some examples: sage: def f(x, bits=53): : R = RealField(bits); z = R(x) : return cos(R(pi) * factorial(z-1) / z) sage: f(100.00,bits=1000) 0.999999992343 If one wants to do serious math using Python, it would be even better to understand the math before breaking out Sage. Didn't you realize that cos(pi*n) is a red herring? That you only need to know if the rational factorial(z-1)/z has a denominator 1 (although you have to make allowances when it's 2)? 2 Prime: True True Prime: True 1/2 3 Prime: True True Prime: True 2/3 4 Prime: FalseTrue Prime: False 3/2 5 Prime: True True Prime: True 24/5 6 Prime: FalseTrue Prime: False 20 7 Prime: True True Prime: True 720/7 8 Prime: FalseTrue Prime: False 630 9 Prime: FalseTrue Prime: False 4480 10 Prime: FalseTrue Prime: False 36288 11 Prime: True True Prime: True 3628800/11 12 Prime: FalseTrue Prime: False 3326400 13 Prime: True True Prime: True 479001600/13 14 Prime: FalseTrue Prime: False 444787200 15 Prime: FalseTrue Prime: False 5811886080 16 Prime: FalseTrue Prime: False 81729648000 17 Prime: True True Prime: True 20922789888000/17 18 Prime: FalseTrue Prime: False 19760412672000 19 Prime: True True Prime: True 6402373705728000/19 sage: a = 50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749 sage: time ecm.factor(a) CPU times: user 0.00 s, sys: 0.06 s, total: 0.06 s Wall time: 2.63 [3478697, 49998841, 11927295803, 518069464441, 1858900129817, 161610704597143, 157394131396743433859615518992811454816816449] sage: a = ZZ.random_element(10**100); a 1266081670515546883639925088390407903294616094325617831128683357589913968497538978358203322629420841 sage: a.is_prime() False sage: b = a.next_prime(); b 8975665868645752218769838623717890808871334875974244952657480072373614614471639002293590745490978883 sage: b.is_prime() True --Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib proxy support confusion
On Mar 11, 12:26 pm, Grant Edwards [EMAIL PROTECTED] wrote: Before I submit a bug, I'll give it a try to find out if it does support explicit specification of proxys or not. Sounds good. If it does, then I think the whole paragraph (from The urlopeen() function does not support explicit proxy ... to ...subclass such as FancyURLopener.) should just be removed. Looking at the source, there are some slight oddities: a plain urlopen() caches the URLopener instance it creates (in a module-level global) and uses this cached instance in future calls to urlopen or urlretrieve. If proxies are specified then it doesn't do the caching. I don't *think* this really affects usage, except that there are presumably some inefficiencies involved in multiple uses of urlopen with explicitly specified proxies, and those inefficiencies can be overcome by using URLopener or FancyURLopener directly instead. And it doesn't make a lot of sense that urlopen accepts proxies, but urlretrieve does not. But that's a different issue... Mark -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Python 2.3.7 and 2.4.5 (final)
On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.5 and 2.3.7 (final). Both releases include only security fixes. Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.3 or 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of bugs fixed; most of them prevent interpreter crashes (and now cause proper Python exceptions in cases where the interpreter may have crashed before). Since the release candidate, we received various reports that the this release may fail to build on current operating systems, in particular on OS X. We have made no attempt to fix these problems, as the release is targeted for systems that were current at the time Python 2.4 was originally released. For more recent systems, you might have to come up with work-arounds. For OS X in particular, try invoking:: ./configure MACOSX_DEPLOYMENT_TARGET=10.5 We have made no changes since the release candidate (except for the version numbers). For more information on Python 2.3.7 and 2.4.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.7 http://www.python.org/2.4.5 Highlights of the previous major Python releases are available from the Python 2.4 page, at http://www.python.org/2.3/highlights.html http://www.python.org/2.4/highlights.html Enjoy this release, Martin Martin v. Loewis [EMAIL PROTECTED] Python Release Manager (on behalf of the entire python-dev team) -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with zipfile and newlines
Sorry my initial post was muddled. Let me try again. I've got a zipped archive that I can extract files from with my standard archive unzipping program, 7-zip. I'd like to extract the files in python via the zipfile module. However, when I extract the file from the archive with ZipFile.read(), it isn't the same as the 7- zip-extracted file. For text files, the zipfile-extracted version has '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't tried comparing binary files via the two extraction methods yet. Regarding the code I posted; I was writing it from memory, and made a mistake. I didn't use: z = zipfile.ZipFile(open('foo.zip', 'r')) I used this: z = zipfile.ZipFile('foo.zip') But Duncan's comment was useful, as I generally only ever work with text files, and I didn't realise you have to use 'rb' or 'wb' options when reading and writing binary files. To answer John's questions - I was calling '\r' a newline. I should have said carriage return. I'm not sure what operating system the original zip file was created on. I didn't fiddle with the extracted file contents, other than replacing '\r' with ''. I wrote out all the files with open('outputfile','w') - I seems that I should have been using 'wb' when writing out the binary files. Thanks for the quick responses - any ideas why the zipfile-extracted files and 7-zip-extracted files are different? On Mar 10, 9:37 pm, John Machin [EMAIL PROTECTED] wrote: On Mar 10, 11:14 pm, Duncan Booth [EMAIL PROTECTED] wrote: Neil Crighton [EMAIL PROTECTED] wrote: I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances of '\r' in the extracted file seems to fix the problem, but I can't find an easy solution for binary files. The code I'm using is something like: from zipfile import Zipfile z = Zipfile(open('zippedfile.zip')) extractedfile = z.read('filename_in_zippedfile') I'm using Python version 2.5. Has anyone else had this problem before, or know how to fix it? Thanks, Zip files aren't text. Try opening the zipfile file in binary mode: open('zippedfile.zip', 'rb') Good pickup, but that indicates that the OP may have *TWO* problems, the first of which is not posting the code that was actually executed. If the OP actually executed the code that he posted, it is highly likely to have died in a hole long before it got to the z.read() stage, e.g. import zipfile z = zipfile.ZipFile(open('foo.zip')) Traceback (most recent call last): File stdin, line 1, in module File C:\python25\lib\zipfile.py, line 346, in __init__ self._GetContents() File C:\python25\lib\zipfile.py, line 366, in _GetContents self._RealGetContents() File C:\python25\lib\zipfile.py, line 404, in _RealGetContents centdir = struct.unpack(structCentralDir, centdir) File C:\python25\lib\struct.py, line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 46 z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK z = zipfile.ZipFile('foo.zip', 'r') # OK If it somehow made it through the open stage, it surely would have blown up at the read stage, when trying to decompress a contained file. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
RE: Obtaining the PyObject * of a class
I'd strongly disagree. SWIG is very useful for wrapping large scale projects in a non-interfering manner. If you have to generate bindings for 1000+ classes, it is by far the easiest way to do things. It isn't clear what you are doing that requires the PyObject*, or which one you'd like. In general, the output one is found in $result, and $input is input PyObject for that typemap. From: Michael Wieher [mailto:[EMAIL PROTECTED] Sent: Tuesday, March 11, 2008 3:09 PM To: python-list@python.org Subject: Re: Obtaining the PyObject * of a class 2 things: 1st. there is a python mailing list for people interested in C++ extension type stuff 2nd. SWIG is useless and overly complicated, its much easier to just generate your own C++ code by hand, less confusion, and much more clarity. I find no value in using anything else. People complain about the boilerplate code, but honestly, copy paste, change three characters, and you're done. And you know exactly what is happening, how when and why. 2008/3/11, Chris Mellon [EMAIL PROTECTED]: On Tue, Mar 11, 2008 at 12:13 PM, Terry Reedy [EMAIL PROTECTED] wrote: Cooper, Andrew [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Are there any Python C API experts/SWIG experts out there that can help | me with this issue please. | I',m currently using SWIG to generate a python interface to a C DLL. Some people have switched to using ctypes for this, and many other SWIG users have stopped reading clp. But I hope someone answers who can. Using Pyrex or Cython is likely to be much easier than using SWIG for this. -- http://mail.python.org/mailman/listinfo/python-list - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - This message is intended only for the personal and confidential use of the designated recipient(s) named above. If you are not the intended recipient of this message you are hereby notified that any review, dissemination, distribution or copying of this message is strictly prohibited. This communication is for information purposes only and should not be regarded as an offer to sell or as a solicitation of an offer to buy any financial product, an official confirmation of any transaction, or as an official statement of Lehman Brothers. Email transmission cannot be guaranteed to be secure or error-free. Therefore, we do not represent that this information is complete or accurate and it should not be relied upon as such. All information is subject to change without notice. IRS Circular 230 Disclosure: Please be advised that any discussion of U.S. tax matters contained within this communication (including any attachments) is not intended or written to be used and cannot be used for the purpose of (i) avoiding U.S. tax related penalties or (ii) promoting, marketing or recommending to another party any transaction or matter addressed herein. -- http://mail.python.org/mailman/listinfo/python-list
Re: any library for SOAP 1.1 or SOAP 1.2?
On Fri, 2008-01-25 at 16:52 +0530, Amogh Hooshdar wrote: Hi, I wish to know which python library is popular for SOAP related programming, especially for sending SOAP requests and parsing SOAP responses. I can't find any such library in the Python standard library but I could find ZSI and soap.py libraries. However, ZSI does not support SOAP 1.2. Does anyone know about a library that supports SOAP 1.2 also? Support for SOAP 1.2 is on the ZSI wishlist. It may not happen until you and I do it. Have you found anything else? Are you using ZSI? -- http://mail.python.org/mailman/listinfo/python-list
SOAP access to SharePoint
Has anyone successfully accessed a Microsoft SharePoint WSS using Python? No, not IronPython. I need for this to be able to run on all machines the customer might choose. Which libs are you using? ZSI, SOAPpy, soaplib, ??? http://wiki.python.org/moin/WebServices -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with zipfile and newlines
I think I've worked it out after reading the 'Binary mode for files' section of http://zephyrfalcon.org/labs/python_pitfalls.html zipfile extracts as file as a binary series of characters, and I'm writing out this binary file as a text file with open('foo','w'). Normally Python converts a '\n' in a text file to whatever the platform-dependent indication of a new line is ('\n' on Unix, '\r\n' on Windows, '\r' on Macs). So it sees '\r\n' in the binary file and converts it to '\r\r\n' for the text file. The upshot of this is that writing out the zipfile-extracted files with open('foo','wb') instead of open('foo','w') solves my problem. On Mar 11, 8:43 pm, [EMAIL PROTECTED] wrote: Sorry my initial post was muddled. Let me try again. I've got a zipped archive that I can extract files from with my standard archive unzipping program, 7-zip. I'd like to extract the files in python via the zipfile module. However, when I extract the file from the archive with ZipFile.read(), it isn't the same as the 7- zip-extracted file. For text files, the zipfile-extracted version has '\r\n' everywhere the 7-zip-extracted file only has '\n'. I haven't tried comparing binary files via the two extraction methods yet. Regarding the code I posted; I was writing it from memory, and made a mistake. I didn't use: z = zipfile.ZipFile(open('foo.zip', 'r')) I used this: z = zipfile.ZipFile('foo.zip') But Duncan's comment was useful, as I generally only ever work with text files, and I didn't realise you have to use 'rb' or 'wb' options when reading and writing binary files. To answer John's questions - I was calling '\r' a newline. I should have said carriage return. I'm not sure what operating system the original zip file was created on. I didn't fiddle with the extracted file contents, other than replacing '\r' with ''. I wrote out all the files with open('outputfile','w') - I seems that I should have been using 'wb' when writing out the binary files. Thanks for the quick responses - any ideas why the zipfile-extracted files and 7-zip-extracted files are different? On Mar 10, 9:37 pm, John Machin [EMAIL PROTECTED] wrote: On Mar 10, 11:14 pm, Duncan Booth [EMAIL PROTECTED] wrote: Neil Crighton [EMAIL PROTECTED] wrote: I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances of '\r' in the extracted file seems to fix the problem, but I can't find an easy solution for binary files. The code I'm using is something like: from zipfile import Zipfile z = Zipfile(open('zippedfile.zip')) extractedfile = z.read('filename_in_zippedfile') I'm using Python version 2.5. Has anyone else had this problem before, or know how to fix it? Thanks, Zip files aren't text. Try opening the zipfile file in binary mode: open('zippedfile.zip', 'rb') Good pickup, but that indicates that the OP may have *TWO* problems, the first of which is not posting the code that was actually executed. If the OP actually executed the code that he posted, it is highly likely to have died in a hole long before it got to the z.read() stage, e.g. import zipfile z = zipfile.ZipFile(open('foo.zip')) Traceback (most recent call last): File stdin, line 1, in module File C:\python25\lib\zipfile.py, line 346, in __init__ self._GetContents() File C:\python25\lib\zipfile.py, line 366, in _GetContents self._RealGetContents() File C:\python25\lib\zipfile.py, line 404, in _RealGetContents centdir = struct.unpack(structCentralDir, centdir) File C:\python25\lib\struct.py, line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 46 z = zipfile.ZipFile(open('foo.zip', 'rb')) # OK z = zipfile.ZipFile('foo.zip', 'r') # OK If it somehow made it through the open stage, it surely would have blown up at the read stage, when trying to decompress a contained file. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list