Re: PyPI bdist_wininst upload failing
On May 27, 4:20 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > Steven Bethard wrote: > > I just tried to upload new versions of the argparse module to PyPI, but > > it seems like I can no longer upload Windows installers: [snip] > That seems a little weird to me. Are the bdist_wininst exe files really > zip files? Or did I just misunderstand what "content" is? > > STeVe They are exe files with a zip appended. Try out the above code on your file; it may just help you suss out what the problem is. E.g.: >>> import zipfile >>> zipfile.ZipFile('xlrd-0.6.1a4.win32.exe').namelist() ['PURELIB/xlrd-0.6.1a4-py2.5.egg-info', 'PURELIB/xlrd/biffh.py', ... snip ... 'SCRIPTS/xlrdnameAPIdemo.py'] >>> HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Color Segmentation w/ PIL?
I don't know of any in Python, but an open source image processing package in Java has been developed at Stanford University - http://www.gemident.net GemIdent . GemIdent was originally designed to segment cells from miscroscopic images and, more generally, can identify objects of interest and do color image segmentation. Maybe some of the code can I apply to your project and you can bridge the gap using Jython. Adam MooMaster wrote: > > I'm trying to write a Digital Image Processing program using the PIL > library, and upon consultation of the Handbook I see that it seems to > have built in functions to run Edge Detection (in the ImageFilter > module), but I don't see anything about Segmentation. Are there any > built-in tools to do this operation? Has anyone done this operation > with PIL in the past that can lead me in the right direction? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Color-Segmentation-w--PIL--tf3445941.html#a10822775 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Paul McGuire wrote: > I was under the impression that lower_case_with_underscores was a > dated recommendation, and that recent practice is more inclusive of > mixedCase style identifiers. On the contrary, Steven Bethard > straightened me out, saying that PEP-8 used to accept either style, > but has been amended to accept only lower_case_with_underscores. Underscores are harder to type than any alphanumeric character. Thus I support their use in situations where difficulty of typing is desirable (e.g., magic method names) and I detest them in all other situations. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
On May 27, 1:25 am, Steven Bethard <[EMAIL PROTECTED]> wrote: > Stefan Sonnenberg-Carstens wrote: > > Paul McGuire schrieb: > >> I'm starting a new thread for this topic, so as not to hijack the one > >> started by Steve Howell's excellent post titled "ten small Python > >> programs". > > >> In that thread, there was a suggestion that these examples should > >> conform to PEP-8's style recommendations, including use of > >> lower_case_with_underscores style for function names. I raised some > >> questions about this suggestion, since I liked the names the way they > >> were, but as a result, part of the discussion has drifted into a > >> separate track about PEP-8, and naming styles. > > > I prefer mixedCaseStyle, and I think that should be "standard", as this > > style is commonly > > used in all "major" languages , for example Java,C++,C#. > > It shortens the identifiers but leaves the meaning intact. > > The argument for under_score_names is usually that non-native speakers > can more easily find the word boundaries. Not being a non-native speaker > ;-) I can't verify that one, but it's pretty plausible given the current > amount of money spent on research on automatic word-segmentation for > languages like Chinese. =) > > STeVe- Hide quoted text - > > - Show quoted text - Here is the thread from python-dev where this change (from "mixedCase is no better or worse than lower_case_with_underscores" to "should use l_c_w_u") was discussed, a year ago last December: http://mail.python.org/pipermail/python-dev/2005-December/058750.html At first, Guido seemed ambivalent, and commented on the contentiousness of the issue, but it seems that the "non-English speakers can more easily find word breaks marked with underscores" justification tipped the scale in favor of lower_case_with_underscores. The PEP itself on www.python.org seems to have been updated as recently as May 17 of this year, but I don't seen any way to identify what the change history is. So, those who are the stewards of the core source code have nailed down thier coding standard to be l_c_w_u, so if sometime in the future I find myself working on any code in the Python std libs, l_c_w_u is the style to be followed. It just looks so old-fashioned... Whatev. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Color Segmentation w/ PIL?
You might be interested in the ndimage module of scipy: http://www.scipy.org/SciPyPackages/Ndimage If you need a very serious image processing framework, ITK is might be very interesting: http://www.itk.org/ If so, have a look at the more Pythonic interface developed for it: www.insight-journal.org/ .../1926/188/2/WrapITK_-_Enhanced_languages_support_for_the_Insight_Toolkit.pdf Cheers, -jelle -- http://mail.python.org/mailman/listinfo/python-list
Re: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep(Linux))
"Cameron Laird" <[EMAIL PROTECTED]> wrote: > In article <[EMAIL PROTECTED]>, > Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > . > . > . > >> Did you know that the first military smokeless powder > >> round was for the French Lebel? - It threw a bronze > >> ball, and could punch through a single brick wall. > >> > > Well, extreme high speed wouldn't help for that -- just get a > >surface splatter. Heavy and slower... (or some sort of solid core -- > >depleted uranium with a teflon coating) > . > . > . > Hmmm; now you've got me curious. What *were* the first > composite projectiles? Conceivably archers, catapultists, > and slings would all have the potential to find advantage > in use of coated dense projectiles; is there any evidence > of such? There certainly was "mass production" of cheap > projectiles (clay pellets, for example). How were stones > chosen for large catapults? Was there a body of craft > knowledge for balancing density and total mass in > selection of stones? Would a toggle headed harpoon count as a "composite projectile" ? - they have been around a long time. Also the San people (better known as Bushmen) have made their poison arrows so that the point detaches from the shaft and stays in the wound, ensuring better contact between the sticky gum like poison and the blood of the victim. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Muzzle Velocity (was: High resolution sleep (Linux)
"Cameron Laird" <[EMAIL PROTECTED]> wrote: > . > . > Ha! It's interesting, especially for "computerists", to consider > how some technologies "plateau": steam car speeds, fresco paint- > ing, dry-stone walls, ... > > >From what I remember from my reading, the Stanley Steamer had a reputation as a "Hot Rod" (pun intentional) - and people said that nobody who tried to get its maximum out of it would live. I would suspect that the cause was not the engine, but the cornering performance of the chassis. Would be interesting to put an engine like that into a modern chassis to see what it would do. Probably would not beat a mini fitted with a Kawasaki 1100 engine for each wheel, though - an interesting problem in real time control... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Web archtecture using two layers in Phyton
Hello, I need to develop an web applications that meet the following requirements: - 2 layers: the first one is the user interface (browser) and the second one is the interaction with the operacional system of the server. - the second layer must be developed using Python. I'd like to know if it is possible to implement this system... making the second layer using python and the first layer using another web technologies like AJAX for example. Does anybody have any experience in developing python web applications? Maybe send me some links or documentation about it... The final goal is to make diferent user interfaces (layer 1) that can integrate with the second layer... for example, one web interface and one local interface using python+qt (example)... i don't know if this is possible and how can this be implemented... any help is aprreciated... Thanks in advance, Wagner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and GUI
brad wrote: > Kevin Walzer wrote: > >> 2. wxPython is big, harder to learn than Tkinter, but looks good on >> Mac, Windows, and *Nix. It will require users to install a lot of >> extra stuff (or you'll have to bundle the extra stuff). > > PyInstaller builds binaries beautifully from raw py source. No need to > bundle the wx stuff. I develop on Linux, build on Windows (with > PyInstaller) and it works great. The source runs on any platform, the > Windows binaries is neat for the point and click users. > Hi Brad: This is my preferred method of development, but I am a newcomer to python having lived in the C world for a long time. Have you any experience with this development method using boa constructor as the GUI builder? Cheers, mvdw -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Paul McGuire <[EMAIL PROTECTED]> writes: > At this point, I realized that I was taking things too far > off-topic, so I decided to start a new thread. So, uh, what's the purpose of this thread? Did you have a specific point to start off with, or a question to ask? -- \ "It seems intuitively obvious to me, which means that it might | `\be wrong." -- Chris Torek | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
totally lost newbie
Hi all I posted earlier on this but have changed my approach so here is my latest attempt at solving a problem. I have been working on this for around 12 hours straight and am still struggling with it. Write a program that reads the values for a random list of cards from a file, where each line in the file specifies a single card with the rank and then the suit separated by a space. The rank should be an integer in the range of 1 to 13 (Ace:1, King:13), while the suit should be a lower case character in the set { 'h', 'd', 'c', 's' }. Sort the card entries into suits ordered by rank, and print out the ordered list. Hint: sort the list first by rank, and then by suit. The format of the cards.txt file is; 1 h 1 d 13 c 10 s and so on for the whole deck. Can someone help me to get the mycomp function to work. Any help appreciated J def read_cards(filename): cards = [] for card in open(filename, 'r'): # strip the trailing newline character cards.append(card.strip()) return cards filename = 'cards.txt' cards = read_cards(filename) def cards_str2tup(cards): cards_tup = [] for card in cards: rank, suit = card.split() cards_tup.append((suit, int(rank))) return cards_tup def cards_tup2str(cards_tup): cards = [] space = ' ' for tup in cards_tup: suit, rank = tup s = str(rank) + space + suit cards.append(s) return cards def mycmp( a, b): #define the order in which the characters are to be sorted order = [ 'h', 'd', 'c', 's' ] # if the characters from each element ARENT the same if a[1] <> b[1]: #return the result of comparing the index of each elements character in the order list return cmp( order.index( a[1] ), order.index( b[1] ) ) #otherwise else : #return the result of comparing each elements number return cmp( a[0], b[0] ) cards.sort( mycmp ) #print cards -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a dot's or pixel's RGB with PIL
I got it. Pass python challenge chapter 7. -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
In <[EMAIL PROTECTED]>, mark wrote: > Hi all > > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. > > Write a program that reads the values for a random list of cards from > a file, where each line in the file specifies a single card with the > rank and then the suit separated by a space. The rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), while the suit > should be a lower case character in the set { 'h', 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, and print out the > ordered list. Hint: sort the list first by rank, and then by suit. > > The format of the cards.txt file is; > > 1 h > 1 d > 13 c > 10 s > > and so on for the whole deck. > > Can someone help me to get the mycomp function to work. > > Any help appreciated > > J > > def read_cards(filename): > > cards = [] > for card in open(filename, 'r'): > # strip the trailing newline character > cards.append(card.strip()) > return cards > > filename = 'cards.txt' > cards = read_cards(filename) > > > > def cards_str2tup(cards): > > cards_tup = [] > for card in cards: > rank, suit = card.split() > cards_tup.append((suit, int(rank))) > return cards_tup > > def cards_tup2str(cards_tup): > > cards = [] > space = ' ' > for tup in cards_tup: > suit, rank = tup > s = str(rank) + space + suit > cards.append(s) > return cards > > def mycmp( a, b): > #define the order in which the characters are to be sorted > order = [ 'h', 'd', 'c', 's' ] > # if the characters from each element ARENT the same > if a[1] <> b[1]: > #return the result of comparing the index of each elements > character in the order list > return cmp( order.index( a[1] ), order.index( b[1] ) ) > #otherwise > else : > #return the result of comparing each elements number > return cmp( a[0], b[0] ) > > cards.sort( mycmp ) > #print cards Maybe it's easier to use a key function instead of a compare function. A key function receives an element and must return something that is then sorted and the element ends up where the computed key is in the sorted list. Little example for sorting a list of strings first by length and strings of the same length by alphabetical order: def key_func(item): return (len(item), item) data = ['viking', 'spam', 'parrot', 'ham', 'eric'] data.sort(key=key_func) print data Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: a bug in python windows service?
> No, this is not a bug. You must not call Thread.run(), use Thread.start() > instead - else your code won't run in a different thread of execution. See > http://docs.python.org/lib/thread-objects.htmlon how to use Thread > objects - and note that you should *only* override __init__ and run, if > any. > Instead of extending join(), write a specific method to signal the > quitEvent or just let the caller signal it. And I don't see in this > example why do you need two different events (one on the thread, another > on the service controller), a single event would suffice. > > -- > Gabriel Genellina Thanks for help, It works now:D -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
On May 27, 12:19 pm, mark <[EMAIL PROTECTED]> wrote: > Hi all > > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. > > Write a program that reads the values for a random list of cards from > a file, where each line in the file specifies a single card with the > rank and then the suit separated by a space. The rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), while the suit > should be a lower case character in the set { 'h', 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, and print out the > ordered list. Hint: sort the list first by rank, and then by suit. > > The format of the cards.txt file is; > > 1 h > 1 d > 13 c > 10 s > > and so on for the whole deck. > > Can someone help me to get the mycomp function to work. > > Any help appreciated > > J > > def read_cards(filename): > > cards = [] > for card in open(filename, 'r'): > # strip the trailing newline character > cards.append(card.strip()) > return cards > > filename = 'cards.txt' > cards = read_cards(filename) > > def cards_str2tup(cards): > > cards_tup = [] > for card in cards: > rank, suit = card.split() > cards_tup.append((suit, int(rank))) > return cards_tup > > def cards_tup2str(cards_tup): > > cards = [] > space = ' ' > for tup in cards_tup: > suit, rank = tup > s = str(rank) + space + suit > cards.append(s) > return cards > > def mycmp( a, b): > #define the order in which the characters are to be sorted > order = [ 'h', 'd', 'c', 's' ] > # if the characters from each element ARENT the same > if a[1] <> b[1]: > #return the result of comparing the index of each elements > character in the order list > return cmp( order.index( a[1] ), order.index( b[1] ) ) > #otherwise > else : > #return the result of comparing each elements number > return cmp( a[0], b[0] ) > > cards.sort( mycmp ) > #print cards You need to exploit the lexicographic order as in the following function. def sort_carddeck(card_deck_pairs): # card deck pairs have to be a list of # the form [(rank1, suit1), (rank1, suit2),...] suit_order = [ 'h', 'd', 'c', 's' ] def cmp(p1, p2): i1 = suit_order.index(p1[1]) i2 = suit_order.index(p2[1]) if i1http://mail.python.org/mailman/listinfo/python-list
Help with PySMS
Hello - Background: I'm not a coder, but I got a degree in Chem Engg about 7 years ago. I have done some coding in my life, and I'm only beginning to pick up Python. So assume that I'm very stupid when and if you are kind enough to help me out. Problem: I need an SMS server running on my WinXP PC, as soon as possible. I'm currently using a Nokia 6300 phone which has the S60 platform. I downloaded the PySMS by Dave Berkeley from http://www.wordhord.co.uk/pysms.html and started testing it, but I haven't been able to get it working. Maybe I don't know how to do some configurations before using it, I dunno. I'm pretty lost. Do I need to tweak Nokia.ini? What ports am I supposed to use? Can anybody tell me a step-by-step way of setting up and getting this thing running? I don't have enough to pay for this information, or I would gladly shell out some cash. But I can bet that I'll be able to help you out with something or the other in the future, if not money. And I am willing to negotiate a portion of royalties if I make any money off this project. My project is very simple - I will use incoming SMS to generate a visualisation and automatic responder. This system will be part of a multiplayer game that lots of people can play using SMS. cheers, DJ Fadereu http://www.algomantra.com -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
En Sun, 27 May 2007 07:19:15 -0300, mark <[EMAIL PROTECTED]> escribió: > I posted earlier on this but have changed my approach so here is my > latest attempt at solving a problem. I have been working on this for > around 12 hours straight and am still struggling with it. Almost done. Just two things: - You have defined a function to convert the file format into tuples. But you are not consistent with the ordering: in the file they come rank+space+suit. When you convert to tuple you use (suit,rank). Inside the comparison function you use a[0] as rank and a[1] as suit again. Be consistent. - The sort expects a list of tuples, but you still use the lines read from the file; you forgot to call the function above to convert them. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: a bug in python windows service?
> Instead of extending join(), write a specific method to signal the > quitEvent or just let the caller signal it. And I don't see in this > example why do you need two different events (one on the thread, another > on the service controller), a single event would suffice. I don't think a single event is enought, since I think the event python created and windows event are not same kind of event. -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
On May 26, 1:43 pm, Steve Howell <[EMAIL PROTECTED]> wrote: > -- > parentRabbits, babyRabbits = (1, 1) > while babyRabbits < 100: > print 'This generation has %d rabbits' % > babyRabbits > parentRabbits, babyRabbits = (babyRabbits, > parentRabbits + babyRabbits) > > -- > # def defines a method in Python > def tax(itemCharge, taxRate = 0.05): > return itemCharge * taxRate > print '%.2f' % tax(11.35) > print '%.2f' % tax(40.00, 0.08) > For the person new to programming (doesn't come from C or other languages), I think you need to add a separate explanation of string formatting and how it works, or at least add a comment that tells them you are using string formatting so that they can search and find out how it works. If your aim is to teach simple programming concepts, why confuse them so early on with fancy interpolation? Something like # uses Python string formatting # http://docs.python.org/lib/typesseq-strings.html but really I think it will just be a distraction rd -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
On Sun, 2007-05-27 at 07:30 +, OKB (not okblacke) wrote: > Underscores are harder to type than any alphanumeric character. This is a discussion about underscores versus capital letters denoting the word boundaries in identifiers. How is an underscore harder to type than a capital letter? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Newbie question - better way to do this?
I have some working code, but I realized it is just the way I would write it in C, which means there is probably a better (more pythonic) way of doing it. Here's the section of code: accumulate = firstIsCaps = False accumStart = i = 0 while i < len(words): firstIsCaps = firstIsCapitalized(words[i]) if firstIsCaps and not accumulate: accumStart, accumulate = i, True elif accumulate and not firstIsCaps: doSomething(words[accumStart : i]) accumulate = False i += 1 words is a big long array of strings. What I want to do is find consecutive sequences of words that have the first letter capitalized, and then call doSomething on them. (And you can ignore the fact that it won't find a sequence at the very end of words, that is fine for my purposes). Thanks, Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
--- Ben Finney <[EMAIL PROTECTED]> wrote: > Paul McGuire <[EMAIL PROTECTED]> writes: > > > At this point, I realized that I was taking things > too far > > off-topic, so I decided to start a new thread. > > So, uh, what's the purpose of this thread? Did you > have a specific > point to start off with, or a question to ask? > I'll take the liberty of answering on by behalf of Paul. Purpose of the thread--he realized he was taking another thread off topic, decided to start his own, so that people who don't want debate PEP 8 can more easily ignore it Specific point--he was mostly focused on the pain of using underscores, and while he was still off-topic on the previous thread, he had put his problems in the context of working with German colleagues who have slightly different keyboards than the American keyboard he has, the upcoming complications of Unicode in Python 3, etc. Question to ask--note the subject line, although I'm not sure that's his main question Sucker-punch spam with award-winning protection. Try the free Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/features_spam.html -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
--- Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > > Maybe it's easier to use a key function instead of a > compare function. A > key function receives an element and must return > something that is then > sorted and the element ends up where the computed > key is in the sorted > list. Little example for sorting a list of strings > first by length and > strings of the same length by alphabetical order: > > def key_func(item): > return (len(item), item) > > data = ['viking', 'spam', 'parrot', 'ham', 'eric'] > data.sort(key=key_func) > print data > Marc, when did the key feature get introduced, 2.4 or 2.5? I'm asking on behalf of the newbie, who's going to struggle with your solution if he's still running 2.3. Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib, usetex
Bill Jackson <[EMAIL PROTECTED]> writes: > Alexander Schmolck wrote the following on 05/25/2007 02:33 PM: >> I have no idea whether this will resolve your problem, but you could try >> updating to 0.90 (BTW what happens if you do axis([0,128,0,128])). > > The problem appears to be with a matplotlibrc file. If I delete the > matplotlibrc file, then I am able to plot perfectly. Thus, it appears that I > am unable to specify usetex from my configuration file. Why is this > happening? > > ~/.matplotlib/matplotlibrc > text.usetex : True > > test.py > import matplotlib > import pylab > matplotlib.rc('text', usetex=True) I think it might be a good habit to develop to call ``rc`` before ``import pylab`` -- some things won't take effect otherwise (this doesn't affect all parameters and will likely be eventually fixed in general, but notably it does currently affect some latex-related stuff, such as font choice). > pylab.plot(range(10)) > pylab.show() > > > Running 'python test.py' with the above matplotlibrc causes the errors in my > original post. Deleting matplotlibrc resolves the problem. I can't see any problem with you matplotlibrc; what happens if you swap around the lines as I suggested above? Maybe it just appears to work, because the usetex really does have no affect above, and you really are not using latex? I have been using matplotlib with latex for fonts handling for some time now (and I've even submitted a patch to ameliorate the rc problem mentioned above), but the latex stuff has changed somewhat over time, and still has some rough edges -- so for not immediately obvious problems with the latex handling of an older version of matplotlib you're much more likely to find someone who has the relevant details mentally available on the matplotlib-disc list are much better than here; so I'd recommend you give it a try again (yeah sf is a pain). cheers, 'as -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
--- mark <[EMAIL PROTECTED]> wrote: > Hi all > > I posted earlier on this but have changed my > approach so here is my > latest attempt at solving a problem. I have been > working on this for > around 12 hours straight and am still struggling > with it. > > Write a program that reads the values for a random > list of cards from > a file, where each line in the file specifies a > single card with the > rank and then the suit separated by a space. The > rank should be an > integer in the range of 1 to 13 (Ace:1, King:13), > while the suit > should be a lower case character in the set { 'h', > 'd', 'c', 's' }. > Sort the card entries into suits ordered by rank, > and print out the > ordered list. Hint: sort the list first by rank, and > then by suit. > Given that the hint is to sort twice, you can first break down the problem by just trying to sort your list according to the number on the card, and don't worry about the suit. Also, try using a data file that doesn't have any face cards in it, to keep things simple at first. Then, to get the face cards working, think about this--a Jack is really just an 11, a Queen is just a 12, a King is just a 13, and an Ace is just a 1. When you read in your data, maybe you want to just work with the numbers internally? Do you know how to use a dictionary to map K to 13? Then, when it comes time to produce the final output, you'll need to map 13 back to 'K', which again involves using a dictionary. There are other approaches, too, just hope this sparks some thought. Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
En Sun, 27 May 2007 10:44:01 -0300, Eric <[EMAIL PROTECTED]> escribió: > I have some working code, but I realized it is just the way I would > write it in C, which means there is probably a better (more pythonic) > way of doing it. > > Here's the section of code: > > accumulate = firstIsCaps = False > accumStart = i = 0 > while i < len(words): > firstIsCaps = firstIsCapitalized(words[i]) > if firstIsCaps and not accumulate: > accumStart, accumulate = i, True > elif accumulate and not firstIsCaps: > doSomething(words[accumStart : i]) > accumulate = False > i += 1 > > words is a big long array of strings. What I want to do is find > consecutive sequences of words that have the first letter capitalized, > and then call doSomething on them. (And you can ignore the fact that > it won't find a sequence at the very end of words, that is fine for my > purposes). Using groupby: py> from itertools import groupby py> py> words = "Este es un Ejemplo. Los Ejemplos usualmente son tontos. Yo siempre escribo tonterias.".split() py> py> for upper, group in groupby(words, str.istitle): ... if upper: ... print list(group) # doSomething(list(group)) ... ['Este'] ['Ejemplo.', 'Los', 'Ejemplos'] ['Yo'] You could replace your firstIsCapitalized function instead of the string method istitle(), but I think it's the same. See http://docs.python.org/lib/itertools-functions.html -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: > words is a big long array of strings. What I want to do is find > consecutive sequences of words that have the first letter capitalized, > and then call doSomething on them. (And you can ignore the fact that > it won't find a sequence at the very end of words, that is fine for my > purposes). Assuming the list of words will fit into memory, and you can probably expect to fit anything up to millions of words comfortably into memory, something like this might be suitable: list_of_words = "lots of words go here".split() accumulator = [] for word in list_of_words: if word.istitle(): accumulator.append(word) else: doSomething(accumulator) accumulator = [] -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
--- Eric <[EMAIL PROTECTED]> wrote: > I have some working code, but I realized it is just > the way I would > write it in C, which means there is probably a > better (more pythonic) > way of doing it. > > Here's the section of code: > > accumulate = firstIsCaps = False > accumStart = i = 0 > while i < len(words): > firstIsCaps = firstIsCapitalized(words[i]) > if firstIsCaps and not accumulate: > accumStart, accumulate = i, True > elif accumulate and not firstIsCaps: > doSomething(words[accumStart : i]) > accumulate = False > i += 1 > > words is a big long array of strings. What I want > to do is find > consecutive sequences of words that have the first > letter capitalized, > and then call doSomething on them. (And you can > ignore the fact that > it won't find a sequence at the very end of words, > that is fine for my > purposes). > Try out this program: def doSomething(stuff): print stuff def firstIsCapitalized(word): return 'A' <= word[0] <= 'Z' def orig_code(words): print 'C-style' accumulate = firstIsCaps = False accumStart = i = 0 while i < len(words): firstIsCaps = firstIsCapitalized(words[i]) if firstIsCaps and not accumulate: accumStart, accumulate = i, True elif accumulate and not firstIsCaps: doSomething(words[accumStart : i]) accumulate = False i += 1 def another_way(words): print 'more idiomatic, with minor bug fix' group = [] for word in words: if firstIsCapitalized(word): group.append(word) elif group: doSomething(group) group = [] if group: doSomething(group) orig_code(['foo', 'Python', 'Ruby', 'c', 'xxx', 'Perl']) another_way(['foo', 'Python', 'Ruby', 'c', 'xxx', 'Perl']) See also the groupby method in itertools. http://docs.python.org/lib/itertools-functions.html Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php -- http://mail.python.org/mailman/listinfo/python-list
Re: totally lost newbie
In <[EMAIL PROTECTED]>, Steve Howell wrote: >> def key_func(item): >> return (len(item), item) >> >> data = ['viking', 'spam', 'parrot', 'ham', 'eric'] >> data.sort(key=key_func) >> print data >> > > Marc, when did the key feature get introduced, 2.4 or > 2.5? I'm asking on behalf of the newbie, who's going > to struggle with your solution if he's still running > 2.3. It's available in 2.4 but I don't know when it was introduced. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
En Sun, 27 May 2007 10:20:49 -0300, Carsten Haese <[EMAIL PROTECTED]> escribió: > On Sun, 2007-05-27 at 07:30 +, OKB (not okblacke) wrote: >> Underscores are harder to type than any alphanumeric character. > > This is a discussion about underscores versus capital letters denoting > the word boundaries in identifiers. How is an underscore harder to type > than a capital letter? Underscores are not always easily available on non us-layout keyboards, like \ and @ and many other "special" characters. A language that requires more symbols than the 26 english letters has to make room somewhere - keyboards usually have "only" 102 keys (or 105 nowadays). Back to the style, I think that mixedCaseIsEnough to determine_word_endings and looksBetter. alllowercase is hard to read. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
--- Gabriel Genellina <[EMAIL PROTECTED]> wrote: > > Underscores are not always easily available on non > us-layout keyboards, > like \ and @ and many other "special" characters. A > language that requires > more symbols than the 26 english letters has to make > room somewhere - > keyboards usually have "only" 102 keys (or 105 > nowadays). > Back to the style, I think that mixedCaseIsEnough to > Regarding the US keyboard, if you like chess: 1) The right pinkie normally sits on the semicolon, and if you shift it, you get a colon. 2) Typing the "P" character is like moving a pawn up one square (while shifting with the left). 3) Typing the "[" and "{" is like capturing with the pawn (one up, one over). 4) Typing the "_" is like moving the knight (two up, one over), as are typing the "]" an "}" (one up, two over). No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started. http://mobile.yahoo.com/mail -- http://mail.python.org/mailman/listinfo/python-list
Re: File monitoring for all drive
[rohit] >>> i want to detect all file change operations(rename,delete,create) >>> on ALL THE DRIVES of the hard disk >>> using the method ReadDirectoryChanges API , i.e program no. 3 in the >>> webpagehttp://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... >>> . >>> Please suggest some modification to the program so that i can detect >>> changes to ALL the drives >>> (to detect changes on c:\ set >>> path_to_watch = "." to "c:\\" but this works for only one drive [Tim Golden] >> Well, to answer the question specifically: since the >> Windows filesstem has no concept of a "root" above >> the drive letters, the simplest thing to do is to >> kick off a thread or a subprocess or what-have-you >> for each drive letter. [rohit] > actually i want to implement a deamon monitoring file changes on the > system > so u suggesting i should implement the program with multithreading to > include all drives? That's one possibility, but again I'd ask whether this is really quite sane: you're asking the filesystem to tell you about every change to every file on the system which will naturally slow things down. It will get even more complicated if you're actually storing these "change logs" in a file somewhere, since that will then fire the monitoring mechanism itself! I suggest - again - that the NTFS change journal might be better suited to what you're trying to do. Try the threaded approach with the ReadDirectoryChanges API *on a small area of disk* to see how well it scales. Then you'll be better placed to decide if it will work well across all the disks in the system. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with PySMS
DJ Fadereu wrote: > > I need an SMS server running on my WinXP PC, as soon as possible. I'm > currently using a Nokia 6300 phone which has the S60 platform. I > downloaded the PySMS by Dave Berkeley from > http://www.wordhord.co.uk/pysms.html and started testing it, but I > haven't been able to get it working. Maybe I don't know how to do some > configurations before using it, I dunno. I'm pretty lost. Have you contacted the author? He might be able to help you out much more effectively than we can. [...] > My project is very simple - I will use incoming SMS to > generate a visualisation and automatic responder. This system will be > part of a multiplayer game that lots of people can play using SMS. I've extended the t616hack distribution to deal with messages - it contains a library which is used to communicate with Sony Ericsson telephones using AT commands - and that might give you some ideas about the principles involved. See here for the package: http://www.python.org/pypi/t616hack One significant enhancement made to t616hack is support for Bluetooth sockets, meaning that you don't need to worry about baud rates, serial devices and other low-level details. There's no direct support for a message server, but I have a Web application that I use personally for accessing messages on my telephone. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: PyPI bdist_wininst upload failing
John Machin wrote: > On May 27, 4:20 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: >> Steven Bethard wrote: >>> I just tried to upload new versions of the argparse module to PyPI, but >>> it seems like I can no longer upload Windows installers: > [snip] >> That seems a little weird to me. Are the bdist_wininst exe files really >> zip files? Or did I just misunderstand what "content" is? > > They are exe files with a zip appended. Try out the above code on your > file; it may just help you suss out what the problem is. > E.g.: import zipfile zipfile.ZipFile('xlrd-0.6.1a4.win32.exe').namelist() > ['PURELIB/xlrd-0.6.1a4-py2.5.egg-info', 'PURELIB/xlrd/biffh.py', > ... snip ... > 'SCRIPTS/xlrdnameAPIdemo.py'] Interesting. Thanks! >>> zipfile.ZipFile('argparse-0.8.0.win32.exe').namelist() ['.../lib/argparse-0.8.0-py2.5.egg-info', '.../lib/argparse.py'] Interestingly, it looks like none of these are "safe_zipnames" according to: https://svn.python.org/packages/trunk/pypi/verify_filetype.py I wonder why that is... Also, I couldn't get the StringIO code from there to work: >>> import StringIO >>> content = open('argparse-0.8.0.win32.exe').read() >>> t = StringIO.StringIO(content) >>> t.filename = 'argparse-0.8.0.win32.exe' >>> z = zipfile.ZipFile(t) Traceback (most recent call last): File "", line 1, in 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 378, in _RealGetContents raise BadZipfile, "File is not a zip file" BadZipfile: File is not a zip file STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- BartlebyScrivener <[EMAIL PROTECTED]> wrote: > On May 26, 1:43 pm, Steve Howell > <[EMAIL PROTECTED]> wrote: > > -- > > # def defines a method in Python > > def tax(itemCharge, taxRate = 0.05): > > return itemCharge * taxRate > > print '%.2f' % tax(11.35) > > print '%.2f' % tax(40.00, 0.08) > > > I decided to go with a simpler example up front. -- # def defines a method in Python def say_hello(name): print 'hello', name say_hello('Jack') say_hello('Jill') More here: http://wiki.python.org/moin/SimplePrograms Somebody also fixed a few style things in my other examples, changing a tuple to a list, catching a more specific exception. Whoever you are, thanks, I agree. Sick sense of humor? Visit Yahoo! TV's Comedy with an Edge to see what's on, when. http://tv.yahoo.com/collections/222 -- http://mail.python.org/mailman/listinfo/python-list
Re: a bug in python windows service?
En Sun, 27 May 2007 09:07:36 -0300, momobear <[EMAIL PROTECTED]> escribió: >> Instead of extending join(), write a specific method to signal the >> quitEvent or just let the caller signal it. And I don't see in this >> example why do you need two different events (one on the thread, another >> on the service controller), a single event would suffice. > > I don't think a single event is enought, since I think the event > python created and windows event are not same kind of event. They are not the same object, of course (altough the threading.Event object relies eventually on a mutex implemented using CreateEvent). But in this case both can be successfully used; of course, having the Python object a more "pythonic" interfase (not a surprise!), it's easier to use. The same example modified using only a threading.Event object (and a few messages to verify how it runs): import threading from win32api import OutputDebugString as ODS class workingthread(threading.Thread): def __init__(self, quitEvent): self.quitEvent = quitEvent self.waitTime = 1 threading.Thread.__init__(self) def run(self): while not self.quitEvent.isSet(): ODS("Running...\n") self.quitEvent.wait(self.waitTime) ODS("Exit run.\n") import win32serviceutil import win32event class testTime(win32serviceutil.ServiceFramework): _svc_name_ = "testTime" _svc_display_name_ = "testTime" _svc_deps_ = ["EventLog"] def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = threading.Event() self.thread = workingthread(self.hWaitStop) def SvcStop(self): self.hWaitStop.set() def SvcDoRun(self): self.thread.start() self.hWaitStop.wait() self.thread.join() if __name__ == '__main__': win32serviceutil.HandleCommandLine(testTime) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
On May 26, 8:21 pm, John Machin <[EMAIL PROTECTED]> wrote: > On May 27, 5:25 am, erikcw <[EMAIL PROTECTED]> wrote: > > > > > On May 25, 11:28 am, Carsten Haese <[EMAIL PROTECTED]> wrote: > > > > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > > > > > I'm trying to run the following query: > > > > ... > > > > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > > > > Shouldn't you be using the bind variable '?' instead of '%s' ? > > > > The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > > > The OP is using parameter substitution correctly, though in an > > > obfuscated fashion. 'sql' is a misnamed tuple containing both the query > > > string *and* the parameters, which is being unpacked with '*' into two > > > arguments to the execute call. > > > > The only problem I see is that the parameters should be a sequence, i.e. > > > (self.uid,) instead of just (self.uid). > > > > HTH, > > > > -- > > > Carsten Haesehttp://informixdb.sourceforge.net > > > I tried adding the comma to make it a sequence - but now change. > > > ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > > expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > > <21)', (1608L,)) > > () > > > What else could it be? > > Possibly a type mismatch. How is member_id declared in the CREATE > TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). Here is a copy of the table schema and the first 2 rows. -- phpMyAdmin SQL Dump -- version 2.9.0.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: May 27, 2007 at 11:29 AM -- Server version: 5.0.27 -- PHP Version: 4.4.2 -- -- Database: `lybp_lybp` -- -- -- -- Table structure for table `amember_payments` -- CREATE TABLE `amember_payments` ( `payment_id` int(11) NOT NULL auto_increment, `member_id` int(11) NOT NULL default '0', `product_id` int(11) NOT NULL default '0', `begin_date` date NOT NULL default '-00-00', `expire_date` date NOT NULL default '-00-00', `paysys_id` varchar(32) NOT NULL default '', `receipt_id` varchar(32) NOT NULL default '', `amount` decimal(12,2) NOT NULL default '0.00', `completed` smallint(6) default '0', `remote_addr` varchar(15) NOT NULL default '', `data` text, `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, `aff_id` int(11) NOT NULL default '0', `payer_id` varchar(255) NOT NULL default '', `coupon_id` int(11) NOT NULL default '0', `tm_added` datetime NOT NULL default '-00-00 00:00:00', `tm_completed` datetime default NULL, `tax_amount` decimal(12,2) NOT NULL default '0.00', PRIMARY KEY (`payment_id`), KEY `member_id` (`member_id`), KEY `payer_id` (`payer_id`), KEY `coupon_id` (`coupon_id`), KEY `tm_added` (`tm_added`,`product_id`), KEY `tm_completed` (`tm_completed`,`product_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; -- -- Dumping data for table `amember_payments` -- INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 19:21:43', 0.00); INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 19:20:13', 0.00); Thanks for your help! Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: PyPI bdist_wininst upload failing
En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard <[EMAIL PROTECTED]> escribió: > Also, I couldn't get the StringIO code from there to work: > > >>> import StringIO > >>> content = open('argparse-0.8.0.win32.exe').read() Use open("...","rb").read() - the "b" is important on Windows. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- BartlebyScrivener <[EMAIL PROTECTED]> wrote: > > For the person new to programming (doesn't come from > C or other > languages), I think you need to add a separate > explanation of string > formatting and how it works, or at least add a > comment that tells them > you are using string formatting so that they can > search and find out > how it works. If your aim is to teach simple > programming concepts, why > confuse them so early on with fancy interpolation? > It's a thought provoking question, and I think my aim here is not exactly to teach simple programming concepts, but more to expose people to what Python looks like. I'm not really intending this page to be a tutorial, as several good tutorials already exist. I'm really targeting a particular niche of people. There are folks that know how to program, but don't know anything about Python, and they really just want to see a bunch of small examples all in one place, without a lot of explanation cluttering their presentation. That may sound like I'm narrowing my audience too much, but I do think it's a niche group that's not adequately addressed. I do hope, though, that folks more in a teaching role can reuse the examples, add better explanation, etc., as needed. Also, I wouldn't mind at all to add a little link called "Read more..." after each example. Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
PHP5 programmer learning Python
Hi all, I'm a PHP5 developer looking to "broaden my horizons" so to speak by learning a new language. I emphasize the 5 in PHP since I have fully engrossed myself in the full OOP of version 5 with my own ground-up projects as well as some work with PRADO (http://pradosoft.com) I've dabbled with a number of languages in the past, Python being no exception, but always ended up coming back to PHP due to being comfortable with it. Python has stuck to me as a language I _really_ think I should know more about. I've recently tried C#, a very short lived re-attempt at C++ and Java, and Ruby. None of those seemed "fun" except for Ruby, although from what I've seen the syntax between Ruby and Python are very similar to each other compared to the other languages. Anyway, my first question was if anyone knows of a tutorial that focuses on PHP -> Python learning, in such that there might be a block of PHP code alongside an example of how to do the same thing in Python. One example of something I've already mapped a comparison to thanks to standard tutorials is a PHP numeric indexed array being similar to a list and a PHP associative array being similar to a dictionary. Of course finding such of a tutorial isn't a deal breaker by any means, but I figured that having it available would be a boon for me to actually make some headway in my Python learning adventure. If there's anything else that could be said about the migration between the two languages, I'm all ears. I also don't really need to hear about how "disgusting" php is as a language...I am aware of the contained chaos that is PHP4, which is why I develop strictly in 5 using its OOP to the extent my feeble brain allows, a wariness toward the insecure pitfalls the language has begat in the past, and an attempt to produce as clean of a syntax as the language can allow. Thanks in advance for any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > # def defines a method in Python > def say_hello(name): > print 'hello', name > say_hello('Jack') > say_hello('Jill') > Doesn't def define methods *xor* functions, depending on the context? And in this example, say_hello (*yuck*, underscores ...) is certainly a function. Or is it that functions are considered "module-methods"? W -- http://mail.python.org/mailman/listinfo/python-list
Re: PyPI bdist_wininst upload failing
Gabriel Genellina wrote: > En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard > <[EMAIL PROTECTED]> escribió: > >> Also, I couldn't get the StringIO code from there to work: >> >> >>> import StringIO >> >>> content = open('argparse-0.8.0.win32.exe').read() > > Use open("...","rb").read() - the "b" is important on Windows. Ahh, great. Thanks. So any ideas why distutils is generating a bdist_wininst installer with file names like: lib/argparse-0.8.0-py2.5.egg-info lib/argparse.py instead of what John Machin had: PURELIB/xlrd-0.6.1a4-py2.5.egg-info PURELIB/xlrd/biffh.py The ones with 'lib' instead of 'PURELIB' will get rejected by the safe_zipnames regular expression in verify_filetype.py: re.compile(r'(purelib|platlib|headers|scripts|data).+', re.I) Is there something I need to do when running 'setup.py bdist_wininst' to get 'PURELIB' instead of 'lib'? STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
quoth the romiro: > Hi all, ... > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in > Python. One example of something I've already mapped a comparison to > thanks to standard tutorials is a PHP numeric indexed array being > similar to a list and a PHP associative array being similar to a > dictionary. Of course finding such of a tutorial isn't a deal breaker > by any means, but I figured that having it available would be a boon > for me to actually make some headway in my Python learning adventure. Not a tutorial, and the code is not alongside each other, but the PLEAC [1] website may serve as a decent code comparison between PHP and Python. As for a tutorial, if you are already experienced you will probably want to check out "Dive into Python. [2] Have fun, -d [1] http://pleac.sourceforge.net/ [2] http://diveintopython.org/toc/index.html -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
En Sun, 27 May 2007 12:41:36 -0300, romiro <[EMAIL PROTECTED]> escribió: > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in I don't know of a specific PHP->Python tutorial, but "Instant Python" would give you a brief tour, and "Dive into Python" is a good book for people with some previous programming background. Both should be easy to find using Google. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
--- romiro <[EMAIL PROTECTED]> wrote: > > Anyway, my first question was if anyone knows of a > tutorial that > focuses on PHP -> Python learning, in such that > there might be a block > of PHP code alongside an example of how to do the > same thing in > Python. I know exactly what you mean, and I couldn't find anything in my quick Google search either. Maybe you could send us a couple small snippets of PHP code, and we could translate them for you? You may also find this helpful, if you just want to get a real quick look at some representative Python code: http://wiki.python.org/moin/SimplePrograms In case you're not aware that Python has a tutorial, here's a link for you, but it doesn't have the focus on transition from PHP that you're looking for. http://docs.python.org/tut/ Get the Yahoo! toolbar and be alerted to new email wherever you're surfing. http://new.toolbar.yahoo.com/toolbar/features/mail/index.php -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
On May 27, 9:41 am, romiro <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm a PHP5 developer looking to "broaden my horizons" so to speak by > learning a new language. I emphasize the 5 in PHP since I have fully > engrossed myself in the full OOP of version 5 with my own ground-up > projects as well as some work with PRADO (http://pradosoft.com) > > I've dabbled with a number of languages in the past, Python being no > exception, but always ended up coming back to PHP due to being > comfortable with it. Python has stuck to me as a language I _really_ > think I should know more about. I've recently tried C#, a very short > lived re-attempt at C++ and Java, and Ruby. None of those seemed > "fun" except for Ruby, although from what I've seen the syntax between > Ruby and Python are very similar to each other compared to the other > languages. > > Anyway, my first question was if anyone knows of a tutorial that > focuses on PHP -> Python learning, in such that there might be a block > of PHP code alongside an example of how to do the same thing in > Python. One example of something I've already mapped a comparison to > thanks to standard tutorials is a PHP numeric indexed array being > similar to a list and a PHP associative array being similar to a > dictionary. Of course finding such of a tutorial isn't a deal breaker > by any means, but I figured that having it available would be a boon > for me to actually make some headway in my Python learning adventure. > > If there's anything else that could be said about the migration > between the two languages, I'm all ears. I also don't really need to > hear about how "disgusting" php is as a language...I am aware of the > contained chaos that is PHP4, which is why I develop strictly in 5 > using its OOP to the extent my feeble brain allows, a wariness toward > the insecure pitfalls the language has begat in the past, and an > attempt to produce as clean of a syntax as the language can allow. > > Thanks in advance for any help. Read "Learning Python(2nd ed)" and do all the exercises. If you have questions, post them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
On May 27, 3:35 am, Ben Finney <[EMAIL PROTECTED]> wrote: > Paul McGuire <[EMAIL PROTECTED]> writes: > > At this point, I realized that I was taking things too far > > off-topic, so I decided to start a new thread. > > So, uh, what's the purpose of this thread? Did you have a specific > point to start off with, or a question to ask? > > -- > \ "It seems intuitively obvious to me, which means that it might | > `\be wrong." -- Chris Torek | > _o__) | > Ben Finney (Nice sig quote, by the way.) Mostly, I started this thread so any discussion of lower_case_with_underscores (l_c_w_u) vs. mixedCase naming styles would not (further) clutter up Steve Howell's thread. To recap: - I was surprised at the comments to convert Steve's example to l_c_w_u, as the last time I read PEP-8, it had the more liberal "use whichever you prefer, just be consistent" wording. - I posted one comment that I thought l_c_w_u looks old-fashioned, and was an odd choice in the face of mixedCase, which has been adopted as de facto practice in recent languages. - I also mused on the implications for l_c_w_u in the face of Py3K's recent acceptance of non-ASCII identifiers, and added as a related point my own personal experience with typing '_' on a non-US keyboard layout. - At this point, I tracked down the python-dev archive of the discussion thread that led to the stricter version of PEP-8, and I can see that this is a windmill (like the choice of '@' sign for decorators) that is not worth tilting at. It is a bit reassuring that I am not the only one who turns a blind eye to this part of the PEP, that l_c_w_u bothers others as well. But as to the further purpose for this thread, I think there is little to none. We will continue to see std lib code written using l_c_w_u. Ordinarily, this would little concern me, since I go to read std lib code about once/year. But it does mean that additions to the external API to the std lib will contain method calls such as get_files, send_message, delete_record, etc. I think this just promotes a perception of Python as "so last century." It would also seem we will continue to see 3rd party developers use whatever their personal taste and/or project coding standards dictate. So for these users, this part of the PEP is "not really a code, its more of a guideline."* -- Paul *same joke was in Ghostbusters and Pirates of the Caribbean, Pt.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
--- romiro <[EMAIL PROTECTED]> wrote: > I've recently tried > C#, a very short > lived re-attempt at C++ and Java, and Ruby. To the extend that you're familiar with C++/Java/Ruby, you may find this link as an interesting way to see how Python looks: http://www.dmh2000.com/cjpr/cmpframe.html Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 -- http://mail.python.org/mailman/listinfo/python-list
Re: Large Amount of Data
John, thanks for your reply. I will then use the files as input to generate an index. So the files are temporary, and provide some attributes in the index. So I do this multiple times to gather different attributes, merge, etc. "John Machin" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On May 27, 11:24 am, "Jack" <[EMAIL PROTECTED]> wrote: >> I'll save them in a file for further processing. > > Further processing would be what? > Did you read the remainder of what I wrote? > -- http://mail.python.org/mailman/listinfo/python-list
Re: PyPI bdist_wininst upload failing
Steven Bethard wrote: > Gabriel Genellina wrote: >> En Sun, 27 May 2007 12:19:03 -0300, Steven Bethard >> <[EMAIL PROTECTED]> escribió: >> >>> Also, I couldn't get the StringIO code from there to work: >>> >>> >>> import StringIO >>> >>> content = open('argparse-0.8.0.win32.exe').read() >> >> Use open("...","rb").read() - the "b" is important on Windows. > > Ahh, great. Thanks. > > So any ideas why distutils is generating a bdist_wininst installer with > file names like: > > lib/argparse-0.8.0-py2.5.egg-info > lib/argparse.py > > instead of what John Machin had: > > PURELIB/xlrd-0.6.1a4-py2.5.egg-info > PURELIB/xlrd/biffh.py > > The ones with 'lib' instead of 'PURELIB' will get rejected by the > safe_zipnames regular expression in verify_filetype.py: > > re.compile(r'(purelib|platlib|headers|scripts|data).+', re.I) > > Is there something I need to do when running 'setup.py bdist_wininst' to > get 'PURELIB' instead of 'lib'? I figured it out. As suggested here: http://peak.telecommunity.com/DevCenter/EasyInstall#administrator-installation I had created a distutils.cfg to redirect my installs from the regular site-packages directory. Since the distutils.cfg settings are read in for all distutils uses at the command line, they were also being read in when I tried to run "setup.py bdist_wininst", and so all my filenames were getting the altered paths instead of the regular PURELIB ones. Thanks everyone for the help! STeVe -- http://mail.python.org/mailman/listinfo/python-list
[ANN] argparse 0.8 - Command-line parsing library
=== Announcing argparse 0.8 === The argparse module is an optparse-inspired command line parser that improves on optparse by supporting: * positional arguments * sub-commands * required options * options with a variable number of args * better usage messages * a much simpler extension mechanism and a number of other improvements on the optparse API. Download argparse = argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ Example argparse code = Here's a simple program that sums its the command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', nargs='+', type=int) parser.add_argument('--log', default=sys.stdout, type=argparse.FileType('w')) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() About this release == This release adds support for options with different prefix characters, a parser-level default for all arguments, and help messages for subparser commands. The deprecated 'outfile' type was finally removed in this release. Please update your code to use the FileType factory. New features * Options with different prefix characters, e.g. ``+foo`` or ``/bar``, using the new ``prefix_chars=`` keyword argument to ArgumentParser. * A parser-level argument default using the new ``argument_default=`` keyword argument to ArgumentParser. * Support for ``help=`` in the ``add_parser()`` method of subparsers. Bugs fixed -- * ``set_defaults()`` now correctly overrides defaults from ``add_argument()`` calls * ``default=SUPPRESS`` now correctly suppresses the action for positional arguments with ``nargs='?'`` or ``nargs='*'``. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
--- erikcw <[EMAIL PROTECTED]> wrote: > > > > > ('SELECT payment_id FROM amember_payments WHERE > member_id=%s AND > > > expire_date > NOW() AND completed=1 AND > (product_id >11 AND product_id > > > <21)', (1608L,)) > > > () > > > > Here is a copy of the table schema and the first 2 > rows. > Does your table actually contain any rows that meet the criteria that expire_date is in the future, completed is 1, product id is between 11 and 21, etc.? Have you tried debugging the SQL outside of Python? Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. http://tv.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- Wildemar Wildenburger <[EMAIL PROTECTED]> wrote: > Steve Howell wrote: > > # def defines a method in Python > > def say_hello(name): > > print 'hello', name > > say_hello('Jack') > > say_hello('Jill') > > > Doesn't def define methods *xor* functions, > depending on the context? > And in this example, say_hello (*yuck*, underscores > ...) is certainly a > function. Or is it that functions are considered > "module-methods"? > Goodness, I didn't expect such a simple example to be so controversial. But please see the new version here: http://wiki.python.org/moin/SimplePrograms I changed the method name to "greet" and removed the comment, as hopefully the intent of the program will be pretty obvious to anyone that reads it. Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP5 programmer learning Python
In article <[EMAIL PROTECTED]>, Gabriel Genellina <[EMAIL PROTECTED]> wrote: >En Sun, 27 May 2007 12:41:36 -0300, romiro <[EMAIL PROTECTED]> escribió: > >> Anyway, my first question was if anyone knows of a tutorial that >> focuses on PHP -> Python learning, in such that there might be a block >> of PHP code alongside an example of how to do the same thing in > >I don't know of a specific PHP->Python tutorial, but "Instant Python" >would give you a brief tour, and "Dive into Python" is a good book for >people with some previous programming background. Both should be easy to >find using Google. . . . Along with accurate advice others have already given you here ("Dive into Python" would be my preferred starting point), it occurs to me you might want http://www.unixreview.com/documents/s=7822/ur0303j/ > at your side. Also, back in the PHP world, http://www.unixreview.com/documents/s=10102/ur0611c/ > might interest you, if you're not already familiar with it. -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > --- Steven Bethard <[EMAIL PROTECTED]> wrote: >> Very cool! Do you mind putting this up on the Wiki >> somewhere so that we >> can link to it more easily? Maybe something like: >> >> http://wiki.python.org/moin/SimplePrograms >> > > Done. I think I would rewrite the current unit-testing example to use the standard library unittest module:: # Let's write reusable code, and unit test it. def add_money(amounts): # do arithmetic in pennies so as not to accumulate float errors pennies = sum([round(int(amount * 100)) for amount in amounts]) return float(pennies / 100.0) import unittest class TestAddMoney(unittest.TestCase): def test_float_errors(self): self.failUnlessEqual(add_money([0.13, 0.02]), 0.15) self.failUnlessEqual(add_money([100.01, 99.99]), 200) self.failUnlessEqual(add_money([0, -13.00, 13.00]), 0) if __name__ == '__main__': unittest.main() I believe I've still kept it to 13 lines. STeVe P.S. The "right" way to add money is using the decimal module, but I couldn't think of a better example. -- http://mail.python.org/mailman/listinfo/python-list
itertools.groupby
Bejeezus. The description of groupby in the docs is a poster child for why the docs need user comments. Can someone explain to me in what sense the name 'uniquekeys' is used this example: import itertools mylist = ['a', 1, 'b', 2, 3, 'c'] def isString(x): s = str(x) if s == x: return True else: return False uniquekeys = [] groups = [] for k, g in itertools.groupby(mylist, isString): uniquekeys.append(k) groups.append(list(g)) print uniquekeys print groups --output:-- [True, False, True, False, True] [['a'], [1], ['b'], [2, 3], ['c']] -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- 7stud <[EMAIL PROTECTED]> wrote: > Bejeezus. The description of groupby in the docs is > a poster child > for why the docs need user comments. Can someone > explain to me in > what sense the name 'uniquekeys' is used this > example: [...] > The groupby method has its uses, but it's behavior is going to be very surprising to anybody that has used the "group by" syntax of SQL, because Python's groupby method will repeat groups if your data is not sorted, whereas SQL has the luxury of (knowing that it's) working with a finite data set, so it can provide the more convenient semantics. You snooze, you lose. Get messages ASAP with AutoCheck in the all-new Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_html.html -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
On May 27, 11:28 am, Steve Howell <[EMAIL PROTECTED]> wrote: > --- 7stud <[EMAIL PROTECTED]> wrote: > > Bejeezus. The description of groupby in the docs is > > a poster child > > for why the docs need user comments. Can someone > > explain to me in > > what sense the name 'uniquekeys' is used this > > example: [...] > > The groupby method has its uses, but it's behavior is > going to be very surprising to anybody that has used > the "group by" syntax of SQL, because Python's groupby > method will repeat groups if your data is not sorted, > whereas SQL has the luxury of (knowing that it's) > working with a finite data set, so it can provide the > more convenient semantics. > > ___ > _You snooze, you lose. Get messages ASAP with AutoCheck > in the all-new Yahoo! Mail > Beta.http://advision.webevents.yahoo.com/mailbeta/newmail_html.html > The groupby method has its uses I'd settle for a simple explanation of what it does in python. -- http://mail.python.org/mailman/listinfo/python-list
What's the best way to iniatilize a function
I have a set of functions to wrap a library. For example, mylib_init() mylib_func() mylib_exit() or handle = mylib_init() mylib_func(handle) mylib_exit(handle) In order to call mylib_func(), mylib_init() has to be called once. When it's done, or when program exits, mylib_exit() should be called once to free resources. I can list all three functions in a module and let the application manage the init call and exit call. Or, better, to have the wrapper function manage these calls. I'm currently using a singleton class (see below.) It seems to work fine. My questions here are: 1. every time I call the function: MyLib().func() part of the object creation code is called, at least to check if there is an existing instance of the class, then return it. So it may not be very efficient. Is there a better way? 2. what's the right way to call mylib_exit()? I put it in __del__(self) but it is not being called in my simple test. STATUS_UNINITIALIZED = 0 STATUS_INITIALIZED = 1 STATUS_ERROR = 2 class MyLib (object): instance = None status = STATUS_UNINITIALIZED def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance def __init__(self): if self.status == STATUS_UNINITIALIZED: mylib_init() self.status = STATUS_INITIALIZED def func(self): return mylib_func() def __del__(self): mylib_exit() -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- 7stud <[EMAIL PROTECTED]> wrote: > Bejeezus. The description of groupby in the docs is > a poster child > for why the docs need user comments. I would suggest an example with a little more concreteness than what's currently there. For example, this code... import itertools syslog_messages = [ 'out of file descriptors', 'out of file descriptors', 'unexpected access', 'out of file descriptors', ] for message, messages in itertools.groupby(syslog_messages): print message, len(list(messages)) ...produces this... out of file descriptors 2 unexpected access 1 out of file descriptors 1 Get the free Yahoo! toolbar and rest assured with the added security of spyware protection. http://new.toolbar.yahoo.com/toolbar/features/norton/index.php -- http://mail.python.org/mailman/listinfo/python-list
Announcing: ACM SIGAPL apl 2007 -- Arrays and Objects
The APL 2007 conference, sponsored by ACM SIGAPL, has as its principal theme "Arrays and Objects" and, appropriately, is co-located with OOPSLA 2007, in Montreal this October. APL 2007 starts with a tutorial day on Sunday, October 21, followed by a two-day program on Monday and Tuesday, October 22 and 23. APLers are welcome to attend OOPSLA program events on Monday and Tuesday (and OOPSLA attendees are welcome to come to APL program events). Registrants at APL 2007 can add full OOPSLA attendance at a favorable price. Dates: Sunday Oct 21 Tutorials Monday, Tuesday Oct 22,23APL 2007 program Monday-Friday Oct 22-26OOPSLA program APL 2007 keynote speaker: Guy Steele, Sun Microsystems Laboratories Tutorials Using objects within APL Array language practicum Intro to [language] for other-language users ( We expect that there will be at least one introductory tutorial on "classic" APL, and hope to have introductions to a variety of array languages ) We solicit papers and proposals for tutorials, panels and workshops on all aspects of array-oriented programming and languages; this year we have particular interest in the themes of integrating the use of arrays and objects languages that support the use of arrays as a central and thematic technique marketplace and education: making practitioners aware of array thinking and array languages Our interest is in the essential use of arrays in programming in any language (though our historical concern has been the APL family of languages: classic APL, J, K, NIAL, ). Dates: Tutorial, panel, and workshop proposals, and notice of intent to submit papers, are due by Friday June 15, to the Program Chair. Contributed papers, not more than 10 pages in length, are due by Monday, July 23, to the Program Chair. Details of form of submission can be obtained from the program chair. Deadline for detailed tutorial/panel/workshop information TBA. Cost (to SIGAPL and ACM members, approximate $US, final cost TBA) APL2007 registration $375 Tutorial day $250 Single conference days $200 Social events:Opening reception Monday Others TBA Conference venue: Palais de Congres, Montreal, Quebec, CANADA Conference hotel: Hyatt Regency Montreal Committee General Chair Guy Laroque [EMAIL PROTECTED] Program Chair Lynne C. Shaw[EMAIL PROTECTED] Treasurer Steven H. Rogers [EMAIL PROTECTED] Publicity Mike Kent[EMAIL PROTECTED] Links APL2007 http://www.sigapl.org/apl2007 OOPSLA 2007 http://www.oopsla.org/oopsla2007 Palais de Congreshttp://www.congresmtl.com/ Hyatt Regency Montreal http://montreal.hyatt.com Guy Steelehttp://research.sun.com/people/mybio.php?uid=25706 ACM SIGAPLhttp://www.sigapl.org -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > I think I would rewrite the current unit-testing > example to use the > standard library unittest module:: > > # Let's write reusable code, and unit test it. > def add_money(amounts): > # do arithmetic in pennies so as not to > accumulate float errors > pennies = sum([round(int(amount * 100)) for > amount in amounts]) > return float(pennies / 100.0) > import unittest > class TestAddMoney(unittest.TestCase): > def test_float_errors(self): > self.failUnlessEqual(add_money([0.13, > 0.02]), 0.15) > self.failUnlessEqual(add_money([100.01, > 99.99]), 200) > self.failUnlessEqual(add_money([0, > -13.00, 13.00]), 0) > if __name__ == '__main__': > unittest.main() > > I believe I've still kept it to 13 lines. > I approve this change, although in a sense, it's harder for a Python newbie, because it introduces inheritance a little earlier than I would have liked. FWIW I'm in the minority (I think) of people that prefer roll-your-own testing, but I don't want to argue that, because I think it mostly comes down to personal preference. I'll only defend my position by posting this link, which suggests that roll-your-own even has validity in an educational setting: http://www.elkner.net/jeff/testFirst/index.html > P.S. The "right" way to add money is using the > decimal module, but I > couldn't think of a better example. Agreed. Maybe somebody else will come up with something more creative, but I'm happy enough with our current version. Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > > I think I would rewrite the current unit-testing > example to use the > standard library unittest module:: > > # Let's write reusable code, and unit test it. > def add_money(amounts): > # do arithmetic in pennies so as not to > accumulate float errors > pennies = sum([round(int(amount * 100)) for > amount in amounts]) > return float(pennies / 100.0) > import unittest > class TestAddMoney(unittest.TestCase): > def test_float_errors(self): > self.failUnlessEqual(add_money([0.13, > 0.02]), 0.15) > self.failUnlessEqual(add_money([100.01, > 99.99]), 200) > self.failUnlessEqual(add_money([0, > -13.00, 13.00]), 0) > if __name__ == '__main__': > unittest.main() > Just a minor quibble, but wouldn't you want the import and test class to only get executed in the ___main__ context? Got a little couch potato? Check out fun summer activities for kids. http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Stefan Sonnenberg-Carstens wrote: > Paul McGuire schrieb: > > I'm starting a new thread for this topic, so as not to hijack the one > > started by Steve Howell's excellent post titled "ten small Python > > programs". > > > > In that thread, there was a suggestion that these examples should > > conform to PEP-8's style recommendations, including use of > > lower_case_with_underscores style for function names. I raised some > > questions about this suggestion, since I liked the names the way they > > were, but as a result, part of the discussion has drifted into a > > separate track about PEP-8, and naming styles. > > > > I was under the impression that lower_case_with_underscores was a > > dated recommendation, and that recent practice is more inclusive of > > mixedCase style identifiers. On the contrary, Steven Bethard > > straightened me out, saying that PEP-8 used to accept either style, > > but has been amended to accept only lower_case_with_underscores. > > > > My latest thought on the topic relates back to the Martin v. Lo:wis > > thread-that-would-not-die requesting feedback about PEP 3131, on > > adding support for non-ASCII identifiers in Py3K. I posted an out-of- > > curiosity comment asking about how underscore separators mix with > > Unicode identifiers, including the mechanics of actually typing an > > underscore on a non-US keyboard. At this point, I realized that I was > > taking things too far off-topic, so I decided to start a new thread. > > > > Steve, sorry for taking your thread down a rathole. I hope we can > > move any further PEP-8-related discussion (if the point merits any) to > > this thread. > > > > -- Paul > > > > > I prefer mixedCaseStyle, and I think that should be "standard", as this > style is commonly > used in all "major" languages , for example Java,C++,C#. > It shortens the identifiers but leaves the meaning intact. Actually, proper_case is standard in C++ (see, e.g., the naming section of http://www.research.att.com/~bs/bs_faq2.html ) . And C is still more common than Java, and Perl and Lisp are about as common as C#--all use proper case (though Lisp uses - instead of _). Historically, it's only Java and the Windows world (including non- standard Windows-style C++) that use forcedCase significantly (C# draws from both). The underscore version is not "lower case"; it is "proper case"--case is used as in normal English. Compare plot_line_slope() vs. plot_line_Besenheim(); with the underscore method, you preserve all the natural meaning of case. Especially when you have, say, acronyms in variable names, forcedCase can be somewhat confusing even for native English speakers; the style forces you to use a specific case for naming convention reasons, losing the natural meaning of the case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Carsten Haese wrote: > On Sun, 2007-05-27 at 07:30 +, OKB (not okblacke) wrote: >> Underscores are harder to type than any alphanumeric >> character. > > This is a discussion about underscores versus capital letters > denoting the word boundaries in identifiers. How is an underscore > harder to type than a capital letter? It is harder in that the key that has the underscore on it is quite out of the way compared to any letter key. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- 7stud <[EMAIL PROTECTED]> wrote: > > I'd settle for a simple explanation of what it does > in python. > The groupby function prevents you have from having to write awkward (and possibly broken) code like this: group = [] lastKey = None for item in items: newKey = item.key() if newKey == lastKey: group.append(word) elif group: doSomething(group) group = [] lastKey = newKey if group: doSomething(group) See my other reply for what it actually does in a simple example. Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- Steve Howell <[EMAIL PROTECTED]> wrote: > > --- 7stud <[EMAIL PROTECTED]> wrote: > > > Bejeezus. The description of groupby in the docs > is > > a poster child > > for why the docs need user comments. > Regarding the pitfalls of groupby in general (even assuming we had better documentation), I invite people to view the following posting that I made on python-ideas, entitled "SQL-like way to manipulate Python data structures": http://mail.python.org/pipermail/python-ideas/2007-May/000807.html In the thread, I don't really make a proposal, so much as a problem statement, but my radical idea is that lists of dictionaries fit the relational model perfectly, so why not allow some kind of native SQL syntax in Python that allows you to manipulate those data structures more naturally? Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > --- Steven Bethard <[EMAIL PROTECTED]> wrote: >> I think I would rewrite the current unit-testing >> example to use the >> standard library unittest module:: >> >> # Let's write reusable code, and unit test it. >> def add_money(amounts): >> # do arithmetic in pennies so as not to >> accumulate float errors >> pennies = sum([round(int(amount * 100)) for >> amount in amounts]) >> return float(pennies / 100.0) >> import unittest >> class TestAddMoney(unittest.TestCase): >> def test_float_errors(self): >> self.failUnlessEqual(add_money([0.13, >> 0.02]), 0.15) >> self.failUnlessEqual(add_money([100.01, >> 99.99]), 200) >> self.failUnlessEqual(add_money([0, >> -13.00, 13.00]), 0) >> if __name__ == '__main__': >> unittest.main() >> > > Just a minor quibble, but wouldn't you want the import > and test class to only get executed in the ___main__ > context? That would be fine too. In the real world, I'd put the tests in a different module. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
"OKB (not okblacke)" <[EMAIL PROTECTED]> writes: > Underscores are harder to type than any alphanumeric character. I know of no keyboard layout in common use where it's more complicated than +, exactly the same as a single uppercase letter. Care to enlighten me? -- \"Conscience is the inner voice that warns us somebody is | `\looking." -- Henry L. Mencken | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Stefan Sonnenberg-Carstens <[EMAIL PROTECTED]> writes: > I prefer mixedCaseStyle, and I think that should be "standard", I dislike it. It's inconsistent, and confusingly similar to TitleCaseStyle used for class names in Python. > as this style is commonly used in all "major" languages , for > example Java,C++,C#. Is C no longer a "major" language? The long-standing convention there is for lower_case_with_underscores. > It shortens the identifiers but leaves the meaning intact. The shortening is both minor, and irrelevant: clarity is worth more than shorter names merely for the sake of shorter names. -- \ "If you're a young Mafia gangster out on your first date, I bet | `\it's real embarrassing if someone tries to kill you." -- Jack | _o__) Handey | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > --- Steven Bethard <[EMAIL PROTECTED]> wrote: > >> I think I would rewrite the current unit-testing >> example to use the >> standard library unittest module:: >> >> # Let's write reusable code, and unit test it. >> def add_money(amounts): >> # do arithmetic in pennies so as not to >> accumulate float errors >> pennies = sum([round(int(amount * 100)) for >> amount in amounts]) >> return float(pennies / 100.0) >> import unittest >> class TestAddMoney(unittest.TestCase): >> def test_float_errors(self): >> self.failUnlessEqual(add_money([0.13, >> 0.02]), 0.15) >> self.failUnlessEqual(add_money([100.01, >> 99.99]), 200) >> self.failUnlessEqual(add_money([0, >> -13.00, 13.00]), 0) >> if __name__ == '__main__': >> unittest.main() >> >> I believe I've still kept it to 13 lines. >> > > I approve this change, although in a sense, it's > harder for a Python newbie, because it introduces > inheritance a little earlier than I would have liked. > > FWIW I'm in the minority (I think) of people that > prefer roll-your-own testing, but I don't want to > argue that, because I think it mostly comes down to > personal preference. Have you tried py.test? http://codespeak.net/py/dist/test.html I've heard good things about it, but haven't gotten around to trying it yet. Here's a two-line test suite from the page above: def test_answer(): assert 42 == 43 STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > Steve Howell wrote: > > --- Steven Bethard <[EMAIL PROTECTED]> > wrote: > >> I think I would rewrite the current unit-testing > >> example to use the > >> standard library unittest module:: > >> > >> # Let's write reusable code, and unit test > it. > >> def add_money(amounts): > >> # do arithmetic in pennies so as not to > >> accumulate float errors > >> pennies = sum([round(int(amount * 100)) > for > >> amount in amounts]) > >> return float(pennies / 100.0) > >> import unittest > >> class TestAddMoney(unittest.TestCase): > >> def test_float_errors(self): > >> > self.failUnlessEqual(add_money([0.13, > >> 0.02]), 0.15) > >> > self.failUnlessEqual(add_money([100.01, > >> 99.99]), 200) > >> self.failUnlessEqual(add_money([0, > >> -13.00, 13.00]), 0) > >> if __name__ == '__main__': > >> unittest.main() > >> > > > > Just a minor quibble, but wouldn't you want the > import > > and test class to only get executed in the > ___main__ > > context? > > That would be fine too. In the real world, I'd put > the tests in a > different module. > Maybe this is the first good example that motivates a hyperlink to alternatives. Would you accept the idea that we keep my original example on the SimplePrograms page, but we link to a UnitTestingPhilosophies page, and we show your alternative there? Or vice versa, show your example on the first page, but then show mine on the hyperlinked page? I am in 100% agreement with you that most unit tests would be completely outside the module, although I often follow the practice that my modules have a little "if __main__" section that runs a few simple unit tests, as sort of a bit of self-documentation. Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > --- Steven Bethard <[EMAIL PROTECTED]> wrote: > >> Steve Howell wrote: >>> --- Steven Bethard <[EMAIL PROTECTED]> >> wrote: I think I would rewrite the current unit-testing example to use the standard library unittest module:: # Let's write reusable code, and unit test >> it. def add_money(amounts): # do arithmetic in pennies so as not to accumulate float errors pennies = sum([round(int(amount * 100)) >> for amount in amounts]) return float(pennies / 100.0) import unittest class TestAddMoney(unittest.TestCase): def test_float_errors(self): >> self.failUnlessEqual(add_money([0.13, 0.02]), 0.15) >> self.failUnlessEqual(add_money([100.01, 99.99]), 200) self.failUnlessEqual(add_money([0, -13.00, 13.00]), 0) if __name__ == '__main__': unittest.main() >>> Just a minor quibble, but wouldn't you want the >> import >>> and test class to only get executed in the >> ___main__ >>> context? >> That would be fine too. In the real world, I'd put >> the tests in a >> different module. >> > > Maybe this is the first good example that motivates a > hyperlink to alternatives. Would you accept the idea > that we keep my original example on the SimplePrograms > page, but we link to a UnitTestingPhilosophies page, > and we show your alternative there? Or vice versa, > show your example on the first page, but then show > mine on the hyperlinked page? Sure. Either way is fine. STeVe -- http://mail.python.org/mailman/listinfo/python-list
unit testing
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > Have you tried py.test? > > http://codespeak.net/py/dist/test.html > > I've heard good things about it, but haven't gotten > around to trying it > yet. Here's a two-line test suite from the page > above: > > def test_answer(): > assert 42 == 43 > Changed the subject line. Nope, I haven't. I'm a tremendous advocate of unit testing, but I've never felt compelled to try out other libraries, because I work mostly on private code now, so the following-standard-practices-to-benefit-from-familiarity argument doesn't carry much weight with me, and also because I find it easy enough to do things on a roll-your-own basis. YMMV, of course. I have slowly introduced unit testing into my own work environment, with some success. We don't use a 3rd party testing framework, but here's my roll-your-own approach: 1) For flat-out failures, we just fail with a traceback right away. We don't bother to capture stats on how many tests failed. If one test fails, that's enough to clue in a developer that he/she broke something. 2) We don't use assertions very often, but rather just diff the output files to the GOLD files. This may eventually stop to scale, but it hasn't yet. 3)We have a little trickery to override imports, etc., as 99.99% of our code was never written with unit testing in mind, but I still want to regression test it. 4) We have quite a few mock-ish objects, mainly relating to simulating I/O situations. Pinpoint customers who are looking for what you sell. http://searchmarketing.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
--- Steven Bethard <[EMAIL PROTECTED]> wrote: > > > > Maybe this is the first good example that > motivates a > > hyperlink to alternatives. Would you accept the > idea > > that we keep my original example on the > SimplePrograms > > page, but we link to a UnitTestingPhilosophies > page, > > and we show your alternative there? Or vice > versa, > > show your example on the first page, but then show > > mine on the hyperlinked page? > > Sure. Either way is fine. > Ok, for now, I'm taking no action, let's let the unit testing discussion progress a little. Despite my saying early that I don't want to debate it, I do want to discuss it :), as it is near in dear to my heart. Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
On Sun, 2007-05-27 at 10:17 -0700, 7stud wrote: > Bejeezus. The description of groupby in the docs is a poster child > for why the docs need user comments. Can someone explain to me in > what sense the name 'uniquekeys' is used this example: > > > import itertools > > mylist = ['a', 1, 'b', 2, 3, 'c'] > > def isString(x): > s = str(x) > if s == x: > return True > else: > return False > > uniquekeys = [] > groups = [] > for k, g in itertools.groupby(mylist, isString): > uniquekeys.append(k) > groups.append(list(g)) > > print uniquekeys > print groups > > --output:-- > [True, False, True, False, True] > [['a'], [1], ['b'], [2, 3], ['c']] The so-called example you're quoting from the docs is not an actual example of using itertools.groupby, but suggested code for how you can store the grouping if you need to iterate over it twice, since iterators are in general not repeatable. As such, 'uniquekeys' lists the key values that correspond to each group in 'groups'. groups[0] is the list of elements grouped under uniquekeys[0], groups[1] is the list of elements grouped under uniquekeys[1], etc. You are getting surprising results because your data is not sorted by the group key. Your group key alternates between True and False. Maybe you need to explain to us what you're actually trying to do. User-supplied comments to the documentation won't help with that. Regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Paul McGuire <[EMAIL PROTECTED]> writes: > code about once/year. But it does mean that additions to the external > API to the std lib will contain method calls such as get_files, > send_message, delete_record, etc. I think this just promotes a > perception of Python as "so last century." I think you've got it backwards; the godawful MixedCase style goes back to Smalltalk, which couldn't use underscores in identifiers because it had assigned some other purpose to that character. That it was picked up by Java is not evidence of anything other than Java's Vogon-like tastelessness, and of course C# uses it since C# is basically a Java dialect. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
Steve Howell wrote: > --- erikcw <[EMAIL PROTECTED]> wrote: ('SELECT payment_id FROM amember_payments WHERE >> member_id=%s AND expire_date > NOW() AND completed=1 AND >> (product_id >11 AND product_id <21)', (1608L,)) () >> Here is a copy of the table schema and the first 2 >> rows. >> > > Does your table actually contain any rows that meet > the criteria that expire_date is in the future, > completed is 1, product id is between 11 and 21, etc.? > > Have you tried debugging the SQL outside of Python? > This thread all started because a manual query was claimed to succeed when a Python-based one was claimed not to. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
Steve Howell schrieb: > --- Steve Howell <[EMAIL PROTECTED]> wrote: > >> --- 7stud <[EMAIL PROTECTED]> wrote: >> >>> Bejeezus. The description of groupby in the docs >> is >>> a poster child >>> for why the docs need user comments. > > Regarding the pitfalls of groupby in general (even > assuming we had better documentation), I invite people > to view the following posting that I made on > python-ideas, entitled "SQL-like way to manipulate > Python data structures": > > http://mail.python.org/pipermail/python-ideas/2007-May/000807.html > > In the thread, I don't really make a proposal, so much > as a problem statement, but my radical idea is that > lists of dictionaries fit the relational model > perfectly, so why not allow some kind of native SQL > syntax in Python that allows you to manipulate those > data structures more naturally? LINQ? cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
erikcw wrote: > On May 26, 8:21 pm, John Machin <[EMAIL PROTECTED]> wrote: >> On May 27, 5:25 am, erikcw <[EMAIL PROTECTED]> wrote: >> >> >> >>> On May 25, 11:28 am, Carsten Haese <[EMAIL PROTECTED]> wrote: On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >> I'm trying to run the following query: > ... >> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > Shouldn't you be using the bind variable '?' instead of '%s' ? The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. The OP is using parameter substitution correctly, though in an obfuscated fashion. 'sql' is a misnamed tuple containing both the query string *and* the parameters, which is being unpacked with '*' into two arguments to the execute call. The only problem I see is that the parameters should be a sequence, i.e. (self.uid,) instead of just (self.uid). HTH, -- Carsten Haesehttp://informixdb.sourceforge.net >>> I tried adding the comma to make it a sequence - but now change. >>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND >>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id >>> <21)', (1608L,)) >>> () >>> What else could it be? >> Possibly a type mismatch. How is member_id declared in the CREATE >> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). > > Here is a copy of the table schema and the first 2 rows. > > -- phpMyAdmin SQL Dump > -- version 2.9.0.2 > -- http://www.phpmyadmin.net > -- > -- Host: localhost > -- Generation Time: May 27, 2007 at 11:29 AM > -- Server version: 5.0.27 > -- PHP Version: 4.4.2 > -- > -- Database: `lybp_lybp` > -- > > -- > > -- > -- Table structure for table `amember_payments` > -- > > CREATE TABLE `amember_payments` ( > `payment_id` int(11) NOT NULL auto_increment, > `member_id` int(11) NOT NULL default '0', > `product_id` int(11) NOT NULL default '0', > `begin_date` date NOT NULL default '-00-00', > `expire_date` date NOT NULL default '-00-00', > `paysys_id` varchar(32) NOT NULL default '', > `receipt_id` varchar(32) NOT NULL default '', > `amount` decimal(12,2) NOT NULL default '0.00', > `completed` smallint(6) default '0', > `remote_addr` varchar(15) NOT NULL default '', > `data` text, > `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update > CURRENT_TIMESTAMP, > `aff_id` int(11) NOT NULL default '0', > `payer_id` varchar(255) NOT NULL default '', > `coupon_id` int(11) NOT NULL default '0', > `tm_added` datetime NOT NULL default '-00-00 00:00:00', > `tm_completed` datetime default NULL, > `tax_amount` decimal(12,2) NOT NULL default '0.00', > PRIMARY KEY (`payment_id`), > KEY `member_id` (`member_id`), > KEY `payer_id` (`payer_id`), > KEY `coupon_id` (`coupon_id`), > KEY `tm_added` (`tm_added`,`product_id`), > KEY `tm_completed` (`tm_completed`,`product_id`) > ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; > > -- > -- Dumping data for table `amember_payments` > -- > > INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', > '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, > '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 > 19:21:43', 0.00); > INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', > '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, > '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 > 19:20:13', 0.00); > > Thanks for your help! > Erik > I feel obliged to point out that there ARE no rows meeting the criteria you query specified! mysql> SELECT expire_date, NOW() FROM amember_payments; +-+-+ | expire_date | NOW() | +-+-+ | 2004-10-21 | 2007-05-27 15:59:21 | | 2004-11-21 | 2007-05-27 15:59:21 | +-+-+ 2 rows in set (0.02 sec) mysql> So I am not sure how you managed to get a manual query to work, but do be sure that the Python query you mentioned at the start of the thread sql = """SELECT payment_id FROM amember_payments WHERE member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > >11 AND product_id <21)""", (self.uid) doesn't stand a chance of returning any results unless you use a time machine to go back almost three years! regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden -- Asciimercial - Get on the web: Blog, lens and tag your way to fame!! holdenweb.blogspot.comsquidoo.com/pythonology tagged items: del.icio.us/steve.holden/python All these services currently offer free registration! -- Thank You for Reading -- http://mail.python.org/mail
Re: ten small Python programs
Steven Bethard <[EMAIL PROTECTED]> writes: > I think I would rewrite the current unit-testing example to use the > standard library unittest module:: I think these days we're supposed to like doctest better than unittest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
On May 27, 2007, at 4:01 PM, Steve Holden wrote: > erikcw wrote: >> On May 26, 8:21 pm, John Machin <[EMAIL PROTECTED]> wrote: >>> On May 27, 5:25 am, erikcw <[EMAIL PROTECTED]> wrote: >>> >>> >>> On May 25, 11:28 am, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: >>> I'm trying to run the following query: >> ... >>> member_id=%s AND expire_date > NOW() AND completed=1 AND >>> (product_id >> Shouldn't you be using the bind variable '?' instead of '%s' ? > The parameter placeholder for MySQLdb is, indeed and > unfortunately, %s. > The OP is using parameter substitution correctly, though in an > obfuscated fashion. 'sql' is a misnamed tuple containing both > the query > string *and* the parameters, which is being unpacked with '*' > into two > arguments to the execute call. > The only problem I see is that the parameters should be a > sequence, i.e. > (self.uid,) instead of just (self.uid). > HTH, > -- > Carsten Haesehttp://informixdb.sourceforge.net I tried adding the comma to make it a sequence - but now change. ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id <21)', (1608L,)) () What else could it be? >>> Possibly a type mismatch. How is member_id declared in the CREATE >>> TABLE? For diagnostic purposes, try passing in (1608,) and >>> ('1608',). >> >> Here is a copy of the table schema and the first 2 rows. >> >> -- phpMyAdmin SQL Dump >> -- version 2.9.0.2 >> -- http://www.phpmyadmin.net >> -- >> -- Host: localhost >> -- Generation Time: May 27, 2007 at 11:29 AM >> -- Server version: 5.0.27 >> -- PHP Version: 4.4.2 >> -- >> -- Database: `lybp_lybp` >> -- >> >> -- >> >> -- >> -- Table structure for table `amember_payments` >> -- >> >> CREATE TABLE `amember_payments` ( >> `payment_id` int(11) NOT NULL auto_increment, >> `member_id` int(11) NOT NULL default '0', >> `product_id` int(11) NOT NULL default '0', >> `begin_date` date NOT NULL default '-00-00', >> `expire_date` date NOT NULL default '-00-00', >> `paysys_id` varchar(32) NOT NULL default '', >> `receipt_id` varchar(32) NOT NULL default '', >> `amount` decimal(12,2) NOT NULL default '0.00', >> `completed` smallint(6) default '0', >> `remote_addr` varchar(15) NOT NULL default '', >> `data` text, >> `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update >> CURRENT_TIMESTAMP, >> `aff_id` int(11) NOT NULL default '0', >> `payer_id` varchar(255) NOT NULL default '', >> `coupon_id` int(11) NOT NULL default '0', >> `tm_added` datetime NOT NULL default '-00-00 00:00:00', >> `tm_completed` datetime default NULL, >> `tax_amount` decimal(12,2) NOT NULL default '0.00', >> PRIMARY KEY (`payment_id`), >> KEY `member_id` (`member_id`), >> KEY `payer_id` (`payer_id`), >> KEY `coupon_id` (`coupon_id`), >> KEY `tm_added` (`tm_added`,`product_id`), >> KEY `tm_completed` (`tm_completed`,`product_id`) >> ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; >> >> -- >> -- Dumping data for table `amember_payments` >> -- >> >> INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', >> '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, >> '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 >> 19:21:43', 0.00); >> INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', >> '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, >> '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 >> 19:20:13', 0.00); >> >> Thanks for your help! >> Erik >> > I feel obliged to point out that there ARE no rows meeting the > criteria > you query specified! > > mysql> SELECT expire_date, NOW() FROM amember_payments; > +-+-+ > | expire_date | NOW() | > +-+-+ > | 2004-10-21 | 2007-05-27 15:59:21 | > | 2004-11-21 | 2007-05-27 15:59:21 | > +-+-+ > 2 rows in set (0.02 sec) > > mysql> > > So I am not sure how you managed to get a manual query to work, but do > be sure that the Python query you mentioned at the start of the thread > > sql = """SELECT payment_id FROM amember_payments WHERE > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id >>> 11 AND product_id <21)""", (self.uid) > And doesn't the above comma, need to be a percent symbol? Dave > doesn't stand a chance of returning any results unless you use a time > machine to go back almost three years! > > regards > Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Is PEP-8 a Code or More of a Guideline?
Ben Finney <[EMAIL PROTECTED]> wrote: > Is C no longer a "major" language? The long-standing convention there > is for lower_case_with_underscores. Which dates back to the days of ASR-33's which only had one case (upper case, as a matter of fact). Does nobody else remember C compilers which accepted \( and \) for { and }? -- http://mail.python.org/mailman/listinfo/python-list
Can python create a dictionary from a list comprehension?
Hi, I'm trying to turn o list of objects into a dictionary using a list comprehension. Something like entries = {} [entries[int(d.date.strftime('%m'))] = d.id] for d in links] I keep getting errors when I try to do it. Is it possible? Do dictionary objects have a method equivalent to [].append? Maybe a lambda? Thanks for your help! Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: Why isn't this query working in python?
On May 27, 4:01 pm, Steve Holden <[EMAIL PROTECTED]> wrote: > erikcw wrote: > > On May 26, 8:21 pm, John Machin <[EMAIL PROTECTED]> wrote: > >> On May 27, 5:25 am, erikcw <[EMAIL PROTECTED]> wrote: > > >>> On May 25, 11:28 am, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Fri, 2007-05-25 at 09:51 -0500, Dave Borne wrote: > >> I'm trying to run the following query: > > ... > >> member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > Shouldn't you be using the bind variable '?' instead of '%s' ? > The parameter placeholder for MySQLdb is, indeed and unfortunately, %s. > The OP is using parameter substitution correctly, though in an > obfuscated fashion. 'sql' is a misnamed tuple containing both the query > string *and* the parameters, which is being unpacked with '*' into two > arguments to the execute call. > The only problem I see is that the parameters should be a sequence, i.e. > (self.uid,) instead of just (self.uid). > HTH, > -- > Carsten Haesehttp://informixdb.sourceforge.net > >>> I tried adding the comma to make it a sequence - but now change. > >>> ('SELECT payment_id FROM amember_payments WHERE member_id=%s AND > >>> expire_date > NOW() AND completed=1 AND (product_id >11 AND product_id > >>> <21)', (1608L,)) > >>> () > >>> What else could it be? > >> Possibly a type mismatch. How is member_id declared in the CREATE > >> TABLE? For diagnostic purposes, try passing in (1608,) and ('1608',). > > > Here is a copy of the table schema and the first 2 rows. > > > -- phpMyAdmin SQL Dump > > -- version 2.9.0.2 > > --http://www.phpmyadmin.net > > -- > > -- Host: localhost > > -- Generation Time: May 27, 2007 at 11:29 AM > > -- Server version: 5.0.27 > > -- PHP Version: 4.4.2 > > -- > > -- Database: `lybp_lybp` > > -- > > > -- > > > -- > > -- Table structure for table `amember_payments` > > -- > > > CREATE TABLE `amember_payments` ( > > `payment_id` int(11) NOT NULL auto_increment, > > `member_id` int(11) NOT NULL default '0', > > `product_id` int(11) NOT NULL default '0', > > `begin_date` date NOT NULL default '-00-00', > > `expire_date` date NOT NULL default '-00-00', > > `paysys_id` varchar(32) NOT NULL default '', > > `receipt_id` varchar(32) NOT NULL default '', > > `amount` decimal(12,2) NOT NULL default '0.00', > > `completed` smallint(6) default '0', > > `remote_addr` varchar(15) NOT NULL default '', > > `data` text, > > `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update > > CURRENT_TIMESTAMP, > > `aff_id` int(11) NOT NULL default '0', > > `payer_id` varchar(255) NOT NULL default '', > > `coupon_id` int(11) NOT NULL default '0', > > `tm_added` datetime NOT NULL default '-00-00 00:00:00', > > `tm_completed` datetime default NULL, > > `tax_amount` decimal(12,2) NOT NULL default '0.00', > > PRIMARY KEY (`payment_id`), > > KEY `member_id` (`member_id`), > > KEY `payer_id` (`payer_id`), > > KEY `coupon_id` (`coupon_id`), > > KEY `tm_added` (`tm_added`,`product_id`), > > KEY `tm_completed` (`tm_completed`,`product_id`) > > ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=11020 ; > > > -- > > -- Dumping data for table `amember_payments` > > -- > > > INSERT INTO `amember_payments` VALUES (423, 107, 1, '2004-10-01', > > '2004-10-21', 'authorize_aim', '5687944', 3.95, 1, '', NULL, > > '2004-11-30 19:21:43', 0, '', 0, '2004-11-30 19:21:43', '2004-11-30 > > 19:21:43', 0.00); > > INSERT INTO `amember_payments` VALUES (422, 107, 1, '2004-10-22', > > '2004-11-21', 'authorize_aim', '5873225', 9.95, 1, '', NULL, > > '2004-11-30 19:22:18', 0, '', 0, '2004-11-30 19:20:13', '2004-11-30 > > 19:20:13', 0.00); > > > Thanks for your help! > > Erik > > I feel obliged to point out that there ARE no rows meeting the criteria > you query specified! > > mysql> SELECT expire_date, NOW() FROM amember_payments; > +-+-+ > | expire_date | NOW() | > +-+-+ > | 2004-10-21 | 2007-05-27 15:59:21 | > | 2004-11-21 | 2007-05-27 15:59:21 | > +-+-+ > 2 rows in set (0.02 sec) > > mysql> > > So I am not sure how you managed to get a manual query to work, but do > be sure that the Python query you mentioned at the start of the thread > > sql = """SELECT payment_id FROM amember_payments WHERE > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id > > >11 AND product_id <21)""", (self.uid) > > doesn't stand a chance of returning any results unless you use a time > machine to go back almost three years! > > regards > Steve > -- > Steve Holden+1 571 484 6266 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://del.icio.us/steve.holden > -- Asciimercial - > Get on the web: Blog, lens and tag your
Re: Can python create a dictionary from a list comprehension?
On May 27, 1:55 pm, erikcw <[EMAIL PROTECTED]> wrote: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik try... [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in links] btw...I was curious of this too. I used 'dir(dict)' and looked for a method that might do what we wanted and bingo! ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python create a dictionary from a list comprehension?
erikcw schrieb: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik > > normally a dict(whatEver) will do ;-) Example: a = [1,2,3,4,5,6,7,8,9,10] aDict = dict([(x,x+1) for x in a if x%2==0]) print aDict -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python create a dictionary from a list comprehension?
On 27 mai, 22:55, erikcw <[EMAIL PROTECTED]> wrote: > Hi, > > I'm trying to turn o list of objects into a dictionary using a list > comprehension. > > Something like > > entries = {} > [entries[int(d.date.strftime('%m'))] = d.id] for d in links] > > I keep getting errors when I try to do it. Is it possible? Do > dictionary objects have a method equivalent to [].append? Maybe a > lambda? > > Thanks for your help! > Erik entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] ) With Python2.4 and above you can use a "generator expression" entries = dict( (int(d.date.strftime('%m')),d.id) for d in links ) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
expat parser
I have this code: import xml.parsers.expat def start_element(name, attrs): print 'Start element:', name, attrs def end_element(name): print 'End element:', name def char_data(data): print 'Character data:', repr(data) p = xml.parsers.expat.ParserCreate() p.StartElementHandler = start_element p.EndElementHandler = end_element p.CharacterDataHandler = char_data fh=open("/home/sbassi/bioinfo/smallUniprot.xml","r") p.ParseFile(fh) And I get this on the output: ... Start element: sequence {u'checksum': u'E0C0CC2E1F189B8A', u'length': u'393'} Character data: u'\n' Character data: u'MPKKKPTPIQLNPAPDGSAVNGTSSAETNLEALQKKLEELELDEQQRKRL' Character data: u'\n' Character data: u'EAFLTQKQKVGELKDDDFEKISELGAGNGGVVFKVSHKPSGLVMARKLIH' ... End element: sequence ... Is there a way to have the character data together in one string? I guess it should not be difficult, but I can't do it. Each time the parse reads a line, return a line, and I want to have it in one variable. (the file is here: http://sbassi.googlepages.com/smallUniprot.xml) -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- paul <[EMAIL PROTECTED]> wrote: > > > > Regarding the pitfalls of groupby in general (even > > assuming we had better documentation), I invite > people > > to view the following posting that I made on > > python-ideas, entitled "SQL-like way to manipulate > > Python data structures": > > > > LINQ? > Maybe. I think they're at least trying to solve the same problem as I am. Expecting? Get great news right away with email Auto-Check. Try the Yahoo! Mail Beta. http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
--- Carsten Haese <[EMAIL PROTECTED]> wrote: > On Sun, 2007-05-27 at 10:17 -0700, 7stud wrote: > > Bejeezus. The description of groupby in the docs > is a poster child > > for why the docs need user comments. Can someone > explain to me in > > what sense the name 'uniquekeys' is used this > example: > > > > > > import itertools > > > > mylist = ['a', 1, 'b', 2, 3, 'c'] > > > > def isString(x): > > s = str(x) > > if s == x: > > return True > > else: > > return False > > > > uniquekeys = [] > > groups = [] > > for k, g in itertools.groupby(mylist, isString): > > uniquekeys.append(k) > > groups.append(list(g)) > > > > print uniquekeys > > print groups > > > > --output:-- > > [True, False, True, False, True] > > [['a'], [1], ['b'], [2, 3], ['c']] > > The so-called example you're quoting from the docs > is not an actual > example of using itertools.groupby [...] Huh? How is code that uses itertools.groupby not an actual example of using itertools.groupby? These docs need work. Please do not defend them; please suggest improvements. Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with PySMS
Maybe you can try python binding for gammu, which works great for me. HTH Petr Jakes http://cihar.com/gammu/python/ -- http://mail.python.org/mailman/listinfo/python-list
Error in optparse documentation
In the python documentation section 14.3.2.6 (http://docs.python.org/ lib/optparse-generating-help.html) in the last line it is written "options that have a default value can include %default in the help string--optparse will replace it with str() of the option's default value. If an option has no default value (or the default value is None), %default expands to none." However this is true only for python 2.4 and newer and not for older versions. Though the documentation for optparse (section 14.3, http://docs.python.org/lib/module-optparse.html) says that the module is new for python 2.3, in this version a help string (default value = intermediate) e.g. help="interaction mode: novice, intermediate, or expert [default: %default]" prints interaction mode: novice, intermediate, or expert [default: %default] and not: interaction mode: novice, intermediate, or expert [default: intermediate] Only in python 2.4 and newer do you see the help string print as interaction mode: novice, intermediate, or expert [default: intermediate] I think the documentation should be modified so that it is made clear that %default in the help string behaves as is claimed only in version 2.4 and higher. O.S. used is RHEL 9 -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
On May 28, 12:46 am, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: > > words is a big long array of strings. What I want to do is find > > consecutive sequences of words that have the first letter capitalized, > > and then call doSomething on them. (And you can ignore the fact that > > it won't find a sequence at the very end of words, that is fine for my > > purposes). > > Assuming the list of words will fit into memory, and you can probably > expect to fit anything up to millions of words comfortably into memory, > something like this might be suitable: > > list_of_words = "lots of words go here".split() > > accumulator = [] > for word in list_of_words: > if word.istitle(): > accumulator.append(word) > else: > doSomething(accumulator) > accumulator = [] > Bzzzt. Needs the following code at the end: if accumulator: doSomething(accumulator) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
--- John Machin <[EMAIL PROTECTED]> wrote: (And you can > > > ignore the fact that > > > it won't find a sequence at the very end of > words, that is fine for my > > > purposes). > > [...] > > Bzzzt. Needs the following code at the end: > if accumulator: > doSomething(accumulator) > FWIW the OP already conceded that bug, but you're right that it's a common anti-pattern, which is just a nice word for bug. :) The itertools.groupby() function is a well-intended attempt to steer folks away from this anti-pattern, although I think it has usability issues, mostly related to the docs (see other thread). Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. http://smallbusiness.yahoo.com/webhosting -- http://mail.python.org/mailman/listinfo/python-list
Re: How to do this in python with regular expressions
On May 25, 6:51 am, Jia Lu <[EMAIL PROTECTED]> wrote: > Hi all > > I'm trying to parsing html with re module. > > html = """ > > > > DATA1DATA2DATA3 HT>DATA4 > > > DATA5DATA6DATA7DATA8 > > > """ > > I want to get DATA1-8 from that string.(DATA maybe not english words.) > Can anyone tell me how to do it with regular expression in python? > > Thank you very much. # example1.py # This example will print out more than what's in the HTML table. It would also print # out text between tags, and so on. import HTMLParser class DataParser(HTMLParser.HTMLParser): def handle_data (self, data): data = data.strip() if data: print data html = ''' DATA1DATA2DATA3DATA4 DATA5DATA6DATA7DATA8 ''' parser = DataParser() parser.feed(html) parser.close() example1.py output: $ python example1.py DATA1 DATA2 DATA3 DATA4 DATA5 DATA6 DATA7 DATA8 # example2.py # This example uses the re module to pull out only the table portions of HTML. This # should only print out data between tags. Notice that there is some # data between the tags that is not present in the output. import HTMLParser import re class DataParser(HTMLParser.HTMLParser): def handle_data (self, data): data = data.strip() if data: print data html = ''' body data 1 table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 body data 2 ''' tables_list = re.findall('.*?', html, re.DOTALL | re.IGNORECASE) tables_html = str.join(' ', tables_list) parser = DataParser() parser.feed(tables_html) parser.close() example2.py output: $ python example2.py table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 # example3.py # This example does basically the same thing as example2.py, but it uses HTMLParser # to keep track of whether the data is between tags. import HTMLParser class DataParser(HTMLParser.HTMLParser): def __init__ (self): HTMLParser.HTMLParser.__init__(self) self.table_count = 0 def handle_starttag (self, tag, attrs): if tag == 'table': self.table_count += 1 def handle_endtag (self, tag): if tag == 'table': self.table_count -= 1 def handle_data (self, data): data = data.strip() if data and self.table_count > 0: print data html = ''' body data 1 table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 body data 2 ''' parser = DataParser() parser.feed(html) parser.close() example3.py output: $ python example3.py table 1 data 1 table 1 data 2 table 2 data 1 table 2 data 2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
On Sun, 27 May 2007 14:55:42 -0700, John Machin wrote: > On May 28, 12:46 am, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: >> On Sun, 27 May 2007 06:44:01 -0700, Eric wrote: >> > words is a big long array of strings. What I want to do is find >> > consecutive sequences of words that have the first letter capitalized, >> > and then call doSomething on them. (And you can ignore the fact that >> > it won't find a sequence at the very end of words, that is fine for my >> > purposes). >> >> Assuming the list of words will fit into memory, and you can probably >> expect to fit anything up to millions of words comfortably into memory, >> something like this might be suitable: >> >> list_of_words = "lots of words go here".split() >> >> accumulator = [] >> for word in list_of_words: >> if word.istitle(): >> accumulator.append(word) >> else: >> doSomething(accumulator) >> accumulator = [] >> > Bzzzt. Needs the following code at the end: > if accumulator: > doSomething(accumulator) Bzzzt! Somebody didn't read the Original Poster's comment "And you can ignore the fact that it won't find a sequence at the very end of words, that is fine for my purposes". Of course, for somebody whose requirements _aren't_ broken, you would be completely right. Besides, I'm under no obligation to write all the O.P.'s code for him, just point him in the right direction. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: ten small Python programs
Steve Howell wrote: > I've always thought that the best way to introduce new > programmers to Python is to show them small code > examples. You could try this wiki page: http://rosettacode.org/wiki/Main_Page It has a fair amount of Python examples as well as many more other languages (doing the same algorithm). Hope this helps. Adonis -- http://mail.python.org/mailman/listinfo/python-list
Re: Error in optparse documentation
Shatadal wrote: > In the python documentation section 14.3.2.6 (http://docs.python.org/ > lib/optparse-generating-help.html) in the last line it is written > > "options that have a default value can include %default in the help > string--optparse will replace it with str() of the option's default > value. If an option has no default value (or the default value is > None), %default expands to none." > > However this is true only for python 2.4 and newer and not for older > versions. The optparse module is externally maintained. You should file a documentation bug at http://optik.sourceforge.net/ STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question - better way to do this?
--- Steven D'Aprano wrote: > On Sun, 27 May 2007 14:55:42 -0700, John Machin > wrote: > > Bzzzt. > Bzzzt! Can we please refrain from buzzer sounds in this mostly civil forum, even if one beep deserves another? Looking for earth-friendly autos? Browse Top Cars by "Green Rating" at Yahoo! Autos' Green Center. http://autos.yahoo.com/green_center/ -- http://mail.python.org/mailman/listinfo/python-list