content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: implementing a basic queue/thread process within python looking for some eyeballs to verifiy that the following chunk of psuedo python makes sense. i'm looking to spawn a number of threads to implement some inproc functions as fast as possible. the idea is to spawn the threads in the master loop, so the app will run the threads simultaneously in a parallel/concurrent manner chunk of code -get the filenames from a dir -write each filename ot a queue -spawn a thread for each filename, where each thread waits/reads value/data from the queue -the threadParse function then handles the actual processing based on the file that's included via the "execfile" function... # System modules from Queue import Queue from threading import Thread import time # Local modules #import feedparser # Set up some global variables appqueue = Queue() # more than the app will need # this matches the number of files that will ever be in the # urldir # num_fetch_threads = 200 def threadParse(q) #decompose the packet to get the various elements line = q.get() college,level,packet=decompose (line) #build name of included file fname=college+"_"+level+"_Parse.py" execfile(fname) q.task_done() #setup the master loop while True time.sleep(2) # get the files from the dir # setup threads filelist="ls /urldir" if filelist foreach file_ in filelist: worker = Thread(target=threadParse, args=(appqueue,)) worker.start() # again, get the files from the dir #setup the queue filelist="ls /urldir" foreach file_ in filelist: #stuff the filename in the queue appqueue.put(file_) # Now wait for the queue to be empty, indicating that we have # processed all of the downloads. #don't care about this part #print '*** Main thread waiting' #appqueue.join() #print '*** Done' Thoughts/comments/pointers are appreciated... thanks A: If I understand this right: You spawn lots of threads to get things done faster. This only works if the main part of the job done in each thread is done without holding the GIL. So if there is a lot of waiting for data from network, disk or something like that, it might be a good idea. If each of the tasks are using a lot of CPU, this will run pretty much like on a single core 1-CPU machine and you might as well do them in sequence. I should add that what I wrote is true for CPython, but not necessarily for Jython/IronPython. Also, I should add that if you need to utilize more CPUs/cores, there's the multiprocessing module that might help.
implementing a basic queue/thread process within python
looking for some eyeballs to verifiy that the following chunk of psuedo python makes sense. i'm looking to spawn a number of threads to implement some inproc functions as fast as possible. the idea is to spawn the threads in the master loop, so the app will run the threads simultaneously in a parallel/concurrent manner chunk of code -get the filenames from a dir -write each filename ot a queue -spawn a thread for each filename, where each thread waits/reads value/data from the queue -the threadParse function then handles the actual processing based on the file that's included via the "execfile" function... # System modules from Queue import Queue from threading import Thread import time # Local modules #import feedparser # Set up some global variables appqueue = Queue() # more than the app will need # this matches the number of files that will ever be in the # urldir # num_fetch_threads = 200 def threadParse(q) #decompose the packet to get the various elements line = q.get() college,level,packet=decompose (line) #build name of included file fname=college+"_"+level+"_Parse.py" execfile(fname) q.task_done() #setup the master loop while True time.sleep(2) # get the files from the dir # setup threads filelist="ls /urldir" if filelist foreach file_ in filelist: worker = Thread(target=threadParse, args=(appqueue,)) worker.start() # again, get the files from the dir #setup the queue filelist="ls /urldir" foreach file_ in filelist: #stuff the filename in the queue appqueue.put(file_) # Now wait for the queue to be empty, indicating that we have # processed all of the downloads. #don't care about this part #print '*** Main thread waiting' #appqueue.join() #print '*** Done' Thoughts/comments/pointers are appreciated... thanks
[ "If I understand this right: You spawn lots of threads to get things done faster. \nThis only works if the main part of the job done in each thread is done without holding the GIL. So if there is a lot of waiting for data from network, disk or something like that, it might be a good idea.\nIf each of the tasks are ...
[ 0 ]
[]
[]
[ "multithreading", "parallel_processing", "python", "queue", "simultaneous" ]
stackoverflow_0003357078_multithreading_parallel_processing_python_queue_simultaneous.txt
Q: How to use csv.reader in python with french character like é,à,ç,ê,ë, I have a csv file like 120 column by 4500 row. I read the field "customer name" in the first column, first row. I then look fot this field in a second cvs file containing the "customer name , and customer ID" I write a new cvs file with "customer name", customer ID", and all the rest of the 119 colunm.and continue until end of first file. This is working, but I have special character everywhere in the first two csv files. And I dont want to have 'Montr\xe9al-Nord' instead of Montréal-Nord or 'Val\xe9rie Lamarche' instead of 'Valérie Lamarche' in the resulting csv file. here is a test code exemple: # -*- coding: utf-8 -*- import types import wx import sys import os, os.path import win32file import shutil import string import wx.lib.dialogs import re import EmailAttache import StringIO,csv import time import csv outputfile=open(os.path.join(u"c:\\transales","Resultat-second_contact_act.csv"), "wb") resultat = csv.writer (outputfile ) def Writefile ( info1, info2 ): print info1, info2 resultat.writerow( [ `info1`,`info2` ,`line[1]`,`line[2]`,`line[3]`,`line[4]`,`line[5]`,`line[6]`,`line[7]`,`line[8]`,`line[9]`,`line[10]`,`line[11]`,`line[12]`,`line[13]`,`line[14]`,`line[15]`,`line[16]`,`line[17]` ] ) data = open(os.path.join(u"c:\\transales","SECONDARY_CONTACTS.CSV"),"rb") data2 = open(os.path.join(u"c:\\transales","AccountID+ContactID.csv"),"rb") source1 = csv.reader(data) source2 = csv.reader(data2) for line in source1: name= line[0] data2.seek(0) for line2 in source2: if line[0] == line2[0]: Writefile(line[0],line2[1]) break outputfile.close() Any help ? regards, francois A: Although I am not familiar with csv.reader or writer, I have been dealing with utf-8 file reading recently and perhaps using the codecs module might help you out. Instead of, data = open(..., "wb") try, import codecs and then for all your utf-8 files, use, data = codecs.open(..., "rb", "utf-8") This automatically reads your files in as unicode (utf-8) and might write them to your file correctly. A: The problem is in this line: resultat.writerow( [ `info1`,`info2` ,`line[1]`,`line[2]`,`line[3]`,`line[4]`,`line[5]`,`line[6]`,`line[7]`,`line[8]`,`line[9]`,`line[10]`,`line[11]`,`line[12]`,`line[13]`,`line[14]`,`line[15]`,`line[16]`,`line[17]` ] ) Wrapping an expression in "back-ticks" aka "grave accents" is an old-fashioned and deprecated way of saying repr(expression). Please consider the following: >>> s = "Montréal" >>> print s Montréal >>> print repr(s) 'Montr\xe9al' >>> ord(s[5]) 233 >>> hex(233) '0xe9' >>> s == "Montr\xe9al" True >>> `s` == repr(s) True The offending (in 3 ways) line should be simply replaced by resultat.writerow([info1, info2] + [line[1:18]]) # WRONG (sorry!) resultat.writerow([info1, info2] + line[1:18]) # RIGHT
How to use csv.reader in python with french character like é,à,ç,ê,ë,
I have a csv file like 120 column by 4500 row. I read the field "customer name" in the first column, first row. I then look fot this field in a second cvs file containing the "customer name , and customer ID" I write a new cvs file with "customer name", customer ID", and all the rest of the 119 colunm.and continue until end of first file. This is working, but I have special character everywhere in the first two csv files. And I dont want to have 'Montr\xe9al-Nord' instead of Montréal-Nord or 'Val\xe9rie Lamarche' instead of 'Valérie Lamarche' in the resulting csv file. here is a test code exemple: # -*- coding: utf-8 -*- import types import wx import sys import os, os.path import win32file import shutil import string import wx.lib.dialogs import re import EmailAttache import StringIO,csv import time import csv outputfile=open(os.path.join(u"c:\\transales","Resultat-second_contact_act.csv"), "wb") resultat = csv.writer (outputfile ) def Writefile ( info1, info2 ): print info1, info2 resultat.writerow( [ `info1`,`info2` ,`line[1]`,`line[2]`,`line[3]`,`line[4]`,`line[5]`,`line[6]`,`line[7]`,`line[8]`,`line[9]`,`line[10]`,`line[11]`,`line[12]`,`line[13]`,`line[14]`,`line[15]`,`line[16]`,`line[17]` ] ) data = open(os.path.join(u"c:\\transales","SECONDARY_CONTACTS.CSV"),"rb") data2 = open(os.path.join(u"c:\\transales","AccountID+ContactID.csv"),"rb") source1 = csv.reader(data) source2 = csv.reader(data2) for line in source1: name= line[0] data2.seek(0) for line2 in source2: if line[0] == line2[0]: Writefile(line[0],line2[1]) break outputfile.close() Any help ? regards, francois
[ "Although I am not familiar with csv.reader or writer, I have been dealing with utf-8 file reading recently and perhaps using the codecs module might help you out. \nInstead of,\ndata = open(..., \"wb\")\n\ntry,\nimport codecs\n\nand then for all your utf-8 files, use,\ndata = codecs.open(..., \"rb\", \"utf-8\")\n\...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003356074_csv_python.txt
Q: Django, Borg pattern, API calls, caching results I'm using an API from a different site that returns a couple of 'pricepoint URL's that my users use to buy Virtual Goods. I'm supposed to cache those results for at least an hour, since they don't change the price points on their system much. (And we want to save both our's and their bandwidth.) After looking for singleton's in Python I discovered the borg pattern, which seems even cooler, so this is what i did: def fetchPrices(): #uses urllib2.urlopen() to fetch prices #parses results with ElementTree return prices class PriceStore(): __shared_state = {} def update(self): if self.lastUpdate is not None and (datetime.now() - self.lastUpdate).seconds >= 3600: self.prices = fetchPrices() self.lastUpdate = datetime.now() elif self.lastUpdate is not None: return else: self.lastUpdate = datetime.now() - timedelta(hours=1) self.update() def __init__(self): self.__dict__ = self.__shared_state self.lastUpdate = None self.update() The idea is to use this in the following way: store = PriceStore() url = store.prices['2.9900']['url'] And the store should initialize correctly and only fetch new price point info, if the existing info is older than one hour. I seem to be hitting their API with every time that PriceStore is initialized, though. Can anyone spot my problem? Can I use a global variable like __shared_state in django and expect it to still contain pricing info? Thanks! A: I seem to be hitting their API with every time that PriceStore is initialized, though. Can anyone spot my problem? Yep, it's easy to spot: def __init__(self): self.__dict__ = self.__shared_state self.lastUpdate = None the self.lastUpdate = None absolutely guarantees that the immediately following call to self.update() will find self.lastUpdate's value to be None -- you just forced it to be so! Remove that self.lastUpdate = None in the __init__ and, for example, use instead a lastUpdate = None at class body level, e.g. just after the __shared_state = {} assignment and with the same alignment as that assignment. That will make things work as you intend. A: Your main problem is that when you create a new PriceStore, you set self.lastUpdate to None (in your second-to-last line). So although they all share state, every new object clobbers the state. Instead do this: class PriceStore(): __shared_state = {'lastUpdate': None} Another problem you might face is that depending on how your Django is deployed, you may be using more than one process. Each one would have its own copy of the shared state. A: In __init__ you set self.lastUpdate = None. Don't do that. Specifically, consider the following code: A = PriceStore() # some time later B = PriceStore() Now A.lastUpdate == None, which you didn't want! Instead, try if "lastUpdate" not in self.__dict__: self.lastUpdate = None That way you never overwrite it.
Django, Borg pattern, API calls, caching results
I'm using an API from a different site that returns a couple of 'pricepoint URL's that my users use to buy Virtual Goods. I'm supposed to cache those results for at least an hour, since they don't change the price points on their system much. (And we want to save both our's and their bandwidth.) After looking for singleton's in Python I discovered the borg pattern, which seems even cooler, so this is what i did: def fetchPrices(): #uses urllib2.urlopen() to fetch prices #parses results with ElementTree return prices class PriceStore(): __shared_state = {} def update(self): if self.lastUpdate is not None and (datetime.now() - self.lastUpdate).seconds >= 3600: self.prices = fetchPrices() self.lastUpdate = datetime.now() elif self.lastUpdate is not None: return else: self.lastUpdate = datetime.now() - timedelta(hours=1) self.update() def __init__(self): self.__dict__ = self.__shared_state self.lastUpdate = None self.update() The idea is to use this in the following way: store = PriceStore() url = store.prices['2.9900']['url'] And the store should initialize correctly and only fetch new price point info, if the existing info is older than one hour. I seem to be hitting their API with every time that PriceStore is initialized, though. Can anyone spot my problem? Can I use a global variable like __shared_state in django and expect it to still contain pricing info? Thanks!
[ "\nI seem to be hitting their API with\n every time that PriceStore is\n initialized, though. Can anyone spot\n my problem?\n\nYep, it's easy to spot:\ndef __init__(self):\n self.__dict__ = self.__shared_state\n self.lastUpdate = None\n\nthe self.lastUpdate = None absolutely guarantees that the immediately...
[ 4, 1, 0 ]
[]
[]
[ "api", "caching", "django", "python" ]
stackoverflow_0003357158_api_caching_django_python.txt
Q: using Python/Pexpect to crawl a network This is more a logical thinking issue rather than coding. I already have some working code blocks - one which telnets to a device, one which parses results of a command, one which populates a dictionary etc etc Now lets say I want to analyse a network with unknown nodes, a,b,c etc (but I only know about 1) I give my code block node a. The results are a table including b, c. I save that in a dictionary I then want to use that first entry (b) as a target and see what it can see. Possibly d, e, etc And add those (if any) to the dict And then do the same on the next node in this newly populated dictionary. The final output would be that all nodes have been visited once only, and all devices seen are recorded in this (or another) dictionary. However I can't figure out how to keep re-reading the dict as it grows, and I can't figure out how to avoid looking at a device more than once. I understand this is clearer to me than I have explained, apologies if it's confusing A: You are looking at graph algorithms, specifically DFS or BFS. Are you asking specifically about implementation details, or more generally about the algorithms? Recursion would be a very neat way of doing this. seen = {} def DFS( node ): for neighbour in node.neighbours(): if neighbour not in seen: seen[ neighbour ] = some_info_about_neighbour DFS( neighbour )
using Python/Pexpect to crawl a network
This is more a logical thinking issue rather than coding. I already have some working code blocks - one which telnets to a device, one which parses results of a command, one which populates a dictionary etc etc Now lets say I want to analyse a network with unknown nodes, a,b,c etc (but I only know about 1) I give my code block node a. The results are a table including b, c. I save that in a dictionary I then want to use that first entry (b) as a target and see what it can see. Possibly d, e, etc And add those (if any) to the dict And then do the same on the next node in this newly populated dictionary. The final output would be that all nodes have been visited once only, and all devices seen are recorded in this (or another) dictionary. However I can't figure out how to keep re-reading the dict as it grows, and I can't figure out how to avoid looking at a device more than once. I understand this is clearer to me than I have explained, apologies if it's confusing
[ "You are looking at graph algorithms, specifically DFS or BFS. Are you asking specifically about implementation details, or more generally about the algorithms?\nRecursion would be a very neat way of doing this.\nseen = {}\ndef DFS( node ):\n for neighbour in node.neighbours():\n if neighbour not in seen:...
[ 2 ]
[]
[]
[ "dictionary", "pexpect", "python" ]
stackoverflow_0003357396_dictionary_pexpect_python.txt
Q: python: iterating through array i have a list like this: brand_names={'MORPHINE':['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH', 'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH', 'ORAMORPH SR','ROXANOL','ROXANOL 100'], 'OXYCODONE':['COMBUNOX','DIHYDRONE','DINARCON','ENDOCET','ENDODAN', 'EUBINE','EUCODAL','EUKODAL','EUTAGEN','OXYCODONE WITH ACETAMINOPHEN CAPSULES', 'OXYCODONE WITH ASPIRIN,','OXYCONTIN','OXYDOSE','OXYFAST','OXYIR', 'PANCODINE','PERCOCET','PERCODAN','PROLADONE','ROXICET', 'ROXICODONE','ROXIPRIM','ROXIPRIN','TECODIN','TEKODIN', 'THECODIN','THEKOKIN','TYLOX'], 'OXYMORPHONE':['NUMORPHAN','OPANA','OPANA ER'], 'METHADONE':['ALGIDON','ALGOLYSIN','AMIDON','DEPRIDOL','DOLOPHINE','FENADONE', 'METHADOSE','MIADONE','PHENADONE'], 'BUPRENORPHINE':['BUPRENEX','LEPTAN','SUBOXONE','SUBUTEX','TEMGESIC'], 'HYDROMORPHONE':['DILAUDID','HYDAL','HYDROMORFAN','HYDROMORPHAN','HYDROSTAT', 'HYMORPHAN','LAUDICON','NOVOLAUDON','OPIDOL','PALLADONE', 'PALLADONE IR','PALLADONE SR'], 'CODEINE':['ACETAMINOPHEN WITH CODEINE','ASPIRIN WITH CODEINE','EMPIRIN WITH CODEINE', 'FLORINAL WITH CODEINE','TYLENOL 3','TYLENOL 4','TYLENOL 5'] 'HYDROCODONE':['ANEXSIA','BEKADID','CO-GESIC','CODAL-DH','CODICLEAR-DH', 'CODIMAL-DH','CODINOVO','CONATUSSIN-DC','CYNDAL-HD','CYTUSS-HC', 'DETUSSIN','DICODID','DUODIN','DURATUSS-HD','ENDAL-HC','ENTUSS', 'ENTUSS-D','G-TUSS','HISTINEX-D','HISTINEX-HC','HISTUSSIN-D','HISTUSSIN-HC', 'HYCET','HYCODAN','HYCOMINE','HYDROCODONE/APAP','HYDROKON', 'HYDROMET','HYDROVO','KOLIKODOL','LORCET','LORTAB', 'MERCODINONE','NOROCO','NORGAN','NOVAHISTEX','ORTHOXYCOL', 'POLYGESIC','STAGESIC','SYMTAN','SYNKONIN','TUSSIONEX','VICODIN', 'VICOPROFEN','XODOL','ZYDONE']} i would like to know whether anything in brand_names['OXYCODONE':] or brand_names['HYDROCODONE:] == some_value something like this?? for brand in brand_names['OXYCODONE','HYDROCODONE']: if brand = some_value: append to arrayC A: for brand in ['OXYCODONE','HYDROCODONE']: if some_value in brand_names[brand]: print brand A: Instead of writing a for loop and appending to a list, you can instead write it as a list comprehension: somevalue = 'EUKODAL' result = [brand_name for brand_name in ['OXYCODONE', 'HYDROCODONE'] if somevalue in brand_names[brand_name]] print result Result: ['OXYCODONE'] A: if any(some_value in brand_names[key] for key in ('OXYCODONE','HYDROCODONE')): append to arrayC A: No need to loop, you can just do: 'some_value' in brand_names['OXYCODONE'] + brand_names['HYDROCODONE'] A: Here is one answer if you need to do this a lot. Then it is worthwhile to build once a lookup dictionary you can use for immediate access to reverse lookup. brand_names={'MORPHINE':['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH', 'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH', 'ORAMORPH SR','ROXANOL','ROXANOL 100'], 'OXYCODONE':['COMBUNOX','DIHYDRONE','DINARCON','ENDOCET','ENDODAN', 'EUBINE','EUCODAL','EUKODAL','EUTAGEN','OXYCODONE WITH ACETAMINOPHEN CAPSULES', 'OXYCODONE WITH ASPIRIN,','OXYCONTIN','OXYDOSE','OXYFAST','OXYIR', 'PANCODINE','PERCOCET','PERCODAN','PROLADONE','ROXICET', 'ROXICODONE','ROXIPRIM','ROXIPRIN','TECODIN','TEKODIN', 'THECODIN','THEKOKIN','TYLOX'], 'OXYMORPHONE':['NUMORPHAN','OPANA','OPANA ER'], 'METHADONE':['ALGIDON','ALGOLYSIN','AMIDON','DEPRIDOL','DOLOPHINE','FENADONE', 'METHADOSE','MIADONE','PHENADONE'], 'BUPRENORPHINE':['BUPRENEX','LEPTAN','SUBOXONE','SUBUTEX','TEMGESIC'], 'HYDROMORPHONE':['DILAUDID','HYDAL','HYDROMORFAN','HYDROMORPHAN','HYDROSTAT', 'HYMORPHAN','LAUDICON','NOVOLAUDON','OPIDOL','PALLADONE', 'PALLADONE IR','PALLADONE SR'], 'CODEINE':['ACETAMINOPHEN WITH CODEINE','ASPIRIN WITH CODEINE','EMPIRIN WITH CODEINE', 'FLORINAL WITH CODEINE','TYLENOL 3','TYLENOL 4','TYLENOL 5'], 'HYDROCODONE':['ANEXSIA','BEKADID','CO-GESIC','CODAL-DH','CODICLEAR-DH', 'CODIMAL-DH','CODINOVO','CONATUSSIN-DC','CYNDAL-HD','CYTUSS-HC', 'DETUSSIN','DICODID','DUODIN','DURATUSS-HD','ENDAL-HC','ENTUSS', 'ENTUSS-D','G-TUSS','HISTINEX-D','HISTINEX-HC','HISTUSSIN-D','HISTUSSIN-HC', 'HYCET','HYCODAN','HYCOMINE','HYDROCODONE/APAP','HYDROKON', 'HYDROMET','HYDROVO','KOLIKODOL','LORCET','LORTAB', 'MERCODINONE','NOROCO','NORGAN','NOVAHISTEX','ORTHOXYCOL', 'POLYGESIC','STAGESIC','SYMTAN','SYNKONIN','TUSSIONEX','VICODIN', 'VICOPROFEN','XODOL','ZYDONE']} lookup=dict((v,a) for a in brand_names for v in brand_names[a]) print ['%s has %s' % (lookup[something],something) for something in ('NOROCO','AMIDON') if (something in lookup and lookup[something] in ('OXYCODONE','HYDROCODONE')) ] """ Output: ['HYDROCODONE has NOROCO'] """
python: iterating through array
i have a list like this: brand_names={'MORPHINE':['ASTRAMORPH','AVINZA','CONTIN','DURAMORPH','INFUMORPH', 'KADIAN','MS CONTIN','MSER','MSIR','ORAMORPH', 'ORAMORPH SR','ROXANOL','ROXANOL 100'], 'OXYCODONE':['COMBUNOX','DIHYDRONE','DINARCON','ENDOCET','ENDODAN', 'EUBINE','EUCODAL','EUKODAL','EUTAGEN','OXYCODONE WITH ACETAMINOPHEN CAPSULES', 'OXYCODONE WITH ASPIRIN,','OXYCONTIN','OXYDOSE','OXYFAST','OXYIR', 'PANCODINE','PERCOCET','PERCODAN','PROLADONE','ROXICET', 'ROXICODONE','ROXIPRIM','ROXIPRIN','TECODIN','TEKODIN', 'THECODIN','THEKOKIN','TYLOX'], 'OXYMORPHONE':['NUMORPHAN','OPANA','OPANA ER'], 'METHADONE':['ALGIDON','ALGOLYSIN','AMIDON','DEPRIDOL','DOLOPHINE','FENADONE', 'METHADOSE','MIADONE','PHENADONE'], 'BUPRENORPHINE':['BUPRENEX','LEPTAN','SUBOXONE','SUBUTEX','TEMGESIC'], 'HYDROMORPHONE':['DILAUDID','HYDAL','HYDROMORFAN','HYDROMORPHAN','HYDROSTAT', 'HYMORPHAN','LAUDICON','NOVOLAUDON','OPIDOL','PALLADONE', 'PALLADONE IR','PALLADONE SR'], 'CODEINE':['ACETAMINOPHEN WITH CODEINE','ASPIRIN WITH CODEINE','EMPIRIN WITH CODEINE', 'FLORINAL WITH CODEINE','TYLENOL 3','TYLENOL 4','TYLENOL 5'] 'HYDROCODONE':['ANEXSIA','BEKADID','CO-GESIC','CODAL-DH','CODICLEAR-DH', 'CODIMAL-DH','CODINOVO','CONATUSSIN-DC','CYNDAL-HD','CYTUSS-HC', 'DETUSSIN','DICODID','DUODIN','DURATUSS-HD','ENDAL-HC','ENTUSS', 'ENTUSS-D','G-TUSS','HISTINEX-D','HISTINEX-HC','HISTUSSIN-D','HISTUSSIN-HC', 'HYCET','HYCODAN','HYCOMINE','HYDROCODONE/APAP','HYDROKON', 'HYDROMET','HYDROVO','KOLIKODOL','LORCET','LORTAB', 'MERCODINONE','NOROCO','NORGAN','NOVAHISTEX','ORTHOXYCOL', 'POLYGESIC','STAGESIC','SYMTAN','SYNKONIN','TUSSIONEX','VICODIN', 'VICOPROFEN','XODOL','ZYDONE']} i would like to know whether anything in brand_names['OXYCODONE':] or brand_names['HYDROCODONE:] == some_value something like this?? for brand in brand_names['OXYCODONE','HYDROCODONE']: if brand = some_value: append to arrayC
[ "for brand in ['OXYCODONE','HYDROCODONE']:\n if some_value in brand_names[brand]:\n print brand\n\n", "Instead of writing a for loop and appending to a list, you can instead write it as a list comprehension:\nsomevalue = 'EUKODAL'\nresult = [brand_name for brand_name in ['OXYCODONE', 'HYDROCODONE']\n ...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003356548_list_python.txt
Q: Django Admin "Helper" Functionality Not Working on Server In my localhost Django administrator I am able to fill-in Date and Time fields by clicking on the little "Date" and "Time" helper icons next to my pub_date field. However, the same administrator on my Server does NOT show these icons. The server-side admin also doesn't pop open a pop-up window for the little "+" plus sign for fields in related tables. Is there a server setting or something that I've missed? BTW, my admin media directory is working correctly otherwise. Thank you in advance! L. A: You are probably not serving javascript files properly. To have this functionality, proper javascript must loaded.
Django Admin "Helper" Functionality Not Working on Server
In my localhost Django administrator I am able to fill-in Date and Time fields by clicking on the little "Date" and "Time" helper icons next to my pub_date field. However, the same administrator on my Server does NOT show these icons. The server-side admin also doesn't pop open a pop-up window for the little "+" plus sign for fields in related tables. Is there a server setting or something that I've missed? BTW, my admin media directory is working correctly otherwise. Thank you in advance! L.
[ "You are probably not serving javascript files properly. To have this functionality, proper javascript must loaded.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003357779_django_django_admin_python.txt
Q: Request whith Q() object There is code and Tracebeck. What I'm doing wrong? media=MediaObject.objects.get( Q(on_air__range=(strt_time,end_time)), Q(channel=3), Q(name__icontains="qwwwwwww".decode('utf-8')|Q(name__icontains="cccccccc dddddd".decode('utf-8'))) ) Traceback (most recent call last): File "C:\Documents and Settings\POLINOM\web\website\manage.py", line 16, in <module> execute_manager(settings) File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 362, in execute_manager utility.execute() File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python26\lib\site-packages\django\core\management\base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "C:\Python26\lib\site-packages\django\core\management\base.py", line 222, in execute output = self.handle(*args, **options) File "C:\Documents and Settings\POLINOM\web\website\video\remmedia\management\commands\pull.py", line 38, in handle self.FirstTimeLoad() File "C:\Documents and Settings\POLINOM\web\website\video\remmedia\management\commands\pull.py", line 74, in FirstTimeLoad Q(name__icontains="╨Ь╨░╨╗╨░╤Е╨╛╨▓".decode('utf-8')|Q(name__icontains="╨Ф╨░╨▓╨░╨╣ ╨┐╨╛╨╢╨╡╨╜╨╕╨╝╤Б╤П".decode('utf-8'))) TypeError: unsupported operand type(s) for |: 'unicode' and 'Q' A: You are just missing a right parenthesis: Q(name__icontains="Малахов".decode('utf-8'))|Q(name__icontains="Давай поженимся".decode('utf-8')) # here ---^
Request whith Q() object
There is code and Tracebeck. What I'm doing wrong? media=MediaObject.objects.get( Q(on_air__range=(strt_time,end_time)), Q(channel=3), Q(name__icontains="qwwwwwww".decode('utf-8')|Q(name__icontains="cccccccc dddddd".decode('utf-8'))) ) Traceback (most recent call last): File "C:\Documents and Settings\POLINOM\web\website\manage.py", line 16, in <module> execute_manager(settings) File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 362, in execute_manager utility.execute() File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python26\lib\site-packages\django\core\management\base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "C:\Python26\lib\site-packages\django\core\management\base.py", line 222, in execute output = self.handle(*args, **options) File "C:\Documents and Settings\POLINOM\web\website\video\remmedia\management\commands\pull.py", line 38, in handle self.FirstTimeLoad() File "C:\Documents and Settings\POLINOM\web\website\video\remmedia\management\commands\pull.py", line 74, in FirstTimeLoad Q(name__icontains="╨Ь╨░╨╗╨░╤Е╨╛╨▓".decode('utf-8')|Q(name__icontains="╨Ф╨░╨▓╨░╨╣ ╨┐╨╛╨╢╨╡╨╜╨╕╨╝╤Б╤П".decode('utf-8'))) TypeError: unsupported operand type(s) for |: 'unicode' and 'Q'
[ "You are just missing a right parenthesis:\nQ(name__icontains=\"Малахов\".decode('utf-8'))|Q(name__icontains=\"Давай поженимся\".decode('utf-8'))\n# here ---^\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_q", "python" ]
stackoverflow_0003357908_django_django_q_python.txt
Q: win32api vs Python What are the Pro's and Con's of using win32api for I/O and other things instead of simply Python, if both have a specific function for it I mean, using PyWin32 vs Win32Api A: con (lack of) portability harder/more error prone pro performance (potentially, it must be measured, as will depend on more than just the api calls) A: The most obvious thing seems to be losing cross-platform compatibilty. Python runs on a number of different platforms, none of which has a win32 API except MS Windows.
win32api vs Python
What are the Pro's and Con's of using win32api for I/O and other things instead of simply Python, if both have a specific function for it I mean, using PyWin32 vs Win32Api
[ "con\n\n(lack of) portability\nharder/more error prone\n\npro\n\nperformance (potentially, it must be measured, as will depend on more than just the api calls)\n\n", "The most obvious thing seems to be losing cross-platform compatibilty. Python runs on a number of different platforms, none of which has a win32 AP...
[ 5, 4 ]
[]
[]
[ "io", "python", "winapi" ]
stackoverflow_0003358126_io_python_winapi.txt
Q: debugging in python i am using the python shell to try to do debugging i set a breakpoint i did: >>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()') but it is just running my program without stopping at the breakpoint! what am i donig wrong? A: How did you set a breakpoint? Try adding the line in your code: import pdb pdb.set_trace() and then run it. If you're in the pdb shell, then "break foo.py:45" will break on line 45 of file foo.py. Here are some useful commands: h help, list commands s step through current line n step to next line u go up the stack c continue execution Check the full list by typing 'h'. And "help X" will give you help on command X. Also, see this tutorial: Interactive Debugging in Python A: The typical usage to break into the debugger from a running program is to insert import pdb; pdb.set_trace() at the location you want to break into the debugger. You can then step through the code following this statement, and continue running without the debugger using the c command. The typical usage to inspect a crashed program is: >>> import pdb >>> import mymodule >>> mymodule.test() Traceback (most recent call last): File "<stdin>", line 1, in ? File "./mymodule.py", line 4, in test test2() File "./mymodule.py", line 3, in test2 print spam NameError: spam >>> pdb.pm() > ./mymodule.py(3)test2() -> print spam (Pdb) The Python site offers a very elaborate tutorial for pdb. Go to http://docs.python.org/library/pdb.html.
debugging in python
i am using the python shell to try to do debugging i set a breakpoint i did: >>> import pdb >>> import mymodule >>> pdb.run('mymodule.test()') but it is just running my program without stopping at the breakpoint! what am i donig wrong?
[ "How did you set a breakpoint? Try adding the line in your code:\nimport pdb\npdb.set_trace()\n\nand then run it. If you're in the pdb shell, then \"break foo.py:45\" will break on line 45 of file foo.py.\nHere are some useful commands:\nh help, list commands\ns step through current line\nn step to next ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003358153_python.txt
Q: Is it considered bad practice to use a widgets title attribute to refer to it? Would it be considered bad practice to use a widgets title attribute to refer it? For example I have a number of custom radioBoxCtrls on a panel I only ever need to get/set all the values at once so the container class(a panel) for the radioBoxCtrls objects has the following methods get_options() set_options() To set options for all the radioBoxCtrls a dictionary is passed to the set_options() method. Each key, value pair in the dictionary is a title of a radioBoxCtrl and the title of the button on the radioBoxCtrl that should be set def set_options(self, options={}): """ This method sets which radio button is selected on each RadioBoxCtrl object @param options: A dictionary Each key is the title of a RadioBoxCtrl each keys value is the button on the radio box that is to be selected """ for option_box in self.option_boxes: if option_box.title in options.keys() option_box.set_selected_button(options[option_box.title]) def get_options(self): """ This method returns a dictionary of the selected options Each key is the title of a RadioBoxCtrl object and each keys value is the name of the button selected on the radio box """ options = defaultdict(list) for option_box in self.option_boxes: options[option_box.title]=option_box.get_selected_btn() return options So (in an attempt to be clear) when I call the set method from my controller I pass in a dictionary like so: options = {"Name of radioBoxCtrl": "Option 2", ... } self.gui.optionsPanel.set_options(options) Why the hell do you want do that? (you may ask) Short answer: mvc I want to create a suitable layer of abstraction. All that my controller needs to know with regard to the options is how to get them to pass to the model when some processing needs to be done and how set them when a config file is loaded... I thought it would simplify things if I could just call one method to set and vice-versa -but Im not so sure now! I realize that this is probably more of question on the acceptability of refering to objects by some string attribute they posses, which in my case just happens to be the title.. so feel free to answer it accordingly.. Please feel free to improve the title of question(I wasnt really sure how to word it) and add tags. Thanks A: I can't tell whether the gurus would call it bad practive. I just know I'd never do it - it is slower, more error-prone, possibly makes it very hard to change a title's name (admittedly, only if you hardcode it everywhere) and (arguably) very inelegant. At least you should associate te options with the widget's identity, which still smells imho, but at least has a few problems less. Maybe that whole part of the application should be refactored to be less centralized so the issue disappears completely. Edit on how to refactor: Honestly, I can't tell - I know little about the application. The obvious approach would be subclassing all widgets and making them responsible for somehow getting the options and changing accordingly. But I can't tell whether that's really feasible.
Is it considered bad practice to use a widgets title attribute to refer to it?
Would it be considered bad practice to use a widgets title attribute to refer it? For example I have a number of custom radioBoxCtrls on a panel I only ever need to get/set all the values at once so the container class(a panel) for the radioBoxCtrls objects has the following methods get_options() set_options() To set options for all the radioBoxCtrls a dictionary is passed to the set_options() method. Each key, value pair in the dictionary is a title of a radioBoxCtrl and the title of the button on the radioBoxCtrl that should be set def set_options(self, options={}): """ This method sets which radio button is selected on each RadioBoxCtrl object @param options: A dictionary Each key is the title of a RadioBoxCtrl each keys value is the button on the radio box that is to be selected """ for option_box in self.option_boxes: if option_box.title in options.keys() option_box.set_selected_button(options[option_box.title]) def get_options(self): """ This method returns a dictionary of the selected options Each key is the title of a RadioBoxCtrl object and each keys value is the name of the button selected on the radio box """ options = defaultdict(list) for option_box in self.option_boxes: options[option_box.title]=option_box.get_selected_btn() return options So (in an attempt to be clear) when I call the set method from my controller I pass in a dictionary like so: options = {"Name of radioBoxCtrl": "Option 2", ... } self.gui.optionsPanel.set_options(options) Why the hell do you want do that? (you may ask) Short answer: mvc I want to create a suitable layer of abstraction. All that my controller needs to know with regard to the options is how to get them to pass to the model when some processing needs to be done and how set them when a config file is loaded... I thought it would simplify things if I could just call one method to set and vice-versa -but Im not so sure now! I realize that this is probably more of question on the acceptability of refering to objects by some string attribute they posses, which in my case just happens to be the title.. so feel free to answer it accordingly.. Please feel free to improve the title of question(I wasnt really sure how to word it) and add tags. Thanks
[ "I can't tell whether the gurus would call it bad practive. I just know I'd never do it - it is slower, more error-prone, possibly makes it very hard to change a title's name (admittedly, only if you hardcode it everywhere) and (arguably) very inelegant. At least you should associate te options with the widget's id...
[ 2 ]
[]
[]
[ "oop", "python", "user_interface" ]
stackoverflow_0003357831_oop_python_user_interface.txt
Q: Should I use Pylon's Paste to host my Pylons website? Or can I use Apache? I'm looking into Pylons and was wondering, should I use Paste as the webserver or can I use Apache? Are there advantages to using Paste? Would you recommend against using Apache? How should I host the sites? A: I guess it depends on whether you need webserver for development or production. For development just stick to Paste. I don't think there's one best way to host production application, but if you're not a pro in system administration, you can just go with Apache and mod_wsgi. By the way, there's a great and comprehensive comparison of Python WSGI servers at http://nichol.as/benchmark-of-python-web-servers. A: I'm using Nginx (with fastcgi) or Apache for hosting Pylons sites, mostly because lack of some "production" features in Paste, but for development Paste is very usefull and handy.
Should I use Pylon's Paste to host my Pylons website? Or can I use Apache?
I'm looking into Pylons and was wondering, should I use Paste as the webserver or can I use Apache? Are there advantages to using Paste? Would you recommend against using Apache? How should I host the sites?
[ "I guess it depends on whether you need webserver for development or production. For development just stick to Paste. I don't think there's one best way to host production application, but if you're not a pro in system administration, you can just go with Apache and mod_wsgi.\nBy the way, there's a great and compre...
[ 2, 0 ]
[]
[]
[ "pylons", "python", "web_services" ]
stackoverflow_0003333113_pylons_python_web_services.txt
Q: python: casting to upper and finding string i am getting stuck on this line: row[1].upper().find('CELEBREX',1) (this is returning -1) it seems to not find CELEBREX even though it is there row[1] = 'celebrex, TRAMADOL' am i casting to UPPER incorrectly? A: The second argument of find() shouldn't be 1, because it will start search after the first character of the string. >>> s = 'celebrex, TRAMADOL' >>> print s.upper().find('CELEBREX') 0 Find() will return 0 because it found the first match at position 0, the first position in the string. So it's important to note that, as you've already discovered, the if find() doesn't find the string, it will return -1. Return value 0 is actually a match. A: upper() seems fine, but find doesn't. You want to find at the start of the string (not offset). row[1].upper().find('CELEBREX') A: You are starting search from second letter 1 which is e: row=("",'celebrex, TRAMADOL') print row[1].upper().find('CELEBREX',1) print row[1][1:] """Output: -1 elebrex, TRAMADOL """
python: casting to upper and finding string
i am getting stuck on this line: row[1].upper().find('CELEBREX',1) (this is returning -1) it seems to not find CELEBREX even though it is there row[1] = 'celebrex, TRAMADOL' am i casting to UPPER incorrectly?
[ "The second argument of find() shouldn't be 1, because it will start search after the first character of the string.\n>>> s = 'celebrex, TRAMADOL'\n>>> print s.upper().find('CELEBREX')\n0\n\nFind() will return 0 because it found the first match at position 0, the first position in the string. So it's important to n...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003358301_python.txt
Q: Iterating variables to change its features in Python I assigned values with setattr() function in a loop: for i in range(30): for j in range(6): setattr(self, "e"+str(i)+str(j), Entry(self.top)) , then I want to apply .grid() func. to all these variables with a loop. For example, self.e00.grid(row= 0, column= 0) How can I do that? A: This is not the right way to go about things. Make one attribute and put all the data in it. import numpy as np self.matrix = np.array( ( 6, 30 ), Entry( self.top ) ) for row in self.matrix: for elt in row: elt.grid( ... ) A: Use getattr(): getattr(self, "e00").grid(row=0, column=0) or correspondingly in a loop: getattr(self, "e"+str(i)+str(j)).grid(row=0, column=0) Though there might be a better solution, depending on what your code is actually doing. A: Perhaps use a list of lists for your matrix instead: self.ematrix = [ [ Entry(self.top) for j in range(6)] # columns for i in range(30)] # rows for i,row in enumerate(self.ematrix): for j,elt in enumerate(row): elt.grid(row=i,column=j)
Iterating variables to change its features in Python
I assigned values with setattr() function in a loop: for i in range(30): for j in range(6): setattr(self, "e"+str(i)+str(j), Entry(self.top)) , then I want to apply .grid() func. to all these variables with a loop. For example, self.e00.grid(row= 0, column= 0) How can I do that?
[ "This is not the right way to go about things. Make one attribute and put all the data in it.\nimport numpy as np\nself.matrix = np.array( ( 6, 30 ), Entry( self.top ) )\n\nfor row in self.matrix:\n for elt in row:\n elt.grid( ... )\n\n", "Use getattr():\ngetattr(self, \"e00\").grid(row=0, column=0)\n\n...
[ 6, 3, 1 ]
[]
[]
[ "loops", "naming", "python", "variables" ]
stackoverflow_0003357845_loops_naming_python_variables.txt
Q: What is the best way to load a CCITT T.3 compressed tiff using python? I am trying to load a CCITT T.3 compressed tiff into python, and get the pixel matrix from it. It should just be a logical matrix. I have tried using pylibtiff and PIL, but when I load it with them, the matrix it returns is empty. I have read in a lot of places that these two tools support loading CCITT but not accessing the pixels. I am open to converting the image, as long as I can get the logical matrix from it and do it in python code. The crazy thing is is that if I open one of my images in paint, save it without altering it, then try to load it with pylibtiff, it works. Paint re-compresses it to the LZW compression. So I guess my real question is: Is there a way to either natively load CCITT images to matricies or convert the images to LZW using python?? Thanks, tylerthemiler A: It seems the best way is to not use Python entirely but lean on netpbm: import Image import ImageFile import subprocess tiff = 'test.tiff' im = Image.open(tiff) print 'size', im.size try: print 'extrema', im.getextrema() except IOError as e: print 'help!', e, '\n' print 'I Get by with a Little Help from my Friends' pbm_proc = subprocess.Popen(['tifftopnm', tiff], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (pbm_data, pbm_error) = pbm_proc.communicate() ifp = ImageFile.Parser() ifp.feed(pbm_data) im = ifp.close() print 'conversion message', pbm_error, print 'extrema', im.getextrema() print 'size', im.size # houston: we have an image im.show() Seems to do the trick: $ python g3fax.py size (1728, 2156) extrema help! decoder group3 not available I Get by with a Little Help from my Friends conversion message tifftopnm: writing PBM file extrema (0, 255) size (1728, 2156) A: How about running tiffcp with subprocess to convert to LZW (-c lzw switch), then process normally with pylibtiff? There are Windows builds of tiffcp lying around on the web. Not exactly Python-native solution, but still...
What is the best way to load a CCITT T.3 compressed tiff using python?
I am trying to load a CCITT T.3 compressed tiff into python, and get the pixel matrix from it. It should just be a logical matrix. I have tried using pylibtiff and PIL, but when I load it with them, the matrix it returns is empty. I have read in a lot of places that these two tools support loading CCITT but not accessing the pixels. I am open to converting the image, as long as I can get the logical matrix from it and do it in python code. The crazy thing is is that if I open one of my images in paint, save it without altering it, then try to load it with pylibtiff, it works. Paint re-compresses it to the LZW compression. So I guess my real question is: Is there a way to either natively load CCITT images to matricies or convert the images to LZW using python?? Thanks, tylerthemiler
[ "It seems the best way is to not use Python entirely but lean on netpbm:\nimport Image\nimport ImageFile\nimport subprocess\n\ntiff = 'test.tiff'\nim = Image.open(tiff)\nprint 'size', im.size\ntry:\n print 'extrema', im.getextrema()\nexcept IOError as e:\n print 'help!', e, '\\n'\n\nprint 'I Get by with a Lit...
[ 1, 0 ]
[]
[]
[ "compression", "image_formats", "imaging", "python", "tiff" ]
stackoverflow_0003355962_compression_image_formats_imaging_python_tiff.txt
Q: How can I create a session-local cookie-aware HTTP client in Django? I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(myTargetService) but this doesn't pass the cookie for the current session along. I have created a session access middleware to store the session in the settings: class SessionAccessMiddleware: def process_request(self, request): settings.current_session = request.session So, I can access the request session in get_request and post_request, but I don't know how to have urllib2 remember my cookies in a session-specific way. How do I do this? A: Here: http://docs.python.org/library/cookielib.html#examples are examples of doing exactly what you try to do with urllib2 and cookielib. So according to docs you need to create cookielib.CookieJar, set cookie with correct data (from session), build an opener that uses your CookieJar and use it to fetch yourTargetService. If settings in your middleware code means from django.conf import settings it's not good idea. Look at http://github.com/svetlyak40wt/django-globals/ for a place where you can safely store request-wide data for access from somewhere where request object is unaccessible. Also, it would be probably good idea to write custom authentication backend and use it with django.contrib.auth - instead of rolling your own auth system from scratch - which is covered here: http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend .
How can I create a session-local cookie-aware HTTP client in Django?
I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(myTargetService) but this doesn't pass the cookie for the current session along. I have created a session access middleware to store the session in the settings: class SessionAccessMiddleware: def process_request(self, request): settings.current_session = request.session So, I can access the request session in get_request and post_request, but I don't know how to have urllib2 remember my cookies in a session-specific way. How do I do this?
[ "Here: http://docs.python.org/library/cookielib.html#examples are examples of doing exactly what you try to do with urllib2 and cookielib. So according to docs you need to create cookielib.CookieJar, set cookie with correct data (from session), build an opener that uses your CookieJar and use it to fetch yourTarget...
[ 0 ]
[]
[]
[ "cookies", "django", "http", "python", "urllib2" ]
stackoverflow_0003358030_cookies_django_http_python_urllib2.txt
Q: Convert multiline string to single line string I'm using Google App Engine and I need to put a multiline string in the datastore. Unfortunately, GAE does not allow that. I need this string to be multiline, so is there any way to convert a multiline string to a single line string and store it? A: You don't need no conversion: google.appengine.ext.db.StringProperty(multiline=True) A: Replace all newlines with "\n", and replace all "\" with "\\", just like the way you do with string literals: def encode(s): return s.replace("\\", "\\\\").replace("\n", "\\n") def decode(s): return s.replace("\\\\", "\\").replace("\\n", "\n")
Convert multiline string to single line string
I'm using Google App Engine and I need to put a multiline string in the datastore. Unfortunately, GAE does not allow that. I need this string to be multiline, so is there any way to convert a multiline string to a single line string and store it?
[ "You don't need no conversion:\ngoogle.appengine.ext.db.StringProperty(multiline=True)\n", "Replace all newlines with \"\\n\", and replace all \"\\\" with \"\\\\\", just like the way you do with string literals:\ndef encode(s):\n return s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\n\", \"\\\\n\")\ndef decode(...
[ 7, 0 ]
[]
[]
[ "google_app_engine", "python", "string" ]
stackoverflow_0003358426_google_app_engine_python_string.txt
Q: Pylons 1.0 and SQLAlchemy 0.6 - How do I Model? I've been reading http://pylonsbook.com/en/1.1/starting-the-simplesite-tutorial.html and following along with their SimpleSite tutorial but am having some issues with creating the Model. The Model imports they use on the tutorial are: """The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from simplesite.model import meta # Add these two imports: import datetime from sqlalchemy import schema, types They then use this to create a table: page_table = schema.Table('page', meta.metadata, Though, when I try that, I get: AttributeError: 'module' object has no attribute 'metadata' I'm guessing Pylons changed their ways during the version upgrade... So how do I do this? Can someone link me to an updated tutorial on making a Model and handling database connections/queries? :/ A: Pylons 1.0 use declarative Base as default to model. exemple: from sqlalchemy import Column from sqlalchemy.types import Integer, Unicode, from MYPROJECT.model.meta import Base class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) username = Column(Unicode(100)) You can see the updated reference in http://pylonshq.com/docs/en/1.0/models/ A: I think you should use Base.metadata instead of meta.metadata for Pylons 1.0. A: It should be something like that: from blog.model.meta import Session, Base article_table = sa.Table("article", Base.metadata, sa.Column("id", sa.types.Integer, primary_key=True), sa.Column("lang", sa.types.String(255), nullable=False), )
Pylons 1.0 and SQLAlchemy 0.6 - How do I Model?
I've been reading http://pylonsbook.com/en/1.1/starting-the-simplesite-tutorial.html and following along with their SimpleSite tutorial but am having some issues with creating the Model. The Model imports they use on the tutorial are: """The application's model objects""" import sqlalchemy as sa from sqlalchemy import orm from simplesite.model import meta # Add these two imports: import datetime from sqlalchemy import schema, types They then use this to create a table: page_table = schema.Table('page', meta.metadata, Though, when I try that, I get: AttributeError: 'module' object has no attribute 'metadata' I'm guessing Pylons changed their ways during the version upgrade... So how do I do this? Can someone link me to an updated tutorial on making a Model and handling database connections/queries? :/
[ "Pylons 1.0 use declarative Base as default to model.\nexemple:\nfrom sqlalchemy import Column\nfrom sqlalchemy.types import Integer, Unicode,\nfrom MYPROJECT.model.meta import Base\n\nclass User(Base):\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key=True)\n username = Column(Unicode(100))\n\...
[ 3, 1, 1 ]
[]
[]
[ "model", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003353755_model_pylons_python_sqlalchemy.txt
Q: Handling missing packages or DLLs in a PyQt app What's a good way to handle fatal errors - missing packages, .ui files not compiled, Qt DLLs or shared objects not found, etc. - in a PyQt app (or other Python app)? Displaying a cross-platform message box without Qt DLLs or shared objects seems like a lot of work. Dumping a message to the console seems not very helpful, since the end user will likely not see the console. How do other Python apps handle this? Or do they simply assume that a properly installed app won't run into these problems? A: The distutils model handles installing a python app correctly, or there is a third party setuptools package that is even easier for end users.
Handling missing packages or DLLs in a PyQt app
What's a good way to handle fatal errors - missing packages, .ui files not compiled, Qt DLLs or shared objects not found, etc. - in a PyQt app (or other Python app)? Displaying a cross-platform message box without Qt DLLs or shared objects seems like a lot of work. Dumping a message to the console seems not very helpful, since the end user will likely not see the console. How do other Python apps handle this? Or do they simply assume that a properly installed app won't run into these problems?
[ "The distutils model handles installing a python app correctly, or there is a third party setuptools package that is even easier for end users.\n" ]
[ 1 ]
[]
[]
[ "error_handling", "installation", "package", "pyqt", "python" ]
stackoverflow_0003358759_error_handling_installation_package_pyqt_python.txt
Q: how to set up python web dev environment the set the i have so far is: windows 7 64bit Apache 2.2.14/mysql/php 5.3.1 i installed python 2.7. not configured. i tried installing mod_python but it kept telling python 2.5 is required A: Dump mod_python. It's dead, Jim.
how to set up python web dev environment
the set the i have so far is: windows 7 64bit Apache 2.2.14/mysql/php 5.3.1 i installed python 2.7. not configured. i tried installing mod_python but it kept telling python 2.5 is required
[ "Dump mod_python. It's dead, Jim.\n" ]
[ 1 ]
[]
[]
[ "apache", "python" ]
stackoverflow_0003358817_apache_python.txt
Q: Using a remote stylesheet that includes other stylesheets with relative paths I'd like to do an XSL transform on a DocBook document using lxml.etree.XSLT. Although the documentation mentions that etree.XSLT() takes a first parameter of xslt_input, I can't seem to find any docs on what this parameter is meant to be. Passing it a file that is open for reading seems to work; passing it a filename in a string does not. edit After a sanity check, I realized that etree.XSLT takes an parsed etree._ElementTree. So . . . maybe there's a way to parse an element tree in a way that gives it a path to use for mapping relative paths? . . . investigating. If the XML file that it is passed includes others, relative paths in those include statements are taken from the current working directory. I'd like to use this class to transform a DocBook document, and would prefer to be able to access the DocBook XSL remotely. The Docbook XSL is pretty complex, and includes numerous other files. Is there a way that I can cause etree.XSLT to pull these files from a remote location? A: This is actually dead easy, I just had mental indigestion, and forgot that there was that all-important intermediate step of parsing the XSL stylesheet. It's at that point that you let it know the base URL for the stylesheet. If you grab the stylesheet from an URL, it just deducts it from the URL. I didn't realize this was an option at first, which may have been the start of my confusion. Otherwise you can pass the location in via the base_url parameter. In three easy steps: >>> xsl_url = 'http://docbook.sourceforge.net/release/xsl/current/xhtml/docbook.xsl' >>> document = 'path/to/document.xml' >>> output_filename = 'path/to/transformed-document.xhtml' >>> from lxml import etree >>> transform = etree.XSLT(etree.parse(xsl_url)) >>> with open(document) as f: >>> transformed_document = transform(etree.parse(f)) >>> transformed_document.write(output_filename) Voilà! What I had been doing was initializing the stylesheet etree from a local file, mostly because I didn't realize that I could just pass in a URL. A: The xslt_input argument requires an XSL document. Here's a snippet of usage from http://snipplr.com/view/19433/lxml-xslt/: from lxml.etree import XSLT,fromstring xml = fromstring("<a key='value'>ez</a>") xsl= fromstring("""<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method = "html" version="1.0" encoding="UTF-8" omit-xml-declaration="yes" standalone="yes" indent="no" /> <xsl:template match="a"> <xsl:value-of select="@key"/> </xsl:template> </xsl:stylesheet>""") style = XSLT(xsl) result = style.apply( xml) print style.tostring(result)
Using a remote stylesheet that includes other stylesheets with relative paths
I'd like to do an XSL transform on a DocBook document using lxml.etree.XSLT. Although the documentation mentions that etree.XSLT() takes a first parameter of xslt_input, I can't seem to find any docs on what this parameter is meant to be. Passing it a file that is open for reading seems to work; passing it a filename in a string does not. edit After a sanity check, I realized that etree.XSLT takes an parsed etree._ElementTree. So . . . maybe there's a way to parse an element tree in a way that gives it a path to use for mapping relative paths? . . . investigating. If the XML file that it is passed includes others, relative paths in those include statements are taken from the current working directory. I'd like to use this class to transform a DocBook document, and would prefer to be able to access the DocBook XSL remotely. The Docbook XSL is pretty complex, and includes numerous other files. Is there a way that I can cause etree.XSLT to pull these files from a remote location?
[ "This is actually dead easy, I just had mental indigestion, and forgot that there was that all-important intermediate step of parsing the XSL stylesheet. It's at that point that you let it know the base URL for the stylesheet.\nIf you grab the stylesheet from an URL, it just deducts it from the URL. I didn't real...
[ 1, 0 ]
[]
[]
[ "docbook", "lxml", "python", "xslt" ]
stackoverflow_0003358481_docbook_lxml_python_xslt.txt
Q: How can I get html content from a browser that can do the html correction and js scripting? I need a solution for getting HTML content from a browser. As rendering in a browser, js will be ran, and if not, js won't be ran. So any html libraries like lxml, beautifulsoup and others are all not gonna work. I've searched a project named pywebkitgtk, but it's purpose is to create a browser with a front end. Is there any way to put a url into a "fake browser" and render it and run its all javascript and save it into a html file? I don't need any front-end, just back-end is ok. I need to use Python or java to do that. A: selenium-rc lets you drive an actual browser for your purpose, under control of any of several languages at your choice, which include both Python and Java. Check it out! For a detailed example of use with Python, see here.
How can I get html content from a browser that can do the html correction and js scripting?
I need a solution for getting HTML content from a browser. As rendering in a browser, js will be ran, and if not, js won't be ran. So any html libraries like lxml, beautifulsoup and others are all not gonna work. I've searched a project named pywebkitgtk, but it's purpose is to create a browser with a front end. Is there any way to put a url into a "fake browser" and render it and run its all javascript and save it into a html file? I don't need any front-end, just back-end is ok. I need to use Python or java to do that.
[ "selenium-rc lets you drive an actual browser for your purpose, under control of any of several languages at your choice, which include both Python and Java. Check it out!\nFor a detailed example of use with Python, see here.\n" ]
[ 3 ]
[]
[]
[ "browser", "java", "python" ]
stackoverflow_0003359141_browser_java_python.txt
Q: A forgiving dictionary I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] In order not to get one I would 1. Have to catch the exception or use get. I would like to not to have to do that with my dictionary... A: import collections a = collections.defaultdict(lambda: 3) a.update({'one':1,'two':2}) print a['three'] emits 3 as required. You could also subclass dict yourself and override __missing__, but that doesn't make much sense when the defaultdict behavior (ignoring the exact missing key that's being looked up) suits you so well... Edit ...unless, that is, you're worried about a growing by one entry each time you look up a missing key (which is part of defaultdict's semantics) and would rather get slower behavior but save some memory. For example, in terms of memory...: >>> import sys >>> a = collections.defaultdict(lambda: 'blah') >>> print len(a), sys.getsizeof(a) 0 140 >>> for i in xrange(99): _ = a[i] ... >>> print len(a), sys.getsizeof(a) 99 6284 ...the defaultdict, originally empty, now has the 99 previously-missing keys that we looked up, and takes 6284 bytes (vs. the 140 bytes it took when it was empty). The alternative approach...: >>> class mydict(dict): ... def __missing__(self, key): return 3 ... >>> a = mydict() >>> print len(a), sys.getsizeof(a) 0 140 >>> for i in xrange(99): _ = a[i] ... >>> print len(a), sys.getsizeof(a) 0 140 ...entirely saves this memory overhead, as you see. Of course, performance is another issue: $ python -mtimeit -s'import collections; a=collections.defaultdict(int); r=xrange(99)' 'for i in r: _=a[i]' 100000 loops, best of 3: 14.9 usec per loop $ python -mtimeit -s'class mydict(dict): > def __missing__(self, key): return 0 > ' -s'a=mydict(); r=xrange(99)' 'for i in r: _=a[i]' 10000 loops, best of 3: 92.9 usec per loop Since defaultdict adds the (previously-missing) key on lookup, it gets much faster when such a key is next looked up, while mydict (which overrides __missing__ to avoid that addition) pays the "missing key lookup overhead" every time. Whether you care about either issue (performance vs memory footprint) entirely depends on your specific use case, of course. It is in any case a good idea to be aware of the tradeoff!-) A: New in version 2.5: If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable. For an example, see collections.defaultdict. http://docs.python.org/library/stdtypes.html A: Here is how to subclass dict as suggested by NullUserException >>> class forgiving_dict(dict): ... def __missing__(self, key): ... return 3 ... >>> a = forgiving_dict() >>> a.update({'one':1,'two':2}) >>> print a['three'] 3 One big difference between this answer and Alex's is that the missing key is not added to the dictionary >>> print a {'two': 2, 'one': 1} Which is quite significant if you expect a lot of misses A: You'll probably want to use a defaultdict (it requires atleast python2.5 I believe) from collections import defaultdict def default(): return 'Default Value' d = defaultdict(default) print(d['?']) The function that is passed to the constructor tells the class what to return as a default value. See the documentation for additional examples. A: Sometimes what you really want is .setdefault() which is not very intuitive, but it's a method that "returns the key specified, if it doesn't exist, set that key to this value". Here is an example of setdefault() being used to good effect: collection = {} for elem in mylist: key = key_from_elem(elem) collection.setdefault(key, []).append(elem) This will allow us to create a dictionary like: {'key1':[elem1, elem3], 'key2':[elem3]} without having to have an ugly check to see if there's a key already there and creating a list for it.
A forgiving dictionary
I am wondering how to create forgiving dictionary (one that returns a default value if a KeyError is raised). In the following code example I would get a KeyError; for example a = {'one':1,'two':2} print a['three'] In order not to get one I would 1. Have to catch the exception or use get. I would like to not to have to do that with my dictionary...
[ "import collections\na = collections.defaultdict(lambda: 3)\na.update({'one':1,'two':2})\nprint a['three']\n\nemits 3 as required. You could also subclass dict yourself and override __missing__, but that doesn't make much sense when the defaultdict behavior (ignoring the exact missing key that's being looked up) s...
[ 22, 7, 6, 3, 0 ]
[]
[]
[ "defaultdict", "dictionary", "dictionary_missing", "python" ]
stackoverflow_0003358580_defaultdict_dictionary_dictionary_missing_python.txt
Q: How can I remove all elements matching an xpath in python using lxml? So I have some XML like this: <bar> <foo>Something</foo> <baz> <foo>Hello</foo> <zap>Another</zap> <baz> <bar> And I want to remove all the foo nodes. Something like this doesn't work params = xml.xpath('//foo') for n in params: xml.getroot().remove(n) Giving ValueError: Element is not a child of this node. What is a neat way to do this? A: try: for elem in xml.xpath( '//foo' ) : elem.getparent().remove(elem) remove it from it's parent, not the root ( unless it IS a child of the root element )
How can I remove all elements matching an xpath in python using lxml?
So I have some XML like this: <bar> <foo>Something</foo> <baz> <foo>Hello</foo> <zap>Another</zap> <baz> <bar> And I want to remove all the foo nodes. Something like this doesn't work params = xml.xpath('//foo') for n in params: xml.getroot().remove(n) Giving ValueError: Element is not a child of this node. What is a neat way to do this?
[ "try:\n for elem in xml.xpath( '//foo' ) :\n elem.getparent().remove(elem)\n\nremove it from it's parent, not the root \n( unless it IS a child of the root element )\n" ]
[ 21 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003359151_lxml_python.txt
Q: GUI in python programing the fallowing is a tic tak toe game code in python, can some one show me how i can make it in GUI form with a reset option and shows who wins at the end. like X win or O win? board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9" . checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8,3,6,9,1,5,9,3,5,7] spaces=range(1,10) def moveHandler(board,spaces,checkboard,player,n): if player==1: check="X" else: check="O" while spaces.count(n)==0: print "\nInvalid Space" n=playerinput(player) spaces=spaces.remove(n) board=board.replace(str(n),check) for c in range(len(checkboard)): if checkboard[c]==n: checkboard[c]=check status = checkwinner(checkboard,check) return board,status def checkwinner(checkboard,check): a,b,c=0,1,2 while a<=21: combo = [checkboard[a],checkboard[b],checkboard[c]] if combo.count(check) == 3: status =1 break else: status =0 a+=3 b+=3 c+=3 return status def playerinput(player): try: key = int(raw_input('\n\nPlayer ' + str(player) + ': Please select a space ')) except ValueError: print "Invalid Space" key = playerinput(player) return key while True: player = len(spaces)%2 +1 if player == 1: player = 2 else: player =1 print "\n\n" + board key = playerinput(player) board,status =moveHandler(board,spaces,checkboard,player,key) if status == 1: print '\n\nPlayer ' + str(player) + ' is the winner!!!' print board break elif len(spaces)==0: print "No more spaces left. Game ends in a TIE!!!" print board break else: continue A: Clearly you need to choose a GUI toolkit (Python supports many of them), use it to paint the board as a 3 x 3 grid of squares, and change the playerinput function to accept input by (e.g.) the current player double clicking on the empty square he or she wants to play in. Then, you need to change the print statements to show information on the GUI surface. The game however would be much better if it didn't try to control the flow of events but rather responded to events initiated by the players -- that's how real GUI apps should be done, rather than by minimal retrofitting of some interface on top of what's intrinsically designed as a command-line interactive procedure. Each of these tasks is a substantial one, especially the overall refactoring I recommend in the last paragraph, and entirely depends in its details on what GUI toolkit you choose -- so you might want to start with that, and then generally break the question up into the various subtasks ("one question per question", since many of the latter may arise;-). There are several SO questions on the subject of GUI choice for Python, so I recommend you study them rather than asking a new one. My personal favorite is PyQt (though more and more often I just do a simple browser-based interface with a local-only server powering it), but other popular ones include wxPython, Tkinter, PyGtk, and others listed here -- happy hunting! A: Check out the python wiki for info about different GUI toolkits. I would recommend looking at wxPython, and going from there
GUI in python programing
the fallowing is a tic tak toe game code in python, can some one show me how i can make it in GUI form with a reset option and shows who wins at the end. like X win or O win? board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9" . checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8,3,6,9,1,5,9,3,5,7] spaces=range(1,10) def moveHandler(board,spaces,checkboard,player,n): if player==1: check="X" else: check="O" while spaces.count(n)==0: print "\nInvalid Space" n=playerinput(player) spaces=spaces.remove(n) board=board.replace(str(n),check) for c in range(len(checkboard)): if checkboard[c]==n: checkboard[c]=check status = checkwinner(checkboard,check) return board,status def checkwinner(checkboard,check): a,b,c=0,1,2 while a<=21: combo = [checkboard[a],checkboard[b],checkboard[c]] if combo.count(check) == 3: status =1 break else: status =0 a+=3 b+=3 c+=3 return status def playerinput(player): try: key = int(raw_input('\n\nPlayer ' + str(player) + ': Please select a space ')) except ValueError: print "Invalid Space" key = playerinput(player) return key while True: player = len(spaces)%2 +1 if player == 1: player = 2 else: player =1 print "\n\n" + board key = playerinput(player) board,status =moveHandler(board,spaces,checkboard,player,key) if status == 1: print '\n\nPlayer ' + str(player) + ' is the winner!!!' print board break elif len(spaces)==0: print "No more spaces left. Game ends in a TIE!!!" print board break else: continue
[ "Clearly you need to choose a GUI toolkit (Python supports many of them), use it to paint the board as a 3 x 3 grid of squares, and change the playerinput function to accept input by (e.g.) the current player double clicking on the empty square he or she wants to play in.\nThen, you need to change the print stateme...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003359289_python.txt
Q: How to create a table and its related model.py automatically from a csv file in Django Think of this: You create a CMS of some sort, which asks you for an application name and a csv file for that application. Then it automatically creates that app on the fly, creates the required model.py based on the csv columns, activates the admin page for it and allows only you to have the full permission to this new table via django admin, then it inserts the the app into the url.py and creates the view.py for it as well. Then all you'd have to do is upload a csv, name your app and whola!, you have an admin page to play with. Now, is there anyway to create an app or at least a model.py out of a csv file in django or is there any django-app that can do this? Note: Look beyond (./manage.py inspectdb > models.py) A: While this does not involve creating an actual models.py and application, you may want to look into dynamically creating Model classes at runtime. You could have "meta" models that store the information on the dynamic models, and then have your CSV view import the data into those models, create the classes, and register them with the admin. Or something like that. Creating an actual application directory, with models.py, views.py, and so on, is fairly easy (just create the directory, create the files, and write formatted strings to them based on the CSV data). Editing the project's settings.py and urls.py, and reloading the modules, wouldn't be too difficult either. But, I wouldn't trust automatically generated Django applications without first looking at them.
How to create a table and its related model.py automatically from a csv file in Django
Think of this: You create a CMS of some sort, which asks you for an application name and a csv file for that application. Then it automatically creates that app on the fly, creates the required model.py based on the csv columns, activates the admin page for it and allows only you to have the full permission to this new table via django admin, then it inserts the the app into the url.py and creates the view.py for it as well. Then all you'd have to do is upload a csv, name your app and whola!, you have an admin page to play with. Now, is there anyway to create an app or at least a model.py out of a csv file in django or is there any django-app that can do this? Note: Look beyond (./manage.py inspectdb > models.py)
[ "While this does not involve creating an actual models.py and application, you may want to look into dynamically creating Model classes at runtime. You could have \"meta\" models that store the information on the dynamic models, and then have your CSV view import the data into those models, create the classes, and ...
[ 0 ]
[]
[]
[ "csv", "django", "django_admin", "django_models", "python" ]
stackoverflow_0003359336_csv_django_django_admin_django_models_python.txt
Q: Python string split what would be the best way to split this in python. (address, city, state, zip) <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div> in some case zip code is as <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634</div> A: Depending on how tight or lax you want to be on various aspects that can't be deduced from a single example, something like the following should work...: import re s = re.compile(r'^<div.*?>([^<]+)<br.*?>([^,]+), (\w\w) (\d{5}-\d{4})</div>$') mo = s.match(thestring) if mo is None: raise ValueError('No match for %r' % thestring) address, city, state, zip = mo.groups() A: Just a hint: there are much better ways to parse HTML than regular expressions, for example Beautiful Soup. Here's why you shouldn't do that with regular expressions. EDIT: Oh well, @teepark linked it first. :) A: Combining beautifulsoup and the regular expressions should give you something like: import BeautifulSoup import re thestring = r'<div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div>' re0 = re.compile(r'(?P<address>[^<]+)') re1 = re.compile(r'(?P<city>[^,]+), (?P<state>\w\w) (?P<zip>\d{5}-\d{4})') soup = BeautifulSoup.BeautifulSoup(thestring) (address,) = re0.search(soup.div.contents[0]).groups() city, state, zip = re1.search(soup.div.contents[2]).groups()
Python string split
what would be the best way to split this in python. (address, city, state, zip) <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634-3225</div> in some case zip code is as <div class="adtxt">7616 W Belmont Ave<br />Chicago, IL 60634</div>
[ "Depending on how tight or lax you want to be on various aspects that can't be deduced from a single example, something like the following should work...:\nimport re\n\ns = re.compile(r'^<div.*?>([^<]+)<br.*?>([^,]+), (\\w\\w) (\\d{5}-\\d{4})</div>$')\nmo = s.match(thestring)\nif mo is None:\n raise ValueError('No...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003359614_python.txt
Q: pydev eclipse configuration for __builtins__? suppose on init I've install my function under builtins then throughout my project I can access it directly that function, no need to import, but how can I tell this to eclipse - so it should not show RED Error "undefined variable" __builtins__['_'] = gettext.gettext A: Look in Preferences -> PyDev -> Editor -> Code Analysis. There's a bunch of options for adjusting code analysis in there. On my PyDev, _ is already in the Consider the following names as globals list though - which version of PyDev do you have?
pydev eclipse configuration for __builtins__?
suppose on init I've install my function under builtins then throughout my project I can access it directly that function, no need to import, but how can I tell this to eclipse - so it should not show RED Error "undefined variable" __builtins__['_'] = gettext.gettext
[ "Look in Preferences -> PyDev -> Editor -> Code Analysis. There's a bunch of options for adjusting code analysis in there. \nOn my PyDev, _ is already in the Consider the following names as globals list though - which version of PyDev do you have? \n" ]
[ 2 ]
[]
[]
[ "built_in", "configuration", "eclipse", "python" ]
stackoverflow_0003359697_built_in_configuration_eclipse_python.txt
Q: Removing values from a list in python I have a large file of names and values on a single line separated by a space: name1 name2 name3.... Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na. For instance, the final line of name in this file is like so: namenexttolast nameonemore namethelast 0 na 2 I would like the following output: namenexttolast namethelast 0 2 How would I do this using Python? A: Let's say you read the names into one list, then the values into another. Once you have a names and values list, you can do something like: result = [n for n, v in zip(names, values) if v != 'na'] result is now a list of all names whose value is not "na". A: s = "name1 name2 name3 v1 na v2" s = s.split(' ') names = s[:len(s)/2] values = s[len(s)/2:] names_and_values = zip(names, values) names, values = [], [] [(names.append(n) or values.append(v)) for n, v in names_and_values if v != "na"] names.extend(values) print ' '.join(names) Update Minor improvement after suggestion from Paul. I'm sure the list comprehension is fairly unpythonic, as it leverages the fact that list.append returns None, so both append expressions will be evaluated and a list of None values will be constructed and immediately thrown away. A: or say you have a string which you have read from a file. Let's call this string as "s" words = filter(lambda x: x!="na", s.split()) should give you all the strings except for "na" edit: the code above obviously doesn't do what you want it to do. the one below should work though d = s.split() keys = d[:len(d)/2] vals = d[len(d)/2:] w = " ".join(map(lambda (k,v): (k + " " + v) if v!="na" else "", zip(keys, vals))) print " ".join([" ".join(w.split()[::2]), " ".join(w.split()[1::2])]) A: I agree with Justin than using zip is a good idea. The problems is how to put the data into two different lists. Here is a proposal that should work ok. reader = open('input.txt') writer = open('output.txt', 'w') names, nums = [], [] row = reader.read().split(' ') x = len(row)/2 for (a, b) in [(n, v) for n, v in zip(row[:x], row[x:]) if v!='na']: names.append(a) nums.append(b) writer.write(' '.join(names)) writer.write(' ') writer.write(' '.join(nums)) #writer.write(' '.join(names+nums)) is nicer but cause list to be concat A: strlist = 'namenexttolast nameonemore namethelast 0 na 2'.split() vals = ('0', '1', '2', '3', '4', 'na') key_list = [s for s in strlist if s not in vals] val_list = [s for s in strlist if s in vals] #print [(key_list[i],v) for i, v in enumerate(val_list) if v != 'na'] filtered_keys = [key_list[i] for i, v in enumerate(val_list) if v != 'na'] filtered_vals = [v for v in val_list if v != 'na'] print filtered_keys + filtered_vals If you'd rather group the vals, you could create a list of tuples instead (commented out line) A: Here is a solution that uses just iterators plus a single buffer element, with no calls to len and no other intermediate lists created. (In Python 3, just use map and zip, no need to import imap and izip from itertools.) from itertools import izip, imap, ifilter def iterStartingAt(cond, seq): it1,it2 = iter(seq),iter(seq) while not cond(it1.next()): it2.next() for item in it2: yield item dataline = "namenexttolast nameonemore namethelast 0 na 2" datalinelist = dataline.split() valueset = set("0 1 2 3 4 na".split()) print " ".join(imap(" ".join, izip(*ifilter(lambda (n,v): v != 'na', izip(iter(datalinelist), iterStartingAt(lambda s: s in valueset, datalinelist)))))) Prints: namenexttolast namethelast 0 2
Removing values from a list in python
I have a large file of names and values on a single line separated by a space: name1 name2 name3.... Following the long list of names is a list of values corresponding to the names. The values can be 0-4 or na. What I want to do is consolidate the data file and remove all the names and and values when the value is na. For instance, the final line of name in this file is like so: namenexttolast nameonemore namethelast 0 na 2 I would like the following output: namenexttolast namethelast 0 2 How would I do this using Python?
[ "Let's say you read the names into one list, then the values into another. Once you have a names and values list, you can do something like:\nresult = [n for n, v in zip(names, values) if v != 'na']\n\nresult is now a list of all names whose value is not \"na\".\n", "s = \"name1 name2 name3 v1 na v2\"\ns = s.spl...
[ 5, 4, 1, 1, 0, 0 ]
[]
[]
[ "python", "text_parsing" ]
stackoverflow_0003356460_python_text_parsing.txt
Q: String search in mysqltable using python I want to search the matching strings from a mysql table. The search string is not a correct sentence, its only a part of the sentence.Any one can help me.? Thanks in advance... Nimmy A: Something like this? SELECT * FROM table WHERE string LIKE '%substring%' http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html
String search in mysqltable using python
I want to search the matching strings from a mysql table. The search string is not a correct sentence, its only a part of the sentence.Any one can help me.? Thanks in advance... Nimmy
[ "Something like this?\nSELECT * FROM table WHERE string LIKE '%substring%'\n\nhttp://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003360263_mysql_python.txt
Q: How to simulate clicks on text using python? I want to simulate such clicks without controlling web browsers to do the job. I don't know much about javascript and actually don't know where to start. Any ideas? A: Althoug I have no use it, I think that maybe twill is what you need: twill: a simple scripting language for Web browsing Have a look at this too: Testing Web Applications with Python and Twill A: You can use iMacros in combination with Python... This isn't the most direct solution as it requires you to write an iMacros script to do that actual clicking, and then load the page and call the script from Python. Refereces: iMacros CLICK command iMacros wiki A: If you had control over the link (like adding an ID attribute) you could use javascript to simulate the click var link = document.getElementById['yourLinksIdAttrbuteValue']; link.click(); or you could use jQuery selectors as an easy way to better target the link without altering it... <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script> $(function(){ $("a[href^='javascript']:contains('text')").click() }); </script> With that code it'll load the JQuery library from google's server, wait for the dom to load, then execute the click. for more info on jQuery selectors check out http://api.jquery.com/category/selectors/ A: I recommend you take a look at Selenium.
How to simulate clicks on text using python?
I want to simulate such clicks without controlling web browsers to do the job. I don't know much about javascript and actually don't know where to start. Any ideas?
[ "Althoug I have no use it, I think that maybe twill is what you need:\n\ntwill: a simple scripting language for Web browsing\n\nHave a look at this too:\n\nTesting Web Applications with Python and Twill\n\n", "You can use iMacros in combination with Python... \nThis isn't the most direct solution as it requires y...
[ 1, 0, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0003334278_javascript_python.txt
Q: python : read a line, then instantiate a class named in the line I'm sorry if I wasn't clear enough in the title, don't hesitate to correct it if you find a better way to express that: I have a file where there are class names, i.e.: classa classb classb classc classc classc Then I want to read it line by line and to dynamically create that class. I would do something like that in php: while (!eof()) { $class=fread(..) $tab[] = new $class(); } How would you do that in python (if it's possible)? Thanks a lot! Edit: after reading the answers, to be more precise on what I'm planning to do: I'm not planning to do such a simple stuff. It will be far more complex: I want a user who doesn't know programming to edit a simple text file, and to copy/paste some declarations and change their properties and to re-launch a kind of parser which will re-run a batch and show the result of complex operations. Simplified Example of a file: car:(red,4_wheels,4_places) bike:(blue,2_wheels,1_place) Then the user will change it to: car:(red,4_wheels,4_places) car:(yellow,4_wheels,2_places) bike:(blue,2_wheels,1_place) bike:(green,2_wheels,2_places) And then with python I'll read this file, create two instances of the class car, and two instances of the class bike. Thus a user who doesn't understand / know python will be able to edit the file without touching a line of code. I think this is the right way to go, if you have any other suggestions for this code, you're welcome! Olivier Pons A: Assuming your classes are already in scope (i.e. they're not in a separate module), you can refer to a class by its name very easily through the globals() dict. For example: class Foo: pass foo_cls = globals()['Foo'] foo = foo_cls() # foo is now an instance of __main__.Foo A: The other answers do what you asked, but I wanted to add a small measure of flexibility (and protection.) I would use a dictionary to map the line names to the class objects, so you're not letting the text file instantiate anything it wants. It has to be a class that you allow it to, in your code. This also makes it easier because you can change names on either side without trouble (and you could map multiple line-names to a single class name, if you wanted.) classes = {'classa': classa, 'classb': classb} cls = type(classes[line], (object,), {}) ## or whichever method to instantiate you prefer But in general, it's not a very Pythonic thing to do, in my opinion. A: Reading each line from the file is pretty easy: with open(filename) as f: for line in f: The first thing that comes to mind for class creation is the type function: cls = type(line, (object,), {}) This will create a new empty class which is a subclass of object and has a name given by the contents of the line. I have to wonder why you're trying to do this, though. An empty class like that doesn't seem very useful in Python. A: Assuming that all classes are declared in a module foo: classname = sys.stdin.read().rstrip() cls = getattr(foo, classname)() To access classes in the same module, use the builtin globals() function. A: As you are using YAML anyway, consider using PyYAML with the serialized classes deriving from the yaml.YAMLObject metaclass or registering your own represenenter. From the documentation of PyYAML: class Monster(yaml.YAMLObject): yaml_tag = u'!Monster' def __init__(self, name, hp, ac, attacks): self.name = name self.hp = hp self.ac = ac self.attacks = attacks def __repr__(self): return "%s(name=%r, hp=%r, ac=%r, attacks=%r)" % ( self.__class__.__name__, self.name, self.hp, self.ac, self.attacks) print yaml.load(""" --- !Monster name: Cave spider hp: [2,6] # 2d6 ac: 16 attacks: [BITE, HURT] """) prints Monster(name='Cave spider', hp=[2, 6], ac=16, attacks=['BITE', 'HURT']) That way you can leave out many of the code you need for error handling (e.g. class is not present) and you also have system that is more robust against malicious configuration files. As an additional bonus, you are able to dump objects from your program into a YAML file. A: This should be fairly easily possible using a dictionary of classes (not that this is not necessarily a restriction as each python namespace can be accessed as a dictionary so if you want these classes say to all be within a module or another class, just replace classes with the __dict__ attribute of the class or use globals as others have suggested): classes = dict() with open('filename') as f: for line in f: classes[line] = class() (Implementation details may vary). You may however want to look into using pickling instead as on the face of it, this approach seems flawed (it might work well in PHP though :-) ).
python : read a line, then instantiate a class named in the line
I'm sorry if I wasn't clear enough in the title, don't hesitate to correct it if you find a better way to express that: I have a file where there are class names, i.e.: classa classb classb classc classc classc Then I want to read it line by line and to dynamically create that class. I would do something like that in php: while (!eof()) { $class=fread(..) $tab[] = new $class(); } How would you do that in python (if it's possible)? Thanks a lot! Edit: after reading the answers, to be more precise on what I'm planning to do: I'm not planning to do such a simple stuff. It will be far more complex: I want a user who doesn't know programming to edit a simple text file, and to copy/paste some declarations and change their properties and to re-launch a kind of parser which will re-run a batch and show the result of complex operations. Simplified Example of a file: car:(red,4_wheels,4_places) bike:(blue,2_wheels,1_place) Then the user will change it to: car:(red,4_wheels,4_places) car:(yellow,4_wheels,2_places) bike:(blue,2_wheels,1_place) bike:(green,2_wheels,2_places) And then with python I'll read this file, create two instances of the class car, and two instances of the class bike. Thus a user who doesn't understand / know python will be able to edit the file without touching a line of code. I think this is the right way to go, if you have any other suggestions for this code, you're welcome! Olivier Pons
[ "Assuming your classes are already in scope (i.e. they're not in a separate module), you can refer to a class by its name very easily through the globals() dict. For example:\nclass Foo:\n pass\n\nfoo_cls = globals()['Foo']\nfoo = foo_cls()\n# foo is now an instance of __main__.Foo\n\n", "The other answers do...
[ 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "dynamic", "python" ]
stackoverflow_0003357693_dynamic_python.txt
Q: Python: Locate 3 adjacent list items and determine list index of first of them I need to process weather station data which is in a format like this (SYNOP), where each line represents one measurement and I have thousands of measurements: line = 'AAXX 01004 60265 32970 03404 10048 20010 38997 48605 51014=' Starting with the 6th block, the blocks are numbered (1xxxx 2xxxx 3xxxx etc, sometimes only 5 blocks but sometimes also more with additional data) The crucial point is that the number of blocks between the AAXX and the 1xxxx block is not always the same, but I know that 2 blocks before the 1xxxx block there is data I need. To reliably pinpoint that block I would need to determine the position of the 1xxxx block and count backwards from there. My idea is to split the line along spaces into a list, and then iterate through the list items to find the position in the list of the 1xxxx block. list = line.split(' ') But I don't know how to do this iteration. There must be a reasonably elegant way to look for 3 blocks where the first starts with 1, the second with 2, and the third with 3, then return the list index of the first block? This may be very simple but I'm unable to figure it out, and would be grateful for any tips! EDIT: To clarify, it's possible that another block starting with 1 appears before the one I need, so the only reliable way to pinpoint the block I need is to ensure that it is followed by one that starts with 2 and another that starts with 3 (that should reduce the chance of a false positive to pretty much 0). A: There is more than one way to do this. One way would be to search the list for the index and subtract two: list[ (i for i, j in enumerate( list ) if j.startswith( "1" ) ).next() - 2 ] Another way would be to match a regex onto the (unsplit) string: import re re.search( "\d{5}(?= \d{5} 1\d{4} 2\d{4} 3\d{4})", line ) This matches a block of five digits, as long as it's followed by 1xxxx 2xxxx 3xxxx where x is any digit. A: to iterate over a list is very simple : l = line.split(' ') for element in l: # element is now one of the strings from your list if element[0] == "1": print "This block begins by 1"
Python: Locate 3 adjacent list items and determine list index of first of them
I need to process weather station data which is in a format like this (SYNOP), where each line represents one measurement and I have thousands of measurements: line = 'AAXX 01004 60265 32970 03404 10048 20010 38997 48605 51014=' Starting with the 6th block, the blocks are numbered (1xxxx 2xxxx 3xxxx etc, sometimes only 5 blocks but sometimes also more with additional data) The crucial point is that the number of blocks between the AAXX and the 1xxxx block is not always the same, but I know that 2 blocks before the 1xxxx block there is data I need. To reliably pinpoint that block I would need to determine the position of the 1xxxx block and count backwards from there. My idea is to split the line along spaces into a list, and then iterate through the list items to find the position in the list of the 1xxxx block. list = line.split(' ') But I don't know how to do this iteration. There must be a reasonably elegant way to look for 3 blocks where the first starts with 1, the second with 2, and the third with 3, then return the list index of the first block? This may be very simple but I'm unable to figure it out, and would be grateful for any tips! EDIT: To clarify, it's possible that another block starting with 1 appears before the one I need, so the only reliable way to pinpoint the block I need is to ensure that it is followed by one that starts with 2 and another that starts with 3 (that should reduce the chance of a false positive to pretty much 0).
[ "There is more than one way to do this. One way would be to search the list for the index and subtract two:\nlist[ (i for i, j in enumerate( list ) if j.startswith( \"1\" ) ).next() - 2 ]\n\nAnother way would be to match a regex onto the (unsplit) string:\nimport re\nre.search( \"\\d{5}(?= \\d{5} 1\\d{4} 2\\d{4} 3\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003360447_python.txt
Q: Python: multiple files download by turn In script loop performs files downloading and saving (curl). But loop iterations too quick, so downloading and saving actions have no time to complete it's operations. Thereat result files comes broken def get_images_thread(table): class LoopThread ( threading.Thread ): def run ( self ): global db c=db.cursor() c.execute(""" SELECT * FROM js_stones ORDER BY stone_id LIMIT 1 """) ec = EasyCurl(table) while(1): stone = c.fetchone() if stone == None: break img_fname = stone[2] print img_fname url = "http://www.jstone.it/"+img_fname fname = url.strip("/").split("/")[-1].strip() ec.perform(url, filename="D:\\Var\\Python\\Jstone\\downloadeble_pictures\\"+fname, progress=ec.textprogress) A: This is an excerpt from the examples for the PycURL library, # Make a queue with (url, filename) tuples queue = Queue.Queue() for url in urls: url = url.strip() if not url or url[0] == "#": continue filename = "doc_%03d.dat" % (len(queue.queue) + 1) queue.put((url, filename)) # Check args assert queue.queue, "no URLs given" num_urls = len(queue.queue) num_conn = min(num_conn, num_urls) assert 1 <= num_conn <= 10000, "invalid number of concurrent connections" print "PycURL %s (compiled against 0x%x)" % (pycurl.version, pycurl.COMPILE_LIBCURL_VERSION_NUM) print "----- Getting", num_urls, "URLs using", num_conn, "connections -----" class WorkerThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while 1: try: url, filename = self.queue.get_nowait() except Queue.Empty: raise SystemExit fp = open(filename, "wb") curl = pycurl.Curl() curl.setopt(pycurl.URL, url) curl.setopt(pycurl.FOLLOWLOCATION, 1) curl.setopt(pycurl.MAXREDIRS, 5) curl.setopt(pycurl.CONNECTTIMEOUT, 30) curl.setopt(pycurl.TIMEOUT, 300) curl.setopt(pycurl.NOSIGNAL, 1) curl.setopt(pycurl.WRITEDATA, fp) try: curl.perform() except: import traceback traceback.print_exc(file=sys.stderr) sys.stderr.flush() curl.close() fp.close() sys.stdout.write(".") sys.stdout.flush() # Start a bunch of threads threads = [] for dummy in range(num_conn): t = WorkerThread(queue) t.start() threads.append(t) # Wait for all threads to finish for thread in threads: thread.join()
Python: multiple files download by turn
In script loop performs files downloading and saving (curl). But loop iterations too quick, so downloading and saving actions have no time to complete it's operations. Thereat result files comes broken def get_images_thread(table): class LoopThread ( threading.Thread ): def run ( self ): global db c=db.cursor() c.execute(""" SELECT * FROM js_stones ORDER BY stone_id LIMIT 1 """) ec = EasyCurl(table) while(1): stone = c.fetchone() if stone == None: break img_fname = stone[2] print img_fname url = "http://www.jstone.it/"+img_fname fname = url.strip("/").split("/")[-1].strip() ec.perform(url, filename="D:\\Var\\Python\\Jstone\\downloadeble_pictures\\"+fname, progress=ec.textprogress)
[ "This is an excerpt from the examples for the PycURL library,\n# Make a queue with (url, filename) tuples\nqueue = Queue.Queue()\nfor url in urls:\n url = url.strip()\n if not url or url[0] == \"#\":\n continue\n filename = \"doc_%03d.dat\" % (len(queue.queue) + 1)\n queue.put((url, filename))\n\...
[ 4 ]
[ "If you're asking what I think you're asking, \nfrom time import sleep\nsleep(1)\n\nshould \"solve\"(It's hacky to the max!) your problem. Docs here. I would check that that really is your problem, though. It seems catastrophically unlikely that pausing for a few seconds would stop files from downloading brokenly. ...
[ -1 ]
[ "python" ]
stackoverflow_0003359929_python.txt
Q: Simple list comprehension I want a dictionary of files: files = [files for (subdir, dirs, files) in os.walk(rootdir)] But I get, files = [['filename1', 'filename2']] when I want files = ['filename1', 'filename2'] How do I prevent looping through that tuple? Thanks! A: Both of these work: [f for (subdir, dirs, files) in os.walk(rootdir) for f in files] sum([files for (subdir, dirs, files) in os.walk(rootdir)], []) Sample output: $ find /tmp/test /tmp/test /tmp/test/subdir1 /tmp/test/subdir1/file1 /tmp/test/subdir2 /tmp/test/subdir2/file2 $ python >>> import os >>> rootdir = "/tmp/test" >>> [f for (subdir, dirs, files) in os.walk(rootdir) for f in files] ['file1', 'file2'] >>> sum([files for (subdir, dirs, files) in os.walk(rootdir)], []) ['file1', 'file2'] A: for (subdir, dirs, f) in os.walk(rootdir): files.extend(f) A: files = [filename for (subdir, dirs, files) in os.walk(rootdir) for filename in files] A: import os, glob files = [file for file in glob.glob('*') if os.path.isfile(file)] if your files have extensions, then even simpler: import glob files = glob.glob('*.*')
Simple list comprehension
I want a dictionary of files: files = [files for (subdir, dirs, files) in os.walk(rootdir)] But I get, files = [['filename1', 'filename2']] when I want files = ['filename1', 'filename2'] How do I prevent looping through that tuple? Thanks!
[ "Both of these work:\n[f for (subdir, dirs, files) in os.walk(rootdir) for f in files]\n\nsum([files for (subdir, dirs, files) in os.walk(rootdir)], [])\n\nSample output:\n$ find /tmp/test\n/tmp/test\n/tmp/test/subdir1\n/tmp/test/subdir1/file1\n/tmp/test/subdir2\n/tmp/test/subdir2/file2\n$ python\n>>> import os\n>>...
[ 7, 2, 2, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003326428_list_comprehension_python.txt
Q: Crawl Images, Whole Web Pages and cache them I am starting a project and wonder the relationship between the characters in images and the whole web page where the images reside. I want to crawl some images and their web pages. I need to save the crawl result in local disk for further analysis. I wonder if there is any open source for this issue? A: Here's a list of open source crawlers http://www.google.co.uk/#hl=en&source=hp&q=open+source+web+crawler&aq=f&aqi=g9g-m1&aql=&oq=&gs_rfai=&fp=77130048d7e0701a Near top of the list are Java crawlers, and the Wikipedia article has some more as well A: You can use crawler4j for this purpose. It is a simple java crawler that can be configured in a few minutes and you can use it for crawling images as well. You can also find an ImageCrawler example in the source codes.
Crawl Images, Whole Web Pages and cache them
I am starting a project and wonder the relationship between the characters in images and the whole web page where the images reside. I want to crawl some images and their web pages. I need to save the crawl result in local disk for further analysis. I wonder if there is any open source for this issue?
[ "Here's a list of open source crawlers\nhttp://www.google.co.uk/#hl=en&source=hp&q=open+source+web+crawler&aq=f&aqi=g9g-m1&aql=&oq=&gs_rfai=&fp=77130048d7e0701a\nNear top of the list are Java crawlers, and the Wikipedia article has some more as well\n", "You can use crawler4j for this purpose. It is a simple java...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003052348_python.txt
Q: Dynamically Created Top Articles List in Django? I'm creating a Django-powered site for my newspaper-ish site. The least obvious and common-sense task that I have come across in getting the site together is how best to generate a "top articles" list for the sidebar of the page. The first thing that came to mind was some sort of database column that is updated (based on what?) with every view. That seems (to my instincts) ridiculously database intensive and impractical and thus I think I'd like to find another solution. Thanks all. A: I would give celery a try (with django-celery). While it's not so easy to configure and use as cache, it enables you to queue tasks like incrementing counters and do them in background. It could be even combined with cache technique - in views increment counters in cache and define PeriodicTask that will run every now and then, resetting counters and writing them to the database. I just remembered - I once found this blog entry which provides nice way of incrementing 'viewed_count' (or similar) column in database with AJAX JS call. If you don't have heavy traffic maybe it's good idea? Also mentioned in this post is django-tracking, but I don't know much about it, I never used it myself (yet). A: Premature optimization, first try the db way and then see if it really is too database sensitive. Any decent database has so good caches it probably won't matter very much. And even if it is a problem, take a look at the other db/cache suggestions here. It is most likely by the way is that you will have many more intensive db queries with each view than a simple view update. A: If you do something like sort by top views, it would be fast if you index the view column in the DB. Another option is to only collect the top x articles every hour or so, and toss that value into Django's cache framework. The nice thing about caching the list is that the algorithm you use to determine top articles can be as complex as you like without hitting the DB hard with every page view. Django's cache framework can use memory, db, or file system. I prefer DB, but many others prefer memory. I believe it uses pickle, so you can also store Python objects directly. It's easy to use, recommended. A: An index wouldn't help as them main problem I believe is not so much getting the sorted list as having a DB write with every page view of an article. Another index actually makes that problem worse, albeit only a little. So I'd go with the cache. I think django's cache shim is a problem here because it requires timeouts on all keys. I'm not sure if that's imposed by memcached, if not then go with redis. Actually just go with redis anyway, the python library is great, I've used it from django projects before, and it has atomic increments and powerful sorting - everything you need.
Dynamically Created Top Articles List in Django?
I'm creating a Django-powered site for my newspaper-ish site. The least obvious and common-sense task that I have come across in getting the site together is how best to generate a "top articles" list for the sidebar of the page. The first thing that came to mind was some sort of database column that is updated (based on what?) with every view. That seems (to my instincts) ridiculously database intensive and impractical and thus I think I'd like to find another solution. Thanks all.
[ "I would give celery a try (with django-celery). While it's not so easy to configure and use as cache, it enables you to queue tasks like incrementing counters and do them in background. It could be even combined with cache technique - in views increment counters in cache and define PeriodicTask that will run every...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003359214_django_mysql_python.txt
Q: How do I get the stack trace from an Exception Object in Python? How can I get the full stack trace from the Exception object itself? Consider the following code as reduced example of the problem: last_exception = None try: raise Exception('foo failed') except Exception as e: last_exception = e # this happens somewhere else, decoupled from the original raise print_exception_stack_trace(last_exception) A: Edit: I lied, sorry. e.__traceback__ is what you want. try: raise ValueError except ValueError as e: print( e.__traceback__ ) >c:/python31/pythonw -u "test.py" <traceback object at 0x00C964B8> >Exit code: 0 This is only valid in Python 3; you can't do it in earlier versions.
How do I get the stack trace from an Exception Object in Python?
How can I get the full stack trace from the Exception object itself? Consider the following code as reduced example of the problem: last_exception = None try: raise Exception('foo failed') except Exception as e: last_exception = e # this happens somewhere else, decoupled from the original raise print_exception_stack_trace(last_exception)
[ "Edit: I lied, sorry. e.__traceback__ is what you want.\ntry:\n raise ValueError\nexcept ValueError as e:\n print( e.__traceback__ )\n\n>c:/python31/pythonw -u \"test.py\"\n<traceback object at 0x00C964B8>\n>Exit code: 0\n\nThis is only valid in Python 3; you can't do it in earlier versions.\n" ]
[ 3 ]
[]
[]
[ "exception_handling", "python", "stack_trace" ]
stackoverflow_0003361853_exception_handling_python_stack_trace.txt
Q: How to parse RSS link (get ulr to RSS) from the page in Python framework Scrapy? I want to parse Google search and get links to RSS from each item from the search results. I use Scrapy. I tried this construction, ... def parse_second(self, response): hxs = HtmlXPathSelector(response) qqq = hxs.select('/html/head/link[@type=application/rss+xml]/@href').extract() print qqq item = response.request.meta['item'] if len(qqq) > 0: item['rss'] = qqq.pop() else: item['rss'] = '' yield item ... but "print qqq" gives me [] A: Found a mistake: qqq = hxs.select("/html/head/link[@type='application/rss+xml']/@href").extract() that works
How to parse RSS link (get ulr to RSS) from the page in Python framework Scrapy?
I want to parse Google search and get links to RSS from each item from the search results. I use Scrapy. I tried this construction, ... def parse_second(self, response): hxs = HtmlXPathSelector(response) qqq = hxs.select('/html/head/link[@type=application/rss+xml]/@href').extract() print qqq item = response.request.meta['item'] if len(qqq) > 0: item['rss'] = qqq.pop() else: item['rss'] = '' yield item ... but "print qqq" gives me []
[ "Found a mistake:\nqqq = hxs.select(\"/html/head/link[@type='application/rss+xml']/@href\").extract()\n\nthat works\n" ]
[ 1 ]
[]
[]
[ "parsing", "python", "rss", "scrapy", "xpath" ]
stackoverflow_0003362133_parsing_python_rss_scrapy_xpath.txt
Q: Is there a faster way to get subtrees from tree like structures in python than the standard "recursive"? Let's assume the following data structur with three numpy arrays (id, parent_id) (parent_id of the root element is -1): import numpy as np class MyStructure(object): def __init__(self): """ Default structure for now: 1 / \ 2 3 / \ 4 5 """ self.ids = np.array([1,2,3,4,5]) self.parent_ids = np.array([-1, 1, 1, 3, 3]) def id_successors(self, idOfInterest): """ Return logical index. """ return self.parent_ids == idOfInterest def subtree(self, newRootElement): """ Return logical index pointing to elements of the subtree. """ init_vector = np.zeros(len(self.ids), bool) init_vector[np.where(self.ids==newRootElement)[0]] = 1 if sum(self.id_successors(newRootElement))==0: return init_vector else: subtree_vec = init_vector for sucs in self.ids[self.id_successors(newRootElement)==1]: subtree_vec += self.subtree(sucs) return subtree_vec This get's really slow for many ids (>1000). Is there a faster way to implement that? A: Have you tried to use psyco module if you are using Python 2.6? It can sometimes do dramatic speed up of code. Have you considered recursive data structure: list? Your example is also as standard list: [1, 2, [3, [4],[5]]] or [1, [2, None, None], [3, [4, None, None],[5, None, None]]] By my pretty printer: [1, [2, None, None], [3, [4, None, None], [5, None, None]]] Subtrees are ready there, cost you some time inserting values to right tree. Also worth while to check if heapq module fits your needs. Also Guido himself gives some insight on traversing and trees in http://python.org/doc/essays/graphs.html, maybe you are aware of it. Here is some advanced looking tree stuff, actually proposed for Python as basic list type replacement, but rejected in that function. Blist module A: I think it's not the recursion as such that's hurting you, but the multitude of very wide operations (over all elements) for every step. Consider: init_vector[np.where(self.ids==newRootElement)[0]] = 1 That runs a scan through all elements, calculates the index of every matching element, then uses only the index of the first one. This particular operation is available as the method index for lists, tuples, and arrays - and faster there. If IDs are unique, init_vector is simply ids==newRootElement anyway. if sum(self.id_successors(newRootElement))==0: Again a linear scan of every element, then a reduction on the whole array, just to check if any matches are there. Use any for this type of operation, but once again we don't even need to do the check on all elements - "if newRootElement not in self.parent_ids" does the job, but it's not necessary as it's perfectly valid to do a for loop over an empty list. Finally there's the last loop: for sucs in self.ids[self.id_successors(newRootElement)==1]: This time, an id_successors call is repeated, and then the result is compared to 1 needlessly. Only after that comes the recursion, making sure all the above operations are repeated (for different newRootElement) for each branch. The whole code is a reversed traversal of a unidirectional tree. We have parents and need children. If we're to do wide operations such as numpy is designed for, we'd best make them count - and thus the only operation we care about is building a list of children per parent. That's not very hard to do with one iteration: import collections children=collections.defaultdict(list) for i,p in zip(ids,parent_ids): children[p].append(i) def subtree(i): return i, map(subtree, children[i]) The exact structure you need will depend on more factors, such as how often the tree changes, how large it is, how much it branches, and how large and many subtrees you need to request. The dictionary+list structure above isn't terribly memory efficient, for instance. Your example is also sorted, which could make the operation even easier. A: In theory, every algorithm can be written iteratively as well as recursively. But this is a fallacy (like Turing-completeness). In practice, walking an arbitrarily-nested tree via iteration is generally not feasible. I doubt there is much to optimize (at least you're modifying subtree_vec in-place). Doing x on thousands of elements is inherently damn expensive, no matter whether you do it iteratively or recursively. At most there are a few micro-optimizations possible on the concrete implementation, which will at most yield <5% improvement. Best bet would be caching/memoization, if you need the same data several times. Maybe someone has a fancy O(log n) algorithm for your specific tree structure up their sleeve, I don't even know if one is possible (I'd assume no, but tree manipulation isn't my staff of life). A: This is my answer (written without access to your class, so the interface is slightly different, but I'm attaching it as is so that you can test if it is fast enough): =======================file graph_array.py========================== import collections import numpy def find_subtree(pids, subtree_id): N = len(pids) assert 1 <= subtree_id <= N subtreeids = numpy.zeros(pids.shape, dtype=bool) todo = collections.deque([subtree_id]) iter = 0 while todo: id = todo.popleft() assert 1 <= id <= N subtreeids[id - 1] = True sons = (pids == id).nonzero()[0] + 1 #print 'id={0} sons={1} todo={2}'.format(id, sons, todo) todo.extend(sons) iter = iter+1 if iter>N: raise ValueError() return subtreeids =======================file graph_array_test.py========================== import numpy from graph_array import find_subtree def _random_graph(n, maxsons): import random pids = numpy.zeros(n, dtype=int) sons = numpy.zeros(n, dtype=int) available = [] for id in xrange(1, n+1): if available: pid = random.choice(available) sons[pid - 1] += 1 if sons[pid - 1] == maxsons: available.remove(pid) else: pid = -1 pids[id - 1] = pid available.append(id) assert sons.max() <= maxsons return pids def verify_subtree(pids, subtree_id, subtree): ids = set(subtree.nonzero()[0] + 1) sons = set(ids) - set([subtree_id]) fathers = set(pids[id - 1] for id in sons) leafs = set(id for id in ids if not (pids == id).any()) rest = set(xrange(1, pids.size+1)) - fathers - leafs assert fathers & leafs == set() assert fathers | leafs == ids assert ids & rest == set() def test_linear_graph_gen(n, genfunc, maxsons): assert maxsons == 1 pids = genfunc(n, maxsons) last = -1 seen = set() for _ in xrange(pids.size): id = int((pids == last).nonzero()[0]) + 1 assert id not in seen seen.add(id) last = id assert seen == set(xrange(1, pids.size + 1)) def test_case1(): """ 1 / \ 2 4 / 3 """ pids = numpy.array([-1, 1, 2, 1]) subtrees = {1: [True, True, True, True], 2: [False, True, True, False], 3: [False, False, True, False], 4: [False, False, False, True]} for id in xrange(1, 5): sub = find_subtree(pids, id) assert (sub == numpy.array(subtrees[id])).all() verify_subtree(pids, id, sub) def test_random(n, genfunc, maxsons): pids = genfunc(n, maxsons) for subtree_id in numpy.arange(1, n+1): subtree = find_subtree(pids, subtree_id) verify_subtree(pids, subtree_id, subtree) def test_timing(n, genfunc, maxsons): import time pids = genfunc(n, maxsons) t = time.time() for subtree_id in numpy.arange(1, n+1): subtree = find_subtree(pids, subtree_id) t = time.time() - t print 't={0}s = {1:.2}ms/subtree = {2:.5}ms/subtree/node '.format( t, t / n * 1000, t / n**2 * 1000), def pytest_generate_tests(metafunc): if 'case' in metafunc.function.__name__: return ns = [1, 2, 3, 4, 5, 10, 20, 50, 100, 1000] if 'timing' in metafunc.function.__name__: ns += [10000, 100000, 1000000] pass for n in ns: func = _random_graph for maxsons in sorted(set([1, 2, 3, 4, 5, 10, (n+1)//2, n])): metafunc.addcall( funcargs=dict(n=n, genfunc=func, maxsons=maxsons), id='n={0} {1.__name__}/{2}'.format(n, func, maxsons)) if 'linear' in metafunc.function.__name__: break ===================py.test --tb=short -v -s test_graph_array.py============ ... test_graph_array.py:72: test_timing[n=1000 _random_graph/1] t=13.4850590229s = 13.0ms/subtree = 0.013485ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/2] t=0.318281888962s = 0.32ms/subtree = 0.00031828ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/3] t=0.265519142151s = 0.27ms/subtree = 0.00026552ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/4] t=0.24147105217s = 0.24ms/subtree = 0.00024147ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/5] t=0.211434841156s = 0.21ms/subtree = 0.00021143ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/10] t=0.178458213806s = 0.18ms/subtree = 0.00017846ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/500] t=0.209936141968s = 0.21ms/subtree = 0.00020994ms/subtree/node PASS test_graph_array.py:72: test_timing[n=1000 _random_graph/1000] t=0.245707988739s = 0.25ms/subtree = 0.00024571ms/subtree/node PASS ... Here every subtree of every tree is taken, and the interesting value is the mean time to extract a tree: ~0.2ms per subtree, except for strictly linear trees. I'm not sure what is happening here.
Is there a faster way to get subtrees from tree like structures in python than the standard "recursive"?
Let's assume the following data structur with three numpy arrays (id, parent_id) (parent_id of the root element is -1): import numpy as np class MyStructure(object): def __init__(self): """ Default structure for now: 1 / \ 2 3 / \ 4 5 """ self.ids = np.array([1,2,3,4,5]) self.parent_ids = np.array([-1, 1, 1, 3, 3]) def id_successors(self, idOfInterest): """ Return logical index. """ return self.parent_ids == idOfInterest def subtree(self, newRootElement): """ Return logical index pointing to elements of the subtree. """ init_vector = np.zeros(len(self.ids), bool) init_vector[np.where(self.ids==newRootElement)[0]] = 1 if sum(self.id_successors(newRootElement))==0: return init_vector else: subtree_vec = init_vector for sucs in self.ids[self.id_successors(newRootElement)==1]: subtree_vec += self.subtree(sucs) return subtree_vec This get's really slow for many ids (>1000). Is there a faster way to implement that?
[ "Have you tried to use psyco module if you are using Python 2.6? It can sometimes do dramatic speed up of code.\nHave you considered recursive data structure: list?\nYour example is also as standard list:\n\n[1, 2, [3, [4],[5]]]\n\nor\n\n[1, [2, None, None], [3, [4, None, None],[5, None, None]]]\n\nBy my pretty pri...
[ 4, 4, 3, 0 ]
[]
[]
[ "python", "subtree", "tree" ]
stackoverflow_0003350413_python_subtree_tree.txt
Q: What libraries for modeling complex questionaire in Python? For a medical website I'm trying to model a questionnaire that should result in a range of possible diagnoses. The questionnaire is fairly complex with a lot of conditionals. I made a flowchart/decision tree to reflect this questionnaire. I'm using Django to make the website. Currently I'm thinking of using Python Graph to turn the flow chart into a weighted graph. Each question would be a node and each answer would be an edge+label. I could then walk through the complete graph and the endpoint of the walk would be the fitting diagnose. Is python graph the best library to model this questionnaire or woul you do it differently (other library or other way of modeling the graph)? A: You are modelling a deterministic finite-state automaton. Have a look at python-automata.
What libraries for modeling complex questionaire in Python?
For a medical website I'm trying to model a questionnaire that should result in a range of possible diagnoses. The questionnaire is fairly complex with a lot of conditionals. I made a flowchart/decision tree to reflect this questionnaire. I'm using Django to make the website. Currently I'm thinking of using Python Graph to turn the flow chart into a weighted graph. Each question would be a node and each answer would be an edge+label. I could then walk through the complete graph and the endpoint of the walk would be the fitting diagnose. Is python graph the best library to model this questionnaire or woul you do it differently (other library or other way of modeling the graph)?
[ "You are modelling a deterministic finite-state automaton. Have a look at python-automata.\n" ]
[ 2 ]
[]
[]
[ "decision_tree", "django", "python" ]
stackoverflow_0003362034_decision_tree_django_python.txt
Q: subprocess unable to capture STDOUT - what could be program be doing? I have this program, which when executed on the console like this: prog 1> output 2> error Has the valid output and error. However, when I execute the same program using the subprocess module. p = subprocess.Popen(['prog'],stdout=PIPE, stderr=PIPE,close_fds=True) out, err = p.communicate() The out is empty but err is proper. What could be happening here? I can do a os.system and direct to output and error too. But I had been relying on subprocess for doing till recently. What could be the problem? This is being tried on Linux only. Not on Windows. ` A: Are you trying this on Windows? The use of close_fds is platform dependent, according to the subprocess.Popen() doc. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr. A: Just tried your code and works for me: >>> p = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) >>> out, err = p.communicate() >>> out 'build\nCode\n...' >>> err '' a) Make sure your program is called correctly. b) Did you import PIPE correctly?
subprocess unable to capture STDOUT - what could be program be doing?
I have this program, which when executed on the console like this: prog 1> output 2> error Has the valid output and error. However, when I execute the same program using the subprocess module. p = subprocess.Popen(['prog'],stdout=PIPE, stderr=PIPE,close_fds=True) out, err = p.communicate() The out is empty but err is proper. What could be happening here? I can do a os.system and direct to output and error too. But I had been relying on subprocess for doing till recently. What could be the problem? This is being tried on Linux only. Not on Windows. `
[ "Are you trying this on Windows?\nThe use of close_fds is\nplatform dependent, according to the subprocess.Popen() doc.\n\nIf close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. (Unix only). Or, on Windows, if close_fds is true then no handles will be inher...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003359590_python.txt
Q: How to organise the file structure of my already working plugin system? I am working on a project whose main design guiding principle is extensibility. I implemented a plugin system by defining a metaclass that register - with a class method - the class name of any plugin that gets loaded (each type of plugin inherit from a specific class defined in the core code, as there are different types of plugins in the application). Basically this means that a developer will have to define his class as class PieChart(ChartPluginAncestor): # Duck typing: # Implement compulsory methods for Plugins # extending Chart functionality and the main program will know of his presence because PieChart will be included in the list of registered plugins available at ChartPluginAncestor.plugins. Being the mounting method a class method, all plugins get registered when their class code is loaded into memory (so even before an object of that class is instantiated). The system works good enough™ for me (although I am always open to suggestions on how to improve the architecture!) but I am now wondering what would be the best way to manage the plugin files (i.e. where and how the files containing the plugins should be stored). So far I am using - for developing purposes - a package that I called "plugins". I put all my *.py files containing plugins classes in the package directory, and I simply issue import plugins in the main.py file, for all the plugins to get mounted properly. EDIT: Jeff pointed out in the comments that import plugins the classes contained in the various modules of the packages won't be readily available (I did not realise this as I was - for debugging purposes - importing each class separately with from plugins.myAI import AI). However this system is only good while I am developing and testing the code, as: Plugins might come with their own unittests, and I do not want to load those in memory. All plugins are currently loaded into memory, but indeed there are certain plugins which are alternative versions of the same feature, so you really just need to know that you can switch between the two, but you want to load into memory just the one you picked from the config pane. At some point, I will want to have a double location for installing plugins: a system-wide location (for example somewhere under /usr/local/bin/) and a user-specific one (for example somewhere under /home/<user>/.myprogram/). So my questions are really - perhaps - three: Plugin container: what is the most sensible choice for my goal? single files? packages? a simple directory of .py files?) Recognise the presence of plugins without necessarily loading (importing) them: what is a smart way to use Python introspection to do so? Placing plugins in two different locations: is there a standard way / best practice (under gnu/linux, at least) to do that? A: The question is hard to address, because the needs are complex. Anyway I will try with some suggestions. About Placing plugins in two different locations: is there a standard way / best practice (under gnu/linux, at least) to do that? A good approach is virtualenv. Virtualenv is a python module to build "isolated" python installation. It is the better way to get separate projects working together. You get a brand new site-package where you can put your plugins with the relevant project modules. Give it a try: http://pypi.python.org/pypi/virtualenv Plugin container: what is the most sensible choice for my goal? single files? packages? a simple directory of .py files?) A good approach is a python package which can do a "self registration" upon import: simply define inside the package directory a proper init.py An example can be http://www.qgis.org/wiki/Writing_Python_Plugins and also the API described here http://twistedmatrix.com/documents/current/core/howto/plugin.html See also http://pypi.python.org/pypi/giblets/0.2.1 Giblets is a simple plugin system based on the component architecture of Trac. In a nutshell, giblets allows you to declare interfaces and discover components that implement them without coupling. Giblets also includes plugin discovery based on file paths or entry points along with flexible means to manage which components are enabled or disabled in your application. A: I also have a plugin system with three types of plugins, though I don't claim to have done it well. You can see some details here. For internal plugins, I have a package (e.g., MethodPlugins) and in this package is a module for each plugin (e.g., MethodPlugins.IRV). Here is how I load the plugins: Load the package (import MethodPlugins) Use pkgutil.iter_modules to load all the modules there (e.g., MethodPlugins.IRV) All the plugins descend from a common base class so I can use __subclassess__ to identify them all. I believe this would allow you to recognize plugins without actually loading them, though I don't do that as I just load them all. For external plugins, I have a specified directory where users can put them, and I use os.listdir to import them. The user is required to use the right base class so I can find them. I would be interested in improving this as well, but it also works good enough for me. :)
How to organise the file structure of my already working plugin system?
I am working on a project whose main design guiding principle is extensibility. I implemented a plugin system by defining a metaclass that register - with a class method - the class name of any plugin that gets loaded (each type of plugin inherit from a specific class defined in the core code, as there are different types of plugins in the application). Basically this means that a developer will have to define his class as class PieChart(ChartPluginAncestor): # Duck typing: # Implement compulsory methods for Plugins # extending Chart functionality and the main program will know of his presence because PieChart will be included in the list of registered plugins available at ChartPluginAncestor.plugins. Being the mounting method a class method, all plugins get registered when their class code is loaded into memory (so even before an object of that class is instantiated). The system works good enough™ for me (although I am always open to suggestions on how to improve the architecture!) but I am now wondering what would be the best way to manage the plugin files (i.e. where and how the files containing the plugins should be stored). So far I am using - for developing purposes - a package that I called "plugins". I put all my *.py files containing plugins classes in the package directory, and I simply issue import plugins in the main.py file, for all the plugins to get mounted properly. EDIT: Jeff pointed out in the comments that import plugins the classes contained in the various modules of the packages won't be readily available (I did not realise this as I was - for debugging purposes - importing each class separately with from plugins.myAI import AI). However this system is only good while I am developing and testing the code, as: Plugins might come with their own unittests, and I do not want to load those in memory. All plugins are currently loaded into memory, but indeed there are certain plugins which are alternative versions of the same feature, so you really just need to know that you can switch between the two, but you want to load into memory just the one you picked from the config pane. At some point, I will want to have a double location for installing plugins: a system-wide location (for example somewhere under /usr/local/bin/) and a user-specific one (for example somewhere under /home/<user>/.myprogram/). So my questions are really - perhaps - three: Plugin container: what is the most sensible choice for my goal? single files? packages? a simple directory of .py files?) Recognise the presence of plugins without necessarily loading (importing) them: what is a smart way to use Python introspection to do so? Placing plugins in two different locations: is there a standard way / best practice (under gnu/linux, at least) to do that?
[ "The question is hard to address, because the needs are complex.\nAnyway I will try with some suggestions.\nAbout\n\nPlacing plugins in two different\n locations: is there a standard way /\n best practice (under gnu/linux, at\n least) to do that?\n\nA good approach is virtualenv. Virtualenv is a python module to...
[ 3, 1 ]
[]
[]
[ "file_management", "introspection", "plugins", "python", "software_design" ]
stackoverflow_0003360102_file_management_introspection_plugins_python_software_design.txt
Q: Is Python good for writing standard, compatible and complete SOAP web services? I have used few python soap libraries (SOAPpy, soaplib and Twisted wrapper around SOAPpy) to write my soap web service. When I used python clients (SOAPpy.SOAPProxy and SUDS), I was able to communicate with my web service (returning simple and complex type objects). But, when I tried with C# ASP.net, I got many issues. I came over returning simple types (int, string, double, boolean) issue with some hack into SOAPpy library. But, I am still struggling with returning ComplexTypes from SOAPpy. I could not find any complete, compatible alternative python library for writing my web service. Main Question: Any suggestions/examples for dot net compatible complex type return from python web service would be highly appreciated. Note: I had to hack SOAPpy quite a bit to make it working in first place. And, I had to handwrite wsdl file in case of SOAPpy. A: In my personal opinion, the compatibility of Python SOAP libraries with other platforms is not good. I think that there are two issues here: First, the compatibility of web services among web service stacks is an aspiration rather than reality. For example, look at this question to see how to use web services between Java and WCF. That being said, the concept of WSDL which is largely compile time typing is not in line with Python's original philosophy, so less effort was put into it. I haven't worked with web services for over a year now so may be things have changed. But the advice is the same as in the previous question: Start with the WSDL writing if you are using more than one language/library. As copied from the other question, "start with XSD, but confine yourself to mainstream types. Primitives, complextypes composed of primitives, arrays of same." In the end I settled on using suds for Python web clients, after experimenting with it and soappy and zsi. That was after some time using a C based library (gsoap) and linking to it from Python. I was never satisfied with server implementations in Python, so I used to build Python servers and connect to them from another library which can export SOAP services (in my case Java or C, you will probably use C#). The connection is usually a much simpler protocol. That being said, if you start with WSDL you are likely to get good results using soaplib or may be zsi. But I am afraid there is almost no way around building your types slowly while checking for compatibility.
Is Python good for writing standard, compatible and complete SOAP web services?
I have used few python soap libraries (SOAPpy, soaplib and Twisted wrapper around SOAPpy) to write my soap web service. When I used python clients (SOAPpy.SOAPProxy and SUDS), I was able to communicate with my web service (returning simple and complex type objects). But, when I tried with C# ASP.net, I got many issues. I came over returning simple types (int, string, double, boolean) issue with some hack into SOAPpy library. But, I am still struggling with returning ComplexTypes from SOAPpy. I could not find any complete, compatible alternative python library for writing my web service. Main Question: Any suggestions/examples for dot net compatible complex type return from python web service would be highly appreciated. Note: I had to hack SOAPpy quite a bit to make it working in first place. And, I had to handwrite wsdl file in case of SOAPpy.
[ "In my personal opinion, the compatibility of Python SOAP libraries with other platforms is not good.\nI think that there are two issues here:\n\nFirst, the compatibility of web services among web service stacks is an aspiration rather than reality. For example, look at this question to see how to use web services ...
[ 1 ]
[]
[]
[ "c#", "python", "soap", "twisted" ]
stackoverflow_0003358792_c#_python_soap_twisted.txt
Q: Django: limiting model data I'm searching in a way to limit the queryset which I can get through a model. Suppose I have the following models (with dependencies): Company |- Section | |- Employee | |- Task | `- more models... |- Customer | |- Contract | |- Accounts | `- other great models ... `- some more models... It should be noted that my real models are much deeper and it's not really about business. With a context processor I have added a company instance to request: def magic_view(request): request.company # is a instance of Company model Now my question is what is the best way to limit the access to the child models of Company to the request instance of company? I could make it like task = Task.objects.get(pk=4,section__task=task), but this is a bad way if my model structure is getting deeper. Edit: I could give each other model a foreign key to company, but is this a good practice to store relations redundant? Edit 2: No it isn't. See Is it bad to use redundant relationships?. A: I solved it the following way: First I've created a CurrentCompanyManager. class CurrentCompanyManager(models.Manager): def __init__(self,field,*args,**kwargs): super(CurrentCompanyManager,self).__init__(*args,**kwargs) self.__field_name = field def on(self,company): return self.filter( **{ self.__field_name + '__id__exact':company.id } ) Than I added the manager to all models where I need it. class Employee(models.Model): # some fields and relationships objects = CurrentCompanyManager("section__company") class Accounts(models.Model): # some fields and relationships objects = CurrentCompanyManager("customer__company") And now I can easily limit the model data in the view. def magic_view(request): Employee.objects.on(request.company).all() It should be self-explanatory. If not, then ask me. A: Treat your hierarchy as a graph. Let all your models extend the Node class: class Node(models.Model): parent = models.ForeignKey("Node", blah blah...) def get_root(self): n = self while ((n = n.parent) != None): pass return n Then you can limit your queryset like that: qset = Task.objects.filter(blah...) result = [] for row in qset: if row.get_root() == request.company: result += row It's sloooowwww, but it's all I can come up to at 2:00 AM
Django: limiting model data
I'm searching in a way to limit the queryset which I can get through a model. Suppose I have the following models (with dependencies): Company |- Section | |- Employee | |- Task | `- more models... |- Customer | |- Contract | |- Accounts | `- other great models ... `- some more models... It should be noted that my real models are much deeper and it's not really about business. With a context processor I have added a company instance to request: def magic_view(request): request.company # is a instance of Company model Now my question is what is the best way to limit the access to the child models of Company to the request instance of company? I could make it like task = Task.objects.get(pk=4,section__task=task), but this is a bad way if my model structure is getting deeper. Edit: I could give each other model a foreign key to company, but is this a good practice to store relations redundant? Edit 2: No it isn't. See Is it bad to use redundant relationships?.
[ "I solved it the following way:\nFirst I've created a CurrentCompanyManager.\nclass CurrentCompanyManager(models.Manager):\n def __init__(self,field,*args,**kwargs):\n super(CurrentCompanyManager,self).__init__(*args,**kwargs)\n self.__field_name = field\n\n def on(self,company):\n return...
[ 1, 0 ]
[]
[]
[ "database_design", "django", "django_models", "python" ]
stackoverflow_0003331310_database_design_django_django_models_python.txt
Q: mplot3d in wxPython frame I'm writing an application in wxPython. The button "Plot" shows the wxFrame with 3D surface but I can't rotate the surface. Is it possible to rotate a 3D plot placed in a wxFrame? How can I do? Example: import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx import wx from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt class CanvasFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'CanvasFrame', size=(550,350)) self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = plt.figure() self.axes = axes3d.Axes3D(self.figure) X, Y, Z = axes3d.get_test_data(0.05) self.axes.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3) cset = self.axes.contour(X, Y, Z, zdir='z', offset=-100) cset = self.axes.contour(X, Y, Z, zdir='x', offset=-40) cset = self.axes.contour(X, Y, Z, zdir='y', offset=40) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() self.add_toolbar() def add_toolbar(self): self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() if wx.Platform == '__WXMAC__': self.SetToolBar(self.toolbar) else: tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.toolbar.update() def OnPaint(self, event): self.canvas.draw() class App(wx.App): def OnInit(self): frame = CanvasFrame() frame.Show(True) return True app = App(0) app.MainLoop() A: You'd probably be better off asking on the wxPython google group since I've seen people on there using matplotlib. Anyway, looking at the matplotlib website, it appears that there is a wxMpl module that might help: http://agni.phys.iit.edu/~kmcivor/wxmpl/ My guess is, if matplotlib can rotate the plot outside of wx, then you just need to pass some events from wx to matplotlib to make it work within wx.
mplot3d in wxPython frame
I'm writing an application in wxPython. The button "Plot" shows the wxFrame with 3D surface but I can't rotate the surface. Is it possible to rotate a 3D plot placed in a wxFrame? How can I do? Example: import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import NavigationToolbar2Wx import wx from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt class CanvasFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'CanvasFrame', size=(550,350)) self.SetBackgroundColour(wx.NamedColor("WHITE")) self.figure = plt.figure() self.axes = axes3d.Axes3D(self.figure) X, Y, Z = axes3d.get_test_data(0.05) self.axes.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3) cset = self.axes.contour(X, Y, Z, zdir='z', offset=-100) cset = self.axes.contour(X, Y, Z, zdir='x', offset=-40) cset = self.axes.contour(X, Y, Z, zdir='y', offset=40) self.canvas = FigureCanvas(self, -1, self.figure) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(self.sizer) self.Fit() self.add_toolbar() def add_toolbar(self): self.toolbar = NavigationToolbar2Wx(self.canvas) self.toolbar.Realize() if wx.Platform == '__WXMAC__': self.SetToolBar(self.toolbar) else: tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.toolbar.update() def OnPaint(self, event): self.canvas.draw() class App(wx.App): def OnInit(self): frame = CanvasFrame() frame.Show(True) return True app = App(0) app.MainLoop()
[ "You'd probably be better off asking on the wxPython google group since I've seen people on there using matplotlib. Anyway, looking at the matplotlib website, it appears that there is a wxMpl module that might help: http://agni.phys.iit.edu/~kmcivor/wxmpl/\nMy guess is, if matplotlib can rotate the plot outside of ...
[ 3 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0003362292_matplotlib_python_wxpython.txt
Q: Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation? >>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value return value >>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function ['x', 'x', 'x'] >>> a ['x', 1, 'x', 3, 'x'] # We did assignment anyway A: Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead: for i in range(0,len(a),2): a[i] = 3 Apart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and completely unnecessary here. A: Yes. And I recommend using a[::2] = ['x'] * len(a[::2]) instead. Edit: Microbenchmarks for Python 2.6: ~:249$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * len(a[::2])' 10000 loops, best of 3: 26.2 usec per loop ~:250$ python2.6 -m timeit -s 'a = range(2000)' 'a[::2] = [8] * (len(a)/2)' 10000 loops, best of 3: 19.6 usec per loop ~:251$ python2.6 -m timeit -s 'a = range(2000)' 'for i in xrange(0,len(a),2): a[i] = 8' 10000 loops, best of 3: 92.1 usec per loop ~:252$ python2.6 -m timeit -s 'a = range(2000) > def assign(x,i,v):x[i]=v;return v' '[assign(a,i,8) for i in xrange(0, len(a), 2)]' 1000 loops, best of 3: 336 usec per loop Python 3.1: ~:253$ python3.1 -m timeit -s 'a = list(range(2000))' 'a[::2] = [8] * len(a[::2])' 100000 loops, best of 3: 19.8 usec per loop ~:254$ python3.1 -m timeit -s 'a = list(range(2000))' 'a[::2] = [8] * (len(a)//2)' 100000 loops, best of 3: 13.4 usec per loop ~:255$ python3.1 -m timeit -s 'a = list(range(2000))' 'for i in range(0,len(a),2): a[i] = 8' 10000 loops, best of 3: 119 usec per loop ~:256$ python3.1 -m timeit -s 'a = list(range(2000)) > def assign(x,i,v):x[i]=v;return v' '[assign(a,i,8) for i in range(0, len(a), 2)]' 1000 loops, best of 3: 361 usec per loop A: You can also use list.__setitem__ a = range(5) [a.__setitem__(i,"x") for i in range(0,len(a),2)] Or if you want to avoid the contruction of an intermediate list: any(a.__setitem__(i,"x") for i in range(0,len(a),2)) But assignment in list comprehensions is indeed unpythonic. A: For my timing mentioned (see also the Improving pure Python prime sieve by recurrence formula) from time import clock def rwh_primes1(n): # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Returns a list of primes < n """ sieve = [True] * (n//2) for i in xrange(3,int(n**0.5)+1,2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]] def rwh_primes_tjv(n): # recurrence formula for length by amount1 and amount2 tjv """ Returns a list of primes < n """ sieve = [True] * (n//2) amount1 = n-10 amount2 = 6 for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: ## can you make recurrence formula for whole reciprocal? sieve[i*i//2::i] = [False] * (amount1//amount2+1) amount1-=4*i+4 amount2+=4 return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]] def rwh_primes_len(n): """ Returns a list of primes < n """ sieve = [True] * (n//2) for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: sieve[i*i//2::i] = [False] * len(sieve[i*i//2::i]) return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]] def rwh_primes_any(n): """ Returns a list of primes < n """ halfn=n//2 sieve = [True] * (halfn) for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: any(sieve.__setitem__(item,False) for item in range(i*i//2,halfn,i)) return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]] if __name__ == "__main__": n = 1000000 print("rwh sieve1") t=clock() r=rwh_primes1(n) print("Length %i, %s ms" %(len(r),1000*(clock()-t))) print("rwh sieve with recurrence formula") t=clock() r=rwh_primes_tjv(n) print("Length %i, %s ms" %(len(r),1000*(clock()-t))) print("rwh sieve with len function") t=clock() r=rwh_primes_len(n) print("Length %i, %s ms" %(len(r),1000*(clock()-t))) print("rwh sieve with any with side effects") t=clock() r=rwh_primes_any(n) print("Length %i, %s ms" %(len(r),1000*(clock()-t))) raw_input('Ready') """ Output: rwh sieve1 Length 78498, 213.199442946 ms rwh sieve with recurrence formula Length 78498, 218.34143725 ms rwh sieve with len function Length 78498, 257.80008353 ms rwh sieve with any with side effects Length 78498, 829.977273648 ms Ready """ Length function and all with setitem are not satisfactory alternatives, but the timings are here to demonstrate it. rwh sieve with len function Length 78498, 257.80008353 ms rwh sieve with any with side effects Length 78498, 829.977273648 ms
Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?
>>> a=range(5) >>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects [0, 2, 4] >>> a [0, 1, 2, 3, 4] >>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment SyntaxError: invalid syntax >>> def setitem(listtochange,n,value): ## function to overcome limitation listtochange[n]=value return value >>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function ['x', 'x', 'x'] >>> a ['x', 1, 'x', 3, 'x'] # We did assignment anyway
[ "Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead:\nfor i in range(0,len(a),2):\n a[i] = 3\n\nApart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and comple...
[ 26, 9, 3, -1 ]
[]
[]
[ "list_comprehension", "python", "side_effects", "variable_assignment" ]
stackoverflow_0003362413_list_comprehension_python_side_effects_variable_assignment.txt
Q: Looking for online Judge Engine that support Python I am writing a website which intends to be a place for use to paste/answer coding questions. Especially Python. So, I am looking for an "online judge" engine that could support Python(c/c++/java/# could be a plus), so that the guy who paste the question could provide a simple test, then others could answer it with the onlinejudge to verify it works or not. Is that a known good Online Judge I could use? I do find several here, but not match what I need. A: The Sphere Online Judge supports Python. The questions from the old Google Codejam, along with the problems at Project Euler are both language independent, and are helpful for practicing in any language. A: You can use Ideone API - free for non commercial apps.
Looking for online Judge Engine that support Python
I am writing a website which intends to be a place for use to paste/answer coding questions. Especially Python. So, I am looking for an "online judge" engine that could support Python(c/c++/java/# could be a plus), so that the guy who paste the question could provide a simple test, then others could answer it with the onlinejudge to verify it works or not. Is that a known good Online Judge I could use? I do find several here, but not match what I need.
[ "The Sphere Online Judge supports Python.\nThe questions from the old Google Codejam, along with the problems at Project Euler are both language independent, and are helpful for practicing in any language.\n", "You can use Ideone API - free for non commercial apps.\n" ]
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001253376_python.txt
Q: Clustering after minimum spanning tree cut What would be the optimal way of clustering nodes after cutting a MST with a maximum edge-length? My output from MST edge-length cut is a 2xN array where each element is an integer. The integers are the node identifiers that describe the edges. An example of the output would is given below: >>> print array[0:3] [[ 0 1] [ 0 2] [ 2 17]] I'm typically dealing with 100 to 20,000 nodes. My MST code is sufficiently fast, but it's being bogged down by the clustering/grouping algorithm. It's a loop-heavy set of functions and that's what is slowing it down. Check out the following code. Any ideas on how to speed it up? I'm aware that this is a brute force method, so a cleaner method would be best. Thanks in advance for your help! Cheers, Eli def _super_intersection(edges): group = set(edges[0]) index = np.array([0]) k = 0 while k < 100: k += 1 i = 0 for edge in edges[1:]: i += 1 edge = set(edge) if group & edge: group = group | edge index = np.append(index, i) index = np.unique(np.array(index)) return group, index def cluster(self, gmin = 5): # A 2xN array of node IDs edges = self.edges group_nodes = {} for no, edge in enumerate(edges): try: group, indice = _super_intersection(edges) id_no = no edges = np.delete(edges,indice,0) if len(group) >= gmin: group_nodes[id_no] = list(group) except: self.group_nodes = group_nodes A: The problem has been solved. Go to the NetworkX google group link to see the solution. http://groups.google.com/group/networkx-discuss/browse_thread/thread/4ac4250d460a1b75 Cheers, Eli
Clustering after minimum spanning tree cut
What would be the optimal way of clustering nodes after cutting a MST with a maximum edge-length? My output from MST edge-length cut is a 2xN array where each element is an integer. The integers are the node identifiers that describe the edges. An example of the output would is given below: >>> print array[0:3] [[ 0 1] [ 0 2] [ 2 17]] I'm typically dealing with 100 to 20,000 nodes. My MST code is sufficiently fast, but it's being bogged down by the clustering/grouping algorithm. It's a loop-heavy set of functions and that's what is slowing it down. Check out the following code. Any ideas on how to speed it up? I'm aware that this is a brute force method, so a cleaner method would be best. Thanks in advance for your help! Cheers, Eli def _super_intersection(edges): group = set(edges[0]) index = np.array([0]) k = 0 while k < 100: k += 1 i = 0 for edge in edges[1:]: i += 1 edge = set(edge) if group & edge: group = group | edge index = np.append(index, i) index = np.unique(np.array(index)) return group, index def cluster(self, gmin = 5): # A 2xN array of node IDs edges = self.edges group_nodes = {} for no, edge in enumerate(edges): try: group, indice = _super_intersection(edges) id_no = no edges = np.delete(edges,indice,0) if len(group) >= gmin: group_nodes[id_no] = list(group) except: self.group_nodes = group_nodes
[ "The problem has been solved. Go to the NetworkX google group link to see the solution. \nhttp://groups.google.com/group/networkx-discuss/browse_thread/thread/4ac4250d460a1b75\nCheers,\nEli\n" ]
[ 0 ]
[]
[]
[ "graph", "intersection", "python", "union" ]
stackoverflow_0003176963_graph_intersection_python_union.txt
Q: Is all I need the "identity url"? - OpenID I'm just wondering if all I need is the identity url in order to to theoretically attach an OpenID account to a user's account. I have identity urls that look like the following: https://www.google.com/accounts/o8/id?id=YGnyuGHMUmhUI98nuhUMhu98nuN. Is this different between OpenID 1.0 and 2.0? Just in case someone asks: I'm using Django + django-openid-consumer Thanks guys =) A: All you need to bind to a user account is the "Claimed Identifier" which is what the sample URL you provided is called. OpenID 1.x and 2.0 have a handful of URLs it deals with, including "openid.identity" and "openid.claimed_id" values. It is very important that you're reading from the property that gives you openid.claimed_id rather than openid.identity when storing the value with the user account. In the case of Google as you showed, the same value is put into both parameters so it's hard to know for sure whether you're getting the right thing from the OpenID library you're using. Just review what Django offers to you, and if you see anything that looks like claimed_id, use that.
Is all I need the "identity url"? - OpenID
I'm just wondering if all I need is the identity url in order to to theoretically attach an OpenID account to a user's account. I have identity urls that look like the following: https://www.google.com/accounts/o8/id?id=YGnyuGHMUmhUI98nuhUMhu98nuN. Is this different between OpenID 1.0 and 2.0? Just in case someone asks: I'm using Django + django-openid-consumer Thanks guys =)
[ "All you need to bind to a user account is the \"Claimed Identifier\" which is what the sample URL you provided is called. OpenID 1.x and 2.0 have a handful of URLs it deals with, including \"openid.identity\" and \"openid.claimed_id\" values. It is very important that you're reading from the property that gives ...
[ 2 ]
[]
[]
[ "authentication", "django", "google_openid", "openid", "python" ]
stackoverflow_0003363781_authentication_django_google_openid_openid_python.txt
Q: Color in python? Possible Duplicate: Print in terminal with colors using python ? hello guys did i can do like C# in console? to make print 'hello' write hello with green color and print 'WOW am sexy' write it with red color? A: Previously: Print in terminal with colors using Python? http://pypi.python.org/pypi/termcolor http://docs.python.org/library/curses.html#curses.can_change_color http://en.wikipedia.org/wiki/ANSI_escape_code A: colorama
Color in python?
Possible Duplicate: Print in terminal with colors using python ? hello guys did i can do like C# in console? to make print 'hello' write hello with green color and print 'WOW am sexy' write it with red color?
[ "Previously: \n\nPrint in terminal with colors using Python?\nhttp://pypi.python.org/pypi/termcolor\nhttp://docs.python.org/library/curses.html#curses.can_change_color\nhttp://en.wikipedia.org/wiki/ANSI_escape_code\n\n", "colorama\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003363320_python.txt
Q: Best practices for doing accounting in Python I am writing a web2py application that requires summing dollar amounts without losing precision. I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with: Decimal(str(myval)) Before I go crazy adding that to all of my code, is there a better way? I'm new to Python, so it's very possible that I am overlooking something obvious. Edit: My database is MS SQL Server and I'm storing the amounts in SQL Server money fields (I believe the implementation is analogous to Decimal, ie integer math, not floating point). I am connecting to the db through the web2py framework (which uses pyodbc for SQL Server connections). I believe web2py has some support for decimal types. For example, my web2py field definitions look like: Field('Amount','decimal(19,4)') However, when I return a value from the database using web2py's .executesql method it returns the value as a float and not a Decimal. Edit: This appears to be an issue with FreeTDS and MS SQL Server. As Massimo stated in the comments, web2py supports this properly and returns a Decimal (if it can). It turns out this is only an issue in my production environment (Linux). I am using the FreeTDS driver to connect to MS SQL and it appears to be translating the MS SQL money type to a python float. I think Alex Martelli's answer is pointing in the right direction. Does anyone have any experience with FreeTDS, MS SQL, and python? I think this probably warrants its own question, so I'll move this discussion... (new question posted here: FreeTDS translating MS SQL money type to python float, not Decimal) Update: There was in fact a bug in FreeTDS. This was fixed in the CVS head of FreeTDS as of August 4, 2010. A: First, keep all numbers in decimal form in the database -- you don't mention what DB engine you're using, but every engine supports such functionality, e.g., here is MySQL's DECIMAL type documentation. I hope you're already doing that, but, if you aren't, it's still worth the pain of a schema change. Then, you need to ensure the type conversion to and from the DB matches the database's decimals with Python's. Unfortunately there is no standard way to do it across DB-API implementations, but most do offer a way; for example, with MySQLDB you need to pass a conv= parameter in connect, known as a "type converters dictionary" -- the default is a copy of MySQLdb.converters.conversions but of course you can enrich it to do the right thing with decimals. If you tell us which DB you're using, and what DB-API connector package you prefer for it, we may be able to give you more detailed help on this subject. Edit: @unutbu remarks in a comment that the current MySQLdb converter already does translate decimals correctly, so, unless you're stuck with a very old release of MySQLdb, you should be fine as long as you do correctly keep all the numbers as decimal in the DB (yay!). A: You could write a function which both gets the number from the database and then converts it to decimal. Then just use that in your code.
Best practices for doing accounting in Python
I am writing a web2py application that requires summing dollar amounts without losing precision. I realize I need to use Decimals for this, but I've found myself having to wrap every single number I get from the database with: Decimal(str(myval)) Before I go crazy adding that to all of my code, is there a better way? I'm new to Python, so it's very possible that I am overlooking something obvious. Edit: My database is MS SQL Server and I'm storing the amounts in SQL Server money fields (I believe the implementation is analogous to Decimal, ie integer math, not floating point). I am connecting to the db through the web2py framework (which uses pyodbc for SQL Server connections). I believe web2py has some support for decimal types. For example, my web2py field definitions look like: Field('Amount','decimal(19,4)') However, when I return a value from the database using web2py's .executesql method it returns the value as a float and not a Decimal. Edit: This appears to be an issue with FreeTDS and MS SQL Server. As Massimo stated in the comments, web2py supports this properly and returns a Decimal (if it can). It turns out this is only an issue in my production environment (Linux). I am using the FreeTDS driver to connect to MS SQL and it appears to be translating the MS SQL money type to a python float. I think Alex Martelli's answer is pointing in the right direction. Does anyone have any experience with FreeTDS, MS SQL, and python? I think this probably warrants its own question, so I'll move this discussion... (new question posted here: FreeTDS translating MS SQL money type to python float, not Decimal) Update: There was in fact a bug in FreeTDS. This was fixed in the CVS head of FreeTDS as of August 4, 2010.
[ "First, keep all numbers in decimal form in the database -- you don't mention what DB engine you're using, but every engine supports such functionality, e.g., here is MySQL's DECIMAL type documentation. I hope you're already doing that, but, if you aren't, it's still worth the pain of a schema change.\nThen, you n...
[ 8, 0 ]
[]
[]
[ "accounting", "currency", "decimal", "freetds", "python" ]
stackoverflow_0003364699_accounting_currency_decimal_freetds_python.txt
Q: How do I create / access dynamic form fields in Django from within a View? I have a system which keeps lots of "records" and need to integrate a component which will produce reports of any selected records. To the user, it looks like this: Click "Create Report" Select the records to be included in the report. Hit "Submit" and the report is displayed. To me I think: Load all records. Create a ReportForm which produces a "BooleanField" by iterating over all of the records from part 1 and using code like: self.fields['cid_' + str(record.id)] = BooleanField() Return the HTML, expect it back. Iterate over all of the fields beginning with 'cid_' and create a list of record ids to be included in the report. Pass the numbers to the report generator. But from within the view I cannot access the form data the only way I can imagine doing it. Since I don't know which Record IDs will be available (since some may have been deleted, etc) I need to access it like this: {{form.fields['cid_'+str(record.id)']}} But apparently this is illegal. Does anybody have some suggestions? A: If I understand your question correctly, your answer lies in using the proper Django form widgets. I will give you an example. Let's say you have a Django model: - class Record(models.Model): name = models.CharField() Let's say you create a custom Form for your needs: - class MyCustomForm(forms.Form): records= forms.ModelMultipleChoiceField(queryset=Record.objects.all, widget=forms.CheckboxSelectMultiple) Let's say you have the following view: - def myview(request): if request.method == 'POST': form = MyCustomForm(data=request.POST) if form.is_valid(): #do what you want with your data print form.cleaned_data['records'] #do what you want with your data else: form = MyCustomForm() return render_to_response('mytemplate.html', {'form': form}, context_instance=RequestContext(request)) Your mytemplate.html might look like this: - <div> {{ form.records.label_tag }} {{ form.records }} </div>
How do I create / access dynamic form fields in Django from within a View?
I have a system which keeps lots of "records" and need to integrate a component which will produce reports of any selected records. To the user, it looks like this: Click "Create Report" Select the records to be included in the report. Hit "Submit" and the report is displayed. To me I think: Load all records. Create a ReportForm which produces a "BooleanField" by iterating over all of the records from part 1 and using code like: self.fields['cid_' + str(record.id)] = BooleanField() Return the HTML, expect it back. Iterate over all of the fields beginning with 'cid_' and create a list of record ids to be included in the report. Pass the numbers to the report generator. But from within the view I cannot access the form data the only way I can imagine doing it. Since I don't know which Record IDs will be available (since some may have been deleted, etc) I need to access it like this: {{form.fields['cid_'+str(record.id)']}} But apparently this is illegal. Does anybody have some suggestions?
[ "If I understand your question correctly, your answer lies in using the proper Django form widgets. I will give you an example. Let's say you have a Django model: - \nclass Record(models.Model):\n name = models.CharField()\n\nLet's say you create a custom Form for your needs: - \nclass MyCustomForm(forms.Form):\...
[ 1 ]
[]
[]
[ "django", "dynamic", "forms", "python", "views" ]
stackoverflow_0003358935_django_dynamic_forms_python_views.txt
Q: python: if row[1].upper().find(brand)!=-1: are these two statements equivalent? if row[1].upper().find(brand)!=-1: and if row[1].upper().find(brand): A: No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -1, and false if the expression evaluates to 0 (when it should be true). Use the first statement. A: As others have said, no those statements are not equivalent. However, when you only need to find if the substring exists and not where, I prefer the in operator rather than .find(), e.g.: if brand in row[1].upper(): This is equivalent to the first statement, but more concise and easy to read. A: No. The first one will evaluate to false only if find() returns -1. The second one will evaluate to false only if find() returns 0. This even would give you wrong results as 0 means that the substring was found at the beginning of the string. So this statement would evaluate to false if the substring is at the beginning and true if it was not found. A: To explain what the find() method does: >>> "hello".find("l") 2 >>> "hello".find("he") 0 >>> "hello".find("x") -1 -1 is a "magic value" for "search string not found". Contrast this with index(): >>> "hello".index("l") 2 >>> "hello".index("he") 0 >>> "hello".index("x") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found Personally, I prefer index() because usually, magic values are frowned upon in Python whereas exception handling is the Pythonic way to do it - "EAFP" (it's easier to ask forgiveness than permission). In your case it looks like the "LBYL" programming style (look before you leap), although you're not showing much context so I don't know what the if statement is deciding. A: No, of course not. The first one checks if the result is -1 and the other one checks if the result is anything which Python regards as "false". -1 is not regarded as false by Python. A: The top answer is correct. But I find it easier to read in than to use numeric results. I.e., >>> row [[1, 'lysol']] >>> brand 'Lysol' >>> brand.upper() in row[0][1].upper() True >>> Although, once the "Schlysol" brand shows up, all bets are off. Hm.
python: if row[1].upper().find(brand)!=-1:
are these two statements equivalent? if row[1].upper().find(brand)!=-1: and if row[1].upper().find(brand):
[ "No, they aren't equal. In Python, any nonzero number is treated as being True, so the second statement will be considered true if the expression evaluates to -1, and false if the expression evaluates to 0 (when it should be true).\nUse the first statement.\n", "As others have said, no those statements are not eq...
[ 8, 5, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003364106_python.txt
Q: images API / Error I'm working on a project and I used the the Images Python API . For instance in the example given in http://code.google.com/appengine/docs/python/images/usingimages.html I get an error when ever I do not upload a photo, How can I modify the code so I don't get an error when I don't post anything. thanks A: Try changing the line avatar = images.resize(self.request.get("img"), 32, 32) to check if self.request.get("img") is empty: posted_avatar = self.request.get("img") if posted_avatar: avatar = images.resize(posted_avatar, 32, 32) greeting.avatar = db.Blob(avatar) greeting.put() A: You can simply check if that input element of the form was populated. From the example code: <div><input type="file" name="img" /></div> You'd then add a conditional (if statement) to your handler: if self.request.get("img"): # do image processing stuff here Here's a simple bit of code that does what you want: http://bitbucket.org/abernier/pocasi/src/tip/handlers/admin.py#cl-102 Template code here: http://bitbucket.org/abernier/pocasi/src/tip/templates/create.html
images API / Error
I'm working on a project and I used the the Images Python API . For instance in the example given in http://code.google.com/appengine/docs/python/images/usingimages.html I get an error when ever I do not upload a photo, How can I modify the code so I don't get an error when I don't post anything. thanks
[ "Try changing the line\navatar = images.resize(self.request.get(\"img\"), 32, 32)\n\nto check if self.request.get(\"img\") is empty:\nposted_avatar = self.request.get(\"img\")\nif posted_avatar:\n avatar = images.resize(posted_avatar, 32, 32)\n greeting.avatar = db.Blob(avatar)\n\ngreeting.put()\n\n", "You can ...
[ 2, 1 ]
[]
[]
[ "api", "google_app_engine", "image", "python" ]
stackoverflow_0003365430_api_google_app_engine_image_python.txt
Q: twisted web getPage, 2 clients in 2 classes, manage events between the two i'm trying to create a bridge program in twisted.web that receives data from a web server and sends it to another server, thus i'm using 2 getPage applications that i have wrapped in a class for convenience, the class contains all the callbacks and the client "routine".. 1)auth 2)receive data 3)send data, all this is done in a cyclic way and works perfectly in both clients!! What i am planning to do now is to integrate the two, this would mean that i would have to make some callbacks outside the classes in order to process them. client1<--->main<--->client2 How can i do this? i'm using twisted getPage i'll post one of the two classes class ChatService(): def __init__(self): self.myServID= self.generatemyServID() self.myServServer= "http://localhost" ## This is where the magic starts reactor.callWhenRunning(self.mainmyServ) reactor.run() def generatemyServID(self): a= "" for x in range(60): c= floor(random() * 61) a += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"[int(c):int(c)+1] return a def sentMessage(self, data): print "Message was sent successfully" def sendMessage(self, mess): s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=chat&user=%s&message=%s" % (self.myServID, mess)),]) s1.addCallback(self.sentMessage) s1.addErrback(self.errMessage) def recivedMessage(self,data): chat= loads(data[0][1]) if chat['from'] != "JOINED" and chat['from'] != "TYPING" and chat['from'] != "Ben": print "%s says: %s" % (chat['from'], decode(chat['chat'])) self.sendMessage("Hello") # Restart Loop self.loopChat() def errMessage(self,e): # print "An error occured receiving/sending the messages\n%s" % e print "Still no connectiions, waiting..." self.loopChat() def loopChat(self): s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=poll&user=%s&message=null" % self.myServID),]) s1.addCallback(self.recivedMessage) s1.addErrback(self.errMessage) def error(self,e): print "An error occured\n%s" % e def connectedtomyServService(self,data): if data[0][0] == False: print "Connection to myServ Service was impossible" reactor.stop() return if loads(data[0][1])['action'] == 'join': print "Connected to the server and joined chat" print "Started chat loop" self.loopChat() else: print "An Error Occured" return def mainmyServ(self): # print "Client ID is: " + self.myServID # Joining Chat s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=join&user=%s&message=null" % self.myServID),]) s1.addCallback(self.connectedtomyServService) s1.addErrback(self.error) How can I make callbacks outside the class? I hope I managed to express myself =D Thnaks a lot A: How can I make callbacks outside the class? This sounds like a very common misunderstanding. As a result of the misunderstanding, the question, as asked, doesn't make a lot of sense. So let's forget about the question. You already have some code that's using Deferreds. Let's start with mainmyServ: def mainmyServ(self): # print "Client ID is: " + self.myServID # Joining Chat s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=join&user=%s&message=null" % self.myServID),]) s1.addCallback(self.connectedtomyServService) s1.addErrback(self.error) First, you can get rid of the DeferredList. Your list only has one Deferred in it, so the DeferredList isn't adding any value. You'll get practically the same behavior like this, and your callbacks can be simplified by removing all of the [0][0] expressions. def mainmyServ(self): # print "Client ID is: " + self.myServID # Joining Chat s1= client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=join&user=%s&message=null" % self.myServID) s1.addCallback(self.connectedtomyServService) s1.addErrback(self.error) So this is a perfectly reasonable method which is calling a function that returns a Deferred and then adding a callback and an errback to that Deferred. Say you have another function, perhaps your overall main function: def main(): service = ChatService() service.mainmyServ() What prevents the main function from adding more callbacks to the Deferred in mainmyServ? Only that mainmyServ doesn't bother to return it. So: def mainmyServ(self): # print "Client ID is: " + self.myServID # Joining Chat s1= client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=join&user=%s&message=null" % self.myServID) s1.addCallback(self.connectedtomyServService) s1.addErrback(self.error) return s1 def main(): service = ChatService() d = service.mainmyServ() d.addCallback(doSomethingElse) Nothing special there, it's just another addCallback. All you were missing was a reference to the Deferred. You can set up your loop now, by having doSomethingElse call another method on ChatService. If that other method returns a Deferred, then doSomethingElse can add a callback to it that calls mainmyServ again. And so on. There's your loop, controlled "outside" of the class.
twisted web getPage, 2 clients in 2 classes, manage events between the two
i'm trying to create a bridge program in twisted.web that receives data from a web server and sends it to another server, thus i'm using 2 getPage applications that i have wrapped in a class for convenience, the class contains all the callbacks and the client "routine".. 1)auth 2)receive data 3)send data, all this is done in a cyclic way and works perfectly in both clients!! What i am planning to do now is to integrate the two, this would mean that i would have to make some callbacks outside the classes in order to process them. client1<--->main<--->client2 How can i do this? i'm using twisted getPage i'll post one of the two classes class ChatService(): def __init__(self): self.myServID= self.generatemyServID() self.myServServer= "http://localhost" ## This is where the magic starts reactor.callWhenRunning(self.mainmyServ) reactor.run() def generatemyServID(self): a= "" for x in range(60): c= floor(random() * 61) a += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"[int(c):int(c)+1] return a def sentMessage(self, data): print "Message was sent successfully" def sendMessage(self, mess): s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=chat&user=%s&message=%s" % (self.myServID, mess)),]) s1.addCallback(self.sentMessage) s1.addErrback(self.errMessage) def recivedMessage(self,data): chat= loads(data[0][1]) if chat['from'] != "JOINED" and chat['from'] != "TYPING" and chat['from'] != "Ben": print "%s says: %s" % (chat['from'], decode(chat['chat'])) self.sendMessage("Hello") # Restart Loop self.loopChat() def errMessage(self,e): # print "An error occured receiving/sending the messages\n%s" % e print "Still no connectiions, waiting..." self.loopChat() def loopChat(self): s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=poll&user=%s&message=null" % self.myServID),]) s1.addCallback(self.recivedMessage) s1.addErrback(self.errMessage) def error(self,e): print "An error occured\n%s" % e def connectedtomyServService(self,data): if data[0][0] == False: print "Connection to myServ Service was impossible" reactor.stop() return if loads(data[0][1])['action'] == 'join': print "Connected to the server and joined chat" print "Started chat loop" self.loopChat() else: print "An Error Occured" return def mainmyServ(self): # print "Client ID is: " + self.myServID # Joining Chat s1= DeferredList([client.getPage(self.myServServer+"/chat/", headers={'Content-Type': 'application/x-www-form-urlencoded'}, method="POST", postdata="action=join&user=%s&message=null" % self.myServID),]) s1.addCallback(self.connectedtomyServService) s1.addErrback(self.error) How can I make callbacks outside the class? I hope I managed to express myself =D Thnaks a lot
[ "\nHow can I make callbacks outside the class?\n\nThis sounds like a very common misunderstanding. As a result of the misunderstanding, the question, as asked, doesn't make a lot of sense. So let's forget about the question.\nYou already have some code that's using Deferreds. Let's start with mainmyServ:\ndef ma...
[ 2 ]
[]
[]
[ "client", "http", "python", "twisted", "twisted.web" ]
stackoverflow_0003360819_client_http_python_twisted_twisted.web.txt
Q: Doing an XSL transform of a branch of a Docbook element tree I'd like to use the docbook XSL stylesheets to render various parts of a document, without transforming the entire thing. The complication is that some of these parts have <footnoteref> elements whose linkend attributes are not located within the same chunk. In other words, I want to process a branch of the tree which includes the <footnoteref>s but not the <footnote> elements they reference. My attempts to do this using the Python lxml package have yielded this error message: XSLTApplyError Traceback (most recent call last) /var/www/mpd/<ipython console> in <module>() /var/www/mpd/<ipython console> in <genexpr>((elt,)) /usr/lib/python2.6/dist-packages/lxml/etree.so in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:109204)() XSLTApplyError: Internal error in xsltKeyFunction(): Could not get the document info of a context doc. This happens in response to, e.g. etree.XSLT(etree.parse('docbook.xsl'))(some_element). I'm using the normal xhtml stylesheets. I wouldn't expect it to matter which stylesheet I'm using, though. Is there a supported way to do this? Or am I expected to, for example, apply an XSLT transform on the document to change the <footnoteref> element to a <footnote> element before doing this render? But then that wouldn't work, because then there would be multiple <footnote> tags with the same ID. It would have to only do that <footnoteref> to <footnote> transformation if the <footnote> tag was not being included in the resulting tree. Which I would expect to be happening already. But hopefully I just missed a switch somewhere. edit Thanks to @Jukka's answer, I've figured out that I can pass the rootid parameter to tell the XSLT processor to just render that ID. However, it does so all too faithfully, producing output that just references the footnote with the same fragment that would be useful if the document were being rendered as a single HTML page. EG >>> xsl_url_html = 'http://docbook.sourceforge.net/release/xsl/current/html/docbook.xsl' >>> from lxml import etree >>> consume_result = etree.XSLT(etree.parse(xsl_url_xhtml))( etree.parse(my_xml_file), rootid=etree.XSLT.strparam("command_consume")) >>> etree.tostring(consume_result).split('\n') ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=ASCII" /><title></title><meta name="generator" content="DocBook XSL Stylesheets V1.75.2" /></head><body><dt><a id="command_consume"></a><span class="term">', ' <div class="cmdsynopsis"><p><code class="command">consume</code> {<em class="replaceable"><code>STATE</code></em>}</p></div>', ' </span></dt><dd><p>', ' <sup>[<a href="#ftn.since_0_15" class="footnoteref">2</a>]</sup>', ' Sets consume state to <code class="varname">STATE</code>,', ' <code class="varname">STATE</code> should be 0 or 1.', '\t When consume is activated, each song played is removed from playlist.', ' </p></dd></body></html>'] Maybe there is another parameter that will cause the footnotes to be displayed on the same page, preferably numbered from 1? I guess it would probably be in this list somewhere. I'll go through it when I get some more time. A: Instead of trying to apply the DocBook XSL stylesheet to a single element, you could apply it to the full document, but specify the part of the document you want to transform with the rootid parameter. From the reference documentation: The entire document will be loaded and parsed, but formatting will begin at the element identified, rather than at the root. For example, this allows you to process only chapter 4 of a book. Because the entire document is available to the processor, automatic numbering, cross references, and other dependencies are correctly resolved.
Doing an XSL transform of a branch of a Docbook element tree
I'd like to use the docbook XSL stylesheets to render various parts of a document, without transforming the entire thing. The complication is that some of these parts have <footnoteref> elements whose linkend attributes are not located within the same chunk. In other words, I want to process a branch of the tree which includes the <footnoteref>s but not the <footnote> elements they reference. My attempts to do this using the Python lxml package have yielded this error message: XSLTApplyError Traceback (most recent call last) /var/www/mpd/<ipython console> in <module>() /var/www/mpd/<ipython console> in <genexpr>((elt,)) /usr/lib/python2.6/dist-packages/lxml/etree.so in lxml.etree.XSLT.__call__ (src/lxml/lxml.etree.c:109204)() XSLTApplyError: Internal error in xsltKeyFunction(): Could not get the document info of a context doc. This happens in response to, e.g. etree.XSLT(etree.parse('docbook.xsl'))(some_element). I'm using the normal xhtml stylesheets. I wouldn't expect it to matter which stylesheet I'm using, though. Is there a supported way to do this? Or am I expected to, for example, apply an XSLT transform on the document to change the <footnoteref> element to a <footnote> element before doing this render? But then that wouldn't work, because then there would be multiple <footnote> tags with the same ID. It would have to only do that <footnoteref> to <footnote> transformation if the <footnote> tag was not being included in the resulting tree. Which I would expect to be happening already. But hopefully I just missed a switch somewhere. edit Thanks to @Jukka's answer, I've figured out that I can pass the rootid parameter to tell the XSLT processor to just render that ID. However, it does so all too faithfully, producing output that just references the footnote with the same fragment that would be useful if the document were being rendered as a single HTML page. EG >>> xsl_url_html = 'http://docbook.sourceforge.net/release/xsl/current/html/docbook.xsl' >>> from lxml import etree >>> consume_result = etree.XSLT(etree.parse(xsl_url_xhtml))( etree.parse(my_xml_file), rootid=etree.XSLT.strparam("command_consume")) >>> etree.tostring(consume_result).split('\n') ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=ASCII" /><title></title><meta name="generator" content="DocBook XSL Stylesheets V1.75.2" /></head><body><dt><a id="command_consume"></a><span class="term">', ' <div class="cmdsynopsis"><p><code class="command">consume</code> {<em class="replaceable"><code>STATE</code></em>}</p></div>', ' </span></dt><dd><p>', ' <sup>[<a href="#ftn.since_0_15" class="footnoteref">2</a>]</sup>', ' Sets consume state to <code class="varname">STATE</code>,', ' <code class="varname">STATE</code> should be 0 or 1.', '\t When consume is activated, each song played is removed from playlist.', ' </p></dd></body></html>'] Maybe there is another parameter that will cause the footnotes to be displayed on the same page, preferably numbered from 1? I guess it would probably be in this list somewhere. I'll go through it when I get some more time.
[ "Instead of trying to apply the DocBook XSL stylesheet to a single element, you could apply it to the full document, but specify the part of the document you want to transform with the rootid parameter. \nFrom the reference documentation:\n\nThe entire document will be loaded and\n parsed, but formatting will begi...
[ 0 ]
[]
[]
[ "docbook", "lxml", "python", "xslt" ]
stackoverflow_0003359335_docbook_lxml_python_xslt.txt
Q: What's wrong with my Python installation? I downloaded and installed Python 3.1.2 on Windows 7 x64. But it seems that it's not working as expected. What's wrong here? A: Try this: >>> print "Today's stock price: %f" % 50.4625 File "<stdin>", line 1 print "Today's stock price: %f" % 50.4625 ^ SyntaxError: invalid syntax >>> print("Today's stock price: %f" % 50.4625) Today's stock price: 50.462500 Python 3.X changed how print works, and now requires parentheses around the arguments. A: Python 3.X is not backward-compatible with Python 2.X. Make sure you are reading a 3.X tutorial, or remove 3.X and install 2.X. Here's some reading about why there are differences and to decide which to use: http://wiki.python.org/moin/Python2orPython3. A: In Python 3.x, print is now function and needs (). A: As stated above python 3.x now requires all statements such as those to be function calls, Python 3.x is supposed to bring back the functional aspect of C to python although code that works in 3.x will most likely work in 2.x but not necessarily the other way around.
What's wrong with my Python installation?
I downloaded and installed Python 3.1.2 on Windows 7 x64. But it seems that it's not working as expected. What's wrong here?
[ "Try this:\n>>> print \"Today's stock price: %f\" % 50.4625\n File \"<stdin>\", line 1\n print \"Today's stock price: %f\" % 50.4625\n ^\nSyntaxError: invalid syntax\n>>> print(\"Today's stock price: %f\" % 50.4625)\nToday's stock price: 50.462500\n\nPython 3.X changed how print...
[ 8, 4, 1, 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0003340775_installation_python.txt
Q: How to throw an error window in Python in Windows What's the easiest way to generate an error window for a Python script in Windows? Windows-specific answers are fine; please don't reply how to generate a custom Tk window. A: @Constantin is almost correct, but his example will produce garbage text. Make sure that the text is unicode. I.e., ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0) ...and it'll work fine. A: If you need a GUI error message, you could use EasyGui: >>> import easygui as e >>> e.msgbox("An error has occured! :(", "Error") Otherwise a simple print("Error!") should suffice. A: You can get a one-liner using tkinter. import tkMessageBox tkMessageBox.showerror('error title', 'error message') Here is some documentation for pop-up dialogs. A: If i recall correctly (don't have Windows box at the moment), the ctypes way is: import ctypes ctypes.windll.user32.MessageBoxW(None, u"Error", u"Error", 0) ctypes is a standard module. Note: For Python 3.x you don't need the u prefix. A: Check out the GUI section of the Python Wiki for info on message boxs
How to throw an error window in Python in Windows
What's the easiest way to generate an error window for a Python script in Windows? Windows-specific answers are fine; please don't reply how to generate a custom Tk window.
[ "@Constantin is almost correct, but his example will produce garbage text. Make sure that the text is unicode. I.e., \nctypes.windll.user32.MessageBoxW(0, u\"Error\", u\"Error\", 0)\n\n...and it'll work fine.\n", "If you need a GUI error message, you could use EasyGui:\n>>> import easygui as e\n>>> e.msgbox(\"A...
[ 12, 3, 2, 1, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003365673_python_windows.txt
Q: Custom user authentication. How is it done, with the best practices? I'm using Google Engine App with Python. I want to add custom user authentication. How is it done, with the best practices? I want custom authentication because the app is built in Flex and I don't want to redirect to an HTML page. The user value object is like this: class User(db.Model): email = db.EmailProperty(required = True, indexed = True) masked_password = db.StringProperty(required = True) # maybe more things here I would like to mask the password, is there some built in function in GAE? Then, how I will remember the current user? Through sessions and cookies? Or what else? A: Passwords: The best way to handle the password is store a random salt value for each user and the result of a hash of the password + salt. When the user wants to login, compute hash(password + salt) and see it if is the same as the hash value you stored when the password was originally set. The idea is never to store the password in cleartext and that two users with the same password won't have the same hashed value. You can find many examples of this online and on SO. Sessions: There are many ways to implement sessions and using cookies is popular. I suggest you use one of the libraries already available for this purpose. See this comparison of libraries. A: Don't implement your own authentication. Mark the opening page as authentication required (ie "login: required" in the app.yaml) and then when they hit the front opening page they'll be be asked to authenticate before they even see your Flash/Flex app, or if they're already authenticated then they'll go straight into your app. This avoids your Flash -> HTML -> Flash issue and lets you leverage the in-built proper authentication (my app keeps a table of user settings and permissions in the datastore but simply uses the GAE authenticated current user identity as a key)
Custom user authentication. How is it done, with the best practices?
I'm using Google Engine App with Python. I want to add custom user authentication. How is it done, with the best practices? I want custom authentication because the app is built in Flex and I don't want to redirect to an HTML page. The user value object is like this: class User(db.Model): email = db.EmailProperty(required = True, indexed = True) masked_password = db.StringProperty(required = True) # maybe more things here I would like to mask the password, is there some built in function in GAE? Then, how I will remember the current user? Through sessions and cookies? Or what else?
[ "Passwords:\nThe best way to handle the password is store a random salt value for each user and the result of a hash of the password + salt. \nWhen the user wants to login, compute hash(password + salt) and see it if is the same as the hash value you stored when the password was originally set. The idea is never ...
[ 3, 1 ]
[]
[]
[ "apache_flex", "authentication", "google_app_engine", "python" ]
stackoverflow_0003346265_apache_flex_authentication_google_app_engine_python.txt
Q: Add elements in a list of dictionaries I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to that key in each of the dictionaries. (For example, the value for the key 'apple' in the combined dictionary will be the sum of the value of 'apple' in the first, plus the sum of the value of 'apple' in the second, etc.) I have the following, but it's rather cumbersome and takes ages to execute. Is there a simpler way to achieve the same result? comb_dict = {} for dictionary in list_dictionaries: for key in dictionary: comb_dict.setdefault(key, 0) comb_dict[key] += dictionary[key] return comb_dict A: Here are some microbenchmarks which suggest f2 (see below) might be an improvement. f2 uses iteritems which allows you avoid an extra dict lookup in the inner loop: import collections import string import random def random_dict(): n=random.randint(1,26) keys=list(string.letters) random.shuffle(keys) keys=keys[:n] values=[random.randint(1,100) for _ in range(n)] return dict(zip(keys,values)) list_dictionaries=[random_dict() for x in xrange(100)] def f1(list_dictionaries): comb_dict = {} for dictionary in list_dictionaries: for key in dictionary: comb_dict.setdefault(key, 0) comb_dict[key] += dictionary[key] return comb_dict def f2(list_dictionaries): comb_dict = collections.defaultdict(int) for dictionary in list_dictionaries: for key,value in dictionary.iteritems(): comb_dict[key] += value return comb_dict def union( dict_list ): all_keys = set() for d in dict_list: for k in d: all_keys.add( k ) for key in all_keys: yield key, sum( d.get(key,0) for d in dict_list) def f3(list_dictionaries): return dict(union( list_dictionaries )) Here are the results: % python -mtimeit -s"import test" "test.f1(test.list_dictionaries)" 1000 loops, best of 3: 776 usec per loop % python -mtimeit -s"import test" "test.f2(test.list_dictionaries)" 1000 loops, best of 3: 432 usec per loop % python -mtimeit -s"import test" "test.f3(test.list_dictionaries)" 100 loops, best of 3: 2.19 msec per loop A: Use collections.defaultdict instead. http://docs.python.org/library/collections.html#defaultdict-objects Slightly simpler. A: This could be fast too, but it really depends on your data. It avoids all the changing dicts or extra lists - just one set of all keys and lots of reads :-) from itertools import chain def union( dict_list ): all_keys = set(chain.from_iterable(dict_list)) for key in all_keys: yield key, sum( d.get(key,0) for d in dict_list) combined = dict(union( dict_list )) A: You could take some inspiration from google's map-reduce. From what I understand it was designed to solve just this type of problem.
Add elements in a list of dictionaries
I have a very long list of dictionaries with string indices and integer values. Many of the keys are the same across the dictionaries, though not all. I want to generate one dictionary in which the keys are the union of the keys in the separate dictionaries and the values are the sum of all the values corresponding to that key in each of the dictionaries. (For example, the value for the key 'apple' in the combined dictionary will be the sum of the value of 'apple' in the first, plus the sum of the value of 'apple' in the second, etc.) I have the following, but it's rather cumbersome and takes ages to execute. Is there a simpler way to achieve the same result? comb_dict = {} for dictionary in list_dictionaries: for key in dictionary: comb_dict.setdefault(key, 0) comb_dict[key] += dictionary[key] return comb_dict
[ "Here are some microbenchmarks which suggest f2 (see below) might be an improvement. f2 uses iteritems which allows you avoid an extra dict lookup in the inner loop:\nimport collections\nimport string\nimport random\n\ndef random_dict():\n n=random.randint(1,26)\n keys=list(string.letters)\n random.shuffle...
[ 9, 1, 1, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0003366170_dictionary_nested_python.txt
Q: Eclipse and PyDev I want to start using Eclipse with the PyDev plugin, as recommended by this poster. The PyDev download page says I need Eclipse (3.2 to 3.5) and that I can use the Platform Runtime Binary. Can I also use Eclipse 3.5.2 (or maybe even 3.6) instead of 3.5? Where can I find the Platform Runtime Binary? I'm a little bit lost in the Eclipse download pages. A: Yes I use eclipse 3.5.2 with pydev plugin and it works great. Install the pydev plugin by opening up Help / Install New Software and putting in "Pydev - http://pydev.org/updates" into the Work with field. Then follow on the installation procedure. After pydev is installed make sure that you put the python interpreter into the window / preferences /pydev / Interpreter - python page A: PyDev works great with Eclipse 3.6. I'd download the Java Edition, which is pretty minimal (as far as Eclipse can be minimal). Then you can use the brand new built-in marketplace to install PyDev. No need to look up the update-URL. You find the marketplace under "Help > Eclipse Marketplace..." (why they put the market place in the help menu is beyond me...). Note that if you download the Eclipse Classic edition, you won't get the marketplace. A: Can I also use Eclipse 3.5.2 (or maybe even 3.6) instead of 3.5? Try and find out. :) Yes. Where can I find the Platform Runtime Binary? I'm a little bit lost in the Eclipse download pages. You won't need it.
Eclipse and PyDev
I want to start using Eclipse with the PyDev plugin, as recommended by this poster. The PyDev download page says I need Eclipse (3.2 to 3.5) and that I can use the Platform Runtime Binary. Can I also use Eclipse 3.5.2 (or maybe even 3.6) instead of 3.5? Where can I find the Platform Runtime Binary? I'm a little bit lost in the Eclipse download pages.
[ "Yes I use eclipse 3.5.2 with pydev plugin and it works great. Install the pydev plugin by opening up Help / Install New Software and putting in \"Pydev - http://pydev.org/updates\" into the Work with field. Then follow on the installation procedure. After pydev is installed make sure that you put the python interp...
[ 1, 1, 0 ]
[]
[]
[ "eclipse", "installation", "pydev", "python", "versions" ]
stackoverflow_0003361468_eclipse_installation_pydev_python_versions.txt
Q: Unbuffered stdout in python (as in python -u) from within the program Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on Linux (Ubuntu 8.10 Server). A: The best I could come up with: >>> import os >>> import sys >>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0) >>> unbuffered.write('test') test>>> >>> sys.stdout = unbuffered >>> print 'test' test Tested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it would be much easier: sys.stdout = open('???', 'w', 0) References: http://docs.python.org/library/stdtypes.html#file-objects http://docs.python.org/library/functions.html#open http://docs.python.org/library/os.html#file-object-creation [Edit] Note that it would be probably better to close sys.stdout before overwriting it. A: You could always pass the -u parameter in the shebang line: #!/usr/bin/python -u A: Assuming you're on Windows: msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) ... and on Unix: fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL) fl |= os.O_SYNC fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl) (Unix copied in from commented solution, rather than linking.) A: EDIT (Oct 2020). As pointed out in a note to this answer, in Python3, stderr is buffered too. You might use the fact that stderr is never buffered and try to redirect stdout to stderr: import sys #buffered output is here doStuff() oldStdout = sys.stdout sys.stdout = sys.stderr #unbuffered output from here on doMoreStuff() sys.stdout = oldStdout #the output is buffered again doEvenMoreStuff()
Unbuffered stdout in python (as in python -u) from within the program
Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on Linux (Ubuntu 8.10 Server).
[ "The best I could come up with:\n>>> import os\n>>> import sys\n>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)\n>>> unbuffered.write('test')\ntest>>> \n>>> sys.stdout = unbuffered\n>>> print 'test'\ntest\n\nTested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it ...
[ 52, 37, 9, 8 ]
[]
[]
[ "python" ]
stackoverflow_0000881696_python.txt
Q: Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile? I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap. I need a library that let me add circles or circular arc to it. The library could be in for Python or in Java. A: If you look at OpenMap, it may be possible to write some code using that set of libraries in Java to do what you are asking. I don't know if its possible from a single call, but there is definitely code in OpenMap to generate circles and arcs and it also has code to read in a shapefile. The jump to exporting a shape file shouldn't be too big. A: Matt Perry has a short and sweet example of creating circles in a shapefile in Tissot Indicatrix - Examining the distortion of map projections. Not listed in the post is how to install the prerequiste gdal/ogr; for that see OSGeo4W on windows or a simple apt-get install gdal python-gdal on ubuntu linux.
Which open-source Python or Java library provides an easy way to draw circles on a ESRI Shapefile?
I need to write a software that creates an shapefile with various circles or circumferences on it. The shapefile created should be readable by ESRI ArcMap. I need a library that let me add circles or circular arc to it. The library could be in for Python or in Java.
[ "If you look at OpenMap, it may be possible to write some code using that set of libraries in Java to do what you are asking.\nI don't know if its possible from a single call, but there is definitely code in OpenMap to generate circles and arcs and it also has code to read in a shapefile. The jump to exporting a s...
[ 1, 0 ]
[]
[]
[ "arcgis", "esri", "java", "python", "shapefile" ]
stackoverflow_0000853311_arcgis_esri_java_python_shapefile.txt
Q: escape characters in psycopg2 how do i escape special characters for to_tsquery in psycopg2 python? A: I suggest you build your own parser.
escape characters in psycopg2
how do i escape special characters for to_tsquery in psycopg2 python?
[ "I suggest you build your own parser.\n" ]
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0003364815_postgresql_psycopg2_python.txt
Q: arranging for python's sorted(set( )) I'm trying to eliminate duplicates of an array containing a few thousands of custom objects. For this I'm implementing the __hash__ and __cmp__ functions for these objects. Is it safe to delegate these functions to one of the objects' fields (a guaranteed unique string) ? I.e. class A: def __init__(self, key, etc...): self.key = key ... def __hash__(self): return self.key.__hash__() def __cmp__(self, other): return cmp(self.key, other.key) # then somewhere in code with arr being array of A unique = sorted(set(arr)) Any hint greatly appreciated! A: Yes. The only requirement of __hash__ is that it be unique. In fact, this is quite an elegant and Pythonic way of solving the problem! EDIT: It has been pointed out to me that __hash__ need not even be unique! Instead, one simply requires equal objects to have the same hash. Unequal ones may also have the same hash; in fact, everything could hash to 0 and this would be (technically) fine. A: Eschew __cmp__. Python3 no longer supports this special method, and recommends using __lt__ instead. def __lt__(self,other): return self.key < self.other A: Two unequal objects may have the same hash value, but two equal objects may not have different hash values. The law: a == b --> hash(a) == hash(b) describes this. Otherwise you couldn't use them as dict keys or put them is sets. Well, maybe you could add them, but you couldn't retrieve them later. So, when delegating __hash__(), I always define __eq__() as well, just to be on the safe side: def __hash__(self): return hash(self.key) def __eq__(self, other): return self.key == other.key Since you want to sort your objects, you must also add unutbus __lt__().
arranging for python's sorted(set( ))
I'm trying to eliminate duplicates of an array containing a few thousands of custom objects. For this I'm implementing the __hash__ and __cmp__ functions for these objects. Is it safe to delegate these functions to one of the objects' fields (a guaranteed unique string) ? I.e. class A: def __init__(self, key, etc...): self.key = key ... def __hash__(self): return self.key.__hash__() def __cmp__(self, other): return cmp(self.key, other.key) # then somewhere in code with arr being array of A unique = sorted(set(arr)) Any hint greatly appreciated!
[ "Yes. The only requirement of __hash__ is that it be unique. In fact, this is quite an elegant and Pythonic way of solving the problem!\nEDIT: It has been pointed out to me that __hash__ need not even be unique! Instead, one simply requires equal objects to have the same hash. Unequal ones may also have the same ha...
[ 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003366435_python.txt
Q: Django Pagination on a Changing Queryset On one of my pages I would like to display a subset of a sorted list of objects. The entire list of relevant objects is extremely long and has a good chance of changing while the user is viewing the page. I don't mind that the page is not up to date, but I do need to ensure that when the user goes to the next page, the user will see the next n objects from the original sorted list. Thus, due to potentially changed data, using django's built in pagination or a really nice library like Django-endless-pagination will not return the correct results when going to the "next page". To give an example of what I mean, say we have objects [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] and want to display 5 per page, sorted from small to big. The first page would look like: 1, 2, 3, 4, 5. But while viewing this page, 3 and 4 were deleted. If we go to the "next" page, pagination will re-query the set and return: 8, 9, 10, 11, 12 I realize this is pagination's expected behavior, but I would like an easy way to make the next page display: 6, 7, 8, 9, 10 The most obvious solution is to do some client side pagination, and I realize there is a nice jquery library for this, but the number of objects can be potentially way too big for this solution to be realistic. Is there a simple approach to paginate on a queryset and continue to use the results returned from that original queryset instead of re-fetching the queryset that may have changed? Thanks for any insight you can give me! A: What might be a possibly solution is if you create your own pagination function that instead of the next link referring to a certain page it could pass a record that is the top record on the next page The problem is that this would only work if the items being added/changed are only the first items in a list
Django Pagination on a Changing Queryset
On one of my pages I would like to display a subset of a sorted list of objects. The entire list of relevant objects is extremely long and has a good chance of changing while the user is viewing the page. I don't mind that the page is not up to date, but I do need to ensure that when the user goes to the next page, the user will see the next n objects from the original sorted list. Thus, due to potentially changed data, using django's built in pagination or a really nice library like Django-endless-pagination will not return the correct results when going to the "next page". To give an example of what I mean, say we have objects [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] and want to display 5 per page, sorted from small to big. The first page would look like: 1, 2, 3, 4, 5. But while viewing this page, 3 and 4 were deleted. If we go to the "next" page, pagination will re-query the set and return: 8, 9, 10, 11, 12 I realize this is pagination's expected behavior, but I would like an easy way to make the next page display: 6, 7, 8, 9, 10 The most obvious solution is to do some client side pagination, and I realize there is a nice jquery library for this, but the number of objects can be potentially way too big for this solution to be realistic. Is there a simple approach to paginate on a queryset and continue to use the results returned from that original queryset instead of re-fetching the queryset that may have changed? Thanks for any insight you can give me!
[ "What might be a possibly solution is if you create your own pagination function that instead of the next link referring to a certain page it could pass a record that is the top record on the next page\nThe problem is that this would only work if the items being added/changed are only the first items in a list\n" ]
[ 3 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0003367371_django_pagination_python.txt
Q: Basic python arithmetic - division I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 : >>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> print per_page 2 >>> pages = math.ceil(count/per_pages) >>> print pages 0.0 >>> pages = float(count/per_pages) >>> print pages 0.0 What am I doing wrong, and why math.ceil gives float number instead of int ? A: Python does integer division when both operands are integers, meaning that 1 / 2 is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you expect. (I think this division behavior changes in Python 3.) A: Integer division is the default of the / operator in Python < 3.0. This has behaviour that seems a little weird. It returns the dividend without a remainder. >>> 10 / 3 3 If you're running Python 2.6+, try: from __future__ import division >>> 10 / 3 3.3333333333333335 If you're running a lower version of Python than this, you will need to convert at least one of the numerator or denominator to a float: >>> 10 / float(3) 3.3333333333333335 Also, math.ceil always returns a float... >>> import math >>> help(math.ceil) ceil(...) ceil(x) Return the ceiling of x as a float. This is the smallest integral value >= x. A: From Python documentation (math module): math.ceil(x) Return the ceiling of x as a float, the smallest integer value greater than or equal to x. A: They're integers, so count/per_pages is zero before the functions ever get to do anything beyond that. I'm not a Python programmer really but I know that (count * 1.0) / pages will do what you want. There's probably a right way to do that however. edit — yes see @mipadi's answer and float(x) A: its because how you have it set up is performing the operation and then converting it to a float try count = friends.count() print count per_page = float(2) print per_page pages = math.ceil(count/per_pages) print pages pages = count/per_pages By converting either count or per_page to a float all of its future operations should be able to do divisions and end up with non whole numbers A: >>> 10 / float(3) 3.3333333333333335 >>> #Or >>> 10 / 3.0 3.3333333333333335 >>> #Python make any decimal number to float >>> a = 3 >>> type(a) <type 'int'> >>> b = 3.0 >>> type(b) <type 'float'> >>> The best solution maybe is to use from __future__ import division
Basic python arithmetic - division
I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 : >>> count = friends.count() >>> print count 1 >>> per_page = 2 >>> print per_page 2 >>> pages = math.ceil(count/per_pages) >>> print pages 0.0 >>> pages = float(count/per_pages) >>> print pages 0.0 What am I doing wrong, and why math.ceil gives float number instead of int ?
[ "Python does integer division when both operands are integers, meaning that 1 / 2 is basically \"how many times does 2 go into 1\", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you ...
[ 15, 6, 1, 0, 0, 0 ]
[]
[]
[ "math", "python", "python_2.x" ]
stackoverflow_0003367315_math_python_python_2.x.txt
Q: Problem with 2D collision detection from beginner I've taken an introductory course in Computer Science, but a short while back I decided to try and make a game. I'm having a problem with collision detection. My idea was to move an object, and if there is a collision, move it back the way it came until there is no longer a collision. Here is my code: class Player(object): ... def move(self): #at this point, velocity = some linear combination of (5, 0)and (0, 5) #gPos and velocity are types Vector2 self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) self.gPos += self.velocity while CheckCollisions(self): self.gPos -= self.velocity/n #see footnote self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) ... def CheckCollisions(obj): #archList holds all 'architecture' objects, solid == True means you can't walk #through it. colliderect checks to see if the rectangles are overlapping for i in archList: if i.solid: if i.hitBox.colliderect(obj.hitBox): return True return False *I substituted several different values for n, both integers and floats, to change the increment by which the player moves back. I thought by trying a large float, it would only move one pixel at a time When I run the program, the sprite for the player vibrates very fast over a range of about 5 pixels whenever I run into a wall. If I let go of the arrow key, the sprite will get stuck in the wall permanently. I wondering why the sprite is inside the wall in the first place, since by the time I blit the sprite to the screen, it should have been moved just outside of the wall. Is there something wrong with my method, or does the problem lie within my execution? A: Looks like you're setting the hitbox BEFORE updating the position. The Fix seems simple. Find: self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) self.gPos += self.velocity Replace: self.gPos += self.velocity self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) Other Suggestions: What you should do is check the position BEFORE you move there, and if it's occupied, don't move. This is untested so please just use this as psuedocode intended to illustrate the point: class Player(object): ... def move(self): #at this point, velocity = some linear combination of (5, 0)and (5, 5) #gPos and velocity are types Vector2 selfCopy = self selfCopy.gPos += self.velocity selfCopy.hitBox = Rect(selfCopy.gPos.x, selfCopy.gPos.y, 40, 40) if not CheckCollisions(selfCopy) self.gPos += self.velocity ... def CheckCollisions(obj): #archList holds all 'architecture' objects, solid == True means you can't walk #through it. colliderect checks to see if the rectangles are overlapping for i in archList: if i.solid: if i.hitBox.colliderect(obj.hitBox): return True return False
Problem with 2D collision detection from beginner
I've taken an introductory course in Computer Science, but a short while back I decided to try and make a game. I'm having a problem with collision detection. My idea was to move an object, and if there is a collision, move it back the way it came until there is no longer a collision. Here is my code: class Player(object): ... def move(self): #at this point, velocity = some linear combination of (5, 0)and (0, 5) #gPos and velocity are types Vector2 self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) self.gPos += self.velocity while CheckCollisions(self): self.gPos -= self.velocity/n #see footnote self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40) ... def CheckCollisions(obj): #archList holds all 'architecture' objects, solid == True means you can't walk #through it. colliderect checks to see if the rectangles are overlapping for i in archList: if i.solid: if i.hitBox.colliderect(obj.hitBox): return True return False *I substituted several different values for n, both integers and floats, to change the increment by which the player moves back. I thought by trying a large float, it would only move one pixel at a time When I run the program, the sprite for the player vibrates very fast over a range of about 5 pixels whenever I run into a wall. If I let go of the arrow key, the sprite will get stuck in the wall permanently. I wondering why the sprite is inside the wall in the first place, since by the time I blit the sprite to the screen, it should have been moved just outside of the wall. Is there something wrong with my method, or does the problem lie within my execution?
[ "Looks like you're setting the hitbox BEFORE updating the position. The Fix seems simple.\nFind:\n self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40)\n self.gPos += self.velocity \n\nReplace:\n self.gPos += self.velocity \n self.hitBox = Rect(self.gPos.x, self.gPos.y, 40, 40)\n\nOther Suggestions: W...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0003367664_pygame_python.txt
Q: How to extract first items from a list of tuples I have a rather large list of tuples which contains: [('and', 44023), ('cx', 37711), ('is', 36777), ...] I just want to extract the first string, so the output for the above list would be: and cx is How do I code this (with extensibilty built in to some degree)? A: [tup[0] for tup in mylist] This uses a list comprehension. You could also use parentheses instead of the outer brackets to make it a generator comprehension, so evaluation would be lazy. A: Just to provide an alternative way to the solution by Matthew. tuples = [('and', 44023), ('cx', 37711), ('is', 36777) .... ] strings, numbers = zip(*tuples) In case you at some point decide you want both parts of the tuple in separate sequences (avoids two list comprehensions). A: If you want to get the exact output and cx is Then use a list comprehension in combination with the strings join method to join the newline chararcter like so yourList = [('and', 44023), ('cx', 37711), ('is', 36777)] print '\n'.join([tup[0] for tup in yourList]) A: You can unpack your tuples in a for loop, like so: for word, count in mytuple: print "%r is used %i times!" % (word, count) You can see this used extensively in the Python docs: http://docs.python.org/tutorial/datastructures.html#looping-technique
How to extract first items from a list of tuples
I have a rather large list of tuples which contains: [('and', 44023), ('cx', 37711), ('is', 36777), ...] I just want to extract the first string, so the output for the above list would be: and cx is How do I code this (with extensibilty built in to some degree)?
[ "[tup[0] for tup in mylist]\n\nThis uses a list comprehension. You could also use parentheses instead of the outer brackets to make it a generator comprehension, so evaluation would be lazy.\n", "Just to provide an alternative way to the solution by Matthew.\ntuples = [('and', 44023), ('cx', 37711), ('is', 36777...
[ 15, 6, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0003367450_list_python_tuples.txt
Q: Ascending/descending ordering of Django QuerySet when one attribute is a model method I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the same winning percentage, I want them to be ordered alphabetically by school. How do I get something like this: team pct x 0.75 a 0.50 b 0.50 c 0.50 y 0.25 Because the winning percentage is a model method, I've been using Python to sort a QuerySet that is already in alphabetical order, but the alphabetical order of the schools is lost when I do this: team_list = Team.objects.order_by('school') sorted_team_list = sorted(team_list, key=lambda x: x.win_pct, reverse=True) A: Do it in two steps, not bad since sorts are stable: from operator import attrgetter sorted_team_list = sorted(team_list, key=attrgetter('school')) sorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True)
Ascending/descending ordering of Django QuerySet when one attribute is a model method
I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the same winning percentage, I want them to be ordered alphabetically by school. How do I get something like this: team pct x 0.75 a 0.50 b 0.50 c 0.50 y 0.25 Because the winning percentage is a model method, I've been using Python to sort a QuerySet that is already in alphabetical order, but the alphabetical order of the schools is lost when I do this: team_list = Team.objects.order_by('school') sorted_team_list = sorted(team_list, key=lambda x: x.win_pct, reverse=True)
[ "Do it in two steps, not bad since sorts are stable:\nfrom operator import attrgetter\n\nsorted_team_list = sorted(team_list, key=attrgetter('school'))\nsorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sorting" ]
stackoverflow_0003367706_django_python_sorting.txt
Q: using python to add images to powerpoint files has anyone used python to add images to powerpoint 2007 files? can someone please help me get started with this A: You can do this with Office's COM/OLE automation API. For example, see this post: Automating PowerPoint with Python
using python to add images to powerpoint files
has anyone used python to add images to powerpoint 2007 files? can someone please help me get started with this
[ "You can do this with Office's COM/OLE automation API. For example, see this post:\n\nAutomating PowerPoint with Python\n\n" ]
[ 3 ]
[]
[]
[ "powerpoint", "python", "windows" ]
stackoverflow_0003367736_powerpoint_python_windows.txt
Q: is python the preferred language for mobile applications? a lot of my friends are using Python to build their mobile applications and games. is python the preferred language for mobile applications for developers? if so, why? A: No. Python is an excellent language, but there is nothing about it makes it especially preferred for mobile development. A: No, there is no preferred language for mobile development. Each mobile platform has its own supported language or set of supported languages. Android is programmed primarily with Java (although development in C++ and Python are also supported), while the iPhone is programmed with Objective-C. A common theme in mobile is to implement the core functionality of the application as a webservice, and then to implement a UI for a specific mobile platform that is a thin client to the web service. While the UI will be written in whichever language(s) are supported by the platform, the language that you use for the webservice can be whatever programming language(s) you choose to run on your webserver. If you use a cloud computing service, then that would be whatever languages are supported by that service (e.g. if you use Google AppEngine, then Python and Java are both supported languages).
is python the preferred language for mobile applications?
a lot of my friends are using Python to build their mobile applications and games. is python the preferred language for mobile applications for developers? if so, why?
[ "No. Python is an excellent language, but there is nothing about it makes it especially preferred for mobile development.\n", "No, there is no preferred language for mobile development. Each mobile platform has its own supported language or set of supported languages. Android is programmed primarily with Java (al...
[ 5, 3 ]
[]
[]
[ "mobile", "python" ]
stackoverflow_0003367808_mobile_python.txt
Q: Efficiently carry out multiple string replacements in Python If I would like to carry out multiple string replacements, what is the most efficient way to carry this out? An example of the kind of situation I have encountered in my travels is as follows: >>> strings = ['a', 'list', 'of', 'strings'] >>> [s.replace('a', '')...replace('u', '') for s in strings if len(s) > 2] ['a', 'lst', 'of', 'strngs'] A: The specific example you give (deleting single characters) is perfect for the translate method of strings, as is substitution of single characters with single characters. If the input string is a Unicode one, then, as well as the two above kinds of "substitution", substitution of single characters with multiple character strings is also fine with the translate method (not if you need to work on byte strings, though). If you need to replace substrings of multiple characters, then I would also recommend using a regular expression -- though not in the way @gnibbler's answer recommends; rather, I'd build the regex from r'onestring|another|yetanother|orthis' (join the substrings you want to replace with vertical bars -- be sure to also re.escape them if they contain special characters, of course) and write a simple substituting-function based on a dict. I'm not going to offer a lot of code at this time since I don't know which of the two paragraphs applies to your actual needs, but (when I later come back home and check SO again;-) I'll be glad to edit to add a code example as necessary depending on your edits to your question (more useful than comments to this answer;-). Edit: in a comment the OP says he wants a "more general" answer (without clarifying what that means) then in an edit of his Q he says he wants to study the "tradeoffs" between various snippets all of which use single-character substrings (and check presence thereof, rather than replacing as originally requested -- completely different semantics, of course). Given this utter and complete confusion all I can say is that to "check tradeoffs" (performance-wise) I like to use python -mtimeit -s'setup things here' 'statements to check' (making sure the statements to check have no side effects to avoid distorting the time measurements, since timeit implicitly loops to provide accurate timing measurements). A general answer (without any tradeoffs, and involving multiple-character substrings, so completely contrary to his Q's edit but consonant to his comments -- the two being entirely contradictory it is of course impossible to meet both): import re class Replacer(object): def __init__(self, **replacements): self.replacements = replacements self.locator = re.compile('|'.join(re.escape(s) for s in replacements)) def _doreplace(self, mo): return self.replacements[mo.group()] def replace(self, s): return self.locator.sub(self._doreplace, s) Example use: r = Replacer(zap='zop', zip='zup') print r.replace('allazapollezipzapzippopzip') If some of the substrings to be replaced are Python keywords, they need to be passed in a tad less directly, e.g., the following: r = Replacer(abc='xyz', def='yyt', ghi='zzq') would fail because def is a keyword, so you need e.g.: r = Replacer(abc='xyz', ghi='zzq', **{'def': 'yyt'}) or the like. I find this a good use for a class (rather than procedural programming) because the RE to locate the substrings to replace, the dict expressing what to replace them with, and the method performing the replacement, really cry out to be "kept all together", and a class instance is just the right way to perform such a "keeping together" in Python. A closure factory would also work (since the replace method is really the only part of the instance that needs to be visible "outside") but in a possibly less-clear, harder to debug way: def make_replacer(**replacements): locator = re.compile('|'.join(re.escape(s) for s in replacements)) def _doreplace(mo): return replacements[mo.group()] def replace(s): return locator.sub(_doreplace, s) return replace r = make_replacer(zap='zop', zip='zup') print r('allazapollezipzapzippopzip') The only real advantage might be a very modestly better performance (needs to be checked with timeit on "benchmark cases" considered significant and representative for the app using it) as the access to the "free variables" (replacements, locator, _doreplace) in this case might be minutely faster than access to the qualified names (self.replacements etc) in the normal, class-based approach (whether this is the case will depend on the Python implementation in use, whence the need to check with timeit on significant benchmarks!). A: You may find that it is faster to create a regex and do all the replacements at once. Also a good idea to move the replacement code out to a function so that you can memoize if you are likely to have duplicates in the list >>> import re >>> [re.sub('[aeiou]','',s) for s in strings if len(s) > 2] ['a', 'lst', 'of', 'strngs'] >>> def replacer(s, memo={}): ... if s not in memo: ... memo[s] = re.sub('[aeiou]','',s) ... return memo[s] ... >>> [replacer(s) for s in strings if len(s) > 2] ['a', 'lst', 'of', 'strngs']
Efficiently carry out multiple string replacements in Python
If I would like to carry out multiple string replacements, what is the most efficient way to carry this out? An example of the kind of situation I have encountered in my travels is as follows: >>> strings = ['a', 'list', 'of', 'strings'] >>> [s.replace('a', '')...replace('u', '') for s in strings if len(s) > 2] ['a', 'lst', 'of', 'strngs']
[ "The specific example you give (deleting single characters) is perfect for the translate method of strings, as is substitution of single characters with single characters. If the input string is a Unicode one, then, as well as the two above kinds of \"substitution\", substitution of single characters with multiple...
[ 12, 1 ]
[]
[]
[ "immutability", "python", "string" ]
stackoverflow_0003367809_immutability_python_string.txt
Q: How to replace a non-static substring case-insensitively This question is similar to this except that the substring to be replaced is only known at the runtime. I want to write the definition of ireplace, that behaves like this: >>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26') r'image\python26\lib\site.py' >>> A: In this case, I think this is the simplest way r'c:\Python26\lib\site.py'.lower().replace('python26', r'image\python26') For case insensitive, regexp is the simplest way >>> def ireplace(s, a, b): ... return re.sub("(?i)"+re.escape(a),b,s) ... >>> print ireplace(r'c:\Python26\lib\site.py', 'C:\python26', r'image\python26') image\python26\lib\site.py A: def ireplace(s, a, b): """Replace `a` with `b` in s without caring about case""" re_a = re.compile(re.escape(a), re.IGNORECASE) return re_a.sub(lambda m: b, s) Note: The lambda m: b hack is necessary, as re.escape(b) seems to mangle the string if it it has hyphens.
How to replace a non-static substring case-insensitively
This question is similar to this except that the substring to be replaced is only known at the runtime. I want to write the definition of ireplace, that behaves like this: >>> ireplace(r'c:\Python26\lib\site.py', r'C:\python26', r'image\python26') r'image\python26\lib\site.py' >>>
[ "In this case, I think this is the simplest way\nr'c:\\Python26\\lib\\site.py'.lower().replace('python26', r'image\\python26')\n\nFor case insensitive, regexp is the simplest way\n>>> def ireplace(s, a, b):\n... return re.sub(\"(?i)\"+re.escape(a),b,s)\n...\n>>> print ireplace(r'c:\\Python26\\lib\\site.py', 'C:...
[ 1, 0 ]
[]
[]
[ "case_insensitive", "python", "string" ]
stackoverflow_0003367874_case_insensitive_python_string.txt
Q: converting structures in c to pywin32? i am trying to use TTM_GETTEXT via SendMessage using pywin32. the problem is, the structure of the lparam, which is where the text should be stored, has to be TOOLINFO, which is well documented in MSDN, but has no counterpart in pywin32. is there a way to create the same structure using python and pywin32? Edit: here's the code i came up with using ctypes. I made a Structure for TOOLINFO, created a buffer from it to pass to pywin32's SendMessage, then converted it back to the TOOLINFO ctypes Structure. Only problem is, it isn't working: # My TOOLINFO struct: class TOOLINFO(Structure): _fields_ = [("cbSize", UINT), ("uFlags", UINT), ("hwnd", HWND), ("uId", POINTER(UINT)), ("rect", RECT), ("hinst", HINSTANCE), ("lpszText", LPWSTR), ("lpReserved", c_void_p)] # send() definition from PythonInfo wiki FAQs def send(self): return buffer(self)[:] ti = TOOLINFO() text = "" ti.cbSize = sizeof(ti) ti.lpszText = text # buffer to store text in ti.uId = pointer(UINT(wnd)) # wnd is the handle of the tooltip ti.hwnd = w_wnd # w_wnd is the handle of the window containing the tooltip ti.uFlags = commctrl.TTF_IDISHWND # specify that uId is the control handle ti_buffer = send(ti) # convert to buffer for pywin32 del(ti) win32gui.SendMessage(wnd, commctrl.TTM_GETTEXT, 256, ti_buffer) ti = TOOLINFO() # create new TOOLINFO() to copy result to # copy result (according to linked article from Jeremy) memmove(addressof(ti), ti_buffer, sizeof(ti)) if ti.lpszText: print ti.lpszText # print any text recovered from the tooltip Text isn't being printed, but i assumed that it should contain the text from the tooltip i want to extract from. Is there something wrong with how I used the ctypes? I am quite sure that my values for wnd and w_wnd are correct, so i must be doing something wrong. A: It's not particularly pretty, but you can use the struct module to pack the fields into a string with the appropriate endianess, alignment, and padding. It's a little tricky since you must define the structure with a format string using only corresponding fundamental data types in the correct order. You could also use ctypes for defining structure types or also interfacing with the DLLs directly (rather than using pywin32). ctypes structure definitions are closer to C definitions, so you may like it better. If you choose to use ctypes for structure defs along with pywin32, check out the following for a clue to how to serialize the structs into strings: How to pack and unpack using ctypes (Structure <-> str)
converting structures in c to pywin32?
i am trying to use TTM_GETTEXT via SendMessage using pywin32. the problem is, the structure of the lparam, which is where the text should be stored, has to be TOOLINFO, which is well documented in MSDN, but has no counterpart in pywin32. is there a way to create the same structure using python and pywin32? Edit: here's the code i came up with using ctypes. I made a Structure for TOOLINFO, created a buffer from it to pass to pywin32's SendMessage, then converted it back to the TOOLINFO ctypes Structure. Only problem is, it isn't working: # My TOOLINFO struct: class TOOLINFO(Structure): _fields_ = [("cbSize", UINT), ("uFlags", UINT), ("hwnd", HWND), ("uId", POINTER(UINT)), ("rect", RECT), ("hinst", HINSTANCE), ("lpszText", LPWSTR), ("lpReserved", c_void_p)] # send() definition from PythonInfo wiki FAQs def send(self): return buffer(self)[:] ti = TOOLINFO() text = "" ti.cbSize = sizeof(ti) ti.lpszText = text # buffer to store text in ti.uId = pointer(UINT(wnd)) # wnd is the handle of the tooltip ti.hwnd = w_wnd # w_wnd is the handle of the window containing the tooltip ti.uFlags = commctrl.TTF_IDISHWND # specify that uId is the control handle ti_buffer = send(ti) # convert to buffer for pywin32 del(ti) win32gui.SendMessage(wnd, commctrl.TTM_GETTEXT, 256, ti_buffer) ti = TOOLINFO() # create new TOOLINFO() to copy result to # copy result (according to linked article from Jeremy) memmove(addressof(ti), ti_buffer, sizeof(ti)) if ti.lpszText: print ti.lpszText # print any text recovered from the tooltip Text isn't being printed, but i assumed that it should contain the text from the tooltip i want to extract from. Is there something wrong with how I used the ctypes? I am quite sure that my values for wnd and w_wnd are correct, so i must be doing something wrong.
[ "It's not particularly pretty, but you can use the struct module to pack the fields into a string with the appropriate endianess, alignment, and padding. It's a little tricky since you must define the structure with a format string using only corresponding fundamental data types in the correct order.\nYou could al...
[ 1 ]
[]
[]
[ "python", "pywin32", "winapi" ]
stackoverflow_0003367721_python_pywin32_winapi.txt
Q: Where to host a periodically running Python or Java service? I'm going to build a little service which monitors an IMAP email account and acts on the read messages. For this it just has to run every say 10 min, no external trigger required, but I want to host this service externally (so that I don't need to worry about up times.) To be machine independent I could write the service in Java or Python. What are good hosting providers for this? and which of the two languages is better supported? The service has either to run the whole time (and must do the waiting itself) or it has to be kicked off every 10 min. I guess most (web) hosts are geared towards request driven code (e.g. JSP) and I assume they shut down processes which run forever. Who offers hosting for user-written services like the one mentioned above? A: Depending on what actions you require, and your requirements for resources, Google App Engine might be quite suitable for both Python and Java services (GAE supports both languages quite decently). cron jobs can be set to run every 10 minutes (the URL I gave shows how to do that with Python) and you can queue more tasks if the amount of work you need to perform on a certain occasion exceeds the 30-seconds limit that GAE supports. GAE is particularly nice to get started and experiment since it has reasonably-generous free quotas for most all resources your jobs could consume (you need to enable billing, provide a credit card, and set up a budget, to allow your jobs to consume more than their free quota, though). If you decide that GAE has limitations you can't stand, or would cost you too much for billed use of resources over the free quotas, any hosting provider supporting a Unix-like cron jobs scheduler should be acceptable. Starting up from scratch a Python script every 10 minutes may be faster than starting up from scratch a JVM, but that depends on what it is that you have to do every 10 minutes (for some kinds of tasks Python will be just as fast, or maybe even faster -- for others it will be slower, and we have no way to guess what kinds of tasks you require or at what "tipping point" the possibly-faster JVM will "pay for its own startup" wrt the possibly-slower Python... basically you'll need to assess that for yourself!-). A: You are lucky, since Google AppEngine provides CRON jobs both for Python and Java. GAE - Python GAE - Java A: Check out Google App Engine. You can set up a cron job for your Java or Python script.
Where to host a periodically running Python or Java service?
I'm going to build a little service which monitors an IMAP email account and acts on the read messages. For this it just has to run every say 10 min, no external trigger required, but I want to host this service externally (so that I don't need to worry about up times.) To be machine independent I could write the service in Java or Python. What are good hosting providers for this? and which of the two languages is better supported? The service has either to run the whole time (and must do the waiting itself) or it has to be kicked off every 10 min. I guess most (web) hosts are geared towards request driven code (e.g. JSP) and I assume they shut down processes which run forever. Who offers hosting for user-written services like the one mentioned above?
[ "Depending on what actions you require, and your requirements for resources, Google App Engine might be quite suitable for both Python and Java services (GAE supports both languages quite decently). cron jobs can be set to run every 10 minutes (the URL I gave shows how to do that with Python) and you can queue mor...
[ 6, 3, 0 ]
[]
[]
[ "hosting", "java", "python", "service" ]
stackoverflow_0003368246_hosting_java_python_service.txt
Q: In a python script, how can I save the contents of a string to file, and the file is in current directory? In a python script, how can I save the contents of a string to file, and the file is in current directory? i.e the same directory as the test.py script file A: This will create/overwrite myfile.txt in the current working directory. The Python 'current working directory' is inherited from the operating system. I.e., it's the directory you were 'in' when you ran the script. (Which isn't always the directory containing the script; e.g., scripts in distant directories can be executed by typing the full path.) s = 'My string.' with open('myfile.txt', 'w') as f: f.write(s) A: If you want the path to the currently executing file (and not the working directory) use the __file__ variable. You should note that this is the current file being run. So if you use it in an imported module, you'll get the path to the module, etc.. fH = file(os.path.join(os.path.dirname(__file__), 'someFile.txt'), 'w') fH.write('here is my string') fH.close()
In a python script, how can I save the contents of a string to file, and the file is in current directory?
In a python script, how can I save the contents of a string to file, and the file is in current directory? i.e the same directory as the test.py script file
[ "This will create/overwrite myfile.txt in the current working directory.\nThe Python 'current working directory' is inherited from the operating system. I.e., it's the directory you were 'in' when you ran the script. (Which isn't always the directory containing the script; e.g., scripts in distant directories can b...
[ 3, 3 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003368244_file_io_python.txt
Q: Best way to test for existence of a variable in Python I am reading a million plus files to scrape out some data. The files are generally pretty uniform but there are occasional problems where something that I expected to find is not present. For example, I expect some sgml code to identify a value I need for data_line in temp #temp is a list of lines from a file if <VARIABLENAME> in data_line: VARIABLE_VAL=data_line.split('>')[-1] Later on I use VARIABLE_VAL. But I sometimes get an exception: no line in the file that has <VARIABLENAME>theName To handle this I have added this line after all the lines have been processed: try: if VARIABLE_VAL: pass except NameError: VARIABLE_VAL=somethingELSE I have seen somewhere (but I can't find it anymore) a solution that looks like if not VARIABLE_VAL: VARIABLE_VAL=somethingELSE Any help would be appreciated A: Just initialize your variable to its default value before the loop: VARIABLE_VAL = somethingELSE for dataline in temp: ... this way, VARIABLE_VAL will keep its initial, default value unless bound to something else within the loop, and you need no weird testing whatsoever to ensure that. A: Alex's solution is correct. But just in case you do want to test if a variable exists, try: if 'VARIABLE_VAL' in locals(): ....
Best way to test for existence of a variable in Python
I am reading a million plus files to scrape out some data. The files are generally pretty uniform but there are occasional problems where something that I expected to find is not present. For example, I expect some sgml code to identify a value I need for data_line in temp #temp is a list of lines from a file if <VARIABLENAME> in data_line: VARIABLE_VAL=data_line.split('>')[-1] Later on I use VARIABLE_VAL. But I sometimes get an exception: no line in the file that has <VARIABLENAME>theName To handle this I have added this line after all the lines have been processed: try: if VARIABLE_VAL: pass except NameError: VARIABLE_VAL=somethingELSE I have seen somewhere (but I can't find it anymore) a solution that looks like if not VARIABLE_VAL: VARIABLE_VAL=somethingELSE Any help would be appreciated
[ "Just initialize your variable to its default value before the loop:\nVARIABLE_VAL = somethingELSE\nfor dataline in temp: ...\n\nthis way, VARIABLE_VAL will keep its initial, default value unless bound to something else within the loop, and you need no weird testing whatsoever to ensure that.\n", "Alex's solution...
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003368270_python.txt
Q: Which is better - PyInstaller or cx_Freeze? Could someone tell me which is better of the two for bundling Python applications — cx_Freeze or PyInstaller? I'm looking for a comparison based on factors such as: Popularity (i.e. larger user base) Footprint of the built binary Cross platform compatibility Ease of use A: I tried both for a current project and decided to use cx_freeze. I found it easier to get started. It has an option to bundle dependencies in a zip archive, which makes it easy to check that everything was properly included. I had trouble getting PyInstaller to include certain egg dependencies. It couldn't handle conditional imports as well as I needed and looking through the bundled archive was difficult. On Windows, it requires pywin32 (so it can't be used with virtualenv) and version 1.4 doesn't work with Python 2.6. There's no information on whether Python 2.7 is supported. A: Why not use something like GUI2EXE? GUI2Exe is a Graphical User Interface frontend to all the "executable builders" available for the Python programming language. It can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts. For my experience, I found that for some programs py2exe doesn't work right, but cx_freeze does. haven't tried pyinstaller.
Which is better - PyInstaller or cx_Freeze?
Could someone tell me which is better of the two for bundling Python applications — cx_Freeze or PyInstaller? I'm looking for a comparison based on factors such as: Popularity (i.e. larger user base) Footprint of the built binary Cross platform compatibility Ease of use
[ "I tried both for a current project and decided to use cx_freeze. I found it easier to get started. It has an option to bundle dependencies in a zip archive, which makes it easy to check that everything was properly included.\nI had trouble getting PyInstaller to include certain egg dependencies. It couldn't handle...
[ 26, 1 ]
[]
[]
[ "cx_freeze", "pyinstaller", "python" ]
stackoverflow_0003307966_cx_freeze_pyinstaller_python.txt
Q: How do I setup python to always include my directory of utility files I have been programming in Python for a while now, and have created some utilities that I use a lot. Whenever I start a new project, I start writing, and as I need these utilities I copy them from where ever I think the latest version of the particular utility is. I have enough projects now that I am losing track of where the latest version is. And, I will upgrade one of these scripts to fix a problem in a specific situation, and then wish it had propagated back to all of the other projects that use that script. I am thinking the best way to solve this problem is to create a directory in the site-packages directory, and put all of my utility modules in there. And then add this directory to the sys.path directory list. Is this the best way to solve this problem? How do modify my installation of Python so that this directory is always added to sys.path, and I don't have to explicitly modify sys.path at the beginning of each module that needs to use these utilities? I'm using Python 2.5 on Windows XP, and Wing IDE. A: The site-packages directory within the Python lib directory should always be added to sys.path, so you shouldn't need to modify anything to take care of that. That's actually just what I'd recommend, that you make yourself a Python package within that directory and put your code in there. Actually, something you might consider is packaging up your utilities using distutils. All that entails is basically creating a setup.py file in the root of the folder tree where you keep your utility code. The distutils documentation that I just linked to describes what should go in setup.py. Then, from within that directory, run python setup.py install to install your utility code into the system site-packages directory, creating the necessary folder structure automatically. Or you can use python setup.py install --user to install it into a site-packages folder in your own user account. A: Add your directory to the PYTHONPATH environment variable. For windows, see these directions. A: If it's not in site-packages then you can add a file with the extension .pth to your site-packages directory. The file should have one path per line, that you want included in sys.path
How do I setup python to always include my directory of utility files
I have been programming in Python for a while now, and have created some utilities that I use a lot. Whenever I start a new project, I start writing, and as I need these utilities I copy them from where ever I think the latest version of the particular utility is. I have enough projects now that I am losing track of where the latest version is. And, I will upgrade one of these scripts to fix a problem in a specific situation, and then wish it had propagated back to all of the other projects that use that script. I am thinking the best way to solve this problem is to create a directory in the site-packages directory, and put all of my utility modules in there. And then add this directory to the sys.path directory list. Is this the best way to solve this problem? How do modify my installation of Python so that this directory is always added to sys.path, and I don't have to explicitly modify sys.path at the beginning of each module that needs to use these utilities? I'm using Python 2.5 on Windows XP, and Wing IDE.
[ "The site-packages directory within the Python lib directory should always be added to sys.path, so you shouldn't need to modify anything to take care of that. That's actually just what I'd recommend, that you make yourself a Python package within that directory and put your code in there.\nActually, something you ...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003368459_python.txt
Q: python function fails to return unless the last statement is slow I'm working on a subclass of threading.Thread which allows its methods to be called and run in the thread represented by the object that they are called on as opposed to the usual behavior. I do this by using decorators on the target method that place the call to the method in a collections.deque and using the run method to process the deque. the run method uses a while not self.__stop: statement and a threading.Condition object to wait for a call to be placed in the deque and then call self.__process_calls. The else part of the while loop makes a final call to __process_calls. if self.__stop, an exception is raised on any attempts to call one of the 'callable' methods from another thread. The problem is that __process_calls fails to return unless the last statement is a print which I discovered during debugging. I've tried a = 1 and an explicit return but neither work. with any print statement as the final statement of the function though, it returns and the thread doesn't hang. Any ideas what's going on? EDIT: It was pointed out by David Zaslavsky that the print works because it takes a while and I've confirmed that The code's a little long but hopefully, my explanation above is clear enough to help understand it. import threading import collections class BrokenPromise(Exception): pass class CallableThreadError(Exception): pass class CallToNonRunningThreadError(CallableThreadError): pass class Promise(object): def __init__(self, deque, condition): self._condition = condition self._deque = deque def read(self, timeout=None): if not self._deque: with self._condition: if timeout: self._condition.wait(timeout) else: self._condition.wait() if self._deque: value = self._deque.popleft() del self._deque del self._condition return value else: raise BrokenPromise def ready(self): return bool(self._deque) class CallableThread(threading.Thread): def __init__(self, *args, **kwargs): # _enqueued_calls is used to store tuples that encode a function call. # It is processed by the run method self.__enqueued_calls = collections.deque() # _enqueue_call_permission is for callers to signal that they have # placed something on the queue self.__enqueue_call_permission = threading.Condition() self.__stop = False super(CallableThread, self).__init__(*args, **kwargs) @staticmethod def blocking_method(f): u"""A decorator function to implement a blocking method on a thread""" # the returned function enqueues the decorated function and blocks # until the decorated function# is called and returns. It then returns # the value unmodified. The code in register runs in the calling thread # and the decorated method runs in thread that it is called on f = CallableThread.nonblocking_method_with_promise(f) def register(self, *args, **kwargs): p = f(self, *args, **kwargs) return p.read() return register @staticmethod def nonblocking_method_with_promise(f): u"""A decorator function to implement a non-blocking method on a thread """ # the returned function enqueues the decorated function and returns a # Promise object.N The code in register runs in the calling thread # and the decorated method runs in thread that it is called on. def register(self, *args, **kwargs): call_complete = threading.Condition() response_deque = collections.deque() self.__push_call(f, args, kwargs, response_deque, call_complete) return Promise(response_deque, call_complete) return register @staticmethod def nonblocking_method(f): def register(self, *args, **kwargs): self.__push_call(f, args, kwargs) return register def run(self): while not self.__stop: # while we've not been killed with self.__enqueue_call_permission: # get the condition so that we can wait on it if we need too. if not self.__enqueued_calls: self.__enqueue_call_permission.wait() self.__process_calls() else: # if we exit because self._run == False, finish processing # the pending calls if there are any self.__process_calls() def stop(self): u""" Signal the thread to stop""" with self.__enqueue_call_permission: # we do this in case the run method is stuck waiting on an update self.__stop = True self.__enqueue_call_permission.notify() def __process_calls(self): print "processing calls" while self.__enqueued_calls: ((f, args, kwargs), response_deque, call_complete) = self.__enqueued_calls.popleft() if call_complete: with call_complete: response_deque.append(f(self, *args, **kwargs)) call_complete.notify() else: f(self, *args, **kwargs) # this is where you place the print statement if you want to see the # behavior def __push_call(self, f, args, kwargs, response_deque=None, call_complete=None): if self.__stop: raise CallToNonRunningThreadError( "This thread is no longer accepting calls") with self.__enqueue_call_permission: self.__enqueued_calls.append(((f, args, kwargs), response_deque, call_complete)) self.__enqueue_call_permission.notify() #if __name__=='__main__': i lost the indent on the following code in copying but #it doesn't matter in this context class TestThread(CallableThread): u"""Increment a counter on each call and print the value""" counter = 0 @CallableThread.nonblocking_method_with_promise def increment(self): self.counter += 1 return self.counter class LogThread(CallableThread): @CallableThread.nonblocking_method def log(self, message): print message l = LogThread() l.start() l.log("logger started") t = TestThread() t.start() l.log("test thread started") p = t.increment() l.log("promise aquired") v = p.read() l.log("promise read") l.log("{0} read from promise".format(v)) l.stop() t.stop() l.join() t.join() A: __process_calls is modifying __enqueued_calls without owning the lock. This may be creating a race condition. Edit: deque may be "threadsafe" (ie not corrupted by thread accesses), but the checking of its state still should be locked. The stop condition is also not safe. Comments inline: def run(self): while not self.__stop: # while we've not been killed with self.__enqueue_call_permission: # get the condition so that we can wait on it if we need too. ### should be checking __stop here, it could have been modified before ### you took the lock. if not self.__enqueued_calls: self.__enqueue_call_permission.wait() self.__process_calls() else: # if we exit because self._run == False, finish processing # the pending calls if there are any self.__process_calls()
python function fails to return unless the last statement is slow
I'm working on a subclass of threading.Thread which allows its methods to be called and run in the thread represented by the object that they are called on as opposed to the usual behavior. I do this by using decorators on the target method that place the call to the method in a collections.deque and using the run method to process the deque. the run method uses a while not self.__stop: statement and a threading.Condition object to wait for a call to be placed in the deque and then call self.__process_calls. The else part of the while loop makes a final call to __process_calls. if self.__stop, an exception is raised on any attempts to call one of the 'callable' methods from another thread. The problem is that __process_calls fails to return unless the last statement is a print which I discovered during debugging. I've tried a = 1 and an explicit return but neither work. with any print statement as the final statement of the function though, it returns and the thread doesn't hang. Any ideas what's going on? EDIT: It was pointed out by David Zaslavsky that the print works because it takes a while and I've confirmed that The code's a little long but hopefully, my explanation above is clear enough to help understand it. import threading import collections class BrokenPromise(Exception): pass class CallableThreadError(Exception): pass class CallToNonRunningThreadError(CallableThreadError): pass class Promise(object): def __init__(self, deque, condition): self._condition = condition self._deque = deque def read(self, timeout=None): if not self._deque: with self._condition: if timeout: self._condition.wait(timeout) else: self._condition.wait() if self._deque: value = self._deque.popleft() del self._deque del self._condition return value else: raise BrokenPromise def ready(self): return bool(self._deque) class CallableThread(threading.Thread): def __init__(self, *args, **kwargs): # _enqueued_calls is used to store tuples that encode a function call. # It is processed by the run method self.__enqueued_calls = collections.deque() # _enqueue_call_permission is for callers to signal that they have # placed something on the queue self.__enqueue_call_permission = threading.Condition() self.__stop = False super(CallableThread, self).__init__(*args, **kwargs) @staticmethod def blocking_method(f): u"""A decorator function to implement a blocking method on a thread""" # the returned function enqueues the decorated function and blocks # until the decorated function# is called and returns. It then returns # the value unmodified. The code in register runs in the calling thread # and the decorated method runs in thread that it is called on f = CallableThread.nonblocking_method_with_promise(f) def register(self, *args, **kwargs): p = f(self, *args, **kwargs) return p.read() return register @staticmethod def nonblocking_method_with_promise(f): u"""A decorator function to implement a non-blocking method on a thread """ # the returned function enqueues the decorated function and returns a # Promise object.N The code in register runs in the calling thread # and the decorated method runs in thread that it is called on. def register(self, *args, **kwargs): call_complete = threading.Condition() response_deque = collections.deque() self.__push_call(f, args, kwargs, response_deque, call_complete) return Promise(response_deque, call_complete) return register @staticmethod def nonblocking_method(f): def register(self, *args, **kwargs): self.__push_call(f, args, kwargs) return register def run(self): while not self.__stop: # while we've not been killed with self.__enqueue_call_permission: # get the condition so that we can wait on it if we need too. if not self.__enqueued_calls: self.__enqueue_call_permission.wait() self.__process_calls() else: # if we exit because self._run == False, finish processing # the pending calls if there are any self.__process_calls() def stop(self): u""" Signal the thread to stop""" with self.__enqueue_call_permission: # we do this in case the run method is stuck waiting on an update self.__stop = True self.__enqueue_call_permission.notify() def __process_calls(self): print "processing calls" while self.__enqueued_calls: ((f, args, kwargs), response_deque, call_complete) = self.__enqueued_calls.popleft() if call_complete: with call_complete: response_deque.append(f(self, *args, **kwargs)) call_complete.notify() else: f(self, *args, **kwargs) # this is where you place the print statement if you want to see the # behavior def __push_call(self, f, args, kwargs, response_deque=None, call_complete=None): if self.__stop: raise CallToNonRunningThreadError( "This thread is no longer accepting calls") with self.__enqueue_call_permission: self.__enqueued_calls.append(((f, args, kwargs), response_deque, call_complete)) self.__enqueue_call_permission.notify() #if __name__=='__main__': i lost the indent on the following code in copying but #it doesn't matter in this context class TestThread(CallableThread): u"""Increment a counter on each call and print the value""" counter = 0 @CallableThread.nonblocking_method_with_promise def increment(self): self.counter += 1 return self.counter class LogThread(CallableThread): @CallableThread.nonblocking_method def log(self, message): print message l = LogThread() l.start() l.log("logger started") t = TestThread() t.start() l.log("test thread started") p = t.increment() l.log("promise aquired") v = p.read() l.log("promise read") l.log("{0} read from promise".format(v)) l.stop() t.stop() l.join() t.join()
[ "\n__process_calls is modifying __enqueued_calls without owning the lock. This may be creating a race condition.\nEdit: deque may be \"threadsafe\" (ie not corrupted by thread accesses), but the checking of its state still should be locked.\nThe stop condition is also not safe.\n\nComments inline:\ndef run(self): ...
[ 1 ]
[]
[]
[ "debugging", "multithreading", "python", "python_multithreading" ]
stackoverflow_0003368475_debugging_multithreading_python_python_multithreading.txt
Q: Integrity check going from dev to testing Django app using Git I'm using Git to push my code from my development machine to my testing server. Dev: Mac, Python 2.6, sqllite and Test: Linux, Python 2.7, MySQL I took an early dev database and exported it to MySQL for initial testing. So now I'm regularly pushing new code to the testing server. In general it seems to be working well, but I'm getting an Integrity Error regarding multiple objects with same Primary Key occasionally. Does this ring any bells at this point? Is there something inherently wrong with the setups? Obviously there are some configuration differences for instance Python 2.6 and 2.7. So if there were issues here, I was hoping somebody could target them before I try some platform config syncing. Thanks! A: I'm not able to answer this question directly. Depending on the reasons why you have used a different Python environment for your testing server, there are a few options: First, if you want to test to see whether your code functions in multiple environments, I recommend you look into py.test. It has support for distributed testing. This includes providing the ability to create a virtualenv for each Python version that you wish to test. Once you've done this, it will easier to tell whether your code, Django core or whether MqSQL is at fault. My suspicion is that there may be a problem with the database abstraction. It looks like sqllite is being tolerant but MySQL is not. Secondly, it may be worthwhile to look into virtualenv yourself. This creates a standalone Python environment that makes replicating your dev setup much simpler.
Integrity check going from dev to testing Django app using Git
I'm using Git to push my code from my development machine to my testing server. Dev: Mac, Python 2.6, sqllite and Test: Linux, Python 2.7, MySQL I took an early dev database and exported it to MySQL for initial testing. So now I'm regularly pushing new code to the testing server. In general it seems to be working well, but I'm getting an Integrity Error regarding multiple objects with same Primary Key occasionally. Does this ring any bells at this point? Is there something inherently wrong with the setups? Obviously there are some configuration differences for instance Python 2.6 and 2.7. So if there were issues here, I was hoping somebody could target them before I try some platform config syncing. Thanks!
[ "I'm not able to answer this question directly. \nDepending on the reasons why you have used a different Python environment for your testing server, there are a few options:\nFirst, if you want to test to see whether your code functions in multiple environments, I recommend you look into py.test. It has support for...
[ 1 ]
[]
[]
[ "configuration", "django", "git", "python" ]
stackoverflow_0003367004_configuration_django_git_python.txt
Q: Compile Error IcePy (Ice 3.3.1) : relocation against local symbol I have a problem when I try to build IcePy (from Ice 3.3.1) (for python 2.4.4). Compilation, testing and install of Ice itself (cpp version) is OK but when I tried to build the python interface ("py" directory) I get the following error (sorry for the truncated paths) : .../lib/python2.4/config/libpython2.4.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC .../lib/python2.4/config/libpython2.4.a: could not read symbols: Bad value collect2: ld returned 1 exit status Is anybody able to explain me what this problem of relocation means (or at least give me a link) ? Thank you in avdance for your help. Even if you don't know anything about Ice, your comments on the error message are welcome. (of course the compilation line already contained -fPIC so the "recompile with -fPIC" does not really help me...) A: The abstract.o was very likely not compiled with -fPIC, so the advice linker gave you is correct. Go back to your build log, and verify that -fPIC is not there when libpython2.4.a was built. Note that -fPIC is needed for libpython2.4.a itself, not just for the IcePy. If it is there, you have found a bug in GCC (which is somewhat unlikely). You can learn about linkers and relocations here or here.
Compile Error IcePy (Ice 3.3.1) : relocation against local symbol
I have a problem when I try to build IcePy (from Ice 3.3.1) (for python 2.4.4). Compilation, testing and install of Ice itself (cpp version) is OK but when I tried to build the python interface ("py" directory) I get the following error (sorry for the truncated paths) : .../lib/python2.4/config/libpython2.4.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC .../lib/python2.4/config/libpython2.4.a: could not read symbols: Bad value collect2: ld returned 1 exit status Is anybody able to explain me what this problem of relocation means (or at least give me a link) ? Thank you in avdance for your help. Even if you don't know anything about Ice, your comments on the error message are welcome. (of course the compilation line already contained -fPIC so the "recompile with -fPIC" does not really help me...)
[ "The abstract.o was very likely not compiled with -fPIC, so the advice linker gave you is correct.\nGo back to your build log, and verify that -fPIC is not there when libpython2.4.a was built. Note that -fPIC is needed for libpython2.4.a itself, not just for the IcePy.\nIf it is there, you have found a bug in GCC (...
[ 1 ]
[]
[]
[ "compilation", "linker", "python" ]
stackoverflow_0003364168_compilation_linker_python.txt
Q: How to make float values in Python display .00 instead of .0? Simple question, sorry I can;t figure this out. I have some numbers that are made by float(STRING) and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this? Thanks! EDIT: Python saiys that float doesn't have a cal 'format()' A: >>> '%.2f' % 2.0 '2.00' A: Also: >>> "{0:.2f}".format(2.0) '2.00' A: If you do not like the numbers to be rounded, you need to do little more: >>> "%.2f" % 1.99999 '2.00' >>> "%.2f" % (int(1.99999*100)/100.0) '1.99' A: >>> "{0:.2f}".format(2) '2.00' For more information about the {0}.format() syntax, look here: Format String Syntax
How to make float values in Python display .00 instead of .0?
Simple question, sorry I can;t figure this out. I have some numbers that are made by float(STRING) and they are displayed as xxx.0, but I want them to end in .00 if it is indeed a whole number. How would I do this? Thanks! EDIT: Python saiys that float doesn't have a cal 'format()'
[ ">>> '%.2f' % 2.0\n'2.00'\n\n", "Also:\n>>> \"{0:.2f}\".format(2.0)\n'2.00'\n\n", "If you do not like the numbers to be rounded, you need to do little more:\n>>> \"%.2f\" % 1.99999\n'2.00'\n>>> \"%.2f\" % (int(1.99999*100)/100.0)\n'1.99'\n\n", ">>> \"{0:.2f}\".format(2)\n'2.00'\n\nFor more information about...
[ 11, 2, 1, 1 ]
[]
[]
[ "double", "floating_point", "integer", "python" ]
stackoverflow_0003368514_double_floating_point_integer_python.txt
Q: Zooming With Python Image Library I'm writing a simple application in Python which displays images.I need to implement Zoom In and Zoom Out by scaling the image. I think the Image.transform method will be able to do this, but I'm not sure how to use it, since it's asking for an affine matrix or something like that :P Here's the quote from the docs: im.transform(size, AFFINE, data, filter) => image Applies an affine transform to the image, and places the result in a new image with the given size. Data is a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. This function can be used to scale, translate, rotate, and shear the original image. A: You would be much better off using the EXTENT rather than the AFFINE method. You only need to calculate two things: what part of the input you want to see, and how large it should be. For example, if you want to see the whole image scaled down to half size (i.e. zooming out by 2), you'd pass the data (0, 0, im.size[0], im.size[1]) and the size (im.size[0]/2, im.size[1]/2). A: An affine transformation applies and linear transform followed by a translation. But you should only need to resize a portion of the image using the resize method. There's some sample code in the following SO answer: Image viewer
Zooming With Python Image Library
I'm writing a simple application in Python which displays images.I need to implement Zoom In and Zoom Out by scaling the image. I think the Image.transform method will be able to do this, but I'm not sure how to use it, since it's asking for an affine matrix or something like that :P Here's the quote from the docs: im.transform(size, AFFINE, data, filter) => image Applies an affine transform to the image, and places the result in a new image with the given size. Data is a 6-tuple (a, b, c, d, e, f) which contain the first two rows from an affine transform matrix. For each pixel (x, y) in the output image, the new value is taken from a position (a x + b y + c, d x + e y + f) in the input image, rounded to nearest pixel. This function can be used to scale, translate, rotate, and shear the original image.
[ "You would be much better off using the EXTENT rather than the AFFINE method. You only need to calculate two things: what part of the input you want to see, and how large it should be. For example, if you want to see the whole image scaled down to half size (i.e. zooming out by 2), you'd pass the data (0, 0, im.siz...
[ 6, 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0003368740_image_processing_python_python_imaging_library.txt
Q: Using beautifulsoup, how to I reference table rows in html page I have a html page that looks like: <html> .. <form post="/products.hmlt" ..> .. <table ...> <tr>...</tr> <tr> <td>part info</td> .. </tr> </table> .. </form> .. </html> I tried: form = soup.findAll('form') table = form.findAll('table') # table inside form But I get an error saying: ResultSet object has no attribute 'findAll' I guess the call to findAll doesn't return a 'beautifulsoup' object? what can I do then? Update There are many tables on this page, but only 1 table INSIDE the tag shown above. A: findAll returns a list, so extract the element first: form = soup.findAll('form')[0] table = form.findAll('table')[0] # table inside form Of course, you should do some error checking (i.e. make sure it's not empty) before indexing into the list. A: I like ars's answer, and certainly agree w/ the need for error-checking; especially if this is going to be used in any kind of production code. Here's perhaps a more verbose / explicit way of finding the data you seek: from BeautifulSoup import BeautifulSoup as bs html = '''<html><body><table><tr><td>some text</td></tr></table> <form><table><tr><td>some text we care about</td></tr> <tr><td>more text we care about</td></tr> </table></form></html></body>''' soup = bs(html) for tr in soup.form.findAll('tr'): print tr.text # output: # some text we care about # more text we care about For reference here is the cleaned-up HTML: >>> print soup.prettify() <html> <body> <table> <tr> <td> some text </td> </tr> </table> <form> <table> <tr> <td> some text we care about </td> </tr> <tr> <td> more text we care about </td> </tr> </table> </form> </body> </html>
Using beautifulsoup, how to I reference table rows in html page
I have a html page that looks like: <html> .. <form post="/products.hmlt" ..> .. <table ...> <tr>...</tr> <tr> <td>part info</td> .. </tr> </table> .. </form> .. </html> I tried: form = soup.findAll('form') table = form.findAll('table') # table inside form But I get an error saying: ResultSet object has no attribute 'findAll' I guess the call to findAll doesn't return a 'beautifulsoup' object? what can I do then? Update There are many tables on this page, but only 1 table INSIDE the tag shown above.
[ "findAll returns a list, so extract the element first:\nform = soup.findAll('form')[0]\ntable = form.findAll('table')[0] # table inside form\n\nOf course, you should do some error checking (i.e. make sure it's not empty) before indexing into the list.\n", "I like ars's answer, and certainly agree w/ the need for...
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003368730_beautifulsoup_python.txt
Q: form -> table -> tr using successive findAll calls Ok so I can reference my table correctly in a html page like this: form = soup.findAll('form')[1] table = form.findAll('table', width="79%") # returns 1 table, doing a print shows table with rows tr = table.findAll('tr') I get an error: ResultSet object has no attribute findAll. Why doesn't this work? I used the output of form.findAll to get the table, and the table (using print) does indeed have table rows etc. A: As in the previous question, findAll returns a list. So, table = form.findAll('table', width='79%')[0] tr = table.findAll(...) will extract the first one. As before, check that your list isn't empty first.
form -> table -> tr using successive findAll calls
Ok so I can reference my table correctly in a html page like this: form = soup.findAll('form')[1] table = form.findAll('table', width="79%") # returns 1 table, doing a print shows table with rows tr = table.findAll('tr') I get an error: ResultSet object has no attribute findAll. Why doesn't this work? I used the output of form.findAll to get the table, and the table (using print) does indeed have table rows etc.
[ "As in the previous question, findAll returns a list.\nSo,\ntable = form.findAll('table', width='79%')[0]\ntr = table.findAll(...)\n\nwill extract the first one. As before, check that your list isn't empty first.\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003368854_beautifulsoup_python.txt
Q: Dynamic Django Application Creation Based On a SQL / CSV file Is there any django application that can create other apps merely based on a sql / csv file provided that a default template is found for the new applications. A: You can use database introspection to create models from pre-existing tables. You can divide the models up into apps and fix the odd error it seems to produce now an again. It saves a heap of time when integrating with legacy databases. python manage.py inspectdb > models.py More details: http://docs.djangoproject.com/en/1.2/howto/legacy-databases/ Apart from that I don't know of anything for CSV or SQL files and am not sure what you mean by "default template".
Dynamic Django Application Creation Based On a SQL / CSV file
Is there any django application that can create other apps merely based on a sql / csv file provided that a default template is found for the new applications.
[ "You can use database introspection to create models from pre-existing tables. You can divide the models up into apps and fix the odd error it seems to produce now an again. It saves a heap of time when integrating with legacy databases.\npython manage.py inspectdb > models.py\n\nMore details:\nhttp://docs.djangopr...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_apps", "django_models", "python" ]
stackoverflow_0003368304_django_django_admin_django_apps_django_models_python.txt
Q: how to see the content of a particular file in .tar.gz archive without unzipping the contents? for ex abc.tar.gz has abc/file1.txt abc/file2.txt abc/abc1/file3.txt abc/abc2/file4.txt i need to read/display the contents of file3.txt without extracting the file. Thanks for any input. A: import tarfile spam = tarfile.open( "abc.tar.gz" ) if "abc/abc1/file3.txt" in spam.getnames(): with spam.extractfile( "abc/abc1/file3.txt" ) as ham: print ham.read() See tarfile. A: tar -xzf mytar.tar.gz --to-command=cat filename.in.archive
how to see the content of a particular file in .tar.gz archive without unzipping the contents?
for ex abc.tar.gz has abc/file1.txt abc/file2.txt abc/abc1/file3.txt abc/abc2/file4.txt i need to read/display the contents of file3.txt without extracting the file. Thanks for any input.
[ "import tarfile\nspam = tarfile.open( \"abc.tar.gz\" )\nif \"abc/abc1/file3.txt\" in spam.getnames():\n with spam.extractfile( \"abc/abc1/file3.txt\" ) as ham:\n print ham.read()\n\nSee tarfile.\n", "tar -xzf mytar.tar.gz --to-command=cat filename.in.archive\n\n" ]
[ 11, 5 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0003369732_bash_python.txt
Q: Why python list slice assignment eats memory? I'm fighting a memory leak in a Python project and spent much time on it already. I have deduced the problem to a small example. Now seems like I know the solution, but I can't understand why. import random def main(): d = {} used_keys = [] n = 0 while True: # choose a key unique enough among used previously key = random.randint(0, 2 ** 60) d[key] = 1234 # the value doesn't matter used_keys.append(key) n += 1 if n % 1000 == 0: # clean up every 1000 iterations print 'thousand' for key in used_keys: del d[key] used_keys[:] = [] #used_keys = [] if __name__ == '__main__': main() The idea is that I store some values in the dict d and memorize used keys in a list to be able to clean the dict from time to time. This variation of the program confidently eats memory never returning it back. If I use alternative method to „clear” used_keys that is commented in the example, all is fine: memory consumption stays at constant level. Why? Tested on CPython and many linuxes. A: Here's the reason - the current method does not delete the keys from the dict (only one, actually). This is because you clear the used_keys list during the loop, and the loop exits prematurely. The 2nd (commented) method, however, does work as you assign a new value to used_keys so the loop finishes successfully. See the difference between: >>> a=[1,2,3] >>> for x in a: ... print x ... a=[] ... 1 2 3 and >>> a=[1,2,3] >>> for x in a: ... print x ... a[:] = [] ... 1 >>> A: Why wouldn't something like this work? from itertools import count import uuid def main(): d = {} for n in count(1): # choose a key unique enough among used previously key = uuid.uuid1() d[key] = 1234 # the value doesn't matter if n % 1000 == 0: # clean up every 1000 iterations print 'thousand' d.clear() if __name__ == '__main__': main()
Why python list slice assignment eats memory?
I'm fighting a memory leak in a Python project and spent much time on it already. I have deduced the problem to a small example. Now seems like I know the solution, but I can't understand why. import random def main(): d = {} used_keys = [] n = 0 while True: # choose a key unique enough among used previously key = random.randint(0, 2 ** 60) d[key] = 1234 # the value doesn't matter used_keys.append(key) n += 1 if n % 1000 == 0: # clean up every 1000 iterations print 'thousand' for key in used_keys: del d[key] used_keys[:] = [] #used_keys = [] if __name__ == '__main__': main() The idea is that I store some values in the dict d and memorize used keys in a list to be able to clean the dict from time to time. This variation of the program confidently eats memory never returning it back. If I use alternative method to „clear” used_keys that is commented in the example, all is fine: memory consumption stays at constant level. Why? Tested on CPython and many linuxes.
[ "Here's the reason - the current method does not delete the keys from the dict (only one, actually). This is because you clear the used_keys list during the loop, and the loop exits prematurely.\nThe 2nd (commented) method, however, does work as you assign a new value to used_keys so the loop finishes successfully....
[ 5, 0 ]
[]
[]
[ "memory", "memory_leaks", "memory_management", "python" ]
stackoverflow_0003369771_memory_memory_leaks_memory_management_python.txt
Q: When is using __call__ a good idea? What are peoples' opinions on using the __call__. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour. A: I think your intuition is about right. Historically, callable objects (or what I've sometimes heard called "functors") have been used in the OO world to simulate closures. In C++ they're frequently indispensable. However, __call__ has quite a bit of competition in the Python world: A regular named method, whose behavior can sometimes be a lot more easily deduced from the name. Can convert to a bound method, which can be called like a function. A closure, obtained by returning a function that's defined in a nested block. A lambda, which is a limited but quick way of making a closure. Generators and coroutines, whose bodies hold accumulated state much like a functor can. I'd say the time to use __call__ is when you're not better served by one of the options above. Check the following criteria, perhaps: Your object has state. There is a clear "primary" behavior for your class that's kind of silly to name. E.g. if you find yourself writing run() or doStuff() or go() or the ever-popular and ever-redundant doRun(), you may have a candidate. Your object has state that exceeds what would be expected of a generator function. Your object wraps, emulates, or abstracts the concept of a function. Your object has other auxilliary methods that conceptually belong with your primary behavior. One example I like is UI command objects. Designed so that their primary task is to execute the comnand, but with extra methods to control their display as a menu item, for example, this seems to me to be the sort of thing you'd still want a callable object for. A: Use it if you need your objects to be callable, that's what it's there for I'm not sure what you mean by default behaviour One place I have found it particularly useful is when using a wrapper or somesuch where the object is called deep inside some framework/library. A: More generally, Python has a lot of double-underscore methods. They're there for a reason: they are the Python way of overloading operators. For instance, if you want a new class in which addition, I don't know, prints "foo", you define the __add__ and __radd__ methods. There's nothing inherently good or bad about this, any more than there's anything good or bad about using for loops. In fact, using __call__ is often the more Pythonic approach, because it encourages clarity of code. You could replace MyCalculator.calculateValues( foo ) with MyCalculator( foo ), say. A: Its usually used when class is used as function with some instance context, like some DecoratorClass which would be used as @DecoratorClass('some param'), so 'some param' would be stored in the instance's namespace and then instance being called as actual decorator. It is not very useful when your class provides some different methods, since its usually not obvious what would the call do, and explicit is better than implicit in these cases.
When is using __call__ a good idea?
What are peoples' opinions on using the __call__. I've only very rarely seen it used, but I think it's a very handy tool to use when you know that a class is going to be used for some default behaviour.
[ "I think your intuition is about right.\nHistorically, callable objects (or what I've sometimes heard called \"functors\") have been used in the OO world to simulate closures. In C++ they're frequently indispensable.\nHowever, __call__ has quite a bit of competition in the Python world:\n\nA regular named method, w...
[ 37, 3, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003369640_oop_python.txt
Q: Why < is slower than >= I am using the following code to do the test and it seems like < is slower that >=., does anyone know why? import timeit s = """ x=5 if x<0: pass """ t = timeit.Timer(stmt=s) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) #0.21 usec/pass z = """ x=5 if x>=0: pass """ t2 = timeit.Timer(stmt=z) print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000) #0.18 usec/pass A: In Python 3.1.2, sometime < is faster than >=. I try to read it in disassembler, import dis def f1(): x=5 if x < 0: pass def f2(): x = 5 if x >=0: pass >>> dis.dis(f1) 2 0 LOAD_CONST 1 (5) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 (0) 12 COMPARE_OP 0 (<) 15 POP_JUMP_IF_FALSE 21 18 JUMP_FORWARD 0 (to 21) >> 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> dis.dis(f2) 2 0 LOAD_CONST 1 (5) 3 STORE_FAST 0 (x) 3 6 LOAD_FAST 0 (x) 9 LOAD_CONST 2 (0) 12 COMPARE_OP 5 (>=) 15 POP_JUMP_IF_FALSE 21 18 JUMP_FORWARD 0 (to 21) >> 21 LOAD_CONST 0 (None) 24 RETURN_VALUE Code is almost identical, but f1 is always run line 15 and jump to 21, f2 is always run 15 -> 18 -> 21, so that performance should be affected by true/false in if statement rather than < or >= problem. A: Your first test evaluates to true, the second to false. Perhaps there's marginally different processing as a result. A: The COMPARE_OP opcode contains an optimisation for the case where both operands are integers compatible with C and in that case it just does the comparison inline with a switch statement on the type of comparison: if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) { /* INLINE: cmp(int, int) */ register long a, b; register int res; a = PyInt_AS_LONG(v); b = PyInt_AS_LONG(w); switch (oparg) { case PyCmp_LT: res = a < b; break; case PyCmp_LE: res = a <= b; break; case PyCmp_EQ: res = a == b; break; case PyCmp_NE: res = a != b; break; case PyCmp_GT: res = a > b; break; case PyCmp_GE: res = a >= b; break; case PyCmp_IS: res = v == w; break; case PyCmp_IS_NOT: res = v != w; break; default: goto slow_compare; } x = res ? Py_True : Py_False; Py_INCREF(x); } So the only variations you can have in the comparison are the route through the switch statement and whether the result is True or False. My guess would be that you are just seeing variations due to the CPU's execution path (and maybe branch prediction), so the effect you are seeing could just as easily disappear or be the other way round in other versions of Python. A: I've just tried it in Python 3.1.2 - no difference there. EDIT: After many tries with a higher number of repeats, I'm seeing wildly varying values by a factor of 3 for both versions: >>> import timeit >>> s = """x=5 ... if x<0: pass""" >>> t = timeit.Timer(stmt=s) >>> print ("%.2f usec/pass" % (1000000 * t.timeit(number=1000000)/100000)) 1.48 usec/pass >>> >>> z = """x=5 ... if x>=0: pass""" >>> t2 = timeit.Timer(stmt=z) >>> print ("%.2f usec/pass" % (1000000 * t.timeit(number=1000000)/100000)) 0.59 usec/pass >>> >>> import timeit >>> s = """x=5 ... if x<0: pass""" >>> t = timeit.Timer(stmt=s) >>> print ("%.2f usec/pass" % (1000000 * t.timeit(number=1000000)/100000)) 0.57 usec/pass >>> >>> z = """x=5 ... if x>=0: pass""" >>> t2 = timeit.Timer(stmt=z) >>> print ("%.2f usec/pass" % (1000000 * t.timeit(number=1000000)/100000)) 1.47 usec/pass So I guess that scheduling conflicts with other processes are the main variable here. A: There appears to be some inherent overhead in 'timeit' for certain activations of it (unexpectedly enough). Try - import timeit Times = 30000000 s = """ x=5 if x>=0: pass """ t1 = timeit.Timer( stmt=s ) t2 = timeit.Timer( stmt=s ) t3 = timeit.Timer( stmt=s ) print t1.timeit( number=Times ) print t2.timeit( number=Times ) print t3.timeit( number=Times ) print t1.timeit( number=Times ) print t2.timeit( number=Times ) print t3.timeit( number=Times ) print t1.timeit( number=Times ) print t2.timeit( number=Times ) print t3.timeit( number=Times ) print t1.timeit( number=Times ) print t2.timeit( number=Times ) print t3.timeit( number=Times ) On my machine the output is (consistently, and regardless of how many loops I try - so it probably doesn't just happen to coincide with something else happening on the machine) - 1.96510925271 1.84014169399 1.84004224001 1.97851123537 1.86845451028 1.83624929984 1.94599509155 1.85690220405 1.8338135154 1.98382475985 1.86861430713 1.86006657271 't1' always takes longer. But if you try to reorder the calls or object creation, things behave differently (and not in a pattern I could easily explain). This isn't an answer to your question, just an observation that measuring in this way may have inherent inaccuracies. A: Interesting! the result is more emphasised if you simplify the expression using IPython I see that x<=0 takes 150ns and x<0 takes 320ns - over twice as long other comparisons x>0 and x>=0 seem to take around 300ns too even over 1000000 loops the results fluctuate quite a lot though A: This was a rather intriguing question. I removed the if cond: pass by using v=cond instead, but it did not eliminate the difference entirely. I am still not certain of the answer, but I found one plausible reason: switch (op) { case Py_LT: c = c < 0; break; case Py_LE: c = c <= 0; break; case Py_EQ: c = c == 0; break; case Py_NE: c = c != 0; break; case Py_GT: c = c > 0; break; case Py_GE: c = c >= 0; break; } This is from Objects/object.c funcion convert_3way_to_object. Note that >= is the last branch; that means it, alone, needs no exit jump. That break statement is eliminated. It matches up with the 0 and 5 in shiki's disassembly. Being an unconditional break, it may be handled by branch prediction, but it may also result in less code to load. At this level, the difference is naturally going to be highly machine specific. My measurements aren't very thorough, but this was the one point at C level I saw a bias between the operators. I probably got a larger bias from CPU speed scaling.
Why < is slower than >=
I am using the following code to do the test and it seems like < is slower that >=., does anyone know why? import timeit s = """ x=5 if x<0: pass """ t = timeit.Timer(stmt=s) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) #0.21 usec/pass z = """ x=5 if x>=0: pass """ t2 = timeit.Timer(stmt=z) print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000) #0.18 usec/pass
[ "In Python 3.1.2, sometime < is faster than >=. I try to read it in disassembler,\nimport dis\ndef f1():\n x=5\n if x < 0: pass\n\ndef f2():\n x = 5\n if x >=0: pass\n\n>>> dis.dis(f1)\n 2 0 LOAD_CONST 1 (5) \n 3 STORE_FAST 0 (x) \n\n 3 6 LO...
[ 32, 5, 5, 2, 2, 1, 1 ]
[]
[]
[ "optimization", "performance", "python" ]
stackoverflow_0003369304_optimization_performance_python.txt
Q: Annotate a django query via a reverse relationship I have two models Property and Image, related by foreign key such that each Property has multiple instances of Image. I'm trying to retrieve a queryset of all the properties - listing all fields - and the number of images that each property has. I am aware that I could do this as two distinct queries, but I don't feel that this is a particularly elegant approach, and is proving a little inefficient as this information is being retrieved via XMLHttpRequest. The models are defined as follows: class Property(models.Model): title = models.CharField('title', max_length=255) created = models.DateTimeField('created', auto_now_add=True) modified = models.DateTimeField('modified', auto_now=True) class Meta: pass class Image(models.Model): prop_id = models.ForeignKey(Property) image_file = models.ImageField('image file', upload_to='/path/to/image/') class Meta: pass I have followed the answer posted here: Django Aggregation Across Reverse Relationship, as I believe this was a similar problem, but I've found that this returns an empty queryset. Thanks for any help anyone can offer. EDIT: The query I ran was: Property.objects.all().annotate(image_count=Count('image')).order_by('-image_count') EDIT 2: After some experimentation, I have found a solution, though I'm pretty sure that this qualifies as a bug / non-documented issue: Property.objects.all().annotate(Count('image')).order_by('-image__count') Property.objects.all().annotate(total_images=Count('image')).order_by('-total_images') These both work, but naming the annotation image_count did not. Without delving into the Django source, I can't really speculate as to why that's happening. A: The code you've posted should work - in any case, it should not return an empty queryset as annotate doesn't affect the filtering of the main query. Silly question, but are you sure there are Property elements in the database?
Annotate a django query via a reverse relationship
I have two models Property and Image, related by foreign key such that each Property has multiple instances of Image. I'm trying to retrieve a queryset of all the properties - listing all fields - and the number of images that each property has. I am aware that I could do this as two distinct queries, but I don't feel that this is a particularly elegant approach, and is proving a little inefficient as this information is being retrieved via XMLHttpRequest. The models are defined as follows: class Property(models.Model): title = models.CharField('title', max_length=255) created = models.DateTimeField('created', auto_now_add=True) modified = models.DateTimeField('modified', auto_now=True) class Meta: pass class Image(models.Model): prop_id = models.ForeignKey(Property) image_file = models.ImageField('image file', upload_to='/path/to/image/') class Meta: pass I have followed the answer posted here: Django Aggregation Across Reverse Relationship, as I believe this was a similar problem, but I've found that this returns an empty queryset. Thanks for any help anyone can offer. EDIT: The query I ran was: Property.objects.all().annotate(image_count=Count('image')).order_by('-image_count') EDIT 2: After some experimentation, I have found a solution, though I'm pretty sure that this qualifies as a bug / non-documented issue: Property.objects.all().annotate(Count('image')).order_by('-image__count') Property.objects.all().annotate(total_images=Count('image')).order_by('-total_images') These both work, but naming the annotation image_count did not. Without delving into the Django source, I can't really speculate as to why that's happening.
[ "The code you've posted should work - in any case, it should not return an empty queryset as annotate doesn't affect the filtering of the main query.\nSilly question, but are you sure there are Property elements in the database?\n" ]
[ 6 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0003369904_django_django_queryset_python.txt
Q: "post" method to communicate directly with a server Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it raises HTTP Error 404 which means page not found. Here's my code, please help me find what's wrong: import urllib2 import urllib url='http://localhost/wp-comments-post.php' user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values={'author':'Urllib Test', 'email':'test@test.com', 'url':'', 'comment':'This is a test comment from python', 'submit':'Post Comment', 'comment_post_ID': '1', 'comment_parent':'0'} headers={'User-Agent': user_agent} data=urllib.urlencode(values) req=urllib2.Request(url, data, headers) urllib2.urlopen(req) A: why is there a 'url' in your values ? did you try without it ? then, try replacing localhost with 127.0.0.1 (if localhost is not in your hosts file). Are you on windows or linux ? A: I recommend you to use Mechanize. It will simplify your life.
"post" method to communicate directly with a server
Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it raises HTTP Error 404 which means page not found. Here's my code, please help me find what's wrong: import urllib2 import urllib url='http://localhost/wp-comments-post.php' user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values={'author':'Urllib Test', 'email':'test@test.com', 'url':'', 'comment':'This is a test comment from python', 'submit':'Post Comment', 'comment_post_ID': '1', 'comment_parent':'0'} headers={'User-Agent': user_agent} data=urllib.urlencode(values) req=urllib2.Request(url, data, headers) urllib2.urlopen(req)
[ "why is there a 'url' in your values ? did you try without it ?\nthen, try replacing localhost with 127.0.0.1 (if localhost is not in your hosts file). \nAre you on windows or linux ?\n", "I recommend you to use Mechanize. It will simplify your life.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "urllib", "urllib2", "wordpress" ]
stackoverflow_0003362399_python_urllib_urllib2_wordpress.txt
Q: basic questions about "import" I have some questions about Python's import statement: What is the difference between import <module> and from <module> import *? How can I import a module that is not in the same directory? (and not in PythonHome) Please consider I am a Python newbie A: import imports the module into the global namespace. from import imports the named items into the namespace. So with a plain import you always have to reference the module: >>> import datetime >>> day = datetime.date.today() But with an from import you can reference the items directly: >>> from datetime import date >>> day = date.today() If you use from somemodule import * it will import everything from the module into your namespace. While this might seem convenient it's best not to do this. It's frowned upon as it's harder to tell which things have come from the module when reading the code and there's a possibility of collisions between names you use and names you have inadvertently imported from the module. The easiest way to import a module from a different directory is to add that directory to your PYTHONPATH. A: http://docs.python.org/tutorial/modules.html http://effbot.org/zone/import-confusion.htm How to do relative imports in Python? Don't do from spam import *.
basic questions about "import"
I have some questions about Python's import statement: What is the difference between import <module> and from <module> import *? How can I import a module that is not in the same directory? (and not in PythonHome) Please consider I am a Python newbie
[ "import imports the module into the global namespace. from import imports the named items into the namespace.\nSo with a plain import you always have to reference the module:\n>>> import datetime\n>>> day = datetime.date.today()\n\nBut with an from import you can reference the items directly:\n>>> from datetime im...
[ 6, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003370726_import_python.txt
Q: python error when I use different systems! When I use my system, there is no error in my python codes. When I use another system I get this error:(both systems have same version of python) /usr/lib/pymodules/python2.6/matplotlib/numerix/__init__.py:18: DeprecationWarning: ********************************************************** matplotlib.numerix and all its subpackages are deprecated. They will be removed soon. Please use numpy instead. ********************************************************** warnings.warn(msg, DeprecationWarning) /usr/lib/pymodules/python2.6/networkx/generators/hybrid.py:16: DeprecationWarning: the sets module is deprecated import sets Traceback (most recent call last): File "./check_2.py", line 79, in <module> G.add_edge(u,v,times=[t]) TypeError: add_edge() got an unexpected keyword argument 'times' A: There's a hint. matplotlib.numerix and all its subpackages are deprecated. They will be removed soon. Please use numpy instead. The system that gets this error has old packages installed. While the "version of python" may be the same, the set of installed packages is different.
python error when I use different systems!
When I use my system, there is no error in my python codes. When I use another system I get this error:(both systems have same version of python) /usr/lib/pymodules/python2.6/matplotlib/numerix/__init__.py:18: DeprecationWarning: ********************************************************** matplotlib.numerix and all its subpackages are deprecated. They will be removed soon. Please use numpy instead. ********************************************************** warnings.warn(msg, DeprecationWarning) /usr/lib/pymodules/python2.6/networkx/generators/hybrid.py:16: DeprecationWarning: the sets module is deprecated import sets Traceback (most recent call last): File "./check_2.py", line 79, in <module> G.add_edge(u,v,times=[t]) TypeError: add_edge() got an unexpected keyword argument 'times'
[ "There's a hint.\nmatplotlib.numerix and all its subpackages are deprecated.\nThey will be removed soon. Please use numpy instead.\n\nThe system that gets this error has old packages installed.\nWhile the \"version of python\" may be the same, the set of installed packages is different.\n" ]
[ 4 ]
[]
[]
[ "deprecated", "python", "version" ]
stackoverflow_0003370908_deprecated_python_version.txt
Q: How to store Python 2.6 value in regedit What information about Python 2.6 stored in the Windows registry, under HKEY_LOCAL_MACHINE/SOFTWARE? Where is it stored? Somehow I lost it in my regedit and can't install a module. I googled it, but I can't find any answer, and I don't have an extra computer to try and many modules that I need for my school project is installed inside, so I don't want to take the risk to uninstall. A: Ohh, I found the solution by repairing the Python 2.6 installation.
How to store Python 2.6 value in regedit
What information about Python 2.6 stored in the Windows registry, under HKEY_LOCAL_MACHINE/SOFTWARE? Where is it stored? Somehow I lost it in my regedit and can't install a module. I googled it, but I can't find any answer, and I don't have an extra computer to try and many modules that I need for my school project is installed inside, so I don't want to take the risk to uninstall.
[ "Ohh, I found the solution by repairing the Python 2.6 installation.\n" ]
[ 1 ]
[]
[]
[ "python", "window" ]
stackoverflow_0003371008_python_window.txt
Q: how to send variable to javascript? I am sending a tuple as my variable to javascript. But i could not find a way. I am using bottle framework. A: Encode it into JSON. It'll convert to a javascript array. A: A related tip to add to @Oil's point, Bottle returns JSON by default of you return a dict: @route('/resource.json') def resource_json(): response = dict( data=('tuple', 'of', 'things')) return response See http://bottle.paws.de/page/docs#output-casting
how to send variable to javascript?
I am sending a tuple as my variable to javascript. But i could not find a way. I am using bottle framework.
[ "Encode it into JSON. It'll convert to a javascript array.\n", "A related tip to add to @Oil's point, Bottle returns JSON by default of you return a dict:\n@route('/resource.json')\ndef resource_json():\n response = dict(\n data=('tuple', 'of', 'things'))\nreturn response\n\nSee http://bottle.paws.de/pa...
[ 2, 2 ]
[]
[]
[ "bottle", "javascript", "python" ]
stackoverflow_0003370996_bottle_javascript_python.txt
Q: Assign multiple tags to one entry I have this simple model: class Tag(models.Model): title = models.SlugField() created = models.datetime def __unicode__(self): return self.title class Entry(models.Model): title = models.CharField(max_length=30) created = models.datetime tags = models.ForeignKey(Tag) categories = models.CharField(max_length=15) def __unicode__(self): return self.title class Meta: verbose_name_plural = "Entries" I need to be able to attach multiple tags to the entry so that it could be saved to the database. How can I do that? Now there is only one tag assigned. A: As one tag can have many entries and vice versa, you will want to add a ManyToMany field. A: I would create another class in the Model to support this. class tagEntryJoins(models.Model): tag = models.ForeignKey('Tag') entry = models.ForeignKey('entry')
Assign multiple tags to one entry
I have this simple model: class Tag(models.Model): title = models.SlugField() created = models.datetime def __unicode__(self): return self.title class Entry(models.Model): title = models.CharField(max_length=30) created = models.datetime tags = models.ForeignKey(Tag) categories = models.CharField(max_length=15) def __unicode__(self): return self.title class Meta: verbose_name_plural = "Entries" I need to be able to attach multiple tags to the entry so that it could be saved to the database. How can I do that? Now there is only one tag assigned.
[ "As one tag can have many entries and vice versa, you will want to add a ManyToMany field.\n", "I would create another class in the Model to support this. \nclass tagEntryJoins(models.Model): \n tag = models.ForeignKey('Tag')\n entry = models.ForeignKey('entry') \n\n" ]
[ 4, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003371164_django_django_models_python.txt
Q: How to add audio to video? I record a video with no sound. I save a snapshots and then I compile them to .avi with 25FPS. Now I want to record audio (instead time.sleep(0.04) between following snapshots I will record audio in this time) and compile it wits video. Now I have avi file, and wave file, and I find a solution to mix them. Python, Win32 It is my "video recorder" which use 'mencoder': import os import re from VideoCapture import * import time def makeVideo(device, ftime): folder = 'foto/forVideo/' mencoder = "C:\mencoder.exe" for i in range(ftime * 25) : FN = "foto\\forVideo\\ola-%(#)04d.jpg" % {"#" : i} device.saveSnapshot(FN, quality=100, timestamp=0, boldfont=0) time.sleep(0.04) # Set up regular expressions for later RE = re.compile('.*-(\d*)\.jpg') fbRE = re.compile('(.*)-.*\.jpg') # How many frames to use per movie framestep = 2000 print '\n\n\tlisting contents of %s . . .'%folder files = os.listdir(folder) print '%s files found.\n\n' % len(files) # If a file is called "asdf-003.jpg", the basename will be 'asdf'. basenames = [fbRE.match(i).groups()[0] for i in files if fbRE.match(i)] # Get the set of unique basenames. In the basenames = list(set(basenames)) print '\t***There are %s different runs here.***' % len(basenames) # This loop will only execute once if there was only a single experiment # in the folder. for j,bn in enumerate(basenames): these_files = [i for i in files if bn in i] # Sort using the "decorate-sort-undecorate" approach these_sorted_files = [(int(RE.match(i).groups()[0]),i) for i in these_files if RE.match(i)] these_sorted_files.sort() these_sorted_files = [i[1] for i in these_sorted_files] # these_sorted_files is now a list of the filenames a_001.jpg, a_002.jpg, etc. for k in range(0, len(these_sorted_files), framestep): frame1 = k frame2 = k+framestep this_output_name = 'C:\_%s_%s_%s-%s.avi' % (bn,j,frame1,frame2) print '\n\n\toutput will be %s.' % this_output_name f = open('temp.txt','w') filenames = [os.path.join(folder,i)+'\n' \ for i in these_sorted_files[frame1:frame2]] f.writelines(filenames) f.close() # Finally! Now execute the command to create the video. cmd = '%s "mf://@temp.txt" -mf fps=25 -o %s -ovc lavc\ -lavcopts vcodec=mpeg4' % (mencoder,this_output_name) os.system(cmd) print '\n\nDONE with %s' % this_output_name print 'Done with all marked folders.' A: I think the best bet would be to use an external program to mux them. ffmpeg is a perennial favorite -- quality Windows builds are available at http://ffmpeg.arrozcru.org/autobuilds/ . With ffmpeg, just do ffmpeg -i your_video_file.avi -i your_audio_file.wav -vcodec copy -acodec copy muxed_file.avi and you're done.
How to add audio to video?
I record a video with no sound. I save a snapshots and then I compile them to .avi with 25FPS. Now I want to record audio (instead time.sleep(0.04) between following snapshots I will record audio in this time) and compile it wits video. Now I have avi file, and wave file, and I find a solution to mix them. Python, Win32 It is my "video recorder" which use 'mencoder': import os import re from VideoCapture import * import time def makeVideo(device, ftime): folder = 'foto/forVideo/' mencoder = "C:\mencoder.exe" for i in range(ftime * 25) : FN = "foto\\forVideo\\ola-%(#)04d.jpg" % {"#" : i} device.saveSnapshot(FN, quality=100, timestamp=0, boldfont=0) time.sleep(0.04) # Set up regular expressions for later RE = re.compile('.*-(\d*)\.jpg') fbRE = re.compile('(.*)-.*\.jpg') # How many frames to use per movie framestep = 2000 print '\n\n\tlisting contents of %s . . .'%folder files = os.listdir(folder) print '%s files found.\n\n' % len(files) # If a file is called "asdf-003.jpg", the basename will be 'asdf'. basenames = [fbRE.match(i).groups()[0] for i in files if fbRE.match(i)] # Get the set of unique basenames. In the basenames = list(set(basenames)) print '\t***There are %s different runs here.***' % len(basenames) # This loop will only execute once if there was only a single experiment # in the folder. for j,bn in enumerate(basenames): these_files = [i for i in files if bn in i] # Sort using the "decorate-sort-undecorate" approach these_sorted_files = [(int(RE.match(i).groups()[0]),i) for i in these_files if RE.match(i)] these_sorted_files.sort() these_sorted_files = [i[1] for i in these_sorted_files] # these_sorted_files is now a list of the filenames a_001.jpg, a_002.jpg, etc. for k in range(0, len(these_sorted_files), framestep): frame1 = k frame2 = k+framestep this_output_name = 'C:\_%s_%s_%s-%s.avi' % (bn,j,frame1,frame2) print '\n\n\toutput will be %s.' % this_output_name f = open('temp.txt','w') filenames = [os.path.join(folder,i)+'\n' \ for i in these_sorted_files[frame1:frame2]] f.writelines(filenames) f.close() # Finally! Now execute the command to create the video. cmd = '%s "mf://@temp.txt" -mf fps=25 -o %s -ovc lavc\ -lavcopts vcodec=mpeg4' % (mencoder,this_output_name) os.system(cmd) print '\n\nDONE with %s' % this_output_name print 'Done with all marked folders.'
[ "I think the best bet would be to use an external program to mux them. ffmpeg is a perennial favorite -- quality Windows builds are available at http://ffmpeg.arrozcru.org/autobuilds/ . With ffmpeg, just do ffmpeg -i your_video_file.avi -i your_audio_file.wav -vcodec copy -acodec copy muxed_file.avi and you're done...
[ 3 ]
[]
[]
[ "audio", "python", "video" ]
stackoverflow_0003371407_audio_python_video.txt