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: string mask and offset with regex I have a string on which I try to create a regex mask that will show N number of words, given an offset. Let's say I have the following string: "The quick, brown fox jumps over the lazy dog." I want to show 3 words at the time: offset 0: "The quick, brown" offset 1: "quick, brown ...
string mask and offset with regex
I have a string on which I try to create a regex mask that will show N number of words, given an offset. Let's say I have the following string: "The quick, brown fox jumps over the lazy dog." I want to show 3 words at the time: offset 0: "The quick, brown" offset 1: "quick, brown fox" offset 2: "brown fox jumps" offset...
[ "The prefix-matching option\nYou can make this work by having a variable-prefix regex to skip the first offset words, and capturing the word triplet into a group.\nSo something like this:\nimport re\ns = \"The quick, brown fox jumps over the lazy dog.\"\n\nprint re.search(r'(?:\\w+\\W*){0}((?:\\w+\\W*){3})', s).gro...
[ 5, 2, 1, 1 ]
[]
[]
[ "python", "regex", "regex_negation" ]
stackoverflow_0003275324_python_regex_regex_negation.txt
Q: Processing High-Volume Streaming Data with Twisted or using Threads, Queue in Python I am getting at extremely fast rate, tweets from a long-lived connection to the Twitter API Streaming Server. I proceed by doing some heavy text processing and save the tweets in my database. I am using PyCurl for the connection a...
Processing High-Volume Streaming Data with Twisted or using Threads, Queue in Python
I am getting at extremely fast rate, tweets from a long-lived connection to the Twitter API Streaming Server. I proceed by doing some heavy text processing and save the tweets in my database. I am using PyCurl for the connection and callback function that care of text processing and saving in the db. See below my appro...
[ "You should have a number of threads receiving the messages as they come in. That number should probably be 1 if you are using pycurl, but should be higher if you are using httplib - the idea being you want to be able to have more than one query on the Twitter API at a time, so there is a steady amount of work to p...
[ 2, 1, 1 ]
[]
[]
[ "python", "stream", "twisted", "twitter" ]
stackoverflow_0003180597_python_stream_twisted_twitter.txt
Q: Adding options which both change behaviour and store an argument Using the argparse module, is it possible to perform multiple actions for a given argument? Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving info...
Adding options which both change behaviour and store an argument
Using the argparse module, is it possible to perform multiple actions for a given argument? Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving information about all possibilities in a set or about one particular possi...
[ "Simply implement your own Action subclass. This basically looks like this:\nclass ListAction(argparse.Action):\n def __call__(parser, namespace, values, option_string=None):\n setattr(namespace, 'list', values[0])\n do_something_completely_different()\n\nThe argparse documentation has more detail...
[ 1 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0003276137_argparse_python.txt
Q: Execute Python program using PHP Can I simply execute Python program using PHP like this? (in a browser) exec("python myProgram /Applications/MAMP/htdocs/somefile.xml"); or like this: exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml"); Is any of this method correct? If not, what sho...
Execute Python program using PHP
Can I simply execute Python program using PHP like this? (in a browser) exec("python myProgram /Applications/MAMP/htdocs/somefile.xml"); or like this: exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml"); Is any of this method correct? If not, what should be the right way to do it? Thanks
[ "if you want to capture output as well, use proc_open (full fd connectivity, i.e. input and output) or popen (either in- or output)\n", "I would prefer using proc_open() as suggested by mvds as you can't write to STDIN nor read from STDOUT with exec()/shell_exec(), as well as providing your own set of environment...
[ 1, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003276491_php_python.txt
Q: execute functions in a queue i have a example who should show what i'd like to do queue = 2 def function(): print 'abcd' time.sleep(3) def exec_times(times): #do something function() def exec_queue(queue): #do something function() exec_times(3) #things need be working while it waiting f...
execute functions in a queue
i have a example who should show what i'd like to do queue = 2 def function(): print 'abcd' time.sleep(3) def exec_times(times): #do something function() def exec_queue(queue): #do something function() exec_times(3) #things need be working while it waiting for the function finish time.sleep(...
[ "If you want to avoid threads, one option is to use multiple processes. If you're on python 2.6, take a look at the multiprocessing module. If python 2.5, look at pyprocessing.\nNote \"Process Pools\" in the docs for multiprocessing, which seem to handle your requirements:\n\nOne can create a pool of processes wh...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003276595_python.txt
Q: Optimize a list comprehension Here is a code snippet that shows the code I would like to optimize: result = [(item, foo(item)) for item in item_list if cond1(item) and cond2(foo(item))] In the above snippet I call foo(item) twice. I can't think of a way to iterate over the list only once maint...
Optimize a list comprehension
Here is a code snippet that shows the code I would like to optimize: result = [(item, foo(item)) for item in item_list if cond1(item) and cond2(foo(item))] In the above snippet I call foo(item) twice. I can't think of a way to iterate over the list only once maintain both item and foo(item) for the...
[ "It doesn't, but here:\nresult = [(item, foo_item)\n for item, foo_item in ((i, foo(i)) for i in item_list)\n if cond1(item) and cond2(foo_item)]\n\nTurning the inner list comprehension into a generator expression makes sure that we don't use an unnecessary temporary list.\n", "Like I've been repeatedly tol...
[ 4, 4, 3, 3, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003251480_list_comprehension_python.txt
Q: Find an element and return the XPath to it using Python I'm using Python 2.4/2.5, with libxm2dom. I can import an HTML document, and build the DOM. Is there a way to programmatically "search" for a given term, and be able to craft the XPath function to extract the href for the term? For example, given this chunk o...
Find an element and return the XPath to it using Python
I'm using Python 2.4/2.5, with libxm2dom. I can import an HTML document, and build the DOM. Is there a way to programmatically "search" for a given term, and be able to craft the XPath function to extract the href for the term? For example, given this chunk of HTML from the document: ... <a href="dog">bigdog</a> ... I...
[ "This XPATH will select the @href of the a element who's text is \"bigdog\".\n//a[text()='bigdog']/@href\n\n" ]
[ 0 ]
[]
[]
[ "libxml2", "python", "python_2.x", "xpath" ]
stackoverflow_0003275794_libxml2_python_python_2.x_xpath.txt
Q: why model has the key_name don't has the key().id() on google-app-engine if i use this : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A() a.a='sss' a.put() raise Exception(a.key().id()) i can get the a.key().id() is 961 but if i...
why model has the key_name don't has the key().id() on google-app-engine
if i use this : class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a=A() a.a='sss' a.put() raise Exception(a.key().id()) i can get the a.key().id() is 961 but if i add key_name="aaa" , the a.key().id() will be None : class A(db.Model): a...
[ "You can't, because they're the same thing.\nThe fact that entities have an encoded string key plus either an integer ID or a string name can give the misleading impression that the various ways to refer to an entity are overlapping or redundant. They're not.\nA key name is like a filename within a filesystem. An I...
[ 6 ]
[]
[]
[ "google_app_engine", "key", "python" ]
stackoverflow_0003276558_google_app_engine_key_python.txt
Q: how to Reference the variable via db.run_in_transaction on google-app-engine this is my code: class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a='' def fn(): global a a=A(a='www') a.put() db.run_in_transact...
how to Reference the variable via db.run_in_transaction on google-app-engine
this is my code: class A(db.Model): a=db.StringProperty() class demo(BaseRequestHandler): def get(self): a='' def fn(): global a a=A(a='www') a.put() db.run_in_transaction(fn) raise Exception(a.key()) and the error is : raise Exception(a.key...
[ "Try this:\nclass demo(BaseRequestHandler):\n def get(self):\n def fn():\n a=A(a='www')\n a.put()\n return a\n a = db.run_in_transaction(fn)\n raise Exception(a.key())\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "transactions" ]
stackoverflow_0003276736_google_app_engine_python_transactions.txt
Q: MySQL: conduct a basic search I have a names table in my database and I would wish to conduct a fuzzy search on it for example my database contains: Name ID John Smith 1 Edward Smith 2 Gabriel Gray 3 Paul Roberts 4 At the moment when I search the database via python I can only do exact match searching....
MySQL: conduct a basic search
I have a names table in my database and I would wish to conduct a fuzzy search on it for example my database contains: Name ID John Smith 1 Edward Smith 2 Gabriel Gray 3 Paul Roberts 4 At the moment when I search the database via python I can only do exact match searching. But I would like to be able to do ...
[ "In simplest form, you'd use the LIKE comparison:\nSELECT * FROM table WHERE name LIKE '%smith%';\n\nMore elaborate searches can de done with FULLTEXT index (large amounts of text), SOUNDEX() (works on words in the english language, matching on other languages is everything from 'somewhat workable' to 'terrible'), ...
[ 5, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003276904_mysql_python.txt
Q: Fabric auto-login in Windows Relevant question: fabric password I configured Putty to login with private-public keys (no password) using this guide: http://www.codelathe.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/ It works. Now I want to run Fabric with no password prompt. This does not work...
Fabric auto-login in Windows
Relevant question: fabric password I configured Putty to login with private-public keys (no password) using this guide: http://www.codelathe.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/ It works. Now I want to run Fabric with no password prompt. This does not work and I get prompted for a password...
[ "Adding the following to your fabfile.py should work:\nenv.user = \"your_username\"\nenv.key_filename = [\"/path/to/keyfile\"]\n\nSee the fabric docs.\n" ]
[ 9 ]
[]
[]
[ "fabric", "paramiko", "python", "ssh", "windows" ]
stackoverflow_0003277022_fabric_paramiko_python_ssh_windows.txt
Q: Python: is it possible to mix generator and a recursive function? Is there a way to make the something like the following code work? add = lambda n: (yield n) or add(n+1) (answers don't need to be in functional style) A: I'm not sure of the intent of "yield(n) or add(n+1)", but recursive generators are certainl...
Python: is it possible to mix generator and a recursive function?
Is there a way to make the something like the following code work? add = lambda n: (yield n) or add(n+1) (answers don't need to be in functional style)
[ "I'm not sure of the intent of \"yield(n) or add(n+1)\", but recursive generators are certainly possible. You might want to read the link below to get a grip on what's possible, in particular the section titled \"Recursive Generators\".\n\nPython Generator Tricks\n\n", "def add(n):\n yield n\n for m in add...
[ 3, 3, 0 ]
[]
[]
[ "generator", "python", "recursion" ]
stackoverflow_0003276956_generator_python_recursion.txt
Q: extend/append list I would like to either extend or append a list to the content of another list: I've got the following: l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] m = ['first', 'second', 'third'] for i in range(len(l)): resul...
extend/append list
I would like to either extend or append a list to the content of another list: I've got the following: l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] m = ['first', 'second', 'third'] for i in range(len(l)): result = [] for n in m: ...
[ "All you need is zip:\nl = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33))\nls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)]\n\nfor x,y in zip(l,ls):\n print(list(x+y))\n\n# ['AA', 1.1100000000000001, 'XX', 7.7699999999999996]\n# ['BB', 2.2200000000000002, 'YY', 8.8800000000000008]\n# ['CC', 3.3300000000000001, 'ZZ', ...
[ 11, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003277216_python.txt
Q: how to parse the remainder: [0] on google-app-engine my code is : class demo(BaseRequestHandler): def get(self): a=[[1,2,3],[3,6,9]] self.render_template('map/a.html',{'geo':a}) and the html is : {% for i in geo %} <p><a href="{{ i[0] }}">{{ i[0]}}</a></p> {% endfor%} and the error...
how to parse the remainder: [0] on google-app-engine
my code is : class demo(BaseRequestHandler): def get(self): a=[[1,2,3],[3,6,9]] self.render_template('map/a.html',{'geo':a}) and the html is : {% for i in geo %} <p><a href="{{ i[0] }}">{{ i[0]}}</a></p> {% endfor%} and the error is : raise TemplateSyntaxError, "Could not parse the remai...
[ "If you want the page to show the first item of each list:\n{% for i in geo %}\n <p><a href=\"{{ i.0 }}\">{{ i.0 }}</a></p>\n{% endfor%}\n\n", "It doesn't mean you need to parse the remainder; it's saying the template engine tried to parse your i[0], understood i, but was unable to parse the remainder of the str...
[ 8, 1 ]
[]
[]
[ "arrays", "google_app_engine", "python" ]
stackoverflow_0003277108_arrays_google_app_engine_python.txt
Q: Implementing class descriptors by subclassing the `type` class I'd like to have some data descriptors as part of a class. Meaning that I'd like class attributes to actually be properties, whose access is handled by class methods. It seems that Python doesn't directly support this, but that it can be implemented b...
Implementing class descriptors by subclassing the `type` class
I'd like to have some data descriptors as part of a class. Meaning that I'd like class attributes to actually be properties, whose access is handled by class methods. It seems that Python doesn't directly support this, but that it can be implemented by subclassing the type class. So adding a property to a subclass of...
[ "Is this what you mean by \"class attributes to actually be properties, whose access is handled by class methods\"?\nYou can use a decorator property to make an accessor appear to be an actual data member. Then, you can use the x.setter decorator to make a setter for that attribute.\nBe sure to inherit from object,...
[ 1, 1 ]
[]
[]
[ "class", "class_attributes", "descriptor", "properties", "python" ]
stackoverflow_0003277047_class_class_attributes_descriptor_properties_python.txt
Q: Is Python-based software considered less-professional than C++/compiled software? I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK. The C++ SDK documentation appears incomplete in certain areas and isn't documented th...
Is Python-based software considered less-professional than C++/compiled software?
I'm working on a plugin for some software that I'm planning on selling someday. The software I'm making it for has both a C++ SDK and a Python SDK. The C++ SDK documentation appears incomplete in certain areas and isn't documented that well. The Python SDK docs appear more complete and in general are much easier to wor...
[ "\nA lot of programmers out there don't even considered writing Python to be real \"programming\".\n\nA lot of \"programmers\" out there are incompetent, too.\n\nDo you think that potential customers might say \"Why would I pay money for a measly little Python script?\"?\n\nI'm sure it depends on the type of softwa...
[ 6, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0003277376_c++_python.txt
Q: Set Django ModelForm visible fields at runtime? I have a Django model: class Customer(models.Model): first_name=models.CharField(max_length=20,null=True, blank=True) last_name=models.CharField(max_length=25,null=True, blank=True) address=models.CharField(max_length=60,null=True, blank=True) address2=models...
Set Django ModelForm visible fields at runtime?
I have a Django model: class Customer(models.Model): first_name=models.CharField(max_length=20,null=True, blank=True) last_name=models.CharField(max_length=25,null=True, blank=True) address=models.CharField(max_length=60,null=True, blank=True) address2=models.CharField(max_length=60,null=True, blank=True) cit...
[ "from django.forms import ModelForm\nfrom wherever import Customer\ndef formClassFactory(model,fields):\n ff = fields\n mm = model\n class formClass(ModelForm):\n class Meta:\n model = mm\n fields = ff\n return formClass\nform_class = formClassFactory( ('first_name','last_name') )\n\n" ]
[ 4 ]
[]
[]
[ "django", "modelform", "models", "python", "runtime" ]
stackoverflow_0003276896_django_modelform_models_python_runtime.txt
Q: Python object oriented model I have something like the follwing. A person having many colors of cars of the same model belonging to some state. I have designed a person class as having attributes person name, car model, car year, car state, and car color as attributes. And color should be a list as a person can ha...
Python object oriented model
I have something like the follwing. A person having many colors of cars of the same model belonging to some state. I have designed a person class as having attributes person name, car model, car year, car state, and car color as attributes. And color should be a list as a person can have many cars of different colors b...
[ "You might want to model state and car separately from person. Then, each person can have a list of cars, and live in a state (or even a list of states, depending on your model). These are has-a relationships. It will also allow you to subclass car later and make sportsCar later, if you want.\n", "You wanted to k...
[ 2, 2, 2 ]
[]
[]
[ "class_design", "oop", "python" ]
stackoverflow_0003277404_class_design_oop_python.txt
Q: Error using redirect in pylons Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simplef...
Error using redirect in pylons
Using Pylons verson 1.0: Working on the FormDemo example from the Pylons book: http://pylonsbook.com/en/1.1/working-with-forms-and-validators.html My controller has the following functions: class FormtestController(BaseController): def form(self): return render('/simpleform.html') def submit(self): ...
[ "Try:\nfrom pylons import url\nfrom pylons.controllers.util import redirect\n\n# ...\nredirect(url(controller='formtest', action='result'))\n\nYou might be better off using the current Pylons 1.0 documentation and the QuickWiki tutorial updated for 1.0, among other references on the site.\n" ]
[ 6 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0003277765_pylons_python.txt
Q: Possible to pass more than 1 argument to a context processor in Django? Is it possible to pass more than 1 argument to a context processor in Django? In other words, in addition to the HttpRequest object, I would like to pass 1 or more additional argument? A: Store whatever variables you would want in the sessio...
Possible to pass more than 1 argument to a context processor in Django?
Is it possible to pass more than 1 argument to a context processor in Django? In other words, in addition to the HttpRequest object, I would like to pass 1 or more additional argument?
[ "Store whatever variables you would want in the session. Then you can access it through the request.\n", "You might want to look into custom tags:\nhttp://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags\nMake sure that your template tags module is in a templatetags subdir of a...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003277307_django_python.txt
Q: Using Lambdas to build executable functions from string expressions I'm using python, and I want a function that takes a string containing a mathematical expression of one variable (x) and returns a function that evaluates that expression using lambdas. Syntax should be such: f = f_of_x("sin(pi*x)/(1+x**2)") print...
Using Lambdas to build executable functions from string expressions
I'm using python, and I want a function that takes a string containing a mathematical expression of one variable (x) and returns a function that evaluates that expression using lambdas. Syntax should be such: f = f_of_x("sin(pi*x)/(1+x**2)") print f(0.5) 0.8 syntax should allow ( ) as well as [ ] and use standard oper...
[ "How about this:\nimport math\ndef f_of_x(op):\n return eval(\"lambda x:\" + op, math.__dict__)\n\nIt can easily be made to support [] as well as () and uses standard operator precedence. It does not let you use trig functions without parens, though, nor does it let you imply multiplication by juxtaposition (lik...
[ 5, 0, 0 ]
[]
[]
[ "lambda", "math", "parsing", "python" ]
stackoverflow_0003278151_lambda_math_parsing_python.txt
Q: gdata python analytics metrics and dimensions error I am using the gdata module in python, when using this query I get an 'Illegal combination of dimensions and metrics' error. I have looked at documentation but not found the reason. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': tid, '...
gdata python analytics metrics and dimensions error
I am using the gdata module in python, when using this query I get an 'Illegal combination of dimensions and metrics' error. I have looked at documentation but not found the reason. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': tid, 'start-date': '2010-04-20', 'end-date': '2010-04-2...
[ "I would suggest using the data explorer to manually construct the uri first.\n" ]
[ 1 ]
[]
[]
[ "gdata_api", "python" ]
stackoverflow_0002692126_gdata_api_python.txt
Q: No IDLE Subprocess connection I'm new to python programming, and want to try to edit scripts in IDLE instead of the OSX command line. However, when I try to start it, it gives me the error "Idle Subprocess didn't make a connection. Either Idle can't start a subprocess or personal firewall software is blocking the ...
No IDLE Subprocess connection
I'm new to python programming, and want to try to edit scripts in IDLE instead of the OSX command line. However, when I try to start it, it gives me the error "Idle Subprocess didn't make a connection. Either Idle can't start a subprocess or personal firewall software is blocking the connection." I don't have a firewal...
[ "You can try running IDLE with the \"-n\" option. From the IDLE help:\n\nRunning without a subprocess:\n\n If IDLE is started with the -n command line switch it will run in a\n single process and will not create the subprocess which runs the RPC\n Python execution server. This can be useful if Python can...
[ 2, 2 ]
[]
[]
[ "macos", "python", "subprocess" ]
stackoverflow_0003277946_macos_python_subprocess.txt
Q: Move cursor upon right click in TextView? At the moment, when one right clicks in a TextView, a popup menu is brought up, but the cursor doesn't actually change position to where one is right clicking, it just leaves the cursor alone. For me, whom is trying to implement a spell checking menu, this isn't good since...
Move cursor upon right click in TextView?
At the moment, when one right clicks in a TextView, a popup menu is brought up, but the cursor doesn't actually change position to where one is right clicking, it just leaves the cursor alone. For me, whom is trying to implement a spell checking menu, this isn't good since I have to click THEN right click in order to g...
[ "Well, I stumbled across gtk.TextView.get_iter_at_location, which lead me to gtk.TextView.get_pointer and gtk.TextView.window_to_buffer_coords. Basically, to get this working, I did this:\n x, y = self.textView.get_pointer()\n x, y = self.textView.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET, x, y)\n if ...
[ 3 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003278215_pygtk_python.txt
Q: comparison between the elements of list with keys of dictionary I need to check if a particular key is present in some dictionary. I can use has_key ?? Is there any other method to compare the items of the list to the key of dictionary. I have a list like...[(3,4),(4,5)..] I need to check if the (3,4) is there in...
comparison between the elements of list with keys of dictionary
I need to check if a particular key is present in some dictionary. I can use has_key ?? Is there any other method to compare the items of the list to the key of dictionary. I have a list like...[(3,4),(4,5)..] I need to check if the (3,4) is there in the dictionary.
[ "Something like this?\n>>> d = { (1,3):\"foo\", (2,6):\"bar\" }\n>>> print (1,3) in d\nTrue\n>>> print (1,4) in d\nFalse\n>>> L = [ (1,3), (1,4), (15) ]\n>>> print [ x in d for x in L ]\n[True, False, False]\n\nIf you want to add missing entries you'll need an explicit loop\nfor x in L:\n if x not in d:\n d[x]=...
[ 4, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003278831_dictionary_python.txt
Q: In Python - a way to choose which dictionary to iterate over (and manipulate values in) Here's my problem: Lets say I have two dictionaries, dict_a and dict_b. Each of them have similar keys and values that I can manipulate in the same way, and in fact that's what I'm doing in a large piece of code. Only I don't ...
In Python - a way to choose which dictionary to iterate over (and manipulate values in)
Here's my problem: Lets say I have two dictionaries, dict_a and dict_b. Each of them have similar keys and values that I can manipulate in the same way, and in fact that's what I'm doing in a large piece of code. Only I don't want to have to write it twice. However, I can't do something like this: if choose_a == 1: ...
[ "Perhaps do something like this:\nif choose_a == 1: the_dict=dict_a\nelif choose_b == 1: the_dict=dict_b\n\nfor x,y in the_dict.iteritems():\n # do stuff with x and y.\n\n", "def do_stuff( d ):\n for x and y in d.iteritems():\n whatever with x and y\nif choose_a == 1: do_stuff( dict_a ) \nif choose_b ==...
[ 4, 3, 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003278263_dictionary_python.txt
Q: python dictionary key Vs object attribute suppose i have object has key 'dlist0' with attribute 'row_id' the i can access as getattr(dlist0,'row_id') then it return value but if i have a dictionary ddict0 = {'row_id':4, 'name':'account_balance'} getattr(ddict0,'row_id') it is not work my question is how can i ...
python dictionary key Vs object attribute
suppose i have object has key 'dlist0' with attribute 'row_id' the i can access as getattr(dlist0,'row_id') then it return value but if i have a dictionary ddict0 = {'row_id':4, 'name':'account_balance'} getattr(ddict0,'row_id') it is not work my question is how can i access ddict0 and dlist0 same way any one can ...
[ "Dictionaries have items, and thus use whatever is defined as __getitem__() to retrieve the value of a key.\nObjects have attributes, and thus use __getattr__() to retrieve the value of an attribute.\nYou can theoretically override one to point at the other, if you need to - but why do you need to? Why not just wri...
[ 7, 1 ]
[]
[]
[ "dictionary", "object", "python" ]
stackoverflow_0003279011_dictionary_object_python.txt
Q: Python pack arguments? is to possible to "pack" arguments in python? I have the following functions in the library, that I can't change (simplified): def g(a,b=2): print a,b def f(arg): g(arg) I can do o={'a':10,'b':20} g(**o) 10 20 but can I/how do I pass this through f? That's what I don't want: f(**o...
Python pack arguments?
is to possible to "pack" arguments in python? I have the following functions in the library, that I can't change (simplified): def g(a,b=2): print a,b def f(arg): g(arg) I can do o={'a':10,'b':20} g(**o) 10 20 but can I/how do I pass this through f? That's what I don't want: f(**o) Traceback (most recent cal...
[ "f has to accept arbitrary (positional and) keyword arguments:\ndef f(*args, **kwargs):\n g(*args, **kwargs)\n\nIf you don't want f to accept positional arguments, leave out the *args part.\n" ]
[ 2 ]
[]
[]
[ "arguments", "iterable_unpacking", "python" ]
stackoverflow_0003279449_arguments_iterable_unpacking_python.txt
Q: Python: How do i manipulate the list to get the string starting with '+'? I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here): result = [' etc:\n', ' ArchiveSEL\n...
Python: How do i manipulate the list to get the string starting with '+'?
I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here): result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ..., ' qcleaner\n', '+ extraFile\n', ' rc....
[ "You can use list comprehension:\nnewlist = [file[1:] for file in result if file.startswith('+')]\n# ^-- gets rid of `+` at the beginning\n\nSee the string methods documentation.\nAnd if you want to get rid of the newline character and whitespaces just do:\nnewlist = [file[1:].strip() for file in result ...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003279700_python.txt
Q: How do I convert a python string to ucs2 hex? I've been searching for this one and couldn't find it, although it seems simple. I need to send in a ucs2 hex string in the url, and I don't know how to convert a python string to be ucs2 hex. Any thoughts? A: >>> 'åéîøü'.encode('utf16') b'\xff\xfe\xe5\x00\xe9\x00\xe...
How do I convert a python string to ucs2 hex?
I've been searching for this one and couldn't find it, although it seems simple. I need to send in a ucs2 hex string in the url, and I don't know how to convert a python string to be ucs2 hex. Any thoughts?
[ ">>> 'åéîøü'.encode('utf16')\nb'\\xff\\xfe\\xe5\\x00\\xe9\\x00\\xee\\x00\\xf8\\x00\\xfc\\x00'\n\n(Note that there's a BOM in the beginning. Use the encoding 'utf_16_be' or 'utf_16_le' if the endian is fixed.)\nIf you need hex digits, use binascii.hexlify.\n>>> import binascii\n>>> binascii.hexlify('åéîøü'.encode('u...
[ 5 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003279830_encoding_python.txt
Q: Python: How do i split the file? I have this txt file which is ls -R of etc directory in a linux system. Example file: etc: ArchiveSEL xinetd.d etc/cmm: CMM_5085.bin cmm_sel storage.cfg etc/crontabs: root etc/pam.d: ftp rsh etc/rc.d: eth.set.sh rc.sysinit etc/rc.d/init.d: cmm ...
Python: How do i split the file?
I have this txt file which is ls -R of etc directory in a linux system. Example file: etc: ArchiveSEL xinetd.d etc/cmm: CMM_5085.bin cmm_sel storage.cfg etc/crontabs: root etc/pam.d: ftp rsh etc/rc.d: eth.set.sh rc.sysinit etc/rc.d/init.d: cmm functions userScripts etc/securi...
[ "Maybe something like this? re.M generates a multiline regular expression which can match several lines, and the last part just iterates over the matches and creates the files...\nimport re\n\ndata = '<your input data as above>' # or open('data.txt').read()\nresults = map(lambda m: (m[0], m[1].strip().splitlines())...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003279843_python.txt
Q: How to use a custom __init__ of an app engine Python model class properly? I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying Are you sure?, you get a 2 minute time frame to cancel deletion. I want to track What will be deleted When with a db.Model class (DeleteQueueItem), as I ...
How to use a custom __init__ of an app engine Python model class properly?
I'm trying to implement a delayed blog post deletion scheme. So instead of an annoying Are you sure?, you get a 2 minute time frame to cancel deletion. I want to track What will be deleted When with a db.Model class (DeleteQueueItem), as I found no way to delete a task from the queue and suspect I can query what's ther...
[ "Generally, you shouldn't try and override the init method of Model classes. While it's possible to get right, the correct constructor behaviour is fairly complex, and may even change between releases, breaking your code (though we try to avoid doing so!). Part of the reason for this is that the constructor has to ...
[ 15 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003279833_google_app_engine_python.txt
Q: Does anyone have a code example of AES encryption in python on Google App Engine? I have a query string I need to encrypt using AES in CBC mode with zero padding, before finally encoding it to base64 and I need to run this on Google App Engine in Python. I've had a look around and can't be sure what works in GAE a...
Does anyone have a code example of AES encryption in python on Google App Engine?
I have a query string I need to encrypt using AES in CBC mode with zero padding, before finally encoding it to base64 and I need to run this on Google App Engine in Python. I've had a look around and can't be sure what works in GAE and what doesn't, I'm also finding it hard to get example code of some of those I believ...
[ "PyCrypto is supported on App Engine. I would recommend checking out examples and docs for PyCrypto - they should function the same on App Engine as everywhere else.\n", "Appengine has a limit on source files ( less than 1000) and doesn't run python modules with C extensions. Given this limitations I would recomm...
[ 2, 1 ]
[]
[]
[ "aes", "cryptography", "encryption", "google_app_engine", "python" ]
stackoverflow_0003276685_aes_cryptography_encryption_google_app_engine_python.txt
Q: Best way to check new-line-independent-identity of 2 files with python I tried filecmp.cmp(file1,file2) but it doesn't work since files are identically except for new line characters. Is there an option for that in filecmp or some other convenience function/library or do I have to read both files line by line an...
Best way to check new-line-independent-identity of 2 files with python
I tried filecmp.cmp(file1,file2) but it doesn't work since files are identically except for new line characters. Is there an option for that in filecmp or some other convenience function/library or do I have to read both files line by line and compare those?
[ "I think a simple convenience function like this should do the job:\nfrom itertools import izip\n\ndef areFilesIdentical(filename1, filename2):\n with open(filename1, \"rtU\") as a:\n with open(filename2, \"rtU\") as b:\n # Note that \"all\" and \"izip\" are lazy\n # (will stop at th...
[ 5, 1, 0 ]
[]
[]
[ "compare", "file", "python" ]
stackoverflow_0003280317_compare_file_python.txt
Q: Using trellis as a framework for managing UI interaction rules Does anyone have experience with trellis? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens. A: It seems this project has died. No new stuff to the page has been added to it since yo...
Using trellis as a framework for managing UI interaction rules
Does anyone have experience with trellis? Looking at it as a framework for defining rules for field interaction and validation in grids and data entry screens.
[ "It seems this project has died. No new stuff to the page has been added to it since your question. Also I think that new language features in Python 2.6 and Python 3 are removing the need of some of the offered constructs.\n" ]
[ 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0000214430_python_user_interface.txt
Q: Django - Custom dashboard view authentication issues Django version 1.1.1 I have a custom dashboard view set up to override the django admin default like: (r'^admin/$', 'dashboard.views.dashboard'), (r'^admin/', include(admin.site.urls)), dashboard view authenticates with the @staff_member_required decorator This...
Django - Custom dashboard view authentication issues
Django version 1.1.1 I have a custom dashboard view set up to override the django admin default like: (r'^admin/$', 'dashboard.views.dashboard'), (r'^admin/', include(admin.site.urls)), dashboard view authenticates with the @staff_member_required decorator This has been working fine with all users having superuser per...
[ "Maybe you should clean your browser cookies and logout properly, both in your public logout url and in the admin logout url. I think normal users opens a session and staff users opens another, so is not a good idea to mix both in the same app.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003277065_django_django_admin_python.txt
Q: twitter request limit Regarding the twitter API request limit, how does one counts as a request? I'm using python-twitter, so if I have client = twitter.Api(username='acc',password='pw') self.client.GetFriends(result[0]) Does this count as 1 request? Or as many as the number of friends I have? I asked this bec...
twitter request limit
Regarding the twitter API request limit, how does one counts as a request? I'm using python-twitter, so if I have client = twitter.Api(username='acc',password='pw') self.client.GetFriends(result[0]) Does this count as 1 request? Or as many as the number of friends I have? I asked this because I have the following c...
[ "That's 1 request. For that request Twitter will return a json file representing the list of friends.\nAlso the twitter.API call also produce a request, but this one is not counted for the limit stuff.\nYou can read about it in apiwiki\nYou can also request your limit status.\n" ]
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003278788_python_twitter.txt
Q: terminate script of another user On a linux box I've got a python script that's always started from predefined user. It may take a while for it to finish so I want to allow other users to stop it from the web. Using kill fails with Operation not permitted. Can I somehow modify my long running python script so tha...
terminate script of another user
On a linux box I've got a python script that's always started from predefined user. It may take a while for it to finish so I want to allow other users to stop it from the web. Using kill fails with Operation not permitted. Can I somehow modify my long running python script so that it'll recive a signal from another u...
[ "If you do not want to execute the kill command with the correct permissions, you can send any other signal to the other script. It is then the other scripts' responsibility to terminate. You cannot force it, unless you have the permissions to do so. \nThis can happen with a network connection, or a 'kill' file wh...
[ 1, 1, 1, 0 ]
[]
[]
[ "kill", "linux", "python", "signals" ]
stackoverflow_0003281107_kill_linux_python_signals.txt
Q: Automatically call all functions matching a certain pattern in python In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this...
Automatically call all functions matching a certain pattern in python
In python I have many functions likes the ones below. I would like to run all the functions whose name matches setup_* without having to explicitly call them from main. The order in which the functions are run is not important. How can I do this in python? def setup_1(): .... def setup_2(): .... def setup_3()...
[ "def setup_1():\n print('1')\n\ndef setup_2():\n print('2')\n\ndef setup_3():\n print('3')\n\nif __name__ == '__main__': \n for func in (val for key,val in vars().items()\n if key.startswith('setup_')):\n func()\n\nyields\n# 1\n# 3\n# 2\n\n", "Here is one possible solution:\n...
[ 8, 4, 1, 0 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0003281300_automation_python.txt
Q: How to preload model for ReferenceProperty? I have a models in different files (blog/models.py, forum/models.py, article/models.py). In each of this files I have defined model classes with application prefix (BlobPost, BlogTag, ForumPost, ForumThread, Article, ArticleCategory). Also I have appliation - comment, fo...
How to preload model for ReferenceProperty?
I have a models in different files (blog/models.py, forum/models.py, article/models.py). In each of this files I have defined model classes with application prefix (BlobPost, BlogTag, ForumPost, ForumThread, Article, ArticleCategory). Also I have appliation - comment, for adding comment attached to any model object. Fo...
[ "This isn't possible in the standard db framework, as there's not enough information present to find your models. The only information the framework has to work with is the kind name, which doesn't include the fully qualified package - so it has no way to figure out what package your model definition might be in.\n...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003247971_google_app_engine_python.txt
Q: Really awkward (seemingly simple) bug with python integer comparisons I have the following piece of code which is not working the way I expect it to at all... current_frame = 15 # just for showcasing purposes g_ch = 7 if (current_frame != int(row[0])) and (int(row[1]) != g_ch): current_frame = int...
Really awkward (seemingly simple) bug with python integer comparisons
I have the following piece of code which is not working the way I expect it to at all... current_frame = 15 # just for showcasing purposes g_ch = 7 if (current_frame != int(row[0])) and (int(row[1]) != g_ch): current_frame = int(row[0]) print "curious=================================" ...
[ "Value comparisons are done with the != operator, not with is not, which compares object identity.\nApart from that, I think it's an indentation problem.\n", "In short, you need to use == and !=, and not is. is compares object identity, not equality.\n", "You assign current_frame = int(row[0]) inside the if, wh...
[ 6, 1, 0 ]
[]
[]
[ "equality", "identity", "python" ]
stackoverflow_0003281550_equality_identity_python.txt
Q: best python lib to clean the tag (not safe), and keep the tag that i think safe ex: i want to clean the "script" tag , but i want to keep the 'a' tag , so what lib you using to do this . and i use jquery cleditor for WYSIWYG HTML editor , can it do this for me automatically ? thanks A: I have to do this auto...
best python lib to clean the tag (not safe), and keep the tag that i think safe
ex: i want to clean the "script" tag , but i want to keep the 'a' tag , so what lib you using to do this . and i use jquery cleditor for WYSIWYG HTML editor , can it do this for me automatically ? thanks
[ "I have to do this automatically for a project of mine. The solution I have found is to use the Beautiful Soup module to extract the script tag (I also do this for style and form).\nsoup = BeautifulSoup(html_string, convertEntities=BeautifulSoup.HTML_ENTITIES)\n\nscripts = soup.findAll('script') # find and return...
[ 3, 2, 0 ]
[]
[]
[ "google_app_engine", "jquery", "python", "tags" ]
stackoverflow_0003240009_google_app_engine_jquery_python_tags.txt
Q: Format date based on locale in python I have a date output like >>> import time >>> print time.strftime("%d %B") 19 July Is there a way to format the date based on the locale, but still have control of what is shown (in some cases I don't want the year). For example, on a en_US machine, I want it to output: July ...
Format date based on locale in python
I have a date output like >>> import time >>> print time.strftime("%d %B") 19 July Is there a way to format the date based on the locale, but still have control of what is shown (in some cases I don't want the year). For example, on a en_US machine, I want it to output: July 19'th
[ "The strftime methods always use the current locale. For example:\nfrom datetime import date\nd = date.today()\nprint d.format(\"%B %d\")\n\nwill output \"July 19\" (no \"'th\", sorry...) if your locale is en_US, but \"juillet 19\" if the locale uses French.\nIf you want to make the order of the different parts als...
[ 2 ]
[]
[]
[ "formatting", "locale", "python", "time" ]
stackoverflow_0003280818_formatting_locale_python_time.txt
Q: how to change page selection in wxNotebook or wxChoicebook? Is there any way to change the page of a wxNotebook or wxChoicebook programmatically? Looking at the documentation I would have thought that wxChoicebook::ChangeSelection was the way to go, or wxChoicebook::SetSelection if I want the page changing/change...
how to change page selection in wxNotebook or wxChoicebook?
Is there any way to change the page of a wxNotebook or wxChoicebook programmatically? Looking at the documentation I would have thought that wxChoicebook::ChangeSelection was the way to go, or wxChoicebook::SetSelection if I want the page changing/changed events to be sent. However, I don't know what these functions ...
[ "I think you should be using wxNotebook::ChangeSelection, and in that function the size_t parameter refers to the integer index of the notebook page you would like to switch to. ChangeSelection(0) would change to the first notebook page, ChangeSelection(1) to the second, and so on. \nI did test this in code, and it...
[ 0 ]
[]
[]
[ "python", "user_interface", "wxwidgets" ]
stackoverflow_0003250175_python_user_interface_wxwidgets.txt
Q: python - list operations Given a list of unsorted numbers, I want to find the smallest number larger than N (if any). In C#, I'd do something like this (checks omitted) : var x = list.Where(i => i > N).Min(); What's a short, READABLE way to do this in Python? A: >>> l = [4, 5, 12, 0, 3, 7] >>> min(x for x in l ...
python - list operations
Given a list of unsorted numbers, I want to find the smallest number larger than N (if any). In C#, I'd do something like this (checks omitted) : var x = list.Where(i => i > N).Min(); What's a short, READABLE way to do this in Python?
[ ">>> l = [4, 5, 12, 0, 3, 7]\n>>> min(x for x in l if x > 5)\n7\n\n", "min(x for x in mylist if x > N)\n\n", "Other people have given list comprehension answers. As an alternative filter is useful for 'filtering' out elements of a list.\nmin(filter(lambda t: t > N, mylist))\n\n", "x = min(i for i in mylist if...
[ 19, 4, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003281898_list_python.txt
Q: please expain wx.grid.Grid.create() can any one please expain me the functionality of this function wx.grid.Grid.create() i created a frame and inside that i create a grid using this function every thing is fine but while closing that frame my whole application is closing while closing i just need to distroy the...
please expain wx.grid.Grid.create()
can any one please expain me the functionality of this function wx.grid.Grid.create() i created a frame and inside that i create a grid using this function every thing is fine but while closing that frame my whole application is closing while closing i just need to distroy the frame only not the whole application tha...
[ "Are you using self.Destroy()? If so, try self.Close() instead.\nor bind wx.EVT_CLOSE to your custom close function\nself.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\ndef OnCloseWindow(self,event):\n //do anything here\n\n", "If the frame with the grid in it is the only top-level window, then closing it will clo...
[ 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002415854_python_wxpython.txt
Q: Python Threading with Timer I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this? threading.Timer only starts after the previous one has been completed. A: import threading import time cla...
Python Threading with Timer
I would like 3 Threads in Python to run for n seconds. I want to start them all at the same time and have them finish at the same time (within milliseconds). How do I do this? threading.Timer only starts after the previous one has been completed.
[ "import threading \nimport time\n\nclass A(threading.Thread):\n def run(self):\n print \"here\", time.time()\n time.sleep(10)\n print \"there\", time.time()\n\n\nif __name__==\"__main__\":\n for i in range(3):\n a = A()\n a.start()\n\nprints:\nhere 1279553593.49\nhere 1279553593.49\nhere 12795...
[ 4 ]
[]
[]
[ "multithreading", "python", "timer" ]
stackoverflow_0003282469_multithreading_python_timer.txt
Q: wxPython validator not called for grandchild of dialogue I have something like this: class ADialog(wx.Dialog): def __init__(self, parent, *args, **kwargs): ... self.editor = APanel(parent=self) ... ... class APanel(wx.Panel): def CreatePanel(self, *args, **kwargs): ... ...
wxPython validator not called for grandchild of dialogue
I have something like this: class ADialog(wx.Dialog): def __init__(self, parent, *args, **kwargs): ... self.editor = APanel(parent=self) ... ... class APanel(wx.Panel): def CreatePanel(self, *args, **kwargs): ... self.textCtrls = [] for (key, val) in zip(foo,...
[ "wx.WS_EX_VALIDATE_RECURSIVELY is an extended style, so you need to set it with SetExtraStyle, not by passing it to the base class' __init__\n" ]
[ 3 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003244084_python_user_interface_wxpython.txt
Q: wxPython: Can a wx.PyControl contain a wx.Sizer? Can a wx.PyControl contain a wx.Sizer? Note that what I am ultimately trying to do here (spinner with float values) is already answered in another question. I am particularly interested in layouting widgets within a wx.PyControl, a skill which might prove useful if ...
wxPython: Can a wx.PyControl contain a wx.Sizer?
Can a wx.PyControl contain a wx.Sizer? Note that what I am ultimately trying to do here (spinner with float values) is already answered in another question. I am particularly interested in layouting widgets within a wx.PyControl, a skill which might prove useful if I come across a need to make my own custom widgets. I ...
[ "Yes, it can. You just need to call Layout() to tell the sizer to recalculate/layout its children.\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n blah = CustomWidget(self)\n self.Show(True)\n\nclass CustomWidget(wx.PyControl):\n def __init__(self, parent):\n...
[ 3, 1 ]
[]
[]
[ "custom_controls", "python", "sizer", "widget", "wxpython" ]
stackoverflow_0003271639_custom_controls_python_sizer_widget_wxpython.txt
Q: Getting parameters from a file via shell script into python script in the right format I have the following shell script: #! /bin/sh while read page_section page=${page_section%%\ *} section=${page_section#* } #NOTE: `%* }` is NOT a comment wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tm...
Getting parameters from a file via shell script into python script in the right format
I have the following shell script: #! /bin/sh while read page_section page=${page_section%%\ *} section=${page_section#* } #NOTE: `%* }` is NOT a comment wget --quiet --no-proxy www.cs.sun.ac.za/hons/$page -O html.tmp & wait # echo ${page_section%%\ *} # verify correct string chopping # echo ${page_secti...
[ "Put quotes around $section:\n./DokuWikiHtml2Latex.py html.tmp \"$section\" & wait\n\n", "Just let read do the parsing stuff:\nwhile read page section rest\ndo\n echo \"Page: $page\"\n echo \"Section: $section\"\ndone < inputfile\n\nFor handling the optional argument elegantly, use an array:\nwhile read -a ...
[ 2, 1, 0 ]
[]
[]
[ "argument_passing", "bash", "python" ]
stackoverflow_0003282769_argument_passing_bash_python.txt
Q: Python interface to PayPal - urllib.urlencode non-ASCII characters failing I am trying to implement PayPal IPN functionality. The basic protocol is as such: The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. PayPal calls a page on my server pa...
Python interface to PayPal - urllib.urlencode non-ASCII characters failing
I am trying to implement PayPal IPN functionality. The basic protocol is as such: The client is redirected from my site to PayPal's site to complete payment. He logs into his account, authorizes payment. PayPal calls a page on my server passing in details as POST. Details include a person's name, address, and payment ...
[ "Try converting the params dictionary to utf-8 first... urlencode seems to like that better than unicode:\nparams = urllib.urlencode(dict([k, v.encode('utf-8')] for k, v in params.items()))\n\nOf course, this assumes your input is unicode. If your input is something other than unicode, you'll want to decode it to u...
[ 41, 6, 3 ]
[]
[]
[ "paypal", "python", "unicode", "urllib", "urllib2" ]
stackoverflow_0000787935_paypal_python_unicode_urllib_urllib2.txt
Q: Speeding up regular expressions in Python I need to quickly extract text from HTML files. I am using the following regular expressions instead of a full-fledged parser since I need to be fast rather than accurate (I have more than a terabyte of text). The profiler shows that most of the time in my script is spent ...
Speeding up regular expressions in Python
I need to quickly extract text from HTML files. I am using the following regular expressions instead of a full-fledged parser since I need to be fast rather than accurate (I have more than a terabyte of text). The profiler shows that most of the time in my script is spent in the re.sub procedure. What are good ways of ...
[ "First, use an HTML parser built for this, like BeautifulSoup:\nhttp://www.crummy.com/software/BeautifulSoup/\nThen, you can identify remaining particular slow spots with the profiler:\nhttp://docs.python.org/library/profile.html\nAnd for learning about regular expressions, I've found Mastering Regular Expressions ...
[ 8, 5, 1, 1, 0, 0 ]
[]
[]
[ "optimization", "python", "regex" ]
stackoverflow_0003277239_optimization_python_regex.txt
Q: Looking for a PHP's str_split() replacement Let's say I have this little piece of code: <?php $tmp = str_split('hello world!',2); // $tmp will now be: array('he','ll','o ','wo','rl','d!'); foreach($tmp AS &$a) { // some processing } unset($tmp); ?> How can I do this in Python v2.7? I thought this would do it:...
Looking for a PHP's str_split() replacement
Let's say I have this little piece of code: <?php $tmp = str_split('hello world!',2); // $tmp will now be: array('he','ll','o ','wo','rl','d!'); foreach($tmp AS &$a) { // some processing } unset($tmp); ?> How can I do this in Python v2.7? I thought this would do it: the_string = 'hello world!' tmp = the_string.sp...
[ "for i in range(0, len(the_string), 2):\n print(the_string[i:i+2])\n\n", "tmp = the_string[::2] gives a copy of the_string with every second element. ...[::1] would return a copy with every element, ...[::3] would give every third element, etc.\nNote that this is a slice and the full form is list[start:stop:st...
[ 6, 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003282929_python_string.txt
Q: Python Chain getattr as a string import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom do...
Python Chain getattr as a string
import amara def chain_attribute_call(obj, attlist): """ Allows to execute chain attribute calls """ splitted_attrs = attlist.split(".") current_dom = obj for attr in splitted_attrs: current_dom = getattr(current_dom, attr) return current_dom doc = amara.parse("sample.xml") print ch...
[ "you could also use:\nfrom operator import attrgetter\nattrgetter('x.y.z')(doc)\n\n", "Just copying from Useful code which uses reduce() in Python:\nfrom functools import reduce\nreduce(getattr, \"X.Y.Z\".split('.'), doc)\n\n" ]
[ 31, 13 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0003279082_getattr_python.txt
Q: python and using 'self' in methods From what I read/understand, the 'self' parameter is similiar to 'this'. Is that true? If its optional, what would you do if self wasnt' passed into the method? A: Yes, it's used in similar ways. Note that it's a positional parameter and you can call it what you want; however ...
python and using 'self' in methods
From what I read/understand, the 'self' parameter is similiar to 'this'. Is that true? If its optional, what would you do if self wasnt' passed into the method?
[ "Yes, it's used in similar ways. Note that it's a positional parameter and you can call it what you want; however there is a strong convention to call it self (not this or anything else). Some positional parameter must be there for a usable instance method; it is not optional.\n", "The joy of Python\nThat is tr...
[ 5, 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "self" ]
stackoverflow_0003283178_python_self.txt
Q: 2 digit years using strptime() is not able to parse birthdays very well Consider the following birthdays (as dob): 1-Jun-68 1-Jun-69 When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield: datetime.datetime(2068, 6, 1, 0, 0) datetime.datetime(1969, 6, 1, 0, 0) Well of course they’re supposed t...
2 digit years using strptime() is not able to parse birthdays very well
Consider the following birthdays (as dob): 1-Jun-68 1-Jun-69 When parsed with Python’s datetime.strptime(dob, '%d-%b-%y') will yield: datetime.datetime(2068, 6, 1, 0, 0) datetime.datetime(1969, 6, 1, 0, 0) Well of course they’re supposed to be born in the same decade but now it’s not even in the same century! Accor...
[ "If you're always using it for birthdays, just subtract 100 if the year is after now:\nif d > datetime.now():\n d = datetime(d.year - 100, d.month, d.day)\n\n", "This function shifts the year to 1950:\ndef millenium(year, shift=1950):\n return (year-shift)%100 + shift\n\n", "If you're expecting a birthday...
[ 12, 2, 0 ]
[]
[]
[ "2_digit_year", "python", "strptime" ]
stackoverflow_0003283209_2_digit_year_python_strptime.txt
Q: Python, suds, Error When I'm trying get method from remote webservice it gives me error. My code is: portion=10 start=0 print self.stamp.datetime client=self.client while 1: print 'getting ids...........' fresh_ids=client.service.GetTopicsIDsUpdatedAf...
Python, suds, Error
When I'm trying get method from remote webservice it gives me error. My code is: portion=10 start=0 print self.stamp.datetime client=self.client while 1: print 'getting ids...........' fresh_ids=client.service.GetTopicsIDsUpdatedAfterDateTime(self.stamp.da...
[ "Edit: On another look at the code, I noticed that this line:\n start=+portion\n\nneeds to be changed to\n start += portion\n\nThat might make the following analysis unnecessary... but I think there might still be an issue in your suds source, as explained below.\n\nThe first question I'd ask ...
[ 2 ]
[]
[]
[ "python", "suds" ]
stackoverflow_0003282150_python_suds.txt
Q: finding out absolute path to a file from python If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo, os.curdir will re...
finding out absolute path to a file from python
If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will give the current directory but not the directory where the file lives. If I invoke test.py from some directory foo, os.curdir will return foo but not the path of test.py. thanks.
[ "Here's how to get the directory of the current file:\nimport os\nos.path.abspath(os.path.dirname(__file__))\n\n", "the answer is to use:\n __file__\n\nwhich returns a relative path. \nos.path.abspath(__file__) \n\ncan be used to get the full path.\n", "The answers so far have correctly pointed you to os.path.a...
[ 53, 25, 5, 2, 0 ]
[]
[]
[ "filesystems", "io", "python" ]
stackoverflow_0003283306_filesystems_io_python.txt
Q: Python "NoneType is not callable" error I have a function that looks like the following, with a whole lot of optional parameters. One of these parameters, somewhere amidst all the others, is text. I handle text specially because if it is a boolean, then I want to run to do something based on that. If it's not (w...
Python "NoneType is not callable" error
I have a function that looks like the following, with a whole lot of optional parameters. One of these parameters, somewhere amidst all the others, is text. I handle text specially because if it is a boolean, then I want to run to do something based on that. If it's not (which means it's just a string), then I do som...
[ "I guess you have an argument called type somewhere, I can easily reproduce your error with the following code:\n>>> type('abc')\n<class 'str'>\n>>> type = None\n>>> type('abc')\nTraceback (most recent call last):\n File \"<pyshell#62>\", line 1, in <module>\n type('abc')\nTypeError: 'NoneType' object is not ca...
[ 8, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0003283441_python_types.txt
Q: Is this an acceptable pythonic idiom? I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an accept...
Is this an acceptable pythonic idiom?
I have a class that assists in importing a special type of file, and a 'factory' class that allows me to do these in batch. The factory class uses a generator so the client can iterate through the importers. My question is, did I use the iterator correctly? Is this an acceptable idiom? I've just started using Python...
[ "You could make one thing a little simpler: Instead of try...finally, use a with block:\nwith open(file, \"rb\") as fh:\n yield FileParser(fh)\n\nThis will close the file for you automatically as soon as the with block is left.\n", "It's absolutely fine to have a method that's a generator, as you do. I would ...
[ 12, 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003283479_python.txt
Q: Can I format a variable in python? Is there a way of formating a variable? For example, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution? A: The best solution...
Can I format a variable in python?
Is there a way of formating a variable? For example, I'd like to automate the creation of a variable named M_color, where M is a string of value "bingo". The final result would be bingo_color. What should I do if the value of M changes during the execution?
[ "The best solution for this kind of problem is to use dictionaries:\ncolor_of = {}\nM = \"bingo\"\ncolor_of[M] = \"red\"\nprint(color_of[M])\n\n", "If the 'variable' can be an attribute of an object, you could use setattr()\nclass Color(object):\n pass\n\ncolor = Color()\n\nattr_name = '{foo}_color'.format(foo...
[ 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003283621_python.txt
Q: How to convert a Python string representing bytes into actual bytes? I have a string like: "01030009" and I want to get another string (because in Python 2.x we use strings for bytes) newString which will produce this result: for a in newString: print ord(a) 0 1 0 3 0 0 0 9 Thanks A: ''.join(chr(int(x)) fo...
How to convert a Python string representing bytes into actual bytes?
I have a string like: "01030009" and I want to get another string (because in Python 2.x we use strings for bytes) newString which will produce this result: for a in newString: print ord(a) 0 1 0 3 0 0 0 9 Thanks
[ "''.join(chr(int(x)) for x in oldString)\n\nchr is the inverse of ord.\n", "All the \"deeply builtin\" ways interpret characters as bytes in a different way than the one you want, because the way you appear to desire seems limited to represent bytes worth less than 10 (or less than 16 if you meant to use hex and ...
[ 8, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003282678_python.txt
Q: What python virtual environment and deployment solution should I use? I'm looking for a virtual environment solution for Python applications and I would like something that respects these requirements: Windows and Linux works with x86/x64 Python versions easy to use/maintain Python 2.6-2.7 compatible and preferab...
What python virtual environment and deployment solution should I use?
I'm looking for a virtual environment solution for Python applications and I would like something that respects these requirements: Windows and Linux works with x86/x64 Python versions easy to use/maintain Python 2.6-2.7 compatible and preferably even 3.x source control friendly - I want to keep the packages in SCM. ...
[ "Either virtualenv or zc.buildout will work. Virtualenv is easier to learn and use; buildout is more powerful. I personally use buildout for development/deployment of packages I develop, and virtualenv for deployment of 3rd-party applications (like Trac).\nDisclaimer: I've never attempted to use either on Windows...
[ 2 ]
[]
[]
[ "buildout", "python", "virtualenv" ]
stackoverflow_0003282451_buildout_python_virtualenv.txt
Q: Sorting a list pairs by frequency of the pair elements I'm completely new to Python and while trying various random bits and pieces I've struck upon a problem that I believe I've "solved", but the code doesn't feel right - I strongly suspect there is going to be a better way to get the desired result. FYI - I'm us...
Sorting a list pairs by frequency of the pair elements
I'm completely new to Python and while trying various random bits and pieces I've struck upon a problem that I believe I've "solved", but the code doesn't feel right - I strongly suspect there is going to be a better way to get the desired result. FYI - I'm using whatever the latest version of Python 3 is, on Windows. ...
[ "I would probably use a Counter (needs Python ≥2.7 or ≥3.1) for tallying.\nfrom collections import Counter\nfrom itertools import chain\ndef sortPairList2(data):\n tally = Counter(chain(*map(set, data)))\n data.sort(key=lambda x: sorted(tally[i] for i in x))\n\nNote that:\n\nYou can create an anonymous functi...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003280098_python_sorting.txt
Q: python dictionary, keeping a count of integers I am trying to count a list of say, integers. I have a list of numbers in a csv file I am able to read in, that looks something like 4,245,34,99,340,... What I am doing is trying to return is a dictionary with key:value pairs where the key is an integer value from th...
python dictionary, keeping a count of integers
I am trying to count a list of say, integers. I have a list of numbers in a csv file I am able to read in, that looks something like 4,245,34,99,340,... What I am doing is trying to return is a dictionary with key:value pairs where the key is an integer value from the csv file, and the value is the number of times it ...
[ "Sounds like what you want is a Counter object:\nhttp://docs.python.org/library/collections.html#counter-objects\nAlso I think you may want to use the CSV module:\nhttp://docs.python.org/library/csv.html\nUsing the built-in modules should make it a lot easier :)\nTo get the rows something like this should work: \n...
[ 8, 5, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003283990_dictionary_python.txt
Q: Python in Windows I am new to Python and need some help. i need to write a script that will look for file in c:\script\test\ directory with ext ".dat" and find "^" in there and replace with "|" i am not sure how to write this. There will only be one file for a day in the directory with the current date as the file...
Python in Windows
I am new to Python and need some help. i need to write a script that will look for file in c:\script\test\ directory with ext ".dat" and find "^" in there and replace with "|" i am not sure how to write this. There will only be one file for a day in the directory with the current date as the file name. Please help. I a...
[ "Start here: http://diveintopython3.ep.io/table-of-contents.html\nYou'll be interested in endswith, open, and replace. splitext could be good if you're extra-careful.\n", "Example: Check if file exists or not?\nimport os.path\n# os.path - The key to File I/O\nos.path.exists(\"foo.txt\")\n\nTo learn more details ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003283955_python.txt
Q: How do I get the concrete name (e.g. "".") of a class reference in Python? This is what I have so far: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. """ # TODO: How do I check that klass is actually a class? ...
How do I get the concrete name (e.g. "".") of a class reference in Python?
This is what I have so far: def get_concrete_name_of_class(klass): """Given a class return the concrete name of the class. klass - The reference to the class we're interested in. """ # TODO: How do I check that klass is actually a class? # even better would be determine if it's old style vs new style # at the same ti...
[ "How about just using klass.__name__, or to get the fully qualified name, klass.__module__+'.'+klass.__name__?\n", "You can just say\nklass.__module__ + \".\" + klass.__name__\n\nAs for how to determine whether something is an old class or new class, I recommend saying something like\nfrom types import ClassType ...
[ 2, 2, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003284089_class_python.txt
Q: Checking duplicate while inserting in SQLite I am trying to insert a data into SQLite database using Python. INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK") WHERE "UK" NOT EXISTS IN (SELECT LABEL FROM DATA_TABLE); This query is dynamically generated from Python and I am checking whether the date is al...
Checking duplicate while inserting in SQLite
I am trying to insert a data into SQLite database using Python. INSERT INTO DATA_TABLE(UID,LABEL) VALUES (NULL, "UK") WHERE "UK" NOT EXISTS IN (SELECT LABEL FROM DATA_TABLE); This query is dynamically generated from Python and I am checking whether the date is already exist in the table before inserting and its ...
[ "I'm pretty sure that INSERT doesn't have a WHERE clause (the documentation doesn't mention any). What you can do:\n\ncreate a unique index on LABEL \nuse INSERT OR FAIL\nif that triggers an error, the row already exists.\n\n", "It is giving you a syntax error because it is not allowed syntax. From your example I...
[ 2, 2, 1 ]
[]
[]
[ "pysqlite", "python", "sqlite", "windows" ]
stackoverflow_0003281800_pysqlite_python_sqlite_windows.txt
Q: Building a graph of the structure of an XML document I'd like to build a graph showing which tags are used as children of which other tags in a given XML document. I've written this function to get the unique set of child tags for a given tag in an lxml.etree tree: def iter_unique_child_tags(root, tag): """Ite...
Building a graph of the structure of an XML document
I'd like to build a graph showing which tags are used as children of which other tags in a given XML document. I've written this function to get the unique set of child tags for a given tag in an lxml.etree tree: def iter_unique_child_tags(root, tag): """Iterates through unique child tags for all instances of tag. ...
[ "I ended up using python-graph. I also ended up using argparse to build a command line interface that pulls some basic bits of info from XML documents and builds graph images in formats supported by pydot. It's called xmlearn and is sort of useful:\nusage: xmlearn [-h] [-i INFILE] [-p PATH] {graph,dump,tags} ...\...
[ 3 ]
[]
[]
[ "dotfiles", "graph", "lxml", "python", "xml" ]
stackoverflow_0003273158_dotfiles_graph_lxml_python_xml.txt
Q: Print PDF document with python's win32print module? I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? If so, is there a module available to convert a PDF document into PCL? I contemplated using ShellExecute; however, this is not...
Print PDF document with python's win32print module?
I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? If so, is there a module available to convert a PDF document into PCL? I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default p...
[ "I ended up using Ghostscript to accomplish this task. There is a command line tool that relies on Ghostscript called gsprint.\nYou don't even need Acrobat installed to print PDFs in this fashion which is quite nice. \nHere is an example:\non the command line:\ngsprint -printer \\\\server\\printer \"test.pdf\"\n\nf...
[ 10, 3 ]
[ "I am not sure how to specifically get win32print to work, but there might be a couple of other options. Reportlab is often mentioned when creating PDFs from Python. If you are already invested in your approach, maybe using PyX or pypsg to generate the Postscript files and then feeding that into win32print would ...
[ -1 ]
[ "pdf", "postscript", "python", "winapi", "windows" ]
stackoverflow_0001462842_pdf_postscript_python_winapi_windows.txt
Q: Regex match words and end of string 2 Regex question How can I match a word or 2 words in a subpattern ()? How can i match a word or 2 words that's either followed by a specific word like "with" OR the end of the string $ I tried (\w+\W*\w*\b)(\W*\bwith\b|$) but it's definitely not working edit: I'm thinking of ...
Regex match words and end of string
2 Regex question How can I match a word or 2 words in a subpattern ()? How can i match a word or 2 words that's either followed by a specific word like "with" OR the end of the string $ I tried (\w+\W*\w*\b)(\W*\bwith\b|$) but it's definitely not working edit: I'm thinking of matching both "go to mall" and "go to", i...
[ "Perhaps something like this?\n>>> import re\n>>> r = re.compile(r'(\\w+(\\W+\\w+)?)(\\W+with\\b|\\Z)')\n>>> r.search('bar baz baf bag').group(1)\n'baf bag'\n>>> r.search('bar baz baf with bag').group(1)\n'baz baf'\n>>> r.search('bar baz baf without bag').group(1)\n'without bag'\n>>> r.search('bar with bag').group(...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003284608_python_regex.txt
Q: Using select_related and extra clause I'm trying to achieve some extra select on a queryset and wants to add the needed table to the pool of tables in the query using the select_related method in order to benefit for the '__' syntax. Here is an example with simple models : from django.db import models # Create yo...
Using select_related and extra clause
I'm trying to achieve some extra select on a queryset and wants to add the needed table to the pool of tables in the query using the select_related method in order to benefit for the '__' syntax. Here is an example with simple models : from django.db import models # Create your models here. class testA(models.Model):...
[ "I have developped a Django app to solve this kind of problems : django-cube. The base idea is to emulate a multi-dimensional DB, in order to easily calculate aggregations.\nThe functionnality you require ('__hour' : a field-lookup for 'hour') is not implemented, but implementing it would take probably 15 minutes. ...
[ 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003280165_django_python.txt
Q: Remove items with checkboxes in Django forms I'm writing a form with Django. The form is a model form for a certain model, Experiment. Each Experiment has several TimeSlot models associated with it, defined with a ForeignKey('Experiment'). I'd like to have a form with the option to remove one or more TimeSlot inst...
Remove items with checkboxes in Django forms
I'm writing a form with Django. The form is a model form for a certain model, Experiment. Each Experiment has several TimeSlot models associated with it, defined with a ForeignKey('Experiment'). I'd like to have a form with the option to remove one or more TimeSlot instances from the EditExperimentForm by checking boxe...
[ "It may be a cleaner solution if you used a model formset for your TimeSlot objects. Have you looked at that at all?\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1\n", "This code isn't tested, but something like this should do it:\nclass MyForm(forms.Form):\n # You can change the queryset ...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003285387_django_django_forms_python.txt
Q: CSV, DictWriter, unicode and utf-8 I am having problems with the DictWriter and non-ascii characters. A short version of my problem: #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import csv f = codecs.open("test.csv", 'w', 'utf-8') writer = csv.DictWriter(f, ['field1'], delimiter='\t') writer.write...
CSV, DictWriter, unicode and utf-8
I am having problems with the DictWriter and non-ascii characters. A short version of my problem: #!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import csv f = codecs.open("test.csv", 'w', 'utf-8') writer = csv.DictWriter(f, ['field1'], delimiter='\t') writer.writerow({'field1':u'å'.encode('utf-8')}) f.c...
[ "The object you obtain with codecs.open wants a unicode string in its write method -- that's the whole point. csv.DictWriter of course is calling that method with a utf8-encoded byte string instead, whence the exception.\nChange f's creation to f = open(\"test.csv\", 'wb') (taking codecs out of the picture) and th...
[ 9 ]
[]
[]
[ "csv", "python", "unicode", "utf_8" ]
stackoverflow_0003285578_csv_python_unicode_utf_8.txt
Q: Python 3 chokes on CP-1252/ANSI reading I'm working on a series of parsers where I get a bunch of tracebacks from my unit tests like: File "c:\Python31\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't deco...
Python 3 chokes on CP-1252/ANSI reading
I'm working on a series of parsers where I get a bunch of tracebacks from my unit tests like: File "c:\Python31\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps ...
[ "Position 0x81 is unassigned in Windows-1252 (aka cp1252). It is assigned to U+0081 HIGH OCTET PRESET (HOP) control character in Latin-1 (aka ISO 8859-1). I can reproduce your error in Python 3.1 like this:\n>>> b'\\x81'.decode('cp1252')\nTraceback (most recent call last):\n ...\nUnicodeDecodeError: 'charmap' co...
[ 15, 4, 2 ]
[]
[]
[ "cp1252", "latin1", "python", "python_3.x", "unicode" ]
stackoverflow_0003284827_cp1252_latin1_python_python_3.x_unicode.txt
Q: Python: How to Capture WebPage as Image File? I want to cache a webpage as an image upon a user request, but I don't know where to start with this. I'm developing on App Engine with python. A: Here's a good library for capturing a webpage as a png image: http://github.com/AdamN/python-webkit2png A: One way is...
Python: How to Capture WebPage as Image File?
I want to cache a webpage as an image upon a user request, but I don't know where to start with this. I'm developing on App Engine with python.
[ "Here's a good library for capturing a webpage as a png image:\nhttp://github.com/AdamN/python-webkit2png\n", "One way is to use a web service such as thumbalizr since a lot of the programs for this type of thing aren't always install-able on appengine (because they use C++, etc). Other options include girafa an...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "image_processing", "python" ]
stackoverflow_0003285724_google_app_engine_image_processing_python.txt
Q: How to make a fancy shortcut on the desktop to my python app? I've made this nice python app that runs when i use "python main.py" in terminal, but going thru the terminal each time is boring :-) how can i make a nice shortcut button with a img to have on my desktop? A: From here: http://www.themaemo.com/howto-l...
How to make a fancy shortcut on the desktop to my python app?
I've made this nice python app that runs when i use "python main.py" in terminal, but going thru the terminal each time is boring :-) how can i make a nice shortcut button with a img to have on my desktop?
[ "From here:\nhttp://www.themaemo.com/howto-launch-a-terminal-app-from-a-shortcut/\nBasically, you need to create a .desktop file with the execution of the script in the EXEC line\n" ]
[ 2 ]
[]
[]
[ "maemo", "n900", "nokia", "python" ]
stackoverflow_0003149722_maemo_n900_nokia_python.txt
Q: Any way to run python TK scripts on web page? Is there any way to run a python script that utilizes TKinter on a web page such that a user could run the script and interact with the TK windows without having to download the script or have the appropriate python interpreter? A: No. There is no way to do this. A:...
Any way to run python TK scripts on web page?
Is there any way to run a python script that utilizes TKinter on a web page such that a user could run the script and interact with the TK windows without having to download the script or have the appropriate python interpreter?
[ "No. There is no way to do this.\n", "The only approach I can think of, is to use some virtual screen protocol such as VNC, run your Tkinter script on a server for that protocol (e.g., a VNC server), and use a viewer browser plug-in for that protocol in the user's browser (e.g., maybe this one -- haven't tried it...
[ 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003284779_python_tkinter.txt
Q: wxPython threaded UDP server I am trying to put together a UDP server with a wxPython GUI. Here is a link to the code: UDP Server pastie.org I have linked it as its pretty lengthy. I have successfully got the UDP server running on the thread but I can not figure out how to close the socket when the stopping the t...
wxPython threaded UDP server
I am trying to put together a UDP server with a wxPython GUI. Here is a link to the code: UDP Server pastie.org I have linked it as its pretty lengthy. I have successfully got the UDP server running on the thread but I can not figure out how to close the socket when the stopping the thread. At the moment it will kick ...
[ "Use Python Twisted. It has wxPython integration with twisted.internet.wxreactor and makes networking easy and threadless.\nfrom twisted.internet import wxreactor\nfrom twisted.internet.protocol import DatagramProtocol\n\nwxreactor.install()\n\nclass MyProtocol(DatagramProtocol):\n def datagramReceived(self, dat...
[ 2 ]
[]
[]
[ "multithreading", "python", "sockets", "udp", "wxpython" ]
stackoverflow_0003285907_multithreading_python_sockets_udp_wxpython.txt
Q: Embedding a 3-D editor (such as Blender) in a wxPython application Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.) My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and t...
Embedding a 3-D editor (such as Blender) in a wxPython application
Is it possible to embed a 3-D editor inside my wxPython application? (I'm thinking Blender, but other suggestions are welcome.) My application opens a wxPython window, and I want to have a 3-D editor inside of it. Of course, I want my program and the 3-D editor to interact with each other. Possible? How?
[ "Blender has python plugins, you can write a plugin to interract with your program.\n", "I second Luper Rouch's idea of Blender plugins. But if you must have your own window you need to fork Blender. Take a look at makehuman project. It used to have Blender as a platform. (I'm not sure but I think they have a dif...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "3d", "blender", "embedding", "python", "wxpython" ]
stackoverflow_0000950145_3d_blender_embedding_python_wxpython.txt
Q: How to get an attribute just from the current class and not from possible parent classes? How to get an attribute just from the current class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is not defined in the current class (even if it...
How to get an attribute just from the current class and not from possible parent classes?
How to get an attribute just from the current class and not from possible parent classes? If I use getattr it traverses class hierarchy but I would like to get None if attribute is not defined in the current class (even if it is defined in some parent class).
[ "This is not a 100% proof answer (e.g. it will not work for classes that use __slots__), but it will work in most cases:\n>>> class A(object):\n... x = 42\n... y = 43\n... \n>>> class B(A):\n... x = 11\n... \n>>> b = B()\n\nYou can check if the attribute is defined in the class directly like this:\n>>> 'x'...
[ 4, 0, 0 ]
[]
[]
[ "django", "object", "python" ]
stackoverflow_0003285237_django_object_python.txt
Q: Exception Value field is blank when throwing custom exceptions in django I have custom exceptions in my django project that look like this: class CustomFooError(Exception): def __init__(self, msg="Something went wrong with Foo."): self.msg = msg def __str__(self): return repr(self.msg) ...
Exception Value field is blank when throwing custom exceptions in django
I have custom exceptions in my django project that look like this: class CustomFooError(Exception): def __init__(self, msg="Something went wrong with Foo."): self.msg = msg def __str__(self): return repr(self.msg) At various points in my code I will raise exceptions like this: raise CustomFo...
[ "I would just use super and let the constructor of Exception handle assigning the msg attribute:\nclass CustomFooError(Exception):\n\n def __init__(self, msg=None):\n if msg is None:\n msg = 'Something went wrong with Foo.'\n super(CustomFooError, self).__init__(msg)\n\nI just tested thi...
[ 3, 1 ]
[]
[]
[ "django", "exception_handling", "python" ]
stackoverflow_0003286204_django_exception_handling_python.txt
Q: How does one do the equivalent of "import * from module" with Python's __import__ function? Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlis...
How does one do the equivalent of "import * from module" with Python's __import__ function?
Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to perform as expected (as it doesn't import anything).
[ "Please reconsider. The only thing worse than import * is magic import *.\nIf you really want to:\nm = __import__ (S)\ntry:\n attrlist = m.__all__\nexcept AttributeError:\n attrlist = dir (m)\nfor attr in attrlist:\n globals()[attr] = getattr (m, attr)\n\n", "Here's my solution for dynamic naming of loca...
[ 36, 6, 0, 0 ]
[ "I didn't find a good way to do it so I took a simpler but ugly way from http://www.djangosnippets.org/snippets/600/\ntry:\n import socket\n hostname = socket.gethostname().replace('.','_')\n exec \"from host_settings.%s import *\" % hostname\nexcept ImportError, e:\n raise e\n\n" ]
[ -1 ]
[ "python", "python_import" ]
stackoverflow_0000147507_python_python_import.txt
Q: Import multiple files from a folder in Python I have a folder in my Application directory called Commands.folder. What I want to do is import all the modules in that folder, regardless of the name, into the python file that imports. How can I do this? A: from Commands import * You should create an empty file na...
Import multiple files from a folder in Python
I have a folder in my Application directory called Commands.folder. What I want to do is import all the modules in that folder, regardless of the name, into the python file that imports. How can I do this?
[ "from Commands import *\n\nYou should create an empty file named \"__init__.py\" in the \"Commands\" folder, and your main app script should be in the \"Application\" folder you've mentioned.\nNote however, the \"from module import *\" is not recommended since it may cause namespace pollution. \nRead this.\n", "I...
[ 4, 2 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003286856_import_python.txt
Q: Validate Email Header in Python I have a RegEx for validating email addresses, but I'm really looking to validate a whole From header. Any of these would be valid: name@domain.com <name@domain.com> My Name <name@domain.com> Is there anything out there that would validate these as valid from headers? I'm going t...
Validate Email Header in Python
I have a RegEx for validating email addresses, but I'm really looking to validate a whole From header. Any of these would be valid: name@domain.com <name@domain.com> My Name <name@domain.com> Is there anything out there that would validate these as valid from headers? I'm going to look in the smtp library :)
[ "Be aware that there are plenty of other valid cases of e-mail addresses beyond what you've posted.\nSee here for a recipe that may help. Also read this for a great discussion of parsing email addresses with a regex. There are any number of good regexes in there that will match the uses you're looking for, imho :...
[ 1, 1 ]
[]
[]
[ "email", "python", "regex" ]
stackoverflow_0003268198_email_python_regex.txt
Q: Django-models. Complex request to database I need to make special request to database through django. For example: class Model(models.Model): name=models.CharField() date=models.DateTimeField() other=models.TextField() How do I ask for row which name containe word 'Hello' (it shoul ignor register ...
Django-models. Complex request to database
I need to make special request to database through django. For example: class Model(models.Model): name=models.CharField() date=models.DateTimeField() other=models.TextField() How do I ask for row which name containe word 'Hello' (it shoul ignor register of first letter) end it is must be in diapason o...
[ "Try the following:\nstart_date = datetime.date(2005, 8, 9)\nend_date = datetime.date(2005, 8, 11)\nModel.objects.filter(name__icontains=\"hello\").filter(date__range(start_date,end_date))\n\nYou can stack as many filters as you like and it will be built into a single SQL Query (or whatever database system you use)...
[ 1 ]
[]
[]
[ "django_models", "filter", "python" ]
stackoverflow_0003286999_django_models_filter_python.txt
Q: Numpy records in the c api I'm playing with writing some C code to speed up an inner loop in my python code. This loop operates on a numpy record, e.g. soemthing like this: a = numpy.zeros((10,), dtype=[("myfvalue" ,"float"), ("myc", "int8"), ("anotheri", "uint64")]) which is then pa...
Numpy records in the c api
I'm playing with writing some C code to speed up an inner loop in my python code. This loop operates on a numpy record, e.g. soemthing like this: a = numpy.zeros((10,), dtype=[("myfvalue" ,"float"), ("myc", "int8"), ("anotheri", "uint64")]) which is then passed into c code like so: myCFun...
[ "There are a number of examples on the Scipy Wiki:\n\nC Extensions to NumPy and Python\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003285572_numpy_python.txt
Q: Issue with PPT conversion using python-Django I was just trying to convert a PPT using the following URL http://code.google.com/p/qifei/wiki/PDFConverter python code I could see the same thing happening with the command line option too python documentconverter.py /home/rajeev/Desktop/Downloads/Industry2.ppt /home/...
Issue with PPT conversion using python-Django
I was just trying to convert a PPT using the following URL http://code.google.com/p/qifei/wiki/PDFConverter python code I could see the same thing happening with the command line option too python documentconverter.py /home/rajeev/Desktop/Downloads/Industry2.ppt /home/rajeev/Desktop/test.pdf It appears that the image o...
[ "Mangled images are probably a function of the pdf converter (in this case, Open Office). Try using a different library like pyPDF.\n" ]
[ 0 ]
[]
[]
[ "django", "django_views", "document_conversion", "python" ]
stackoverflow_0003287317_django_django_views_document_conversion_python.txt
Q: Reading from a plain text file Say I have the following in a text file: car apple bike book How can I read it and put them into a dictionary or a list? A: Reading them into a list is trivially done with readlines(): f = open('your-file.dat') yourList = f.readlines() If you need the newlines stripped out...
Reading from a plain text file
Say I have the following in a text file: car apple bike book How can I read it and put them into a dictionary or a list?
[ "Reading them into a list is trivially done with readlines():\nf = open('your-file.dat')\nyourList = f.readlines()\n\nIf you need the newlines stripped out you can use ars' method, or do:\nyourList = [line.rstrip('\\n') for line in f]\n\nIf you want a dictionary with keys from 1 to the length of the list, the first...
[ 10, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003287179_python.txt
Q: SingPath Python Help - cosine problem Any help? I have the following: import math def cosine (a): x = (a * math.pi) / 180 return math.cos(x) The problem: Create a function that calculates the cosine of an angle (in degrees). The math module contains a function math.cos that uses radians to calculat...
SingPath Python Help - cosine problem
Any help? I have the following: import math def cosine (a): x = (a * math.pi) / 180 return math.cos(x) The problem: Create a function that calculates the cosine of an angle (in degrees). The math module contains a function math.cos that uses radians to calculate the cosine. You will need to convert the ...
[ "Your code as listed seems to work fine to me. If you want, you can omit the intermediate variable by just combining:\nreturn math.cos((a * math.pi) / 180)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003287627_python.txt
Q: Django migrations--is it possible to use South in the middle of the project? I already started a project, and the models are all synced and everything. A: Yes. I think it is not too late. I've moved to south in a middle of a project and I am happy with that choice. I think it is a big help for deployment. The in...
Django migrations--is it possible to use South in the middle of the project?
I already started a project, and the models are all synced and everything.
[ "Yes. I think it is not too late. I've moved to south in a middle of a project and I am happy with that choice. I think it is a big help for deployment.\nThe initialization of the south app can be done at any moment.\n", "It's even mentioned in docs:\nhttp://south.aeracode.org/wiki/QuickStartGuide#a1.Setupeveryap...
[ 4, 4, 2 ]
[]
[]
[ "database", "django", "django_south", "mysql", "python" ]
stackoverflow_0002445761_database_django_django_south_mysql_python.txt
Q: Data structure to store key-value pairs and retrive the key for the lowest value quickly I'm implementing something like a cache, which works like this: If a new value for the given key arrives from some external process, store that value, and remember the time when this value arrived. If we are idle, find the ol...
Data structure to store key-value pairs and retrive the key for the lowest value quickly
I'm implementing something like a cache, which works like this: If a new value for the given key arrives from some external process, store that value, and remember the time when this value arrived. If we are idle, find the oldest entry in the cache, fetch the new value for the key from external source and update the c...
[ "Most heap implementations will get you the lowest key in your collection in O(1) time, but there's no guarantees regarding the speed of random lookups or removal. I'd recommend pairing up two data structures: any simple heap implementation and any out-of-the-box hashtable.\nOf course, any balanced binary tree can ...
[ 3, 1, 0 ]
[]
[]
[ "caching", "data_structures", "python" ]
stackoverflow_0003285168_caching_data_structures_python.txt
Q: How can I exclude a declared field in ModelForm in form's subclass? In Django, I am trying to derive (subclass) a new form from ModelForm form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.form...
How can I exclude a declared field in ModelForm in form's subclass?
In Django, I am trying to derive (subclass) a new form from ModelForm form where I would like to remove some fields (or to have only some fields, to be more correct). Of course obvious way would be to do (base form is from django.contrib.auth.forms): class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.M...
[ "Try this:\nclass MyUserChangeForm(UserChangeForm):\n\n def __init__(self, *args, **kwargs):\n super(MyUserChangeForm, self).__init__(*args, **kwargs)\n self.fields.pop('username')\n\n class Meta(UserChangeForm.Meta):\n fields = ('first_name', 'last_name', 'email')\n\nThis dynamically removes a field fro...
[ 3, 1 ]
[]
[]
[ "django", "django_forms", "modelform", "python" ]
stackoverflow_0003287974_django_django_forms_modelform_python.txt
Q: How to create an .app file in mac os x from binaries? I have a project in the form of binaries which can be distributed to other mac pcs. How to create an .app file for that project? Thanks in advance A: Take a look at py2app, it might solve your problem. py2app is a Python setuptools command which will allow y...
How to create an .app file in mac os x from binaries?
I have a project in the form of binaries which can be distributed to other mac pcs. How to create an .app file for that project? Thanks in advance
[ "Take a look at py2app, it might solve your problem.\n\npy2app is a Python setuptools command which will allow you to make standalone application bundles and plugins from Python scripts. py2app is similar in purpose and design to py2exe for Windows.\n\n" ]
[ 2 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003287727_macos_python.txt
Q: Why does this keep going around in a never ending loop? def get_houseid_list(): """Returns a list of all house ids from db""" print 'Building list of all HouseIDs...' houseid_list = [] houseids = session.query(Episode.HouseID).all() for i in houseids: houseid_list.append(i[0]) retur...
Why does this keep going around in a never ending loop?
def get_houseid_list(): """Returns a list of all house ids from db""" print 'Building list of all HouseIDs...' houseid_list = [] houseids = session.query(Episode.HouseID).all() for i in houseids: houseid_list.append(i[0]) return houseid_list def walkDir(top, ignore=[]): """Returns ...
[ "Just some comments on this code, while we wait for you to give us enough information to solve your problem..\nIt's pretty horrible depending on a side effect like this\n[fflist.append(join(root, f)) for f in file_list]\n\nwhen you can just say\nfflist.extend(join(root, f) for f in file_list)\n\nBut that looks like...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003287578_python.txt
Q: Python: How to Sort SQL statements in a text file? The output below is from Oracle; where it generates "create table" statements using a supplied package. I feed them into the python diff tool HtmlDiff which uses difflib under the covers. Each table is followed by a number of "alter table add constraint" commands ...
Python: How to Sort SQL statements in a text file?
The output below is from Oracle; where it generates "create table" statements using a supplied package. I feed them into the python diff tool HtmlDiff which uses difflib under the covers. Each table is followed by a number of "alter table add constraint" commands that add the various constraints. The problem is that th...
[ "Load it all in to a string, then split on \";\" to build an array of SQL commands. Loop the array and build a new sorted array. Pass along the CREATE TABLE bits and slice out the ALTER TABLE statements in to a separate list. sort() the alter list and extend it to the result array. When you're done, ';\\n'.join(res...
[ 0, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003286607_python_sql.txt
Q: Google AppEngine Indexing Delay Am trying to deploy a app to Google AppEngine. But the DataStore index building seems to take forever. The contents of my index.yaml indexes: # AUTOGENERATED # This index.yaml is automatically updated whenever the dev_appserver # detects that a new type of query is run. If you w...
Google AppEngine Indexing Delay
Am trying to deploy a app to Google AppEngine. But the DataStore index building seems to take forever. The contents of my index.yaml indexes: # AUTOGENERATED # This index.yaml is automatically updated whenever the dev_appserver # detects that a new type of query is run. If you want to manage the # index.yaml file m...
[ "The only thing you can do to speed up indexing is to create indexes when you have less data - though this will impose additional overhead on inserts. Other than that, you have to leave it up to the automated system to build the indexes as fast as it can.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003286995_google_app_engine_python.txt
Q: How do I launch a function and wait/don't wait on it depending on whether it's a GUI application? I'm looking for a Python function which behaves just like the Windows command interpreter cmd.exe when it comes to waiting for newly launched processes to finish. Right now I'm using os.system() but this function alw...
How do I launch a function and wait/don't wait on it depending on whether it's a GUI application?
I'm looking for a Python function which behaves just like the Windows command interpreter cmd.exe when it comes to waiting for newly launched processes to finish. Right now I'm using os.system() but this function always blocks, even when launching GUI applications (which, in case they were written in C/C++, have a Win...
[ "You could write a small C wrapper/extension that checks for the subsystem (using ImageNtHeader). If all else fails, you can parse the PE headers directly.\n", "Python has no standard way to examine the executables you can start with the process API.\nHow about you start the external command using cmd.exe? Or cre...
[ 2, 0 ]
[]
[]
[ "process", "python", "windows" ]
stackoverflow_0003288289_process_python_windows.txt
Q: python handle endless XML I am working on a application, and my job just is to develop a sample Python interface for the application. The application can provide XML-based document, I can get the document via HTTP Get method, but the problem is the XML-based document is endless which means there will be no end el...
python handle endless XML
I am working on a application, and my job just is to develop a sample Python interface for the application. The application can provide XML-based document, I can get the document via HTTP Get method, but the problem is the XML-based document is endless which means there will be no end element. I know that the document...
[ "This is what I use for parsing an endless xml stream which I get from a remote computer (in my case I connect over a socket and use socket.makefile('r') to create the file object)\n19.12.2. IncrementalParser Objects\nparser = xml.sax.make_parser(['xml.sax.IncrementalParser'])\nhandler = FooHandler()\nparser.setCon...
[ 7, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003284289_python_xml.txt
Q: Question about nested loops I am new to programming and having some problem figuring out nested loops. I have a list of data that I want to extract from a larger file. I am able to extract one item of data from the larger file successfully but I need to extract 100 different trials from this larger file of thousan...
Question about nested loops
I am new to programming and having some problem figuring out nested loops. I have a list of data that I want to extract from a larger file. I am able to extract one item of data from the larger file successfully but I need to extract 100 different trials from this larger file of thousands of trials. Each trial is one l...
[ "It seems to me that you need a list that holds all the trial numbers that you are interested in. So maybe you could try something like this:\ncompletedataset = open('completedataset.txt', 'r')\nsmallerdataset = open('smallerdataset.txt', 'w')\n\ntrials = [134, 274, 388]\ncompletedata = completedataset.readlines()\...
[ 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "loops", "nested", "python" ]
stackoverflow_0003282785_loops_nested_python.txt