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: Mysterious logging.basicConfig problem (Python) I'm writing a Python script to retrieve data from Flickr. For logging purposes, I have the following setup function: def init_log(logfile): format = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(filename=logfile,level=logging.DEBUG,format=fo...
Mysterious logging.basicConfig problem (Python)
I'm writing a Python script to retrieve data from Flickr. For logging purposes, I have the following setup function: def init_log(logfile): format = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(filename=logfile,level=logging.DEBUG,format=format) I've tested this using the python shell and it...
[ "The logging.basicConfig function only does anything if the root logger has no handlers configured. If called when there are already some handlers attached to the root, it's basically a no-op (as is documented).\nPossibly the Python Flickr API does some logging, in which case you may find that basicConfig should be...
[ 6 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002833186_logging_python.txt
Q: Parsing specific numeric data from csv file using python Good morning. I have series of data in cvs file like below, 1,,, 1,137.1,1198,1.6 2,159,300,0.4 3,176,253,0.3 4,197,231,0.3 5,198,525,0.7 6,199,326,0.4 7,215,183,0.2 8,217.1,178,0.2 9,244.2,416,0.5 10,245.1,316,0.4 I want to extract specific data from seco...
Parsing specific numeric data from csv file using python
Good morning. I have series of data in cvs file like below, 1,,, 1,137.1,1198,1.6 2,159,300,0.4 3,176,253,0.3 4,197,231,0.3 5,198,525,0.7 6,199,326,0.4 7,215,183,0.2 8,217.1,178,0.2 9,244.2,416,0.5 10,245.1,316,0.4 I want to extract specific data from second column for example 217.1 and 245.1 and have them concatenat...
[ "results = []\nreader = csv.reader(open('file.csv'))\nfor line in reader: # iterate over the lines in the csv\n if line[1] in ['217.1','245.1']: # check if the 2nd element is one you're looking for\n results.append(line) # if so, add this line the the results list\n\nor if you want to convert to numb...
[ 2, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002832944_csv_python.txt
Q: Calculating probability that a string has been randomized? - Python this is correlated to a question I asked earlier (question) I have a list of manually created strings such as: lucy87 gordan_king fancy_unicorn77 joplucky_kanga90 base_belong_to_narwhals and a list of randomized strings: johnkdf pancake90kgjd f...
Calculating probability that a string has been randomized? - Python
this is correlated to a question I asked earlier (question) I have a list of manually created strings such as: lucy87 gordan_king fancy_unicorn77 joplucky_kanga90 base_belong_to_narwhals and a list of randomized strings: johnkdf pancake90kgjd fancy_jagookfk manhattanljg What gives away that the last set of strings...
[ "This is just a thought. I've never tried it myself...\nBuild a bloom filter from hashing every (overlapping) 4-letter sequence found in a dictionary. Test a string by counting how many 4-letter sequences in the string don't hit the filter. The more misses, the more likely it is that the word contains random junk.\...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "pattern_recognition", "python", "spam_prevention", "string" ]
stackoverflow_0002833531_pattern_recognition_python_spam_prevention_string.txt
Q: Can't overload python socket.send As we can see, send method is not overloaded. from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.senda...
Can't overload python socket.send
As we can see, send method is not overloaded. from socket import socket class PolySocket(socket): def __init__(self,*p): print "PolySocket init" socket.__init__(self,*p) def sendall(self,*p): print "PolySocket sendall" return socket.sendall(self,*p) def send(self,*p): ...
[ "I am sure you don't actually need it and there are other ways to solve your task (not subclassing but the real task).\nIf you really need to mock object, go with proxy object:\nfrom socket import socket\n\n\nclass PolySocket(object):\n def __init__(self, *p):\n print \"PolySocket init\"\n self._so...
[ 9 ]
[]
[]
[ "inheritance", "overloading", "python" ]
stackoverflow_0002833022_inheritance_overloading_python.txt
Q: Data munging and data import scripting I need to write some scripts to carry out some tasks on my server (running Ubuntu server 8.04 TLS). The tasks are to be run periodically, so I will be running the scripts as cron jobs. I have divided the tasks into "group A" and "group B" - because (in my mind at least), they...
Data munging and data import scripting
I need to write some scripts to carry out some tasks on my server (running Ubuntu server 8.04 TLS). The tasks are to be run periodically, so I will be running the scripts as cron jobs. I have divided the tasks into "group A" and "group B" - because (in my mind at least), they are a bit different. Task Group A import d...
[ "Well, I was you a few years back. Didn't like Perl at all and would re-write\nany scripts my peers wrote in Perl back to Python - because I could not stand Perl.\nLong story short - let's just say I am fairly conversant with Perl now.\nI would recommend a book called \"Impatient Perl\" which explains the really i...
[ 4, 3, 1 ]
[]
[]
[ "data_munging", "perl", "php", "python", "shell" ]
stackoverflow_0002833312_data_munging_perl_php_python_shell.txt
Q: Sending HTTP requests from App Engine Is it possible to send HTTP requests from my AppEngine application? I need to make some requests and pull some data from the other sites. A: Yes. More info here: http://code.google.com/appengine/docs/python/urlfetch/overview.html You can use the Python standard librarie...
Sending HTTP requests from App Engine
Is it possible to send HTTP requests from my AppEngine application? I need to make some requests and pull some data from the other sites.
[ "Yes. More info here: http://code.google.com/appengine/docs/python/urlfetch/overview.html\n\nYou can use the Python standard\n libraries urllib, urllib2 or httplib\n to make HTTP requests. When running in\n App Engine, these libraries perform\n HTTP requests using App Engine's URL\n fetch service, which runs...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002834687_google_app_engine_python.txt
Q: Trouble with encoding and urllib I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8' 1 pageData = unicode(requestHandler.read()).decode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128) 2 pageData = requestHandler.re...
Trouble with encoding and urllib
I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8' 1 pageData = unicode(requestHandler.read()).decode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128) 2 pageData = requestHandler.read() soupHandler = BeautifulSoup(pageD...
[ "In your first snippet, the call unicode(requestHandler.read()) tells Python to convert the bytestring returned by read into unicode: since no code is specified for the conversion, ascii gets tried (and fails). It never gets to the point where you're going to call .decode (which would make no sense to call on that...
[ 2, 1 ]
[]
[]
[ "encoding", "python", "urllib" ]
stackoverflow_0002834714_encoding_python_urllib.txt
Q: Python's behavior for rich comparison (Or, when Decimal('100.0') < .01) So I have a one liner: import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) All it does is make a Decimal object holding 100.0, and compares it to .01 (the float) in various ways. My result is: >>> im...
Python's behavior for rich comparison (Or, when Decimal('100.0') < .01)
So I have a one liner: import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01), h.__lt__(.01)) All it does is make a Decimal object holding 100.0, and compares it to .01 (the float) in various ways. My result is: >>> import decimal; h = decimal.Decimal('100.0'); (h > .01, h < .01, h.__gt__(.01),...
[ "\nWhen a rich comparison method returns\n NotImplemented, what happens? Why\n doesn't it raise an Exception?\n\nit delegates to the converse method (e.g., __lt__ when the operator is >) RHS in the comparison (the float) -- which in this case also returns NotImplemented -- and finally falls back to Python 2's sil...
[ 6, 0 ]
[]
[]
[ "compare", "decimal", "floating_point", "python" ]
stackoverflow_0002834953_compare_decimal_floating_point_python.txt
Q: Python - problem in importing new module - libgmail I downloaded Python module libgmail from sourceforge and extracted all the files in the archive. The archive had setup.py, so I went to that directory in command prompt and did setup.py install I am getting the following error message I:\libgmail-0.1.11>setup.p...
Python - problem in importing new module - libgmail
I downloaded Python module libgmail from sourceforge and extracted all the files in the archive. The archive had setup.py, so I went to that directory in command prompt and did setup.py install I am getting the following error message I:\libgmail-0.1.11>setup.py install Traceback (most recent call last): File "I:\l...
[ "I think this lib depends on this one:\nhttp://wwwsearch.sourceforge.net/mechanize/\nTry installing it first.\n", "You need to download and install the module called mechanize. Depending on your operating system (ie. Linux), your package manager probably has something for this, otherwise you will need to google i...
[ 4, 2, 0 ]
[]
[]
[ "importerror", "libgmail", "python", "python_module" ]
stackoverflow_0002834143_importerror_libgmail_python_python_module.txt
Q: lxml unicode entity parse problems I'm using lxml as follows to parse an exported XML file from another system: xmldoc = open(filename) etree.parse(xmldoc) But im getting: lxml.etree.XMLSyntaxError: Entity 'eacute' not defined, line 4495, column 46 Obviously it's having problems with unicode entity names ...
lxml unicode entity parse problems
I'm using lxml as follows to parse an exported XML file from another system: xmldoc = open(filename) etree.parse(xmldoc) But im getting: lxml.etree.XMLSyntaxError: Entity 'eacute' not defined, line 4495, column 46 Obviously it's having problems with unicode entity names - but how would i get round this? Via op...
[ "eacute is not a predefined entity in XML. To include an &eacute; entity reference in an XML file, it must have a <!DOCTYPE> declaration pointing to a DTD (such as an XHTML 1.0 DTD) that defines the entity.\nIf the XML uses &eacute; but doesn't have a <!DOCTYPE>, it is not well-formed and the system that exported i...
[ 6 ]
[]
[]
[ "lxml", "python", "unicode", "xml" ]
stackoverflow_0002835077_lxml_python_unicode_xml.txt
Q: Reset selection of wx.lib.calendar.Calendar control? I have a wx.lib.calendar.Calendar control (not wx.lib.calendar.CalendarCtrl!). I am selecting a number of days using the following function call: self.cal.AddSelect([days], 'green', 'white') This works, and draws the days highlighted. However, I cannot work out...
Reset selection of wx.lib.calendar.Calendar control?
I have a wx.lib.calendar.Calendar control (not wx.lib.calendar.CalendarCtrl!). I am selecting a number of days using the following function call: self.cal.AddSelect([days], 'green', 'white') This works, and draws the days highlighted. However, I cannot work out how to reverse this (i.e., clear the selection so the day...
[ "Couldn't you just do it manually?\nself.cal.AddSelect([days], 'black', 'white')\n\n" ]
[ 0 ]
[]
[]
[ "calendar", "python", "wxpython", "wxwidgets" ]
stackoverflow_0002834770_calendar_python_wxpython_wxwidgets.txt
Q: IDN aware tools to encode/decode human readable IRI to/from valid URI Let's assume a user enter address of some resource and we need to translate it to: <a href="valid URI here">human readable form</a> HTML4 specification refers to RFC 3986 which allows only ASCII alphanumeric characters and dash in host part an...
IDN aware tools to encode/decode human readable IRI to/from valid URI
Let's assume a user enter address of some resource and we need to translate it to: <a href="valid URI here">human readable form</a> HTML4 specification refers to RFC 3986 which allows only ASCII alphanumeric characters and dash in host part and all non-ASCII character in other parts should be percent-encoded. That's ...
[ "If I understand you correctly, then you can use the batteries included in Python:\n# -*- coding: utf-8 -*-\n\nimport urllib\nimport urlparse\n\nURL1 = u'http://сайт.рф/путь?запрос'\nURL2 = 'http://%D1%81%D0%B0%D0%B9%D1%82.%D1%80%D1%84/'\n\ndef to_idn(url):\n parts = list(urlparse.urlparse(url))\n parts[1] = ...
[ 2 ]
[]
[]
[ "html", "idn", "iri", "javascript", "python" ]
stackoverflow_0002833013_html_idn_iri_javascript_python.txt
Q: How to extract longest of overlapping groups? How can I extract the longest of groups which start the same way For example, from a given string, I want to extract the longest match to either CS or CSI. I tried this "(CS|CSI).*" and it it will return CS rather than CSI even if CSI is available. If I do "(CSI|CS).*"...
How to extract longest of overlapping groups?
How can I extract the longest of groups which start the same way For example, from a given string, I want to extract the longest match to either CS or CSI. I tried this "(CS|CSI).*" and it it will return CS rather than CSI even if CSI is available. If I do "(CSI|CS).*" then I do get CSI if it's a match, so I gues the s...
[ "No, that's just how it works, at least in Perl-derived regex flavors like Python, JavaScript, .NET, etc.\nhttp://www.regular-expressions.info/alternation.html\n", "As Alan says, the patterns will be matched in the order you specified them.\nIf you want to match on the longest of overlapping literal strings, you ...
[ 5, 2, 0 ]
[ "similar functionality is present in vim editor (\"sequence of optionally matched atoms\"), where e.g. col\\%[umn] matches col in color, colum in columbus and full column.\ni am not aware if similar functionality in python re,\nyou can use nested anonymous groups, each one followed by ? quantifier, for that:\n>>> i...
[ -1 ]
[ "python", "regex" ]
stackoverflow_0002835206_python_regex.txt
Q: Why can't I access the instance.__class__ attribute in Python? I'm new to Python, and I know I must be missing something pretty simple, but why doesn't this very, very simple code work? class myClass: pass testObject = myClass print testObject.__class__ I get the following error: AttributeError: class myClas...
Why can't I access the instance.__class__ attribute in Python?
I'm new to Python, and I know I must be missing something pretty simple, but why doesn't this very, very simple code work? class myClass: pass testObject = myClass print testObject.__class__ I get the following error: AttributeError: class myClass has no attribute '__class__' Doesn't every object in Python have ...
[ "I think I realized my mistake. I thought that the code testObject = myClass was creating a new instance/object of the class, but it was actually assigning a reference to the class itself. I changed the code to:\nclass myClass: \n pass \n\ntestObject = myClass() \nprint testObject.__class__ \n\nand it now works ...
[ 3, 2, 1 ]
[]
[]
[ "class_attribute", "python" ]
stackoverflow_0002835558_class_attribute_python.txt
Q: getting global name not defined error i have the following class class notify(): def __init__(self,server="localhost", port=23053): self.host = server self.port = port register = gntp.GNTPRegister() register.add_header('Application-Name',"SVN Monitor") register.add_notif...
getting global name not defined error
i have the following class class notify(): def __init__(self,server="localhost", port=23053): self.host = server self.port = port register = gntp.GNTPRegister() register.add_header('Application-Name',"SVN Monitor") register.add_notification("svnupdate",True) growl(reg...
[ "The instance scope is not searched as part of scope resolution in Python. If you want to call a method on self then you must prefix it with a reference to self.\nself.growl(register)\n\n", "growl is not a global symbol, it's a member of the notify class.\nInside the notify class, call the growl method as follows...
[ 3, 1 ]
[]
[]
[ "growlnotify", "python" ]
stackoverflow_0002835684_growlnotify_python.txt
Q: Using xAuth from python using tweepy I am trying to write a twitter client application in python. I would like to use xAuth for authentication. My choice on the library is tweepy, because it seems that it knows everything I need. Here is my problem: >>> import tweepy >>> auth = tweepy.OAuthHandler(CONSUMER_KEY, CO...
Using xAuth from python using tweepy
I am trying to write a twitter client application in python. I would like to use xAuth for authentication. My choice on the library is tweepy, because it seems that it knows everything I need. Here is my problem: >>> import tweepy >>> auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) >>> auth.get_xauth_access_t...
[ "Have you emailed Twitter support to get them to turn on xAuth for your application?\nTwitter only want xAuth to be used by desktop and mobile applications, so registered applications have xAuth disabled by default, and you need someone at Twitter to turn it on for you. If you application doesn't have xAuth enabled...
[ 2 ]
[]
[]
[ "python", "tweepy", "xauth" ]
stackoverflow_0002834654_python_tweepy_xauth.txt
Q: Simulating Pointers in Python for arithmetic The question at Simulating Pointers in Python asking how to simulate pointers in Python had a nice suggestion in the solutions, namely to do class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj ...
Simulating Pointers in Python for arithmetic
The question at Simulating Pointers in Python asking how to simulate pointers in Python had a nice suggestion in the solutions, namely to do class ref: def __init__(self, obj): self.obj = obj def get(self): return self.obj def set(self, obj): self.obj = obj which can then be used to do e.g. a = ref(1.22) b...
[ "The + operator is implemented via the __add__() method on the left operand, or the __radd__() method on the right operand.\nHere.\n", "There are two potential issues.\nFirst, you seem to be relying on your __getattribute__ implementation to let the interpreter find the right __add__ method. Unfortunately, I hav...
[ 3, 0 ]
[]
[]
[ "pointers", "python" ]
stackoverflow_0002835639_pointers_python.txt
Q: Shared value in parallel python I'm using ParallelPython to develop a performance-critical script. I'd like to share one value between the 8 processes running on the system. Please excuse the trivial example but this illustrates my question. def findMin(listOfElements): for el in listOfElements: if e...
Shared value in parallel python
I'm using ParallelPython to develop a performance-critical script. I'd like to share one value between the 8 processes running on the system. Please excuse the trivial example but this illustrates my question. def findMin(listOfElements): for el in listOfElements: if el < min: min = el impor...
[ "Actually, there is an example at http://www.parallelpython.com/content/view/17/31/#CALLBACK and they simply use the locks from the thread module.\nLike JudoWill pointed out, make sure to experiment with how often you should sync the global min in your jobs. If you do it every time you may end up close to serializi...
[ 1, 1, 0, 0 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0002770157_parallel_processing_python.txt
Q: Group Chat XMPP with Google App Engine Google App Engine has a great XMPP service built in. One of the few limitations it has is that it doesn't support receiving messages from a group chat. That's the one thing I want to do with it. :( Can I run a 3rd party XMPP/Jabber server on App Engine that supports group cha...
Group Chat XMPP with Google App Engine
Google App Engine has a great XMPP service built in. One of the few limitations it has is that it doesn't support receiving messages from a group chat. That's the one thing I want to do with it. :( Can I run a 3rd party XMPP/Jabber server on App Engine that supports group chat? If so, which one?
[ "No. App Engine apps can only directly handle HTTP requests - you can't run arbitrary servers on App Engine.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "java", "python", "xmpp" ]
stackoverflow_0002835472_google_app_engine_java_python_xmpp.txt
Q: pythonic way of selecing a random value that satisfies a certain predicate Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this? I currently do a comprehension followed by a random.choice() but that is unnecess...
pythonic way of selecing a random value that satisfies a certain predicate
Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this? I currently do a comprehension followed by a random.choice() but that is unnecessarily inefficient : intlist = [1,2,3,4,5,6,7,8,9] evenlist = [ i for i in intlis...
[ "The way you've written it above is actually good idiomatic python. If we analyze the algorithm we'll find it's essentially doing this:\n\nMaking a list of elements that satisfy the predicate. (Grows linearly with n)\nChoosing a random element from that list. (Constant time)\n\nThe only other way to go about it w...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002835754_python.txt
Q: Python modify an xml file I have this xml model. link text So I have to add some node (see the text commented) to this file. How I can do it? I have writed this partial code but it doesn't work: xmldoc=minidom.parse(directory) child = xmldoc.createElement("map") for node in xmldoc.getElementsByTagName("Environment...
Python modify an xml file
I have this xml model. link text So I have to add some node (see the text commented) to this file. How I can do it? I have writed this partial code but it doesn't work: xmldoc=minidom.parse(directory) child = xmldoc.createElement("map") for node in xmldoc.getElementsByTagName("Environment"): node.appendChild(child)...
[ "I downloaded your sample xml file and your code works fine. Your problem is most likely with the line: xmldoc=minidom.parse(directory), should this not be the path to the file you are trying to parse not to a directory? The parse() function parses an XML file it does not automatically parse all the XML files in a ...
[ 1 ]
[]
[]
[ "add", "python", "xml" ]
stackoverflow_0002836132_add_python_xml.txt
Q: Working with html generated from javascript I have some html-page. There is a javascript which generates some content. I have to parse this content from python-script. I have saved copy of file on the computer. Are there any ways to work with 'already generated' html? Like I can see in the browser after opening pa...
Working with html generated from javascript
I have some html-page. There is a javascript which generates some content. I have to parse this content from python-script. I have saved copy of file on the computer. Are there any ways to work with 'already generated' html? Like I can see in the browser after opening page-file. As I understand, I have to work with DOM...
[ "Have you saved \"the file\" (web page, I imagine) before or after Javascript has altered it?\nIf \"after\", then it doesn't matter any more that some of the HTML was done via Javascript -- you can just use popular parsers like lxml or BeautifulSoup to handle the HTML you have.\nIf \"before\", then first you need t...
[ 2, 0 ]
[]
[]
[ "dom", "html", "python" ]
stackoverflow_0002836745_dom_html_python.txt
Q: PIL to pyvision conversion How can a PIL image be converted to a Pyvision image? A: Based on the documentation, http://sourceforge.net/apps/mediawiki/pyvision/index.php?title=Quick_Start_1, Pvvision image itself is PIL image. The Image constructor accepts filenames as an argument and will then load that fi...
PIL to pyvision conversion
How can a PIL image be converted to a Pyvision image?
[ "Based on the documentation, http://sourceforge.net/apps/mediawiki/pyvision/index.php?title=Quick_Start_1, Pvvision image itself is PIL image. \n\nThe Image constructor accepts\n filenames as an argument and will then\n load that file from the disk as a PIL image. The Image constructor\n will also accept other p...
[ 1 ]
[]
[]
[ "image", "image_manipulation", "python", "python_imaging_library" ]
stackoverflow_0002835200_image_image_manipulation_python_python_imaging_library.txt
Q: Permission to access network drives when running Python CGI? I have a Python script running on the default OSX webserver, stored in /Library/WebServer/CGI-Executables. That script spits out a list of files on a network drive using os.listdir. If I just execute this from the terminal, it works as expected, but when...
Permission to access network drives when running Python CGI?
I have a Python script running on the default OSX webserver, stored in /Library/WebServer/CGI-Executables. That script spits out a list of files on a network drive using os.listdir. If I just execute this from the terminal, it works as expected, but when I try to access it through a browser (computer.local/cgi-bin/test...
[ "I don't know much about the default osx webserver, but the webserver process is probably being run as some user, that user needs to be able to access those files. To find out who the user is you can use the ps command. Then depending on the configuration of the network shared drive, you can add this user to the us...
[ 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002837181_cgi_python.txt
Q: Turbogears 2.0 with Python 2.6 I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error: File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in <module> load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProj...
Turbogears 2.0 with Python 2.6
I've tried to install TurboGears 2.0 with Python 2.6 on both Windows 7 and Windows XP, but both give the same error: File "D:\PythonProjects\tg2env\Scripts\paster-script.py", line 8, in <module> load_entry_point('pastescript==1.7.3', 'console_scripts', 'paster')() File "D:\PythonProjects\tg2env\lib\site-packages\pastes...
[ "did you run python setup.py develop? (as the error message says)\n\nI was using virtualenv as recommended in the documentation, but the develop command installs the packages in the original python folder.\n\nOkay, that is the cause of your problems. I'm wondering about your comment \"but the develop command instal...
[ 1, 0, 0 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0001536437_python_turbogears.txt
Q: What could cause xmlrpclib.ResponseError: ResponseError()? I am experimenting with XML-RPC. I have the following server script (Python): from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9000)) def return_input(someinput): return someinput server.register_function(retur...
What could cause xmlrpclib.ResponseError: ResponseError()?
I am experimenting with XML-RPC. I have the following server script (Python): from SimpleXMLRPCServer import SimpleXMLRPCServer server = SimpleXMLRPCServer(('localhost', 9000)) def return_input(someinput): return someinput server.register_function(return_input) try: print 'ctrl-c to stop server' server.se...
[ "It looks like something else is running on that port on the remote machine. And sending back an unexpected answer.\nI would check the server is starting correctly. Then check if there is anything in the firewall setup that might be affecting things.\nYou could also turn on the verbose flag in the client to see if ...
[ 3 ]
[]
[]
[ "python", "simplexmlrpcserver", "xml_rpc" ]
stackoverflow_0002837414_python_simplexmlrpcserver_xml_rpc.txt
Q: Help with parsing lxml To implement a college project, I need to handle XML files. For this I choose lxml after doing some research. However I can't seem to find some nice tutorial to help me get started. I can't choose most specifically which type of parsing I need to use. My XML files don't have that much data b...
Help with parsing lxml
To implement a college project, I need to handle XML files. For this I choose lxml after doing some research. However I can't seem to find some nice tutorial to help me get started. I can't choose most specifically which type of parsing I need to use. My XML files don't have that much data but speed is main concern, no...
[ "No applications but examples:\n\nhttp://www.ibm.com/developerworks/xml/library/x-hiperfparse/\nhttp://infohost.nmt.edu/tcc/help/pubs/pylxml/pylxml.pdf\n\n" ]
[ 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002837513_lxml_python.txt
Q: Animate pygame sprite in elliptical path This is pygame 1.9 on python 2.6.. Here is a screenshot of what is currently being drawn in my "game" to give some context. Here is the code. It's supposed to be the moon orbiting around the earth (I'm not trying to make a real simulation or anything, I'm just using the set...
Animate pygame sprite in elliptical path
This is pygame 1.9 on python 2.6.. Here is a screenshot of what is currently being drawn in my "game" to give some context. Here is the code. It's supposed to be the moon orbiting around the earth (I'm not trying to make a real simulation or anything, I'm just using the setting to play around and learn pygame). It's 2 ...
[ "Well here is how you generate points along an ellipse:\nfor degree in range(360):\n x = cos(degree * 2 * pi / 360) * radius * xToYratio\n y = sin(degree * 2 * pi / 360) * radius\n\n(x,y) will follow an ellipse centered at (0,0), with the y radius being radius and the x radius being xToYratio. In your case, y...
[ 5 ]
[]
[]
[ "animation", "pygame", "python" ]
stackoverflow_0002837615_animation_pygame_python.txt
Q: Downloading a web page and all of its resource files in Python I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at Beaut...
Downloading a web page and all of its resource files in Python
I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already a P...
[ "Websucker? See http://effbot.org/zone/websucker.htm\n", "websucker.py doesn't import css links. HTTrack.com is not python, it's C/C++, but it's a good, maintained, utility for downloading a website for offline browsing.\nhttp://www.mail-archive.com/python-bugs-list@python.org/msg13523.html\n[issue1124] Webcheck...
[ 3, 2 ]
[]
[]
[ "python", "urllib2", "wget" ]
stackoverflow_0000844115_python_urllib2_wget.txt
Q: In Python, how to make sure database connection will always close before leaving a code block? I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possibl...
In Python, how to make sure database connection will always close before leaving a code block?
I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possible. def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_h...
[ "The traditional approach is the try/finally statement:\ndef do_something_that_needs_database ():\n dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor)\n try:\n # as much wo...
[ 33, 6, 4, 4 ]
[]
[]
[ "database_connection", "nested", "python" ]
stackoverflow_0002837822_database_connection_nested_python.txt
Q: Huge amount of time sending data with suds and proxy I have the following code to send data through a proxy using suds: import suds t = suds.transport.http.HttpTransport() proxy = urllib2.ProxyHandler({'http': 'http://192.168.3.217:3128'}) opener = urllib2.build_opener(proxy) t.urlopener = opener ws = suds.c...
Huge amount of time sending data with suds and proxy
I have the following code to send data through a proxy using suds: import suds t = suds.transport.http.HttpTransport() proxy = urllib2.ProxyHandler({'http': 'http://192.168.3.217:3128'}) opener = urllib2.build_opener(proxy) t.urlopener = opener ws = suds.client.Client('http://xxxxxxx/web.asmx?WSDL', transport=t) ...
[ "A sniffer output (e.g. from wireshark) could be very helpful to understand this one.\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "suds" ]
stackoverflow_0001922538_proxy_python_suds.txt
Q: Django & custom auth backend (web service) + no database. How to save stuff in session? I've been searching here and there, and based on this answer I've put together what you see below. It works, but I need to put some stuff in the user's session, right there inside authenticate. How would I store acme_token in t...
Django & custom auth backend (web service) + no database. How to save stuff in session?
I've been searching here and there, and based on this answer I've put together what you see below. It works, but I need to put some stuff in the user's session, right there inside authenticate. How would I store acme_token in the user's session, so that it will get cleared if they logged out? The request object is not ...
[ "Shove it onto the returned user, then handle it in middleware.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002836969_django_django_models_python.txt
Q: Python subprocess.Popen hangs in 'for l in p.stdout' until p terminates, why? I have that code: #!/usr/bin/python -u localport = 9876 import sys, re, os from subprocess import * tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT) print "** Started tunnel, waiting to be ready ..." for...
Python subprocess.Popen hangs in 'for l in p.stdout' until p terminates, why?
I have that code: #!/usr/bin/python -u localport = 9876 import sys, re, os from subprocess import * tun = Popen(["./newtunnel", "22", str(localport)], stdout=PIPE, stderr=STDOUT) print "** Started tunnel, waiting to be ready ..." for l in tun.stdout: sys.stdout.write(l) if re.search("Waiting for con...
[ "Ok, it seems that it is a bug in Python: http://bugs.python.org/issue3907\nIf I replace the line\nfor l in tun.stdout:\n\nby\nwhile True:\n l = tun.stdout.readline()\n\nthen it works exactly the way I want.\n" ]
[ 2 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0002838035_popen_python_subprocess.txt
Q: Python msn hook - possible? Is it possible to hook msn via a python application to send messages to your contacts etc? A: You can use twisted.words.protocols.msn or use libpurple through its DBus bindings or Python bindings.
Python msn hook - possible?
Is it possible to hook msn via a python application to send messages to your contacts etc?
[ "You can use twisted.words.protocols.msn or use libpurple through its DBus bindings or Python bindings. \n" ]
[ 3 ]
[]
[]
[ "hook", "msn", "python" ]
stackoverflow_0002838458_hook_msn_python.txt
Q: import problem with twisted.web server I'm just getting started with twisted.web, and I'm having trouble importing a Python module into a .rpy script. in C:\py\twisted\mysite.py, I have this: from twisted.web.resource import Resource from twisted.web import server class MySite(Resource): def render_GET(self, ...
import problem with twisted.web server
I'm just getting started with twisted.web, and I'm having trouble importing a Python module into a .rpy script. in C:\py\twisted\mysite.py, I have this: from twisted.web.resource import Resource from twisted.web import server class MySite(Resource): def render_GET(self, request): request.write("<!DOCTYPE h...
[ "Short answer: you need to set PYTHONPATH to include C:\\py\\twisted.\nLong answer...\nAn rpy script is basically just some Python code, like any other Python code. So an import in a rpy script works just like an import in any other Python code. For the most common case, this means that the directories in sys.pat...
[ 5 ]
[]
[]
[ "python", "twisted", "twisted.web" ]
stackoverflow_0002838145_python_twisted_twisted.web.txt
Q: How can I get sessions to work if I'm using Google App Engine + Django 1.1? Is there a way for me to get sessions working? I know Django has built in session management, and GAE has some tools for it if you're using their watered down version of Django 0.96, but is there a way to get sessions to work if you're tr...
How can I get sessions to work if I'm using Google App Engine + Django 1.1?
Is there a way for me to get sessions working? I know Django has built in session management, and GAE has some tools for it if you're using their watered down version of Django 0.96, but is there a way to get sessions to work if you're trying to use GAE w/ Django 1.1 (i.e. use_library() call). I assume using a db-bac...
[ "If you want to use the django sessions, you need to use the google django helper here: http://code.google.com/p/google-app-engine-django/\nWhich says: \n\nSupport for the db and cache session backed modules when using Django 1.0 alpha\n\nEven though it says 1.0 alpha, it means 1.0 and above.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python", "session" ]
stackoverflow_0002837802_django_google_app_engine_python_session.txt
Q: Efficient update of SQLite table with many records I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they...
Efficient update of SQLite table with many records
I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard update ...
[ "Create an index on table.id\ncreate index table_id_index on table(id)\n\n", "Other than making sure you have an index in place, you can checkout the SQLite Optimization FAQ.\nUsing transactions can give you a very big speed increase as you mentioned and you can also try to turn off journaling.\nExample 1:\n\n2.2...
[ 13, 3 ]
[]
[]
[ "c++", "database", "python", "sql", "sqlite" ]
stackoverflow_0002838790_c++_database_python_sql_sqlite.txt
Q: Why doesn't negative values for the second index in a jagged array work in Python? For example, if I have the following (data from Project Euler): s = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65...
Why doesn't negative values for the second index in a jagged array work in Python?
For example, if I have the following (data from Project Euler): s = [[75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33...
[ "Python doesn't have 2-dimensional lists, it has lists of lists. I think the first [1:] gives everything but the first contained list, and the second [:-1] takes that result and removes the last contained list.\nWhat you want is:\n[r[:-1] for r in s[1:]]\n\n", "You're misdescribing the results: s[1:][:-1] is defi...
[ 4, 2 ]
[]
[]
[ "jagged_arrays", "python" ]
stackoverflow_0002838712_jagged_arrays_python.txt
Q: pywinauto: taking more than one app windows I have a GUI application which can create many similar windows on desktop. All windows have same title. I have to enumerate all dialogs with same title and make some tests against each of such dialogs. If I call: dialog = app['Window Name'] pywinauto returns a WindowSpe...
pywinauto: taking more than one app windows
I have a GUI application which can create many similar windows on desktop. All windows have same title. I have to enumerate all dialogs with same title and make some tests against each of such dialogs. If I call: dialog = app['Window Name'] pywinauto returns a WindowSpecification object which is useful along with acce...
[ "You can't really. WindowSpecification is a single specification for all windows that match the criteria supplied. \nWhen you work with a WindowSpecification instance you are often interacting with an HwndWrapper instance that WindowSpecification is finding and accessing for you.\nSo I think the answer is to work w...
[ 4 ]
[]
[]
[ "matching", "python", "pywinauto", "window" ]
stackoverflow_0002829925_matching_python_pywinauto_window.txt
Q: increasing string size through loop what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc. A: That should do the trick: def iterate_strings(n): if n <= 0: yield '' return for c in string.ascii_lo...
increasing string size through loop
what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc.
[ "That should do the trick:\ndef iterate_strings(n):\n if n <= 0:\n yield ''\n return\n for c in string.ascii_lowercase:\n for s in iterate_strings(n - 1):\n yield c + s\n\nIt returns a generator.\nYou can iterate it with a for loop:\nfor s in iterate_strings(5)\n\nOr get a list...
[ 7, 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002838261_python_string.txt
Q: How to find/replace text in html while preserving html tags/structure I use regexps to transform text as I want, but I want to preserve the HTML tags. e.g. if I want to replace "stack overflow" with "stack underflow", this should work as expected: if the input is stack <sometag>overflow</sometag>, I must obtain s...
How to find/replace text in html while preserving html tags/structure
I use regexps to transform text as I want, but I want to preserve the HTML tags. e.g. if I want to replace "stack overflow" with "stack underflow", this should work as expected: if the input is stack <sometag>overflow</sometag>, I must obtain stack <sometag>underflow</sometag> (i.e. the string substitution is done, bu...
[ "Use a DOM library, not regular expressions, when dealing with manipulating HTML:\n\nlxml: a parser, document, and HTML serializer. Also can use BeautifulSoup and html5lib for parsing.\nBeautifulSoup: a parser, document, and HTML serializer.\nhtml5lib: a parser. It has a serializer.\nElementTree: a document object,...
[ 9, 3, 3, 1, 0 ]
[ "Fun stuff to try. It sorta works. My friends like it when I attach this script to a textarea and let them \"translate\" things. I guess you could use it for anything really. Meh. Check the code over a few times if you're going to use it, it works but I'm new to all this. I think it's been 2 or three weeks since I ...
[ -1 ]
[ "html", "html_parsing", "python" ]
stackoverflow_0001856014_html_html_parsing_python.txt
Q: How to include a dynamic page contents into a template? I have to include a dynamic page content into my template, Say I have a left panel which gets the data dynamically through a view. Now, I have to include this left panel into all my pages but I do not want to duplicate the code for all the pages. Is there any...
How to include a dynamic page contents into a template?
I have to include a dynamic page content into my template, Say I have a left panel which gets the data dynamically through a view. Now, I have to include this left panel into all my pages but I do not want to duplicate the code for all the pages. Is there any way, I can write a single script and include it in all my te...
[ "What you trying to achieve is directly supported in pretty much all template languages I know of. I would strongly recommend using one the many good choices for Python:\n\nGenshi\nKid\nJinja\nMako\n\nIf you were using Genshi for example (the default template language in TurboGears web application framework) what y...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002839513_python.txt
Q: How to delete sentences starting with a lower case letter? In the example below the following regex (".*?") was used to remove all dialogue first. The next step is to remove all remaining sentences starting with a lower case letter. Only sentences starting with an upper case letter should remain. Example: excla...
How to delete sentences starting with a lower case letter?
In the example below the following regex (".*?") was used to remove all dialogue first. The next step is to remove all remaining sentences starting with a lower case letter. Only sentences starting with an upper case letter should remain. Example: exclaimed Wade. Indeed, below them were villages, of crude huts made ...
[ "This should work for the example you posted:\ntext = re.sub(r'(^|(?<=[.!?])\\s+)[a-z].*?[.!?](?=\\s|$)', r'\\1', text)\n\n", "This works for me in Perl on your example:\n$s = \"exclaimed Wade. Indeed, ...\";\n\ndo {\n $prev = $s;\n $s =~ s/(^\\s*|[.!?]\\s+)[a-z][^.!?]*[.!?]\\s*/$1/gs;\n} until ($s eq $prev);\n...
[ 3, 0, 0 ]
[]
[]
[ "perl", "python", "regex", "text" ]
stackoverflow_0002664626_perl_python_regex_text.txt
Q: What are the most valuable certification available for Programming? I would like to know what are the certificates available for programming, like Zend for PHP SUN Certification for java What are the others? Javascript? C++? Python? etc... Please give me some suggestion for other available certifications. A: ...
What are the most valuable certification available for Programming?
I would like to know what are the certificates available for programming, like Zend for PHP SUN Certification for java What are the others? Javascript? C++? Python? etc... Please give me some suggestion for other available certifications.
[ "Most valuable thing for a developer: being able to show you can convert requirements into working and maintainable software.\nCertifications generally are worth very little, except in a few niches that demand them (or at least ask, until they give up and get someone who puts practice before pieces of paper).\n", ...
[ 16, 7, 2, 0, 0 ]
[]
[]
[ "certificate", "javascript", "php", "programming_languages", "python" ]
stackoverflow_0002839663_certificate_javascript_php_programming_languages_python.txt
Q: symbols in command line argument.. python, bash I am writing a python script on Linux for twitter post using API, Is it possible to pass symbols like "(" ")" etc in clear text without apostrophes.... % ./twitterupdate this is me #works fine % ./twitterupdate this is bad :(( #this leaves a error on bash. Is the o...
symbols in command line argument.. python, bash
I am writing a python script on Linux for twitter post using API, Is it possible to pass symbols like "(" ")" etc in clear text without apostrophes.... % ./twitterupdate this is me #works fine % ./twitterupdate this is bad :(( #this leaves a error on bash. Is the only alternative is to enclose the text into --> "" ?...
[ "Yes, quoting the string is the only way. Bash has its syntax and and some characters have special meaning. Btw, using \"\" is not enough, use apostrophes instead. Some characters will still get interpretted with normal quotation marks:\n$ echo \"lots of $$\"\nlots of 15570\n$ echo 'lots of $$'\nlots of $$\n\n", ...
[ 10, 1 ]
[]
[]
[ "bash", "command_line_arguments", "python" ]
stackoverflow_0002840076_bash_command_line_arguments_python.txt
Q: How to have localized style when writing cell with xlwt I'm writing an Excel spreadsheet with Python's xlwt and I need numbers to be formatted using "." as thousands separator, as it is in brazilian portuguese language. I have tried: style.num_format_str = r'#,##0' And it sets the thousands separator as ','. If ...
How to have localized style when writing cell with xlwt
I'm writing an Excel spreadsheet with Python's xlwt and I need numbers to be formatted using "." as thousands separator, as it is in brazilian portuguese language. I have tried: style.num_format_str = r'#,##0' And it sets the thousands separator as ','. If I try setting num_format_str to '#.##0', I'll get number form...
[ "The thousands separator (and the decimal \"point\" etc) are recorded in the XLS file in a locale-independent fashion. The recorded thousands separator is a comma. How it is displayed depends on the user's locale. OpenOffice calc allows the user to override the default locale (Tools / Options / Languages / Locale s...
[ 6 ]
[]
[]
[ "excel", "localization", "python", "xlwt" ]
stackoverflow_0002836358_excel_localization_python_xlwt.txt
Q: Django throws 404 at generic views I'm trying to get the generic views for a date-based archive working in django. I defined the urls as described in a tutorial, but django returns a 404 error whenever I want to access an url with a variable (such as month or year) in it. It don't even produces a TemplateDoesNotEx...
Django throws 404 at generic views
I'm trying to get the generic views for a date-based archive working in django. I defined the urls as described in a tutorial, but django returns a 404 error whenever I want to access an url with a variable (such as month or year) in it. It don't even produces a TemplateDoesNotExist-execption. Normal urls without varia...
[ "You forgot the backslashes in your regexes:\n(r'events/(?P<year>\\d{4})/(?P<month>[a-z]{3})/(?P<day>\\w{1,2})/(?P<slug>[-\\w]+)/$'\n\nAlso you've (correctly) got the URL regex ending with a slash, so your URL should be /events/2010/may/12/this-is-a-slug/.\n", "Check the template_name once again.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "django_generic_views", "http_status_code_404", "python" ]
stackoverflow_0002818073_django_django_generic_views_http_status_code_404_python.txt
Q: Converting a bash script to python (small script) I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is rather simple (I think) and I’ve tried to convert it by google by wa...
Converting a bash script to python (small script)
I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is rather simple (I think) and I’ve tried to convert it by google by way around but can’t convert it successfully. The bash sc...
[ "Answer\nLet's break it down into pieces. Especially the pieces you got wrong. :)\n\nAssignment\n\noutfile=ReadsAgain.txt\n\n\nIt should come to little surprise that you need to put quotes around strings. On the other hand, you have the luxury of putting spaces around the = for readability.\noutfilename = \"ReadsAg...
[ 36, 10, 2 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002839810_bash_python.txt
Q: Is there a method to convert PyUnicodeObject variable to PyObject type? A value which is a PyUnicodeObject need to be passed to PyObject variable. Is there any conversion method for that? thanks karnol A: You can just use a cast in your C code for this purpose: PyUnicodeObject *p = ...whatever...; callsomefun((P...
Is there a method to convert PyUnicodeObject variable to PyObject type?
A value which is a PyUnicodeObject need to be passed to PyObject variable. Is there any conversion method for that? thanks karnol
[ "You can just use a cast in your C code for this purpose:\nPyUnicodeObject *p = ...whatever...;\ncallsomefun((PyObject*)p);\n\nAll the various specific, concrete types PyWhateverObject can be thought of as being \"derived from\" PyObject. Now C doesn't have the concept of inheritance so there's no \"derived\" in i...
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002840144_python_python_3.x.txt
Q: setting url in yaml file for google app engin (page not found) problem I am new to python and I am super excited to learn. I am building my first app on app engin and I am not totally understanding why my yaml file is not resolving to the url that I set up. here is the code handlers: - url: .* script: main.py -...
setting url in yaml file for google app engin (page not found) problem
I am new to python and I am super excited to learn. I am building my first app on app engin and I am not totally understanding why my yaml file is not resolving to the url that I set up. here is the code handlers: - url: .* script: main.py - url: /letmein/.* script: letmein.py so if I go to http://localhost:8080...
[ "Your handlers are in the wrong order as they must always be less general first. Change to:\nhandlers:\n- url: /letmein/.*\n script: letmein.py\n\n- url: .*\n script: main.py\n\nand it works.\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "http_status_code_404", "python", "yaml" ]
stackoverflow_0002840483_google_app_engine_http_status_code_404_python_yaml.txt
Q: Decorator that can take both init args and call args? Is it possible to create a decorator which can be __init__'d with a set of arguments, then later have methods called with other arguments? For instance: from foo import MyDecorator bar = MyDecorator(debug=True) @bar.myfunc(a=100) def spam(): pass @bar.my...
Decorator that can take both init args and call args?
Is it possible to create a decorator which can be __init__'d with a set of arguments, then later have methods called with other arguments? For instance: from foo import MyDecorator bar = MyDecorator(debug=True) @bar.myfunc(a=100) def spam(): pass @bar.myotherfunc(x=False) def eggs(): pass If this is possibl...
[ "You need another level of wrapping for this, using closures for example:\nimport functools\n\ndef say_when_called(what_to_say):\n def decorator(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kw):\n print what_to_say\n return fn(*args, **kw)\n return wrapper\n re...
[ 4, 3, 0, 0 ]
[]
[]
[ "decorator", "design_patterns", "python" ]
stackoverflow_0002839363_decorator_design_patterns_python.txt
Q: How to write a Python lexical analyser? I'm trying to write a C module to lexically analyse Python code. How can I do it? A: The complete, detailed specification for doing lexical analysis of Python code is here. As you can see, there are a lot of cases you need to cover. One help is that you will always be abl...
How to write a Python lexical analyser?
I'm trying to write a C module to lexically analyse Python code. How can I do it?
[ "The complete, detailed specification for doing lexical analysis of Python code is here.\nAs you can see, there are a lot of cases you need to cover. One help is that you will always be able to check most easily if your C-implemented lexical analyzer is correct for a given Python fragment: it will have to return e...
[ 10 ]
[]
[]
[ "c", "lexical_analysis", "python" ]
stackoverflow_0002840547_c_lexical_analysis_python.txt
Q: Prevent web2py from caching? I'm working with web2py and for some reason web2py seems to fail to notice when code has changed in certain cases. I can't really narrow it down, but from time to time changes in the code are not reflected, web2py obviously has the old version cached somewhere. The only thing that hel...
Prevent web2py from caching?
I'm working with web2py and for some reason web2py seems to fail to notice when code has changed in certain cases. I can't really narrow it down, but from time to time changes in the code are not reflected, web2py obviously has the old version cached somewhere. The only thing that helps is quitting web2py and restarti...
[ "web2py does cache your code, except for Google App Engine (for speed). That is not the problem. If you you edit code in models, views or controllers, you see the effect immediately.\nThe problem may be modules; if you edit code in modules you will not see the effect immediately, unless you import them with local_i...
[ 5, 0 ]
[]
[]
[ "caching", "python", "web2py" ]
stackoverflow_0002840201_caching_python_web2py.txt
Q: Adjective Nominalization in Python NLTK Is there a way to obtain Wordnet adjective nominalizations using NLTK? For example, for happy the desired output would be happiness. I tried to dig around, but couldn't find anything. A: The quick and dirty answer is that wordnet does this already: <adj.all>S: (adj) happy...
Adjective Nominalization in Python NLTK
Is there a way to obtain Wordnet adjective nominalizations using NLTK? For example, for happy the desired output would be happiness. I tried to dig around, but couldn't find anything.
[ "The quick and dirty answer is that wordnet does this already:\n\n\n<adj.all>S: (adj) happy (enjoying or showing or marked by joy or pleasure)\n \"a happy smile\"; \"spent many happy\n days on the beach\"; \"a happy marriage\"\n\nattribute\n \n \n<noun.state>S: (n) happiness, felicity (state of\n well-being ch...
[ 4 ]
[]
[]
[ "nlp", "nltk", "python", "wordnet" ]
stackoverflow_0002836959_nlp_nltk_python_wordnet.txt
Q: Purpose of Zope Interfaces? I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I ...
Purpose of Zope Interfaces?
I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if pos...
[ "Where I work, we use Interfaces so that we can use ZCA, or the Zope Component Architecture, which is a whole framework for making components that are swappable and pluggable using Interfaces. We use ZCA so that we can cope with all manner of per-client customisations without necessarily having to fork our software...
[ 52, 24, 19, 2 ]
[]
[]
[ "interface", "python", "zope", "zope.interface" ]
stackoverflow_0002521189_interface_python_zope_zope.interface.txt
Q: Django: What's the correct way to get the requesting IP address? I'm trying to develop an app using Django 1.1 on Webfaction. I'd like to get the IP address of the incoming request, but when I use request.META['REMOTE_ADDR'] it returns 127.0.0.1. There seems to be a number of different ways of getting the address,...
Django: What's the correct way to get the requesting IP address?
I'm trying to develop an app using Django 1.1 on Webfaction. I'd like to get the IP address of the incoming request, but when I use request.META['REMOTE_ADDR'] it returns 127.0.0.1. There seems to be a number of different ways of getting the address, such as using HTTP_X_FORWARDED_FOR or plugging in some middleware ca...
[ "The remote proxy middleware was removed in Django 1.1.1 with a nod towards pointing out that trusting REMOTE_ADDR or HTTP_X_FORWARDED for isn't secure anyway (in case that also helps you decide what to do)\n", "I use the middleware because this way I don't have to change the app's code. \nIf I want to migrate my...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002840329_django_python.txt
Q: Querying datetime.datetime on appengine acts different then dev server help! I'm having some trouble with stuff that work locally and dont work on the app engine python environment: Basically, i want to get a program from an epg between ranges of date and time. i know i cannot do two where > < so i saw a suggestio...
Querying datetime.datetime on appengine acts different then dev server help!
I'm having some trouble with stuff that work locally and dont work on the app engine python environment: Basically, i want to get a program from an epg between ranges of date and time. i know i cannot do two where > < so i saw a suggestion to save the dates as list as datetime.datetime which i did. [datetime.datetime(2...
[ "could this be the issue?\nFrom:\nhttp://code.google.com/appengine/docs/python/datastore/gqlreference.html\n\na datetime, date, or time literal,\n with either numeric values or a string\n representation, in the following\n forms: DATETIME(year, month, day,\n hour, minute, second)\n DATETIME('YYYY-MM-DD HH:MM:S...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002832711_google_app_engine_python.txt
Q: How does one pre-populate a Python Formish form? How does one pre-populate a Formish form? The obvious method as per the documentation doesn't seem right. Using one of the provided examples: import formish, schemaish structure = schemaish.Structure() structure.add( 'a', schemaish.String() ) structure.add( 'b', sch...
How does one pre-populate a Python Formish form?
How does one pre-populate a Formish form? The obvious method as per the documentation doesn't seem right. Using one of the provided examples: import formish, schemaish structure = schemaish.Structure() structure.add( 'a', schemaish.String() ) structure.add( 'b', schemaish.Integer() ) schema = schemaish.Structure() sche...
[ "No, don't require to use dotted dict, you can easily use the post-validate style dict to pre-populate the form:\nform.defaults={'myStruct': {'a': None, 'b': 'default_value'}}\n\nmaybe have old version of formish, try update the libs.\n" ]
[ 1 ]
[]
[]
[ "formish", "python" ]
stackoverflow_0002711083_formish_python.txt
Q: Combinatorial optimisation of a distance metric I have a set of trajectories, made up of points along the trajectory, and with the coordinates associated with each point. I store these in a 3d array ( trajectory, point, param). I want to find the set of r trajectories that have the maximum accumulated distance bet...
Combinatorial optimisation of a distance metric
I have a set of trajectories, made up of points along the trajectory, and with the coordinates associated with each point. I store these in a 3d array ( trajectory, point, param). I want to find the set of r trajectories that have the maximum accumulated distance between the possible pairwise combinations of these traj...
[ "Rather than recalculate the distance between each pair of trajectories on-demand, you can start by calculating the distance between all pairs of trajectories. You can store those in a dictionary and look them up as needed.\nThis way your inner-loop for (i,j) ... will be replaced with a constant-time lookup.\n", ...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "algorithm", "combinatorics", "numpy", "python", "python_itertools" ]
stackoverflow_0002829772_algorithm_combinatorics_numpy_python_python_itertools.txt
Q: C# style properties in python I am looking for a way to define properties in Python similar to C#, with nested get/set definitions. This is how far I got: #### definition #### def Prop(fcn): f = fcn() return property(f['get'], f['set']) #### test #### class Example(object): @Prop def myattr...
C# style properties in python
I am looking for a way to define properties in Python similar to C#, with nested get/set definitions. This is how far I got: #### definition #### def Prop(fcn): f = fcn() return property(f['get'], f['set']) #### test #### class Example(object): @Prop def myattr(): def get(self): ...
[ "You could return get, set (a much more elegant approach) and make your Prop into\ndef Prop(fcn):\n g, s = fcn()\n return property(g, s)\n\nThere is however no clean way to not require any return statement in the decorated function. A function with internal def statements, just like one with internal assignm...
[ 2 ]
[]
[]
[ "c#", "nested", "properties", "python" ]
stackoverflow_0002841432_c#_nested_properties_python.txt
Q: Best data-structure to use for two ended sorted list I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list O(log n) Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples a...
Best data-structure to use for two ended sorted list
I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list O(log n) Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples and want to sort on a particular value Thread-safety is no...
[ "You might get good performance for these kinds of operations using blist or a database (such as the sqlite which is in the stdlib).\n", "I suggest some sort of balanced binary tree such as a red-black tree. \nA search on PyPi throws up a couple of implementations. Searching on google will give you more.\nbintr...
[ 2, 1, 1, 1, 1, 1 ]
[ "If this were Java I'd use a TreeSet with the NavigableSet interface.\nThis is implemented as a Red-Black-Tree.\n" ]
[ -1 ]
[ "algorithm", "collections", "data_structures", "performance", "python" ]
stackoverflow_0002839130_algorithm_collections_data_structures_performance_python.txt
Q: Is there a method to find out if a package is to be installed with distutils instead of setuptools? I can look inside setup.py I suppose to see if it's a distutils package. But in the process of familiarizing myself with python package management I have noticed that there seems to be more than one way to do it. ...
Is there a method to find out if a package is to be installed with distutils instead of setuptools?
I can look inside setup.py I suppose to see if it's a distutils package. But in the process of familiarizing myself with python package management I have noticed that there seems to be more than one way to do it. So: How can I check an unzipped packages directory or setup.py to see how to build it? EDIT: When I say '...
[ "Why do you need to know? What's wrong with just running \n/path/to/your/python setup.py install\n\n?\n" ]
[ 0 ]
[]
[]
[ "distribute", "distutils", "python" ]
stackoverflow_0002839902_distribute_distutils_python.txt
Q: Nested WHILE loops in Python I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). IDLE 2.6.4 >>> a=0 >>> b=0 >>> while a < 4: a=a+1 while b < 4: b=b+1 print a, b 1 1 1 2 1 3 1 4 I am expecting t...
Nested WHILE loops in Python
I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). IDLE 2.6.4 >>> a=0 >>> b=0 >>> while a < 4: a=a+1 while b < 4: b=b+1 print a, b 1 1 1 2 1 3 1 4 I am expecting the outer loop to loop through 1,2,...
[ "You're not resetting b to 0 right inside your outer loop, so b stays at the value it had after the first leg of the outer loop -- 4 -- and the inner loop never executes again.\nThe for loops work fine because they do reset their loop control variables correctly; with the less-structured while loops, such resetting...
[ 7 ]
[]
[]
[ "for_loop", "nested_loops", "python", "while_loop" ]
stackoverflow_0002841489_for_loop_nested_loops_python_while_loop.txt
Q: How can I reshape and aggregate list of tuples in Python? I'm a newb to Python so apologies in advance if my question looks trivial. From a psycopg2 query i have a result in the form of a list of tuples looking like: [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)] Each tuple represents id of a location w...
How can I reshape and aggregate list of tuples in Python?
I'm a newb to Python so apologies in advance if my question looks trivial. From a psycopg2 query i have a result in the form of a list of tuples looking like: [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)] Each tuple represents id of a location where event happened and hour of the day when event took place. ...
[ "Something like...:\nimport collections\n\nraw_data = [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)]\naux = collections.defaultdict(int)\nfor x, y in raw_data:\n aux[x, y] += 1\n\nlocations = sorted(set(x for x, y in raw_data))\nhours = sorted(set(y for x, y in raw_data))\nresult = [(x, y, aux[x, y]) for...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002841442_python.txt
Q: Call function in views.py from command line (django) I'm trying to run a function defined in the views file of my django app, from the command line. Is there a way to do this? I understand view functions are supposed to be called from a request but I need this function to be called from a cron eventually. Thanks ...
Call function in views.py from command line (django)
I'm trying to run a function defined in the views file of my django app, from the command line. Is there a way to do this? I understand view functions are supposed to be called from a request but I need this function to be called from a cron eventually. Thanks
[ "You can use custom management commands.\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002841628_django_python.txt
Q: Python optimization problem? Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter pa...
Python optimization problem?
Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import num...
[ "Interference patterns are fun, aren't they?\nSo, first off this is going to be minor because running this program as-is on my laptop takes a mere twelve and a half seconds.\nBut let's see what can be done about doing the first bit through numpy array operations, shall we? We have basically that you want:\narr[i][...
[ 5, 3, 2, 1 ]
[]
[]
[ "for_loop", "numpy", "optimization", "physics", "python" ]
stackoverflow_0002841567_for_loop_numpy_optimization_physics_python.txt
Q: Python library to validate Excel data Is there any existing Python library that can validate data in Excel format? Or what kind of keyword should I use to search such an open source project? Thanks. A: [Disclosure: I'm the author of xlrd] xlrd allows you to extract data from XLS files. XLSX support is in alpha t...
Python library to validate Excel data
Is there any existing Python library that can validate data in Excel format? Or what kind of keyword should I use to search such an open source project? Thanks.
[ "[Disclosure: I'm the author of xlrd]\nxlrd allows you to extract data from XLS files. XLSX support is in alpha testing; e-mail me if you need it. You get told precisely what is in each cell (Excel cell type and value). It runs on Python 2.1 to 2.7 on any platform. You don't need Windows. You don't need Excel to be...
[ 2, 1 ]
[]
[]
[ "excel", "python", "validation" ]
stackoverflow_0002841451_excel_python_validation.txt
Q: have to invoke (Thread.__init__) in my overridden constructor, but why? i saw this phrase in python 2.6 man: class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) . . . If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) b...
have to invoke (Thread.__init__) in my overridden constructor, but why?
i saw this phrase in python 2.6 man: class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}) . . . If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. i just wanna know why?
[ "Because Thread.__init__ sets some internal variables which will be undefined if you omit the call. In general, it is a good practice to invoke super constructor in all cases unless there is a strong reason to not do it.\n", "If you want to know \"exactly what, in detail, does the superclass's __init__ do for me...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002841718_python.txt
Q: Best tools to create valid XML files from an Excel file I need to create a script that extracts some data from a complex Excel 2003 file (with multiple sheets and different tables inside a single sheet) and produces different XML files that need to be validated against a given XSD file. My preferred language is Py...
Best tools to create valid XML files from an Excel file
I need to create a script that extracts some data from a complex Excel 2003 file (with multiple sheets and different tables inside a single sheet) and produces different XML files that need to be validated against a given XSD file. My preferred language is Python; to create and validate XML files i would go with lxml. ...
[ "Xlrd is OK. We use it extensively to import XLS files full of references and formulas with multiple sheets and data presented in custom (not Latin-1) encoding.\n", "[disclaimer: I'm the author of xlrd]\nxlrd is quite suited for this kind of job. Get the latest version from PyPI. Get the flavour from the tutorial...
[ 2, 2, 1, 0 ]
[]
[]
[ "c#", "excel", "python", "vb6", "xml" ]
stackoverflow_0002825006_c#_excel_python_vb6_xml.txt
Q: Excel Regex, or export to Python? ; "Vlookup" in Python? We have an Excel file with a worksheet containing people records. 1. Phone Number Sanitation One of the fields is a phone number field, which contains phone numbers in the format e.g.: +XX(Y)ZZZZ-ZZZZ (where X, Y and Z are integers). There are also some rec...
Excel Regex, or export to Python? ; "Vlookup" in Python?
We have an Excel file with a worksheet containing people records. 1. Phone Number Sanitation One of the fields is a phone number field, which contains phone numbers in the format e.g.: +XX(Y)ZZZZ-ZZZZ (where X, Y and Z are integers). There are also some records which have less digits, e.g.: +XX(Y)ZZZ-ZZZZ And others ...
[ "In general, avoid Excel formulas; use xlrd to extract the data that you need, then forget it came from Excel and manipulate the data using Python. E.g. addressing the xlrd / vlookup question: the best way would be to create a dictionary ONCE from the relevant parts of the 2 columns containing the keys and values. ...
[ 2, 0 ]
[]
[]
[ "excel", "python", "regex", "vba" ]
stackoverflow_0002770048_excel_python_regex_vba.txt
Q: Joining links together in a dictionary I have a dictionary links which holds a tuple mapped to a number. How can I join the second URL in the second tuple together with the urljoin() function? What I'm trying to do is get complete links so I can run a recursive function search() which takes a complete URL as an ar...
Joining links together in a dictionary
I have a dictionary links which holds a tuple mapped to a number. How can I join the second URL in the second tuple together with the urljoin() function? What I'm trying to do is get complete links so I can run a recursive function search() which takes a complete URL as an arguement, finds all the links in each URL and...
[ "1) There is no concept of \"first\" or \"second\" when considering the keys in a python dictionary; the keys have no defined order.\n2) It's very unclear what you're actually trying to do. You'll get better help if you work harder on describing the problem you're trying to solve. On the other hand, if this is a ho...
[ 0, 0 ]
[]
[]
[ "database", "python" ]
stackoverflow_0002841549_database_python.txt
Q: Compound dictionary keys I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virt...
Compound dictionary keys
I have a particular case where using compound dictionary keys would make a task easier. I have a working solution, but feel it is inelegant. How would you do it? context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.c...
[ ">>> def getitem(context, key):\n try:\n return context[key]\n except KeyError:\n pass\n cur, _, rest = key.partition('.')\n rest = int(rest) if rest.isdigit() else rest\n return getitem(context[cur], rest)\n\n\n>>> getitem(context, 'admins.0')\n'number2@virtucon.com'\n>>> getitem(conte...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "attributes", "dictionary", "python" ]
stackoverflow_0002841971_attributes_dictionary_python.txt
Q: How to enable a method in template of google-app-engine the method is: def printa(x): return x the response is: self.response.out.write(template.render(path, {'printa':printa})) the html is: {{ printa 'sss'}} I want to show 'sss' in my page , so how to do this , updated I create a templatetags folder, and 2...
How to enable a method in template of google-app-engine
the method is: def printa(x): return x the response is: self.response.out.write(template.render(path, {'printa':printa})) the html is: {{ printa 'sss'}} I want to show 'sss' in my page , so how to do this , updated I create a templatetags folder, and 2 py file: templatetags |--------__init__.py |-----...
[ "Using the default webapp template system (which is actually Django 0.96), you can't do this. You're expected to put the program logic in the program files, not in your templates, so you can't pass arguments to your variables.\nYou don't say what you're actually trying to do, though; I assume you don't literally w...
[ 1 ]
[]
[]
[ "google_app_engine", "methods", "python", "templates" ]
stackoverflow_0002842324_google_app_engine_methods_python_templates.txt
Q: How do you set the image attributes using PIL? I'm using PIL. I tried using : img.info = {'Buyer':'Text','Copyright':'Text2'} This is not working. Is there an alternate way to do it? A: I think you are looking for EXIF support which PIL is notoriously lacking. Other people have made their own modules to suppo...
How do you set the image attributes using PIL?
I'm using PIL. I tried using : img.info = {'Buyer':'Text','Copyright':'Text2'} This is not working. Is there an alternate way to do it?
[ "I think you are looking for EXIF support which PIL is notoriously lacking. \nOther people have made their own modules to support it: here is one that claims to write EXIF data properly which I found in a recent survey article of the topic of EXIF and Python.\n", "pyexiv2 library @ http://tilloy.net/dev/pyexiv2\n...
[ 3, 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002831497_python_python_imaging_library.txt
Q: Update Params in Python During Infinite Loop I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this? For example: x = 0 while True: x = x + 1 if x < 30: d...
Update Params in Python During Infinite Loop
I was hoping to get some help on a question. I have an infinite loop that I need run and I need to update a set of variables (x in this case) at random times from the command-line. Is there any way to do this? For example: x = 0 while True: x = x + 1 if x < 30: do something and I need to update x's value from t...
[ "To me it sounds like a better way to implement this would be to use a thread instead of an infinite loop and use the \nnotify()\n\nmethod to instruct when to update with data from command line\nHere is a good reference to get you started:\nhttp://docs.python.org/library/threading.html\n", "This is rather hackish...
[ 2, 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0002840745_loops_python.txt
Q: Using netbeans as IDE for Python I am about to embark on learning Python (largely for the purposes of using it as scripting glue between my applications). I use Netbeans (6.8) on Linux for both my C++ and PHP development work. Ideally, I would like to use the same IDE for Python - and there is a Python plugin for ...
Using netbeans as IDE for Python
I am about to embark on learning Python (largely for the purposes of using it as scripting glue between my applications). I use Netbeans (6.8) on Linux for both my C++ and PHP development work. Ideally, I would like to use the same IDE for Python - and there is a Python plugin for Netbeans (admittedly, its still in Bet...
[ "Although I've not been using it for long, I was in the same situation as yourself and just decided to bite the bullet. I haven't had any issues with it so far and found he most important thing to be that you are using an environment that you are both familiar and comfortable with. Any quirks you find along the way...
[ 0 ]
[]
[]
[ "netbeans", "netbeans6.8", "python" ]
stackoverflow_0002842867_netbeans_netbeans6.8_python.txt
Q: Django: How do I get logging working? I've added the following to my settings.py file: import logging ... logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename=os.path.join(rootdir, 'django.log'), filemode='a+') And in views.py, I've added: import logging lo...
Django: How do I get logging working?
I've added the following to my settings.py file: import logging ... logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename=os.path.join(rootdir, 'django.log'), filemode='a+') And in views.py, I've added: import logging log = logging.getLogger(__name__) ... log.inf...
[ "Python logging for Django is fine on somewhere like Webfaction. If you were on a cloud-based provider (eg Amazon EC2) where you had a number of servers, it might be worth looking at either logging to key-value DB or using Python logging over the network.\nYour logging setup code in settings.py looks fine, but I'd ...
[ 2 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002843092_django_logging_python.txt
Q: How can I write to the previous line in a log file using Python's Logging module? long-time lurker here, finally emerging from the woodwork. Essentially, what I'm trying to do is have my logger write data like this to the logfile: Connecting to database . . . Done. I'd like the 'Connecting to database . . . ' to ...
How can I write to the previous line in a log file using Python's Logging module?
long-time lurker here, finally emerging from the woodwork. Essentially, what I'm trying to do is have my logger write data like this to the logfile: Connecting to database . . . Done. I'd like the 'Connecting to database . . . ' to be written when the function is called, and the 'Done' written after the function has s...
[ "Writing to a log is, and must be, an atomic action -- this is crucial, and a key feature of any logging package (including the one in Python's standard library) that distinguishes logging from the simple appending of information to files (where bits of things being written by different processes and threads might ...
[ 14, 8, 3 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002839928_logging_python.txt
Q: Can this Django query be improved? Given a model structure like this: class Book(models.Model): user = models.ForeignKey(User) class Readingdate(models.Model): book = models.ForeignKey(Book) date = models.DateField() One book may have several Readingdates. How do I list books having at least one Rea...
Can this Django query be improved?
Given a model structure like this: class Book(models.Model): user = models.ForeignKey(User) class Readingdate(models.Model): book = models.ForeignKey(Book) date = models.DateField() One book may have several Readingdates. How do I list books having at least one Readingdate within a specific year? I can d...
[ "Book.objects.filter(readingdate__date__year=2010)\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002843613_django_python.txt
Q: how to make my method running on the template of google-app-engine the model is : class someModel(db.Model): name = db.StringProperty() def name_is_sss(self): return self.name=='sss' the view is : a=someModel() a.name='sss' path = os.path.join(os.path.dirname(__file__), os.path.join('...
how to make my method running on the template of google-app-engine
the model is : class someModel(db.Model): name = db.StringProperty() def name_is_sss(self): return self.name=='sss' the view is : a=someModel() a.name='sss' path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'blog/a.html')) self.response.out.write(template.render(...
[ "Did you try this already?\n{{ a.name_is_x('www') }}\n\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "methods", "python", "templates" ]
stackoverflow_0002842511_google_app_engine_methods_python_templates.txt
Q: How Can I Find a List of All Exceptions That a Given Library Function Throws in Python? Sorry for the long title, but it seems most descriptive for my question. Basically, I'm having a difficult time finding exception information in the official python documentation. For example, in one program I'm currently writi...
How Can I Find a List of All Exceptions That a Given Library Function Throws in Python?
Sorry for the long title, but it seems most descriptive for my question. Basically, I'm having a difficult time finding exception information in the official python documentation. For example, in one program I'm currently writing, I'm using the shutil libary's move function: from shutil import move move('somefile.txt',...
[ "To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote an article that addresses some of the overarching principles as does Eli Bendersky's note.\nThe problem with the sample code is that it is not handling errors, just prettifying them and discarding them. Y...
[ 12, 4, 3, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002843112_exception_python.txt
Q: Ping from AppEngine I know I can fetch url from AppEngine. But I just want to ping a website, without to get any other data. Is it possible? A: "ping" as in ICMP or "ping" as in send an HTTP request without getting the full response? If the latter, just send a HEAD request instead of a GET. If the former, the...
Ping from AppEngine
I know I can fetch url from AppEngine. But I just want to ping a website, without to get any other data. Is it possible?
[ "\"ping\" as in ICMP or \"ping\" as in send an HTTP request without getting the full response? If the latter, just send a HEAD request instead of a GET. \nIf the former, then that probably depends on your language of choice on AppEngine \n\nFor python, check out\nPing a site in Python?\nFor java, check out http:/...
[ 4, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002843838_google_app_engine_python.txt
Q: How to catch an exception thrown in ctypes? I am working with some C code called from Python using ctypes. Somewhere in the bowels of the C library, an exception is occurring and/or abort() is being called. Is there any way I can catch this in my Python caller code? (Platform is Linux) A: You might be able to ...
How to catch an exception thrown in ctypes?
I am working with some C code called from Python using ctypes. Somewhere in the bowels of the C library, an exception is occurring and/or abort() is being called. Is there any way I can catch this in my Python caller code? (Platform is Linux)
[ "You might be able to setup a signal handler on SIGABRT to handle the signal caused by abort().\nHowever, failed assertions might go along with corrupted memory and other bad things - there's usually a reason why an assertion failed. So usually terminating the applications is the best thing you can do (except displ...
[ 3 ]
[]
[]
[ "abort", "ctypes", "exception", "exception_handling", "python" ]
stackoverflow_0002844121_abort_ctypes_exception_exception_handling_python.txt
Q: Feedback on using ASE on Android? Has anyone made use of ASE (Android scripting enviroment) for anything other than proof of concept apps? What are the major limitations? Any feedback would be great. A: As this stage, using the ASE as your actual product's platform would in general be a bad move if performance i...
Feedback on using ASE on Android?
Has anyone made use of ASE (Android scripting enviroment) for anything other than proof of concept apps? What are the major limitations? Any feedback would be great.
[ "As this stage, using the ASE as your actual product's platform would in general be a bad move if performance is critical. It's great for rapidly prototyping something and/or verifying your understanding of how the API works. But the performance hit is nontrivial. This is the approach Google recommends, too:\n\nWit...
[ 4, 0 ]
[ "Since the GUI support is near to zero, my feedbacks about ASE are near to zero too.\n" ]
[ -2 ]
[ "android", "ase", "python" ]
stackoverflow_0002843845_android_ase_python.txt
Q: How does git fetches commits associated to a file? I'm writing a simple parser of .git/* files. I covered almost everything, like objects, refs, pack files etc. But I have a problem. Let's say I have a big 300M repository (in a pack file) and I want to find out all the commits which changed /some/deep/inside/file ...
How does git fetches commits associated to a file?
I'm writing a simple parser of .git/* files. I covered almost everything, like objects, refs, pack files etc. But I have a problem. Let's say I have a big 300M repository (in a pack file) and I want to find out all the commits which changed /some/deep/inside/file file. What I'm doing now is: fetching last commit findi...
[ "That's the basic algorithm that git uses to track changes to a particular file. That's why \"git log -- some/path/to/file.txt\" is a comparatively slow operation, compared to many other SCM systems where it would be simple (e.g. in CVS, P4 et al each repo file is a server file with the file's history).\nIt shouldn...
[ 1 ]
[]
[]
[ "git", "python" ]
stackoverflow_0002841863_git_python.txt
Q: Python Error-Checking Standard Practice I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input: def myFunction(filepath): infile = open(filepath) #etc etc... One possible precondition would be that the file should exist. There are a few possib...
Python Error-Checking Standard Practice
I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input: def myFunction(filepath): infile = open(filepath) #etc etc... One possible precondition would be that the file should exist. There are a few possible ways to check for this precondition, and I...
[ "If all you want to do is raise an exception, use option iii:\ndef myFunction(filepath):\n with open(filepath) as infile:\n pass\n\nTo handle exceptions in a special way, use a try...except block:\ndef myFunction(filepath):\n try:\n with open(filepath) as infile:\n pass\n except IO...
[ 16, 4, 3, 1 ]
[]
[]
[ "assert", "error_handling", "python" ]
stackoverflow_0002843702_assert_error_handling_python.txt
Q: Modify an XML file in Python I have two files, file1 and file2. I have to modify file1 in a particular node and add in a list of children. The list is in file2. Can I do it, and how? from xml.dom.minidom import Document from xml.dom import minidom file1=modificare.xml file2=sorgente.xml xmldoc=minidom.parse(fi...
Modify an XML file in Python
I have two files, file1 and file2. I have to modify file1 in a particular node and add in a list of children. The list is in file2. Can I do it, and how? from xml.dom.minidom import Document from xml.dom import minidom file1=modificare.xml file2=sorgente.xml xmldoc=minidom.parse(file1) for Node in xmldoc.getElemen...
[ "use ElementTree:\nfrom xml.etree.ElementTree import Element, SubElement, Comment, tostring\n\n# Configure one attribute with set()\nroot = Element('opml')\nroot.set('version', '1.0')\n\nroot.append(Comment('Generated by ElementTree_csv_to_xml.py for PyMOTW'))\n\nhttp://broadcast.oreilly.com/2010/03/pymotw-creating...
[ 3 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002844237_python_xml.txt
Q: Is it possible to craft your own packets with python? Well, I know its possible, using external libraries and modules such as scapy. But how about without external modules? Without running the script as root? No external dependencies? I've been doing a lot of googling, but haven't found much help. I'd like to be a...
Is it possible to craft your own packets with python?
Well, I know its possible, using external libraries and modules such as scapy. But how about without external modules? Without running the script as root? No external dependencies? I've been doing a lot of googling, but haven't found much help. I'd like to be able to create my own packets, but without running as root, ...
[ "Here's how to code raw ICMP \"ping\" packets in Python:\nhttp://www.g-loaded.eu/2009/10/30/python-ping/\n", "Many operating systems (Linux) do not allow raw sockets unless your effective user ID is 0 (aka root). This isn't a library issue. Some operating systems (non-server Windows post Windows XP SP2) do not al...
[ 2, 1 ]
[]
[]
[ "packets", "python", "sockets" ]
stackoverflow_0002842561_packets_python_sockets.txt
Q: Google app engine: empty property in datastore Let say I have a model: class A(db.Model): B = db.StringProperty() C = db.StringProperty() How do I query if I wanted to search all empty property (not None, just empty) in C using python? A: From GAE Python documents It is not possible to perform a query ...
Google app engine: empty property in datastore
Let say I have a model: class A(db.Model): B = db.StringProperty() C = db.StringProperty() How do I query if I wanted to search all empty property (not None, just empty) in C using python?
[ "From GAE Python documents\n\nIt is not possible to perform a query\n for entities that are missing a given\n property. One alternative is to create\n a fixed (modeled) property with a\n default value of None, then create a\n filter for entities with None as the\n property value.\n\n" ]
[ 4 ]
[ "Well if you want to return all rows with empty C properties you could do this.\nempty = db.GqlQuery('SELECT * FROM A WHERE C = \"\"')\n" ]
[ -2 ]
[ "google_app_engine", "python" ]
stackoverflow_0002842661_google_app_engine_python.txt
Q: Python: how to inherit and override Consider this situation: I get an object of type A which has the function f: class A: def f(self): print 'in f' def h(self): print 'in h' and I get an instance of this class, but I want to override the f function, yet save the rest of the functionality of A. S...
Python: how to inherit and override
Consider this situation: I get an object of type A which has the function f: class A: def f(self): print 'in f' def h(self): print 'in h' and I get an instance of this class, but I want to override the f function, yet save the rest of the functionality of A. So what I was thinking was something of th...
[ "How you construct an object of subclass B \"based on\" one of class A depends exclusively on how the latter keeps state, if any, and how do you best get to that state and copy it over. In your example, instances of A are stateless, therefore there is absolutely no work you need to do in B's '__init__'. In a more...
[ 11, 5, 2 ]
[]
[]
[ "inheritance", "overriding", "python" ]
stackoverflow_0002843165_inheritance_overriding_python.txt
Q: Go through a number of functions in Python I have an unknown number of functions in my python script (well, it is known, but not constant) that start with site_... I was wondering if there's a way to go through all of these functions in some main function that calls for them. something like: foreach function_that_...
Go through a number of functions in Python
I have an unknown number of functions in my python script (well, it is known, but not constant) that start with site_... I was wondering if there's a way to go through all of these functions in some main function that calls for them. something like: foreach function_that_has_site_ as coolfunc if coolfunc(blabla,yada...
[ "The inspect module, already mentioned in other answers, is especially handy because you get to easily filter the names and values of objects you care about. inspect.getmembers takes two arguments: the object whose members you're exploring, and a predicate (a function returning bool) which will accept (return True...
[ 5, 3, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002843053_python.txt
Q: Running a Python script for a user-specified amount of time I've just started learning Python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified am...
Running a Python script for a user-specified amount of time
I've just started learning Python today. I've been reading a Byte of Python. Right now I have a project for Python that involves time. I can't find anything relating to time in Byte of Python, so I'll ask you: How can I run a block for a user specified amount of time and then break? For example (in some pseudo-code): t...
[ "I recommend spawning another thread, making it a daemon thread, then sleeping until you want the task to die. For example:\nfrom time import sleep\nfrom threading import Thread\n\ndef some_task():\n while True:\n pass\n\nt = Thread(target=some_task) # run the some_task function in another\n ...
[ 26, 15, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002831775_python.txt
Q: Using Python to add/remove Ubuntu login script items I have written a Python application and would like to give my users the option of having the app automatically launch itself when the user logs in. It is important that the user is able to toggle this option on/off from within the app itself, rather than having ...
Using Python to add/remove Ubuntu login script items
I have written a Python application and would like to give my users the option of having the app automatically launch itself when the user logs in. It is important that the user is able to toggle this option on/off from within the app itself, rather than having to manually edit login scripts, so this needs to be done f...
[ "Here's what you need to handle autostart.\n" ]
[ 2 ]
[]
[]
[ "linux", "login_script", "python", "ubuntu" ]
stackoverflow_0002844554_linux_login_script_python_ubuntu.txt
Q: Enterprise Platform in Python, Design Advice I am starting the design of a somewhat large enterprise platform in Python, and was wondering if you guys can give me some advice as to how to organize the various components and which packages would help achieve the goals of scalability, maintainability, and reliabilit...
Enterprise Platform in Python, Design Advice
I am starting the design of a somewhat large enterprise platform in Python, and was wondering if you guys can give me some advice as to how to organize the various components and which packages would help achieve the goals of scalability, maintainability, and reliability. The system is basically a service that collect...
[ "Consider using Celery. It lets your web apps do as little as possible, then fire off other tasks that'll be completed later. It uses AMQP (RabbitMQ) underneath, but it's in Python and plays very well with Django.\nhttp://celeryproject.org/\n(If you want to learn more AMQP, I wrote up some slides:\nhttp://johntell...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002821122_django_python.txt
Q: Get the path to Django itself I've got some code that runs on every (nearly) every admin request but doesn't have access to the 'request' object. I need to find the path to Django installation. I could do: import django django_path = django.__file__ but that seems rather wasteful in the middle of a request. Does ...
Get the path to Django itself
I've got some code that runs on every (nearly) every admin request but doesn't have access to the 'request' object. I need to find the path to Django installation. I could do: import django django_path = django.__file__ but that seems rather wasteful in the middle of a request. Does putting the import at the start of ...
[ "So long as Django has already been imported in the Python process (which it has, if your code is, for example, in a view function), importing it again won't do \"anything\"* — so go nuts, use import django; django.__file__.\nNow, if Django hasn't been imported by the current Python process (eg, you're calling os.s...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002845137_django_python.txt
Q: How to use nose coverage with --timid flag I'd like to run "nosetests --with-coverage" using Ned Batchelder's coverage module, but passing the coverage module the --timid flag. Is there a way (e.g. setting an environment variable) to make coverage run with --timid? A: You've got two options: Use a .coveragerc f...
How to use nose coverage with --timid flag
I'd like to run "nosetests --with-coverage" using Ned Batchelder's coverage module, but passing the coverage module the --timid flag. Is there a way (e.g. setting an environment variable) to make coverage run with --timid?
[ "You've got two options:\n\nUse a .coveragerc file to provide options to coverage.py\nInstead of running coverage inside nose, run nose inside coverage:\ncoverage run c:\\python25\\scripts\\nosetests-script.py \n\n\n(sorry for the Windows syntax if you aren't on Windows)\n" ]
[ 3 ]
[]
[]
[ "code_coverage", "nose", "python" ]
stackoverflow_0002735738_code_coverage_nose_python.txt
Q: Extracting data from a text file to use in a python script? Basically, I have a file like this: Url/Host: www.example.com Login: user Password: password Data_I_Dont_Need: something_else How can I use RegEx to separate the details to place them into variables? Sorry if this is a terrible question, I can...
Extracting data from a text file to use in a python script?
Basically, I have a file like this: Url/Host: www.example.com Login: user Password: password Data_I_Dont_Need: something_else How can I use RegEx to separate the details to place them into variables? Sorry if this is a terrible question, I can just never grasp RegEx. So another question would be, can you pr...
[ "You should put the entries in a dictionary, not in so many separate variables -- clearly, the keys you're using need NOT be acceptable as variable names (that slash in 'Url/Host' would be a killer!-), but they'll be just fine as string keys into a dictionary.\nimport re\n\nthere = re.compile(r'''(?x) # verbos...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002845018_python_regex.txt
Q: Awakening a thread by a queue I want my thread to sleep when a queue is empty and wake up only when a data is put in it. Should I use a condition object? I have never used this object before and I can't find a simple example in python. A: If the queue object in question is bound to name q, just call q.get(): it...
Awakening a thread by a queue
I want my thread to sleep when a queue is empty and wake up only when a data is put in it. Should I use a condition object? I have never used this object before and I can't find a simple example in python.
[ "If the queue object in question is bound to name q, just call q.get(): it will sleep patiently as long as the queue is empty, then return the queue's first item as soon as the queue is made non-empty by another thread executing a .put(whatever) on it. While the docs may not be stellarly clear about this, that's t...
[ 4, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0002845749_multithreading_python.txt
Q: Dreaded python encoding errors, how to stop them? These have been plaguing me endlessly. Why? It seems that my console can't handle the encoding. I take it that the my browser and word processor can handle it. I don't have a master list of all the possible characters that it's choking on. What is the best way to r...
Dreaded python encoding errors, how to stop them?
These have been plaguing me endlessly. Why? It seems that my console can't handle the encoding. I take it that the my browser and word processor can handle it. I don't have a master list of all the possible characters that it's choking on. What is the best way to relieve this without modifying my data? 'charmap' codec ...
[ "You need to find out the encoding of your console (which system, OS, etc...?) -- 'charmap' is unfortunately a somewhat-ambiguous identification for a codec, as the docs explain:\n\nThere’s another group of encodings\n (the so called charmap encodings) that\n choose a different subset of all\n unicode code point...
[ 2 ]
[]
[]
[ "character_encoding", "python", "unicode", "utf_8" ]
stackoverflow_0002846043_character_encoding_python_unicode_utf_8.txt
Q: grabbing a substring while scraping with Python2.6 Hey can someone help with the following? I'm trying to scrape a site that has the following information.. I need to pull just the number after the </strong> tag.. [<li><strong>ISBN-13:</strong> 9780375853401</li>, <li><strong>Pub. Date: </strong> 05/11/2010</li>] ...
grabbing a substring while scraping with Python2.6
Hey can someone help with the following? I'm trying to scrape a site that has the following information.. I need to pull just the number after the </strong> tag.. [<li><strong>ISBN-13:</strong> 9780375853401</li>, <li><strong>Pub. Date: </strong> 05/11/2010</li>] [<li><strong>UPC:</strong> 490355000372</li>, <li><stron...
[ "I imagine upc_code is the list you're showing us, and the local_links one has nothing to do with your question right? Given that you don't mention it further in your code...?\nSo I'm not certain what upc_text would be in your loop's body given that upc is a ul Tag -- upc.contents is going to be a list of li tags ...
[ 2 ]
[]
[]
[ "beautifulsoup", "list", "mechanize", "python", "substring" ]
stackoverflow_0002845689_beautifulsoup_list_mechanize_python_substring.txt