Re: Detect string has non-ASCII chars without checking each char?
Hi! Another way : # -*- coding: utf-8 -*- import unicodedata def test_ascii(struni): strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') if len(struni)==len(strasc): return True else: return False print test_ascii(u"abcde") print test_ascii(u"abcdê") @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 21, 1:33 am, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > > Most programmers probably never use vectors and matrices, so they don't > > care about the inconsistency with standard mathematical notation. > > Perhaps you should ask the numpy programmers what they think about that. Why would I care in the least about something called "numpy"? > Vectors and matrices are just arrays, and the suggestion that most > programmers don't use arrays (or array-like objects like lists) is > ludicrous. But the vast majority of arrays are not vectors or matrices in the mathematical sense. And the vast majority of programmers who use arrays have no clue about vectors and matrices in the mathematical sense. Ask your typical programmer what an SVD is. > > And yes, I understand that zero-based indexing can be slightly more > > efficient. That's why I think it's appropriate for low-level languages > > such as C. However, I think one-based indexing is more appropriate for > > high-level languages. > > Only if your aim is to reduce the learning curve for newbies and non- > programmers, at the expense of making it easier for them to produce buggy > code. If you're suggesting that one-based indexing makes it easier to produce buggy code, I think you must be smoking something. > That's a defensible choice. I'm a great fan of Apple's Hypercard from the > late 80s and early 90s, and it used one-based indexing, as well as > English-like syntax like: Python is a high level language, and high-level languages have many features that make it easier for newbies as well as experienced programmers at the expense of extreme efficiency. But the array indexing in Python is a throwback to C: it is zero-based and uses square brackets. Say what you will, but both of those aspects just seem wrong and awkward to me. However, I've switched from Python to Scala, so I really don't care. You guys can have it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem checking an existing browser cookie
On 16 Αύγ, 14:31, Peter Otten <__pete...@web.de> wrote: > Νίκος wrote: > > # initializecookie > >cookie=Cookie.SimpleCookie() > >cookie.load( os.environ.get('HTTP_COOKIE', '') ) > > mycookie =cookie.get('visitor') > > > if ( mycookie and mycookie.value != 'nikos' ) or re.search( r'(cyta| > > yandex|13448|spider|crawl)', host ) is None: > > blabla... > > > > > I checked and Chrome has acookienames visitor with a value ofnikos > > within. > > So, i have to ask why the if fails? > > Maybe it's because != != == Iwant ti if code block to be executed only if the browser cookie names visitor fetched doesnt cotnain the vbalue of 'nikos' Is there somethign wrong with the way i wrote it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > On Aug 21, 1:33 am, Steven D'Aprano cybersource.com.au> wrote: >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: >> > Most programmers probably never use vectors and matrices, so they don't >> > care about the inconsistency with standard mathematical notation. >> >> Perhaps you should ask the numpy programmers what they think about that. > > Why would I care in the least about something called "numpy"? Because it's a popular matrix math package for Python. Its users are thus a subset of programmers which by definition don't fall into the "most programmers" group you describe. Cheers, Chris -- Google is your friend! http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
freq function
Here is a function which takes any list and creates a freq table, which can be printed unsorted, sorted by cases or items. It's supposed to mirror the proc freq in SAS. Dirk def freq(seq,order='unsorted',prin=True): #order can be unsorted, cases, items freq={} for s in seq: if s in freq: freq[s]+=1 else: freq[s]=1 if prin==True: print 'Items=',len(seq),'Cases=',len(freq) print '' if order=='unsorted': for k in freq.keys(): print k,freq[k],float(freq[k])/len(seq) elif order=='cases': #http://blog.client9.com/2007/11/sorting-python-dict-by- value.html freq2=sorted(freq.iteritems(), key=lambda (k,v): (v,k),reverse=True) for f in freq2: print f[0],f[1],float(f[1])/len(seq) elif order=='items': for k in sorted(freq.iterkeys()): print k,freq[k],float(freq[k])/len(seq) print '' return freq #test import random rand=[] for i in range(1): rand.append(str(int(100*random.random( fr=freq(rand) fr2=freq(rand,order='items') fr2=freq(rand,order='cases') -- http://mail.python.org/mailman/listinfo/python-list
Re: freq function
On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): >#order can be unsorted, cases, items > >freq={} >for s in seq: >if s in freq: >freq[s]+=1 >else: >freq[s]=1 > The above code can be replaced with this: freq = {} for s in seqn: freq[s] = freq.get(s,0) + 1 >if prin==True: >print 'Items=',len(seq),'Cases=',len(freq) >print '' >if order=='unsorted': >for k in freq.keys(): >print k,freq[k],float(freq[k])/len(seq) >elif order=='cases': >#http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html >freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) >for f in freq2: >print f[0],f[1],float(f[1])/len(seq) >elif order=='items': >for k in sorted(freq.iterkeys()): >print k,freq[k],float(freq[k])/len(seq) >print '' >return freq > > #test > > import random > > rand=[] > for i in range(1): >rand.append(str(int(100*random.random( > > fr=freq(rand) > fr2=freq(rand,order='items') > fr2=freq(rand,order='cases') > -- > I feel the code you wrote is bloated a bit. You shall definately give another try to improvise it. > http://mail.python.org/mailman/listinfo/python-list > -- ~l0nwlf -- http://mail.python.org/mailman/listinfo/python-list
Re: freq function
On Sun, Aug 22, 2010 at 1:16 AM, Shashwat Anand wrote: > On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar wrote: >> Here is a function which takes any list and creates a freq table, >> which can be printed unsorted, sorted by cases or items. It's supposed >> to mirror the proc freq in SAS. >> >> Dirk >> >> freq={} >> for s in seq: >> if s in freq: >> freq[s]+=1 >> else: >> freq[s]=1 > > The above code can be replaced with this: > freq = {} > for s in seq: > freq[s] = freq.get(s,0) + 1 Which can be further replaced by: from collections import Counter freq = Counter(seq) Using collections.defaultdict is another possibility if one doesn't have Python 2.7. Cheers, Chris -- It really bothers me that Counter isn't a proper Bag. http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Running python script before user login
I have wrote a python script and want to run it before user login. To do that, I have added it to the ubuntu startup file (init.d). However it seems that the script doesn't work. I want to know does python modules work before user login? // Naderan *Mahmood; -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list
how to use xdrlib
Hi there, I am trying to understand how xdrlib works as I want to read files in this format. The problem is I don't much about xdr (although I read http://docs.python.org/library/xdrlib.html and RFC 1832). Another problem is I don't know how the file I want to read was encoded. So when I do something like: import xdrlib f = open('file.xdr').read() data = xdrlib.Unpacker(f) Then, I don't know which "unpack_*" to use. If I use, repr(data.unpack_string()) sometimes it returns something meaningful like: "'Ryckaert-Bell.'" but other times, '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bProper Dih.\x00' if not a error. Well, as you see, I am a bit lost here and any hint would be very appreciated. Thanks in advance, Alan -- Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate Department of Biochemistry, University of Cambridge. 80 Tennis Court Road, Cambridge CB2 1GA, UK. >>http://www.bio.cam.ac.uk/~awd28<< -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
>Specify exactly how it's not working. I have wrote a script to send my ip address to an email address. It does work when I am login (python sendip.py). I then followed the procedure in https://help.ubuntu.com/community/RcLocalHowto. However after restart, no email is sent. // Naderan *Mahmood; From: Chris Rebert To: Mahmood Naderan Cc: python mailing list Sent: Sun, August 22, 2010 1:28:45 PM Subject: Re: Running python script before user login On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > I have wrote a python script and want to run it before user login. To do > that, I have added it to the ubuntu startup file (init.d). However it seems > that the script doesn't work. Specify exactly how it's not working. Cheers, Chris -- More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list
Wrong unichr docstring in 2.7
I think there is a small point here. >>> sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] >>> print unichr.__doc__ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10. >>> # but >>> unichr(0x10fff) Traceback (most recent call last): File "", line 1, in ValueError: unichr() arg not in range(0x1) (narrow Python build) Note: I find 0x0 <= i <= 0x more logical than 0 <= i <= 0x (orange-apple comparaison) Ditto, for Python 2.6.5 Regards, jmf -- http://mail.python.org/mailman/listinfo/python-list
CodeSnipr Learning can be simple!!
Hi, All the group members right at here, we people recently lunched a website CodeSnipr based on Computer language like (PHP, RUBBY, HTML, CSS, MYSQL, JQURY, IPHONE DEVELOPMENT, JAVASCRIPT, C++,.NET,XML,C# etc.). CodeSnipr will provide you access to user generated tutorials. Here you can post your code snippet and learn from other's snippet. We believe learning can be simple. We want your feedback about this tutorial please visit to join this : http://www.codesnipr.com/. -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrong unichr docstring in 2.7
On Sunday 22 August 2010, it occurred to jmfauth to exclaim: > I think there is a small point here. > > >>> sys.version > > 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] > > >>> print unichr.__doc__ > > unichr(i) -> Unicode character > > Return a Unicode string of one character with ordinal i; 0 <= i <= > 0x10. > > >>> # but > >>> unichr(0x10fff) > > Traceback (most recent call last): > File "", line 1, in > ValueError: unichr() arg not in range(0x1) (narrow Python > build) This is very tricky ground. I consider the behaviour of unichr() to be wrong here. The user shouldn't have to care much about UTF-16 and the difference between wide and narrow Py_UNICODDE builds. In fact, in Python 3.1, this behaviour has changed: on a narrow Python 3 build, chr(0x10fff) == '\ud803\udfff' == '\U00010fff'. Now, the Python 2 behaviour can't be fixed [1] -- it was specified in PEP 261 [2], which means it was pretty much set in stone. Then, it was deemed more important for unichr() to always return a length-one string that for it to work with wide characters. And then add pretty half-arsed utf-16 support... The doc string could be changed for narrow Python builds. I myself don't think docstrings should change depending on build options like this -- it could be amended to document the different behaviours here. Note that the docs [3] already include this information. If you want to, feel free to report a bug at http://bugs.python.org/ > Note: > > I find > 0x0 <= i <= 0x > more logical than > 0 <= i <= 0x > > (orange-apple comparaison) Would a zero by any other name not look as small? Honestly, I myself find it nonsensical to qualify 0 by specifying a base, unless you go all the way and represent the full uint16_t by saying 0x <= i <= 0x - Thomas [1] http://bugs.python.org/issue1057588 [2] http://www.python.org/dev/peps/pep-0261/ [3] http://docs.python.org/library/functions.html#unichr -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrong unichr docstring in 2.7
jmfauth wrote: I think there is a small point here. sys.version 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] print unichr.__doc__ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10. # but unichr(0x10fff) Traceback (most recent call last): File "", line 1, in ValueError: unichr() arg not in range(0x1) (narrow Python build) Note: I find 0x0 <= i <= 0x more logical than 0 <= i <= 0x (orange-apple comparaison) Ditto, for Python 2.6.5 Regards, jmf There are two variants that CPython can be compiled for, 16 bit Unicode and 32 bit. By default, the Windows implementation uses 16 bits, and the Linux one uses 32. I believe you can rebuild your version if you have access to an appropriate version MSC compiler, but I haven't any direct experience. At any rate, the bug here is that the docstring doesn't get patched to match the compile switches for your particular build of CPython. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use xdrlib
On Sunday 22 August 2010, it occurred to Alan Wilter Sousa da Silva to exclaim: > Hi there, > > I am trying to understand how xdrlib works as I want to read files in this > format. The problem is I don't much about xdr (although I read > http://docs.python.org/library/xdrlib.html and RFC 1832). > > Another problem is I don't know how the file I want to read was encoded. > > So when I do something like: > > import xdrlib > > f = open('file.xdr').read() > data = xdrlib.Unpacker(f) > > Then, I don't know which "unpack_*" to use. If you actually have read RFC 1832, then this surprises me: as far as I can see, and I have only skimmed the RFC so I may be wrong, it includes no way to specify the type of a piece of data -- you have to know what you're reading. > > If I use, > > repr(data.unpack_string()) > > sometimes it returns something meaningful like: > > "'Ryckaert-Bell.'" This happens when the data was actually a string -- so you correctly used unpack_string > > but other times, > > '\x00\x00\x00\x04Bond\x00\x00\x00\x05Angle\x00\x00\x00\x00\x00\x00\x0bPrope > r Dih.\x00' Here, you read data that was not originally a string as if it were one. What the xdrlib module did is: it read four bytes. Probably 00 00 00 24. And it interpreted these to be the length of the string you're trying to read. Actually, you probably should have read an int first. After that, you could have called unpack_string, which would have read in 00 00 00 04 -- aha, a four-long string -- and then read another four bytes, the actual string: "Bond". Similarly, "Angle" has length 0x0005, it's followed by padding unto 4-byte margins, followed by the length of "Proper Dih.", which happens to be 0x000b. > > if not a error. That might happen if the number xdrlib interprets as the string length is larger than the length of the rest of the file. > > Well, as you see, I am a bit lost here and any hint would be very > appreciated. Basically, you have to know which file format you're dealing with, and use the right unpack functions in the correct order for the specific file you're dealing with. So you need some documentation for the file format you're using -- XDR (like Microsoft's StructuredStorage, or even XML) doesn't as of itself make any claims about the nature or structure of the data it holds. Cheers, - Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list
ANN: warehouse Objects in SQLite : y_serial module
Module download at SourceForge http://yserial.sourceforge.net Documentation has been revised and v0.60 released. Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data. The module is instructive in the way it unifies the standard batteries: sqlite3 (as of Python v2.5), zlib (for compression), and cPickle (for serializing objects). If your Python program requires data persistance, then y_serial is a module which should be worth importing. All objects are warehoused in a single database file in the most compressed form possible. Tables are used to differentiate projects. Steps for insertion, organization by annotation, and finally retrieval are amazingly simple... y_serial.py module :: warehouse Python objects with SQLite http://yserial.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect string has non-ASCII chars without checking each char?
On Aug 22, 5:07 pm, "Michel Claveau - MVP" wrote: > Hi! > > Another way : > > # -*- coding: utf-8 -*- > > import unicodedata > > def test_ascii(struni): > strasc=unicodedata.normalize('NFD', struni).encode('ascii','replace') > if len(struni)==len(strasc): > return True > else: > return False > > print test_ascii(u"abcde") > print test_ascii(u"abcdê") -1 Try your code with u"abcd\xa1" ... it says it's ASCII. Suggestions: test_ascii = lambda s: len(s.decode('ascii', 'ignore')) == len(s) or test_ascii = lambda s: all(c < u'\x80' for c in s) or use try/except Also: if a == b: return True else: return False is a horribly bloated way of writing return a == b -- http://mail.python.org/mailman/listinfo/python-list
trying to use sdl_pango with python
i'm new to ctypes. can someone help me use sdl_pango with python? here's the documentation: http://sdlpango.sourceforge.net/ here's my code: - import pygame from ctypes import * import win32api MATRIX_TRANSPARENT_BACK_WHITE_LETTER = c_char_p("\xFF\xFF\0\0\xFF\xFF \0\0\xFF\xFF\0\0\0\xFF\0\0") margin_x = margin_y = 10 def sdlwrite(rtext, width, height=None): context = sdlpango.SDLPango_CreateContext() sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) sdlpango.SDLPango_SetMinimumSize(context, width, height) sdlpango.SDLPango_SetMarkup(context, rtext, -1) w = sdlpango.SDLPango_GetLayoutWidth(context) h = sdlpango.SDLPango_GetLayoutHeight(context) surface = sdl.SDL_CreateRGBSurface(sdlpango.SDL_SWSURFACE, w + margin_x, h + margin_y, 32, 255 << (8*3), 255 << (8*2), 255 << (8*1), 255) sp = POINTER(surface) sdlpango.SDLPango_Draw(context, ps, margin_x, margin_y) sdl.SDL_FreeSurface(ps) return context def surfwrite(rtext, width, height=None): sdlcontext = sdlwrite(rtext, width, height) print 'sdlcontext:', sdlcontext #scr = pygame.set_mode() #rloss, gloss, bloss, aloss = scr. sdlpango = windll.LoadLibrary(r"C:\projects\soundshop\pango-1.18.3\bin \sdl_pango.dll") sdl = windll.LoadLibrary(r"sdl.dll") #sdlpango.SDLPango_SetDefaultColor.argtypes = [c_void_p, c_char_p] #sdlpango.SDLPango_SetMinimumSize.argtypes = [c_void_p, c_int, c_int] #sdlpango.SDLPango_SetMarkup.argtypes = [c_void_p, c_char_p, c_int] #sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_void_p] #sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_void_p] #sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] #sdlpango.SDLPango_Draw.argtypes = [c_void_p, c_uint, c_int, c_int] #sdl.SDL_FreeSurface.argtypes = [c_void_p] sdlpango.SDLPango_SetDefaultColor.argtypes = [c_uint, c_uint] sdlpango.SDLPango_SetMinimumSize.argtypes = [c_uint, c_int, c_int] sdlpango.SDLPango_SetMarkup.argtypes = [c_uint, c_char_p, c_int] sdlpango.SDLPango_GetLayoutWidth.argtypes = [c_uint] sdlpango.SDLPango_GetLayoutHeight.argtypes = [c_uint] sdl.SDL_CreateRGBSurface.argtypes = [c_uint, c_int, c_int, c_int, c_uint, c_uint, c_uint, c_uint] sdlpango.SDLPango_Draw.argtypes = [c_uint, c_uint, c_int, c_int] sdl.SDL_FreeSurface.argtypes = [c_uint] surfwrite("hello", 640) - here's the .h file that i got MATRIX_TRANSPARENT_BACK_WHITE_LETTER from. http://sdlpango.sourceforge.net/_s_d_l___pango_8h-source.html - here's my error: Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 54, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ctypes.ArgumentError: argument 2: : wrong type - i've tried other things, like using c_char_p instead for MATRIX_TRANSPARENT_BACK_WHITE_LETTER, but the only other result i can manage to get is this: C:\projects\soundshop>sdlpango.py Traceback (most recent call last): File "C:\projects\soundshop\sdlpango.py", line 52, in surfwrite("hello", 640) File "C:\projects\soundshop\sdlpango.py", line 25, in surfwrite sdlcontext = sdlwrite(rtext, width, height) File "C:\projects\soundshop\sdlpango.py", line 13, in sdlwrite sdlpango.SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER) ValueError: Procedure probably called with too many arguments (8 bytes in excess) - thx for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: freq function
Dirk Nachbar wrote: > Here is a function which takes any list and creates a freq table, > which can be printed unsorted, sorted by cases or items. It's supposed > to mirror the proc freq in SAS. > > Dirk > > def freq(seq,order='unsorted',prin=True): > #order can be unsorted, cases, items > > freq={} > for s in seq: > if s in freq: > freq[s]+=1 > else: > freq[s]=1 > if prin==True: > print 'Items=',len(seq),'Cases=',len(freq) > print '' > if order=='unsorted': > for k in freq.keys(): > print k,freq[k],float(freq[k])/len(seq) > elif order=='cases': > #http://blog.client9.com/2007/11/sorting-python-dict-by- > value.html > freq2=sorted(freq.iteritems(), key=lambda (k,v): > (v,k),reverse=True) Sorting in two steps gives a slightly better result when there are items with equal keys. Compare >>> freq = {"a": 2, "b": 1, "c": 1, "d": 2} >>> sorted(freq.iteritems(), key=lambda (k, v): (v, k), reverse=True) [('d', 2), ('a', 2), ('c', 1), ('b', 1)] with >>> freq2 = sorted(freq.iteritems(), key=lambda (k, v): k) >>> freq2.sort(key=lambda (k, v): v, reverse=True) >>> freq2 [('a', 2), ('d', 2), ('b', 1), ('c', 1)] Here the keys within groups of equal frequency are in normal instead of reversed order. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
I am trying to execute this script before login: #!/bin/sh date > /home/mahmood/dateatboot.txt echo "In local file" /usr/bin/python2.6 /home/mahmood/sendip.py echo "python script finished" after restart, dateatboot.txt was created shows that the script was executed. In the python file, I have this: import smtplib, commands, os, datetime # find IP address and write to file print 'I am in python file' f = open('.ip.txt', 'w') f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) f.close() ... After boot there is no .ip.txt file. // Naderan *Mahmood; From: Thomas Jollans To: python-list@python.org Sent: Sun, August 22, 2010 3:17:57 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > >Specify exactly how it's not working. > > I have wrote a script to send my ip address to an email address. It does > work when I am login (python sendip.py). I then followed the procedure in > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > email is sent. The first step would be to make sure your init script is actually running. Add some simple command that you know will not fail, and where you can see easily that it worked. Say, you could use #!/bin/sh date > /home/[USER]/Desktop/created_during_boot.txt as an init script. Then you could see that, if the file was created on your desktop, that the script is running at all. When you know that, THEN you can start to worry about Python (I think Ubuntu probably doesn't bring up the network before NetworkManager does this after login. So you might just not be able to send e-mail before login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > From: Chris Rebert > To: Mahmood Naderan > Cc: python mailing list > Sent: Sun, August 22, 2010 1:28:45 PM > Subject: Re: Running python script before user login > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan wrote: > > I have wrote a python script and want to run it before user login. To do > > that, I have added it to the ubuntu startup file (init.d). However it > > seems that the script doesn't work. > > Specify exactly how it's not working. > > Cheers, > Chris > -- > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: > > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: > import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... > > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > > > // Naderan *Mahmood; > > > > > > From: Thomas Jollans > To: python-list@python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list
Re: Running python script before user login
It seems that changing the directory before python command is mandatory: #!/bin/sh cd /home/mahmood/ python sendip.py I am now able to receive the IP address right after boot and before login page. Thank you // Naderan *Mahmood; From: Thomas Jollans To: python-list@python.org Sent: Sun, August 22, 2010 5:50:00 PM Subject: Re: Running python script before user login On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > I am trying to execute this script before login: > > #!/bin/sh > date > /home/mahmood/dateatboot.txt > echo "In local file" > /usr/bin/python2.6 /home/mahmood/sendip.py > echo "python script finished" > after restart, dateatboot.txt was created shows that the script was > executed. In the python file, I have this: > import smtplib, commands, os, datetime > # find IP address and write to file > print 'I am in python file' > f = open('.ip.txt', 'w') > f.write( commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]) > f.close() > ... > > After boot there is no .ip.txt file. Where are you looking? Do you actually know in which working directory your script is being executed? How about something like this: #!/bin/sh cd /home/mahmood/ python sendip.py >sendip.log 2>&1 ... this will write Python's output to a log file. If there is an exception, you'd be able to see it. > > > // Naderan *Mahmood; > > > > > > From: Thomas Jollans > To: python-list@python.org > Sent: Sun, August 22, 2010 3:17:57 PM > Subject: Re: Running python script before user login > > On Sunday 22 August 2010, it occurred to Mahmood Naderan to exclaim: > > >Specify exactly how it's not working. > > > > I have wrote a script to send my ip address to an email address. It does > > work when I am login (python sendip.py). I then followed the procedure in > > https://help.ubuntu.com/community/RcLocalHowto. However after restart, no > > email is sent. > > The first step would be to make sure your init script is actually running. > Add some simple command that you know will not fail, and where you can see > easily that it worked. Say, you could use > > #!/bin/sh > > date > /home/[USER]/Desktop/created_during_boot.txt > > as an init script. Then you could see that, if the file was created on your > desktop, that the script is running at all. When you know that, THEN you > can start to worry about Python > > (I think Ubuntu probably doesn't bring up the network before NetworkManager > does this after login. So you might just not be able to send e-mail before > login. You can check this by saving the output of /sbin/ifconfig somewhere) > > > // Naderan *Mahmood; > > > > > > > > > > > > From: Chris Rebert > > To: Mahmood Naderan > > Cc: python mailing list > > Sent: Sun, August 22, 2010 1:28:45 PM > > Subject: Re: Running python script before user login > > > > On Sun, Aug 22, 2010 at 1:52 AM, Mahmood Naderan > > wrote: > > > I have wrote a python script and want to run it before user login. To > > > do that, I have added it to the ubuntu startup file (init.d). However > > > it seems that the script doesn't work. > > > > Specify exactly how it's not working. > > > > Cheers, > > Chris > > -- > > More details = Better assistance -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On 2010-08-21, Steven D'Aprano wrote: > There is room in the world for programming languages aimed at > non- programmers (although HC is an extreme case), but not all > languages should prefer the intuition of non-programmers over > other values. Extremer: Inform 7. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrong unichr docstring in 2.7
Short comments: 1) I'm aware Python can be built in "ucs2" or "ucs4" mode. It remains that the unichr doc string does not seem correct. 2) 0x0 versus 0 Do not take this too seriously. Sure the value of 0x0 and 0 are equal, but the "unit" sounds strange. Eg. If a is a length, I would not express a as beeing 0 mm <= a <= 999 m (or 0 in <= a <= 999 ft) but 0 m <= a <= 999 m . I agree a notation like 0x <= i <= 0x is even the best. 3) Of course, the Python 3 behaviour (chr() instead of unichr()) is correct. jmf -- http://mail.python.org/mailman/listinfo/python-list
windows hook to catch WM_CREATE
Hello all, I'm looking for a method, lib, ... to create a windows hook to catch WM_CREATE message in python 2.6? For keyboard and mouse I use pyHook. any idea ? -- Jacques -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect string has non-ASCII chars without checking each char?
Re ! > Try your code with u"abcd\xa1" ... it says it's ASCII. Ah? in my computer, it say "False" @-salutations -- MCi -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
John Bokma writes: > David Kastrup writes: > >> John Passaniti writes: >> >>> Amen! All this academic talk is useless. Who cares about things like >>> the big-O notation for program complexity. Can't people just *look* >>> at code and see how complex it is?! And take things like the years of >>> wasted effort computer scientists have put into taking data structures >>> (like hashes and various kinds of trees) and extending them along >>> various problem domains and requirements. Real programmers don't >>> waste their time with learning that junk. What good did any of that >>> ever do anyone?! >> >> It is my experience that in particular graduated (and in particular Phd) >> computer scientists don't waste their time _applying_ that junk. > > Question: do you have a degree in computer science? > > Since in my experience: people who talk about their experience with > graduated people often missed the boat themselves and think that reading > a book or two equals years of study. I have a degree in electrical engineering. But that's similarly irrelevant. I have a rather thorough background with computers (started with punched cards), get along with about a dozen assembly languages and quite a few other higher level languages. I've had to write the BIOS for my first computer and a number of other stuff and did digital picture enhancement on DOS computers with EMM (programming 80387 assembly language and using a variant of Hartley transforms). I have rewritten digital map processing code from scratch that has been designed and optimized by graduated computer scientists (including one PhD) to a degree where it ran twice as fast as originally, at the cost of occasional crashes and utter unmaintainability. Twice as fast meaning somewhat less than a day of calculation time for medium size data sets (a few 10 of data points, on something like a 25MHz 68020 or something). So I knew the problem was not likely to be easy. Took me more than a week. After getting the thing to compile and fixing the first few crashing conditions, I got stuck in debugging. The thing just terminated after about 2 minutes of runtime without an apparent reason. I spent almost two more days trying to find the problem before bothering to even check the output. The program just finished regularly. That has not particularly helped my respect towards CS majors and PhDs in the function of programmers (and to be honest: their education is not intended to make them good programmers, but to enable them to _lead_ good programmers). That does not mean that I am incapable of analyzing, say quicksort and mergesort, and come up with something reasonably close to a closed form for average, min, and max comparisons (well, unless a close approximation is good enough, you have to sum about lg n terms which is near instantaneous, with a real closed form mostly available when n is special, like a power of 2). And I know how to work with more modern computer plagues, like the need for cache coherency. So in short, I have a somewhat related scientific education, but I can work the required math. And I can work the computers. > Oh, and rest assured, it works both ways: people who did graduate are > now and then thinking it's the holy grail and no body can beat it with > home study. > > Both are wrong, by the way. Depends. In my personal opinion, living close to the iron and being sharp enough can make a lot of a difference. Donald Knuth never studied computer science. He more or less founded it. As a programmer, he is too much artist and too little engineer for my taste: you can't take his proverbial masterpiece "TeX" apart without the pieces crumbling. He won't write inefficient programs: he has the respective gene and the knowledge to apply it. But the stuff he wrote is not well maintainable and reusable. Of course, he has no need for reuse if he can rewrite as fast as applying an interface. -- David Kastrup -- http://mail.python.org/mailman/listinfo/python-list
Organizing unit test?
Over the years, I've tried different styles of organizing unit tests. I used to create a test directory and put all my tests there. I would maintain a one-to-one correspondence between production source and test source, i.e. the test code for foo.py would be in test/foo.py. More recently, I've taken to having foo.py and test_foo.py in the same directory. My latest experiment is to just put both the production code and the test code in the same file, ending with if __name__ == '__main__': unittest.main() So, if I import the file, I get the production code as a module, and if I run it from the command line, it runs the tests. This makes the file messier, but it makes the directory structure cleaner and (I think) makes the whole thing easier to edit. Any of these work. I'm just curious what organizations other people have used and what the plusses and minuses ended up being. -- http://mail.python.org/mailman/listinfo/python-list
Re: Get authentication error while using 'smtplib'
Well, login plain did the job: session = smtplib.SMTP(smtpserver) session.ehlo() session.esmtp_features["auth"] = "LOGIN PLAIN"if AUTHREQUIRED: session.login(smtpuser, smtppass) // Naderan *Mahmood; From: Mahmood Naderan To: python mailing list Sent: Fri, August 20, 2010 6:13:20 PM Subject: Get authentication error while using 'smtplib' I have this script to send an email via SMTP: import smtplib smtpserver = 'smtp.server.com' AUTHREQUIRED = 1# if you need to use SMTP AUTH set to 1 smtpuser = "username"# for SMTP AUTH, set SMTP username here smtppass = "password"# for SMTP AUTH, set SMTP password here RECIPIENTS ='recipi...@server.com' SENDER = 'sen...@server.com' mssg = open('filename.txt', 'r').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) After running the script I get this error: Traceback (most recent call last): File "my_mail.py", line 14, in session.login(smtpuser, smtppass) File "/usr/lib/python2.6/smtplib.py", line 589, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, '5.7.0 Error: authentication failed: authentication failure') However there is no problem with my user/pass because I can login to my mail account. Thanks for any idea. // Naderan *Mahmood; -- http://mail.python.org/mailman/listinfo/python-list
comparing tuples
level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. However the above example only works if the ELSE clause is positioned under the second FOR loop. As if it was an ELSE clause without an IF statement!? Why/How does this work? tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
Steven D'Aprano writes: > * It throws away information from tracebacks if the recursive function > fails; and [...] > If you're like me, you're probably thinking that the traceback from an > exception in a recursive function isn't terribly useful. Agreed. On the other hand, a full-fledged tail recursion optimization might throw away more than that. For tail recursion elimination to work for those used to it, it needs to also handle the case of mutually recursive tail calls. The obvious way is by eliminating *all* tail calls, not just recursive ones. Tail call optimization, as opposed to tail recursion optimization, means that code such as: def f(n): return g(n + 5) is executed by a conceptual "jump" from the body of f to the body of g, regardless of whether recursion is involved at any point in the call chain. Now, if invocation of g() fails, the stack trace will show no sign of f() having been invoked. On the other hand, if f() invocation remains stored on the stack, mutually recursive functions will overflow it. Python being dynamic, I would expect it to be impossible to determine at compile-time whether a tail call will ultimately lead to a recursive invocation. -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing tuples
On 08/22/10 12:50, Baba wrote: level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. The ELSE clause can be used either with an IF (as you know) or with a FOR loop, which is interpreted as "if this loop reached the end naturally instead of exiting via a BREAK statement, execute this block of code". If you reach the end of t1 without having found a value (and then issuing a "break"), then the current value of t2 (b) should be appended to the result. That said, unless order matters, I'd just use sets: def tuples(t1, t2): return list(set(t2)-set(t1)) which should have better performance characteristics for large inputs. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
David Kastrup writes: > John Bokma writes: > >> David Kastrup writes: >> >>> John Passaniti writes: >>> Amen! All this academic talk is useless. Who cares about things like the big-O notation for program complexity. Can't people just *look* at code and see how complex it is?! And take things like the years of wasted effort computer scientists have put into taking data structures (like hashes and various kinds of trees) and extending them along various problem domains and requirements. Real programmers don't waste their time with learning that junk. What good did any of that ever do anyone?! >>> >>> It is my experience that in particular graduated (and in particular Phd) >>> computer scientists don't waste their time _applying_ that junk. >> >> Question: do you have a degree in computer science? >> >> Since in my experience: people who talk about their experience with >> graduated people often missed the boat themselves and think that reading >> a book or two equals years of study. > > I have a degree in electrical engineering. But that's similarly > irrelevant. Nah, it's not: your attitude towards people with a degree in computer science agrees with what I wrote. > That has not particularly helped my respect towards CS majors and PhDs > in the function of programmers (and to be honest: their education is not > intended to make them good programmers, but to enable them to _lead_ > good programmers). I disagree. > That does not mean that I am incapable of analyzing, say quicksort and > mergesort, Oh, that's what I was not implying. I am convinced that quite some people who do self-study can end up with better understanding of things than people who do it for a degree. I have done both: I already was programming in several languages before I was studying CS. And my experience is that a formal study in CS can't compare to home study unless you're really good and have the time and drive to read formal books written on CS. And my experience is that most self-educaters don't have that time. On the other hand: some people I knew during my studies had no problem at all with introducing countless memory leaks in small programs (and turning off compiler warnings, because it gave so much noise...) > Donald Knuth never studied computer science. Yes, yes, and Albert Einstein worked at an office. Those people are very rare. But my experience (see for plenty of examples: Slashdot) is that quite some people who don't have a degree think that all that formal education is just some paper pushing and doesn't count. While some of those who do have the paper think they know it all. Those people who are right in either group are a minority in my experience. As for electrical engineering: done that (BSc) and one of my class mates managed to connect a transformer the wrong way around twice. Yet he had the highest mark in our class. So in short: yes, self-study can make you good at something. But self-study IMO is not in general a replacement for a degree. Someone who can become great after self-study would excel at a formal study and learn more. Study works best if there is competition and if there are challenges. I still study a lot at home, but I do miss the challenges and competition. -- John Bokma j3b Blog: http://johnbokma.com/Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ -- http://mail.python.org/mailman/listinfo/python-list
[ANN]VTD-XML 2.9
VTD-XML 2.9, the next generation XML Processing API for SOA and Cloud computing, has been released. Please visit https://sourceforge.net/projects/vtd-xml/files/ to download the latest version. * Strict Conformance # VTD-XML now fully conforms to XML namespace 1.0 spec * Performance Improvement # Significantly improved parsing performance for small XML files * Expand Core VTD-XML API # Adds getPrefixString(), and toNormalizedString2() * Cutting/Splitting # Adds getSiblingElementFragment() * A number of bug fixes and code enhancement including: # Fixes a bug for reading very large XML documents on some platforms # Fixes a bug in parsing processing instruction # Fixes a bug in outputAndReparse() -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
Steven D'Aprano writes: > On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: > >> this means that Python should eliminate / optimize tail >> recursion. > > There have been various suggestions to add tail recursion optimization to > the language. Two problems: [snip] > But this is not the only sort of tail-call recursion, and a traceback > like the following is useful: > > recurse(4) > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 5, in recurse > File "", line 3, in f > File "", line 4, in recurse > File "", line 2, in g > ValueError > > > If all you saw was the last line (the call to g), debugging the exception > would be significantly harder. Yup, agreed, good example. > Me personally, I'd like to see either a (preferably) run-time setting or > compile-time switch that enables/disables this optimization. Even an > explicit decorator would be fine. And lo and behold: > > http://hircus.wordpress.com/2008/06/21/python-tail-call-optimization-done-right/ > http://groups.google.com/group/comp.lang.python/msg/9b047d1392f2b8ec > > > Add it to your bag of tricks and have fun. Thanks for the links. And yes, I will add this to my bag of tricks (aka local wiki with notes ;-) ). -- John Bokma j3b Blog: http://johnbokma.com/Facebook: http://www.facebook.com/j.j.j.bokma Freelance Perl & Python Development: http://castleamber.com/ -- http://mail.python.org/mailman/listinfo/python-list
Sphinx cross reference question
In my shopzeus.db.pivot.convert.py file, in the run() method of my Data2Facts class, I can write this into the docstring: class Data2Facts(threading.Thread): # code here... def prepare(self,*args): # code here... # more code here def run(self): """ Start data conversion. You need to call :meth:`prepare` before starting the conversion with :meth:`run`. """ # more code here... This works perfectly - it places cross links in the HTML documentation. I have another file where I'm writting a tutorial for my Data2Facts class. It is not the API, but I would like to make references to the API. So I can do this: The :meth:`shopzeus.db.pivot.convert.Data2Facts.prepare` method is used for blablabla However, I do not want to write "shopzeus.db.pivot.convert." every time. I want to make this my current module for cross-referencing. So I tried this: .. :currentmodule:: shopzeus.db.pivot.convert The :meth:`Data2Facts.prepare` method is used for blablabla But it does not work! It is displayed in bold, but there is no link. The sphinx build command does not give me any warnings about invalid references. What am I doing wrong? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 22, 12:47 am, Chris Rebert wrote: > On Sun, Aug 22, 2010 at 12:23 AM, Russ P. wrote: > > On Aug 21, 1:33 am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Fri, 20 Aug 2010 11:01:42 -0700, Russ P. wrote: > >> > Most programmers probably never use vectors and matrices, so they don't > >> > care about the inconsistency with standard mathematical notation. > > >> Perhaps you should ask the numpy programmers what they think about that. > > > Why would I care in the least about something called "numpy"? > > Because it's a popular matrix math package for Python. Its users are > thus a subset of programmers which by definition don't fall into the > "most programmers" group you describe. Yes, I know what numpy is, and I'm sure it's great. I was just taking a light-hearted jab at the name. -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing tuples
On Aug 22, 7:12 pm, Tim Chase wrote: > On 08/22/10 12:50, Baba wrote: > > > > > level: beginners > > > I was trying to write simple code that compares 2 tuples and returns > > any element in the second tuple that is not in the first tuple. > > > def tuples(t1, t2): > > result = [] > > for b in t2: > > for a in t1: > > if b == a: > > break > > else: > > result=result+[b,] > > return result > > > print tuples([0,5,6], [0,5,6,3,7]) > > > the code works but i was surprised by the following: my understanding > > was that an ELSE clause is part of an IF statement. Therefore it comes > > at the same indentation as the IF statement. > > The ELSE clause can be used either with an IF (as you know) or > with a FOR loop, which is interpreted as "if this loop reached > the end naturally instead of exiting via a BREAK statement, > execute this block of code". > > If you reach the end of t1 without having found a value (and then > issuing a "break"), then the current value of t2 (b) should be > appended to the result. > > That said, unless order matters, I'd just use sets: > > def tuples(t1, t2): > return list(set(t2)-set(t1)) > > which should have better performance characteristics for large > inputs. > > -tkc Thanks Tim! -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
On 8/21/2010 8:32 PM, Steven D'Aprano wrote: On Sat, 21 Aug 2010 19:09:52 -0500, John Bokma wrote: this means that Python should eliminate / optimize tail recursion. There have been various suggestions to add tail recursion optimization to the language. Two problems: * It throws away information from tracebacks if the recursive function fails; and * nobody willing to do the work is willing to champion it sufficiently to get it approved in the face of opposition due to the above. I would rank tail recursion way down on the list of things which make CPython slow. (Unladen Swallow seems to have stalled. Last quarterly release, October 2009. Last wiki update, May 2010. Last issue advanced to "started" state, Feb. 2010. There are still code checkins, so somebody is still working, but little visible progress. They did get a JIT working, but discovered that the performance improvement was very slight. They wanted at least 5x; they got 1x to 2x at best.) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg2 for insertion of binary data to PostgreSQL database
Thanks a lot, this was the solution. It would be greate, if you could also show me a way to extract the inserted binary object from the table on the server to a file on a client. > Peter Otten wrote: Julia Jacobson wrote: Hello everybody out there using python, For the insertion of pictures into my PostgreSQL database [with table foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written the following script: #!/usr/bin/python import psycopg2 try: conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='data'"); except: print "I am unable to connect to the database" cur = conn.cursor() f = open("test.bmp", 'rb') myfile = f.read() try: cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) except: print "Insert unsuccessful" "python script.py" runs the script without any errors or messages. However, the SQL command "SELECT * FROM foo" returns the output "foo (0 rows)" with no entries in the table. I'm using Python 2.7 and PostgreSQL 8.3. Could anyone help me to find a way to pin down the problem? Perhaps you need to conn.commit() your changes. -- http://mail.python.org/mailman/listinfo/python-list
Re: How far can stack [LIFO] solve do automatic garbage collection and prevent memory leak ?
Le Sun, 22 Aug 2010 20:12:36 +0200, John Bokma a écrit: David Kastrup writes: John Bokma writes: David Kastrup writes: John Passaniti writes: Amen! All this academic talk is useless. Who cares about things like the big-O notation for program complexity. Can't people just *look* at code and see how complex it is?! And take things like the years of wasted effort computer scientists have put into taking data structures (like hashes and various kinds of trees) and extending them along various problem domains and requirements. Real programmers don't waste their time with learning that junk. What good did any of that ever do anyone?! It is my experience that in particular graduated (and in particular Phd) computer scientists don't waste their time _applying_ that junk. Question: do you have a degree in computer science? Since in my experience: people who talk about their experience with graduated people often missed the boat themselves and think that reading a book or two equals years of study. I have a degree in electrical engineering. But that's similarly irrelevant. Nah, it's not: your attitude towards people with a degree in computer science agrees with what I wrote. That has not particularly helped my respect towards CS majors and PhDs in the function of programmers (and to be honest: their education is not intended to make them good programmers, but to enable them to _lead_ good programmers). I disagree. That does not mean that I am incapable of analyzing, say quicksort and mergesort, Oh, that's what I was not implying. I am convinced that quite some people who do self-study can end up with better understanding of things than people who do it for a degree. I have done both: I already was programming in several languages before I was studying CS. And my experience is that a formal study in CS can't compare to home study unless you're really good and have the time and drive to read formal books written on CS. And my experience is that most self-educaters don't have that time. On the other hand: some people I knew during my studies had no problem at all with introducing countless memory leaks in small programs (and turning off compiler warnings, because it gave so much noise...) Donald Knuth never studied computer science. Yes, yes, and Albert Einstein worked at an office. Those people are very rare. But my experience (see for plenty of examples: Slashdot) is that quite some people who don't have a degree think that all that formal education is just some paper pushing and doesn't count. While some of those who do have the paper think they know it all. Those people who are right in either group are a minority in my experience. As for electrical engineering: done that (BSc) and one of my class mates managed to connect a transformer the wrong way around twice. Yet he had the highest mark in our class. So in short: yes, self-study can make you good at something. But self-study IMO is not in general a replacement for a degree. Someone who can become great after self-study would excel at a formal study and learn more. Study works best if there is competition and if there are challenges. I still study a lot at home, but I do miss the challenges and competition. Hi all, I quite agree with the fact that self learning is not enough. Another thing you learn in studying in University is the fact that you can be wrong, which is quite difficult to accept for self taught people. When you work in groups, you are bound to admit that you don't have the best solution all the time. To my experience, self-taught people I worked with had tremendous difficulties to accept that they were wrong, that their design was badly done, that their code was badly written or strangely designed. Because self teaching was done with a lot of efforts, in particular to figure out complex problems on their own. Most of the time, the self learned people are attached to the things they learned by themselves and have difficulties to envisage that being right of wrong is often not an issue provided the group comes to the best option. They often live contradiction as a personal offense while it is just work, you know. That's another interest of the degree, confrontation with other people that have the same background. And letting the things learned at the place they should be and not in the affective area. 1001 -- Utilisant le logiciel de courrier révolutionnaire d'Opera : http://www.opera.com/mail/ -- http://mail.python.org/mailman/listinfo/python-list
Re: psycopg2 for insertion of binary data to PostgreSQL database
On Sunday 22 August 2010, it occurred to Julia Jacobson to exclaim: > Thanks a lot, this was the solution. > It would be greate, if you could also show me a way to extract the > inserted binary object from the table on the server to a file on a client. Probably something along the lines of: * execute an appropriate SELECT query * get the record you're interested in * open a file for writing * f.write(data) * f.close() and other clean-up code > > > Peter Otten wrote: > >> Julia Jacobson wrote: > >> > >> Hello everybody out there using python, > >> > >> For the insertion of pictures into my PostgreSQL database [with table > >> foo created by SQL command "CREATE TABLE foo (bmp BYTEA)], I've written > >> the following script: > >> > >> #!/usr/bin/python > >> import psycopg2 > >> > >> try: > >> conn = psycopg2.connect("dbname='postgres' user='postgres' > >> > >> host='localhost' password='data'"); > >> > >> except: > >> print "I am unable to connect to the database" > >> > >> cur = conn.cursor() > >> f = open("test.bmp", 'rb') > >> myfile = f.read() > >> > >> try: > >> cur.execute("INSERT INTO foo VALUES (%s)",(buffer(myfile),)) > >> > >> except: > >> print "Insert unsuccessful" > >> > >> "python script.py" runs the script without any errors or messages. > >> However, the SQL command "SELECT * FROM foo" returns the output "foo (0 > >> rows)" with no entries in the table. > >> I'm using Python 2.7 and PostgreSQL 8.3. > >> Could anyone help me to find a way to pin down the problem? > > > > Perhaps you need to conn.commit() your changes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detect string has non-ASCII chars without checking each char?
On Aug 23, 1:10 am, "Michel Claveau - MVP" wrote: > Re ! > > > Try your code with u"abcd\xa1" ... it says it's ASCII. > > Ah? in my computer, it say "False" Perhaps your computer has a problem. Mine does this with both Python 2.7 and Python 2.3 (which introduced the unicodedata.normalize function): >>> import unicodedata >>> t1 = u"abcd\xa1" >>> t2 = unicodedata.normalize('NFD', t1) >>> t3 = t2.encode('ascii', 'replace') >>> [t1, t2, t3] [u'abcd\xa1', u'abcd\xa1', 'abcd?'] >>> map(len, _) [5, 5, 5] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: expression in an if statement
Thomas Jollans wrote: What if "set" has side effects? A compiler could only exclude this possibility if it knew exactly what "set" will be at run time, And also that 'a' remains bound to the same object, and that object or anything reachable from it is not mutated in any way that could affect the result of set(a). That's quite a lot of information for an optimiser to deduce, particularly in a language as dynamic as Python. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
What is a class method?
I understand the concept of a static method. However I don't know what is a class method. Would anybody pls. explain me? class C: @classmethod def ... ... Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva wrote: > I understand the concept of a static method. > However I don't know what is a class method. > Would anybody pls. explain me? Please read this first: http://docs.python.org/library/functions.html#classmethod Then ask us questions :) cheers James -- -- James Mills -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
Em 23-08-2010 04:30, James Mills escreveu: > On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva > wrote: >> I understand the concept of a static method. >> However I don't know what is a class method. >> Would anybody pls. explain me? > > Please read this first: > http://docs.python.org/library/functions.html#classmethod > > Then ask us questions :) I did it before posting ... The "explanation" is not very clear. It is more like "how to use it". Thanks anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva wrote: > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Without going into the semantics of languages basically the differences are quite clear: @classmethod is a decorator that warps a function with passes the class as it's first argument. @staticmethod (much like C++/Java) is also a decorator that wraps a function but does not pass a class or instance as it's first argument. I won't go into the use-cases as I don't use static or class methods myself personally in any of my work (yet). cheers James -- -- James Mills -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
On Sun, Aug 22, 2010 at 9:53 PM, Paulo da Silva wrote: > Em 23-08-2010 04:30, James Mills escreveu: >> On Mon, Aug 23, 2010 at 12:49 PM, Paulo da Silva >> wrote: >>> I understand the concept of a static method. >>> However I don't know what is a class method. >>> Would anybody pls. explain me? >> >> Please read this first: >> http://docs.python.org/library/functions.html#classmethod >> >> Then ask us questions :) > > I did it before posting ... > The "explanation" is not very clear. It is more like "how to use it". Consider this: class A(object): @staticmethod def new(): return A() class B(A): pass versus this: class C(object): @classmethod def new(cls): return cls() class D(C): pass B.new() will return a new instance of A, not B. D.new() will return a new instance of D. Does this answer your question? -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
On 8/22/2010 11:53 PM, Paulo da Silva wrote: Please read this first: http://docs.python.org/library/functions.html#classmethod Then ask us questions :) I did it before posting ... When you ask a question, it help people answer if they know what you have already tried and failed with ;-) The "explanation" is not very clear. It is more like "how to use it". A function accessed as a class attribute is normal treated as an instance function/method -- with an instance of the class as the first argument. A class method takes the class as the first argument. A 'staticmethod' is a function that takes neither as the first argument and, with one esoteric exception, does not need to be a class attribute but is for convenience. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: What is a class method?
On 8/22/2010 9:16 PM, James Mills wrote: On Mon, Aug 23, 2010 at 1:53 PM, Paulo da Silva wrote: I did it before posting ... The "explanation" is not very clear. It is more like "how to use it". Without going into the semantics of languages basically the differences are quite clear: @classmethod is a decorator that warps a function with passes the class as it's first argument. @staticmethod (much like C++/Java) is also a decorator that wraps a function but does not pass a class or instance as it's first argument. That reads like something the C++ standards revision committee would dream up as they add unnecessary template gimmicks to the language. John Nagle -- http://mail.python.org/mailman/listinfo/python-list