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: Unpickling new-style with kwargs not possible? During instantiation of my class, I initialize some fields that are not picklable. Thus, in order to be able to (un)pickle my classes correctly, I would like my init method to be called on unpickling. This is, it seems, the way it worked with old-style classes. With n...
Unpickling new-style with kwargs not possible?
During instantiation of my class, I initialize some fields that are not picklable. Thus, in order to be able to (un)pickle my classes correctly, I would like my init method to be called on unpickling. This is, it seems, the way it worked with old-style classes. With new style classes, I need to use __new__ and __getnew...
[ "The pickle protocol 2 wants to call cls.__new__(cls, *args) by default, but there is a way around this. If you use __reduce__ you can return a function which will map your arguments to __new__. I was able to modify your example to get **kwargs to work:\nimport cPickle\n\nclass Blubb(object):\n\n def __init__(s...
[ 10 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0005238252_pickle_python.txt
Q: How do I list IRC server's channels using Twisted I would like to list the server's channels when I log into an IRC sevrer. How can I do that? I tried to override the signedOn method: def signedOn(self): print "connected to the server..." self.sendLine("/LIST") but then I don't know if I get something bac...
How do I list IRC server's channels using Twisted
I would like to list the server's channels when I log into an IRC sevrer. How can I do that? I tried to override the signedOn method: def signedOn(self): print "connected to the server..." self.sendLine("/LIST") but then I don't know if I get something back from this request and how to get the response.
[ "Good point lets submit a patch on a ticket I just created to have this feature added.\nhttp://twistedmatrix.com/trac/ticket/4929\nTill then just sendLine('LIST') should work\n" ]
[ 0 ]
[]
[]
[ "irc", "python", "twisted" ]
stackoverflow_0005239231_irc_python_twisted.txt
Q: Fetching HTTP GET variables in Python I'm trying to set up a HTTP server in a Python script. So far I got the server it self to work, with a code similar to the below, from here. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): pr...
Fetching HTTP GET variables in Python
I'm trying to set up a HTTP server in a Python script. So far I got the server it self to work, with a code similar to the below, from here. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): print("Just received a GET request") ...
[ "Import urlparse and do:\ndef do_GET(self):\n qs = {}\n path = self.path\n if '?' in path:\n path, tmp = path.split('?', 1)\n qs = urlparse.parse_qs(tmp)\n print path, qs\n\n", "urlparse.parse_qs()\nprint urlparse.parse_qs(os.environ['QUERY_STRING'])\n\nOr if you care about order or dupl...
[ 9, 6 ]
[]
[]
[ "get", "http", "python" ]
stackoverflow_0005239547_get_http_python.txt
Q: Use Function to Return a List of Words Containing Required Letters I am trying to write a function that takes a string, and checks every letter in that string against every letter, in every line, in a list of words. The code I have written is: def uses_all(required): fin = open('words.txt') for line in fin...
Use Function to Return a List of Words Containing Required Letters
I am trying to write a function that takes a string, and checks every letter in that string against every letter, in every line, in a list of words. The code I have written is: def uses_all(required): fin = open('words.txt') for line in fin: for letter in line: if letter not in required: ...
[ "Lines yielded from iterating over a file have the EOL at the end. Strip that first.\nAlso, the question doesn't match the logic in the code.\n", "Well, the function you´ve written iterates through the file without doing anything, and then returns the last line, so the behavior you see is kinda expected.\nTry thi...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0005227524_function_python.txt
Q: Finding the most popular words in a list I have a list of words: words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah'] And I want to get a list of tuples: [(3, 'all'), (2, 'yeah'), (1, 'bye'), (1, 'awesome')] where each tuple is... (number_of_occurrences, word) The list should be sorted by the number ...
Finding the most popular words in a list
I have a list of words: words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah'] And I want to get a list of tuples: [(3, 'all'), (2, 'yeah'), (1, 'bye'), (1, 'awesome')] where each tuple is... (number_of_occurrences, word) The list should be sorted by the number of occurrences. What I've done so far: def pop...
[ "You can use the counter for this.\nimport collections\nwords = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah']\ncounter = collections.Counter(words)\nprint(counter.most_common())\n>>> [('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]\n\nIt gives the tuple with reversed columns. \nFrom the comments: col...
[ 16, 6, 2 ]
[]
[]
[ "list", "python", "string", "words" ]
stackoverflow_0005239781_list_python_string_words.txt
Q: Equivalent of ruby obj.send in python In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it ...
Equivalent of ruby obj.send in python
In ruby if I have an object obj, with a method called funcname, I can call the method using the following syntax obj.send(funcname) Is there something similar in python. The reason I want to do this, that I have a switch statement where I set the funcname, and want to call it at the end of the switch statement.
[ "getattr(obj, \"name\")(args)\n\n​​​​\n", "hmmm... getattr(obj, funcname)(*args, **kwargs) ?\n>>> s = \"Abc\"\n\n>>> s.upper()\n'ABC'\n\n>>> getattr(s, \"upper\")()\n'ABC'\n\n>>> getattr(s, \"lower\")()\n'abc'\n\n", "Apart from the already mentioned getattr() builtin:\nAs an alternative to an if-elif-else loop ...
[ 25, 10, 1, 1 ]
[]
[]
[ "python", "send" ]
stackoverflow_0005238785_python_send.txt
Q: multilevel caesar cipher Hey, I'm trying to decode a multilevel Caesar cipher. By that I mean a string of letters could have been shifted several times, so if I say apply_shifts[(2,3),(4,5)], that means I shift everything from the 2nd letter by 3 followed by everything from the 4th letter by 5. Here's my code so...
multilevel caesar cipher
Hey, I'm trying to decode a multilevel Caesar cipher. By that I mean a string of letters could have been shifted several times, so if I say apply_shifts[(2,3),(4,5)], that means I shift everything from the 2nd letter by 3 followed by everything from the 4th letter by 5. Here's my code so far. def find_best_shifts_rec...
[ "I think the problem is that you always work on the whole text, but apply the (new) shifting at some start inside of the text. So your check is_word(wordlist,text.split()[0]) will always check the first word, which is - of course - a word after your first shift.\nWhat you need to do instead is to get the first word...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005235636_python.txt
Q: how to make django comment model field Site not required I'm using django-threadedcomments from ericflo on github. This app simply extends the native django comments framework. I am running into the same issue with both frameworks. I continue to get an error relating to mysql that site_id cannot be null. I hav...
how to make django comment model field Site not required
I'm using django-threadedcomments from ericflo on github. This app simply extends the native django comments framework. I am running into the same issue with both frameworks. I continue to get an error relating to mysql that site_id cannot be null. I have no use for the Site field in my comments. I tried to extend...
[ "I found it easier to just define one Site object. django-threadedcomments is not the only extension which requires that.\n", "You will not be able to change this without monkey-patching the current model, but it shouldn't be a big deal setting the site field to Site.objects.get_current() in the view/form when sa...
[ 2, 1 ]
[]
[]
[ "django", "django_comments", "python" ]
stackoverflow_0005236936_django_django_comments_python.txt
Q: Python: Connecting to db without any external libraries I'm working on a client machine running suse linux and python 2.4.2. I'm not allowed to dowload anything from the net including any external libraries. So, is there any way I can connect to a database (oracle) using only the default libraries? A: No. There ...
Python: Connecting to db without any external libraries
I'm working on a client machine running suse linux and python 2.4.2. I'm not allowed to dowload anything from the net including any external libraries. So, is there any way I can connect to a database (oracle) using only the default libraries?
[ "No. There is nothing in the standard library for connecting to database servers.\n", "You could look at the Apex Listener and/or PL/SQL Embedded Gateway (basically a webserver in the DB). These both provide HTTP access to database resources (eg getting data as JSON). Though obviously this shifts the 'heavy lifti...
[ 1, 0 ]
[]
[]
[ "database", "oracle", "python" ]
stackoverflow_0005228728_database_oracle_python.txt
Q: Why doesn't my urls.py work? url(r'^video/?$','stuff.abc.views.video',name="video"), This doesn't work: <a href="{% url video %}">Videos</a> But this works: <a href="/video">Videos</a> the error is: TemplateSyntaxError at / Caught ViewDoesNotExist while rendering: Tried ad in module stuff.abc.views. Error was: ...
Why doesn't my urls.py work?
url(r'^video/?$','stuff.abc.views.video',name="video"), This doesn't work: <a href="{% url video %}">Videos</a> But this works: <a href="/video">Videos</a> the error is: TemplateSyntaxError at / Caught ViewDoesNotExist while rendering: Tried ad in module stuff.abc.views. Error was: 'module' object has no attribute '...
[ "The url itself isn't breaking things, it's the stuff.abc.views module that has the error.\nSomewhere in that module (and probably in the video view function), you are attempting to access an attribute called ad that doesn't exist. \nThe error is confusing because it says ViewDoesNotExist, but that's really just Dj...
[ 3 ]
[]
[]
[ "django", "html", "python", "templates" ]
stackoverflow_0005240247_django_html_python_templates.txt
Q: Map list by partial function vs lambda I was wondering whether for most examples it is more 'pythonic' to use lambda or the partial function? For example, I might want to apply imap on some list, like add 3 to every element using: imap(lambda x : x + 3, my_list) Or to use partial: imap(partial(operator.add, 3), m...
Map list by partial function vs lambda
I was wondering whether for most examples it is more 'pythonic' to use lambda or the partial function? For example, I might want to apply imap on some list, like add 3 to every element using: imap(lambda x : x + 3, my_list) Or to use partial: imap(partial(operator.add, 3), my_list) I realize in this example a loop co...
[ "To be truly equivalent to imap, use a generator expression:\n(x + 3 for x in mylist)\n\nLike imap, this doesn't immediately construct an entire new list, but instead computes elements of the resulting sequence on-demand (and is thus much more efficient than a list comprehension if you're chaining the result into a...
[ 17, 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0005240427_python.txt
Q: need a simple way to add meta information/class to a python list/tuple variable? All, I want simple meta information to be enclosed on an list object, see below code. >>> a = [] >>> a.foo = 100 Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'list' object has no...
need a simple way to add meta information/class to a python list/tuple variable?
All, I want simple meta information to be enclosed on an list object, see below code. >>> a = [] >>> a.foo = 100 Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'list' object has no attribute 'foo' >>> setattr(a,"foo",100) Traceback (most recent call last): File "<...
[ "The base types defined in C cannot have arbitrary attributes added; you must derive a Python type from them in order to change this.\n>>> class MyList(list):\n... pass\n... \n>>> m = MyList((1, 2, 3))\n>>> len(m)\n3\n>>> m.foo = 42\n>>> m.foo\n42\n\n", "\nit does have setattr. it does not have attribute 'foo',...
[ 7, 1 ]
[]
[]
[ "list", "meta", "python", "setattr" ]
stackoverflow_0005240567_list_meta_python_setattr.txt
Q: Persistent Terminal Output Consider something like lynx or nano/pico/vi - is there any way to get a persistent output in the terminal window with Python? Specifically, I'm looking for something like output(char, x, y) which will replace the current character at (x, y) in the terminal with char, rather like the old...
Persistent Terminal Output
Consider something like lynx or nano/pico/vi - is there any way to get a persistent output in the terminal window with Python? Specifically, I'm looking for something like output(char, x, y) which will replace the current character at (x, y) in the terminal with char, rather like the old TI-8(3|4)s.
[ "curses\n", "another way would be http://www.termsys.demon.co.uk/vtansi.htm#cursor\n\n>>> ESC = chr(0x1b)\n>>> print ESC + '[5;5ftest',\n\nworks on most xterms, which tend to be vt100-compliant.\n" ]
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005240633_python.txt
Q: why isn't this python regex statement returning my viewstate information? def ExtractViewState(string): m = re.match("__viewstate[^>]+value=\"\(\?<Value>[^\"]*\)", string, re.IGNORECASE) return m.group(0) I think I'm missing something, but it m keeps returning None. Blagh. UPDATE: <input type="hidden" nam...
why isn't this python regex statement returning my viewstate information?
def ExtractViewState(string): m = re.match("__viewstate[^>]+value=\"\(\?<Value>[^\"]*\)", string, re.IGNORECASE) return m.group(0) I think I'm missing something, but it m keeps returning None. Blagh. UPDATE: <input type="hidden" name="__VIEWSTATE" value="5vzj+3s4pEHFJUQoOJbZicZdf+k2bi0uiXeIxMNTxjocu0FLzTXEI8pE...
[ "You have a few issues:\nimport re\ndef ExtractViewState(string):\n # re.match looks only at the **beginning** of the string\n # dont escape the `( .. )` those capture the group\n m = re.search(\"__viewstate[^>]+value=\\\"([^\\\"]*)\", string, re.IGNORECASE)\n # group(0) is the whole match, you want the...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005240640_python_regex.txt
Q: Use paste.deploy to serve a twisted application I'm working on a project that has two parts: A WSGI-enabled web app written with pylons and served with python-paste A python-twisted application that has nothing to do with HTTP or WSGI. I'd like to keep the configuration for both apps in the same configuration fi...
Use paste.deploy to serve a twisted application
I'm working on a project that has two parts: A WSGI-enabled web app written with pylons and served with python-paste A python-twisted application that has nothing to do with HTTP or WSGI. I'd like to keep the configuration for both apps in the same configuration file. I'd also like to use paste serve to launch both t...
[ "It is extremely unlikely that trying to do this is going to be worth the effort. paster serve has it's own event loop, threadpool, etc. and Twisted apps expect something quite different.\nYou could try writing your own paster subcommand, but you're probably better off writing a .tac file that serves both apps for...
[ 0 ]
[]
[]
[ "python", "twisted", "wsgi" ]
stackoverflow_0004975028_python_twisted_wsgi.txt
Q: Can web2py work with svn? I just start to learn python and web2py. Because of web2py's web interface development, I am wondering how can web2py work with svn? If a team wants to build a website,how do they work together? How to control the iteration of source code? A: Yes, it works fine with svn, hg, whatever s...
Can web2py work with svn?
I just start to learn python and web2py. Because of web2py's web interface development, I am wondering how can web2py work with svn? If a team wants to build a website,how do they work together? How to control the iteration of source code?
[ "Yes, it works fine with svn, hg, whatever source control you need to use. \nSometimes people think that you have to code with web2py's admin interface, but that really is not the case, once you realize it can be edited with any of your regular tools, you will see that you don't have to treat it any differently whe...
[ 5 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0005240646_python_web2py.txt
Q: How to parse a utf-8 encoded query parameter with Python 2.6 I have some lovely (Scandinavian?) user on my website complaining that I cannot parse his username in URLs, and hence I am showing him no results on his page on my website. I am pretty sure that the browser encodes the requests as http://councilroom.com...
How to parse a utf-8 encoded query parameter with Python 2.6
I have some lovely (Scandinavian?) user on my website complaining that I cannot parse his username in URLs, and hence I am showing him no results on his page on my website. I am pretty sure that the browser encodes the requests as http://councilroom.com/player?player=G%C3%B6rling I'd like to get the player string to b...
[ "In [4]: import urlparse\n\nIn [6]: parsed_url = urlparse.urlparse('http://councilroom.com/player?player=G%C3%B6rling')\n\nIn [7]: parsed_url\nOut[7]: ParseResult(scheme='http', netloc='councilroom.com', path='/player', params='', query='player=G%C3%B6rling', fragment='')\n\nIn [8]: query_dict = dict(urlparse.parse...
[ 0, 0 ]
[]
[]
[ "python", "urlparse", "utf8_decode", "web.py" ]
stackoverflow_0005240929_python_urlparse_utf8_decode_web.py.txt
Q: Inserting email into auth_user in web2py on first time login while using pam_auth I am using pam_auth login for my web2py installation. When a user logs in for the first time, I want to store his email which i obtain from a ldap query. How can I do that in web2py. In other words, i want to execute a piece of ldap ...
Inserting email into auth_user in web2py on first time login while using pam_auth
I am using pam_auth login for my web2py installation. When a user logs in for the first time, I want to store his email which i obtain from a ldap query. How can I do that in web2py. In other words, i want to execute a piece of ldap query in python at the time of first login by any user.
[ "web2py default authentication system has an event table, which stores every event for the user. i.e it stores events for registration, login, logout, etc.\nSo you can see if it is the first time login by querying this table.\nUSER_ID = #Get your user ID\nquery = (db.auth_event.description.like('%Logged-in%'))&(db....
[ 1 ]
[]
[]
[ "authentication", "ldap", "python", "web2py" ]
stackoverflow_0005236015_authentication_ldap_python_web2py.txt
Q: Simple way to toggle fullscreen with F11 in PyGTK I am not a professional programmer but am regularly using PyGTK and Cairo for data visualization testing and prototyping. I have a standard template of PyGTK that I took from the web, which does the "standard things" GTK needs to work: import pygtk pygtk.require('2...
Simple way to toggle fullscreen with F11 in PyGTK
I am not a professional programmer but am regularly using PyGTK and Cairo for data visualization testing and prototyping. I have a standard template of PyGTK that I took from the web, which does the "standard things" GTK needs to work: import pygtk pygtk.require('2.0') import gtk """ lots of stuff """ if __name__ == ...
[ "Let's start with how to pick up on the keypress: we need to connect to the key-press-event signal. But we need something to connect it to, of course.\nThis something should keep track of the window state, so it makes sense to use a class that connects to the window-state-event signal and keeps track of whether the...
[ 19 ]
[]
[]
[ "fullscreen", "gtk", "pygtk", "python" ]
stackoverflow_0005234434_fullscreen_gtk_pygtk_python.txt
Q: how to get the number in a python string this is my code : print int('adw第五代222') it show error : Traceback (most recent call last): File "a.py", line 5, in <module> print int('adw第五代222') ValueError: invalid literal for int() with base 10: 'adw\xe7\xac\xac\xe4\xba\x94\xe4\xbb\xa3222' what can i do , than...
how to get the number in a python string
this is my code : print int('adw第五代222') it show error : Traceback (most recent call last): File "a.py", line 5, in <module> print int('adw第五代222') ValueError: invalid literal for int() with base 10: 'adw\xe7\xac\xac\xe4\xba\x94\xe4\xbb\xa3222' what can i do , thanks
[ ">>> int(re.search('\\d+', u'adw第五代222').group())\n222\n\n", "You're trying to turn something that's not a number into an integer. So that's obviously not going to work. You will have to extract the digits from the string. If you don't want to use a regular expression, you could try something like this:\ns = u'ad...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005241003_python.txt
Q: Django: How do I redirect to page where form originated In my Django app I have multiple pages displaying a link that loads a new page displaying a form. When the form is submitted, what is the cleanest way to redirect to the originating page from which this form was accessed? originating page -> form page -> orig...
Django: How do I redirect to page where form originated
In my Django app I have multiple pages displaying a link that loads a new page displaying a form. When the form is submitted, what is the cleanest way to redirect to the originating page from which this form was accessed? originating page -> form page -> originating page Using a next variable seems unellegant since I h...
[ "There are a couple of options, all with the cons and benefits ofcourse.\n\npassing the originating page withi POST/GET\nstoring the originating page in the session (won't work with multiple tabs obviously)\nstoring the originating page in a cookie (won't work with multiple tabs either)\nif it's a single page, redi...
[ 6, 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004203417_django_python.txt
Q: Redirect to different webpage based on URL entered I am trying to create a script to redirect users to a different URL based on the URL entered. Ex: test.foo.com/1234 redirects to a.b.com/abc/def?info=1234 or test.foo.com/9999 redirects to a.b.com/abc/def?info=9999 What would be the easiest way to do this? Thanks!...
Redirect to different webpage based on URL entered
I am trying to create a script to redirect users to a different URL based on the URL entered. Ex: test.foo.com/1234 redirects to a.b.com/abc/def?info=1234 or test.foo.com/9999 redirects to a.b.com/abc/def?info=9999 What would be the easiest way to do this? Thanks!
[ "Use this to extract the requested page in your php script.\n$_SERVER['REQUEST_URI']\nThen do this to redirect the user\nheader(\"Location: http://www.abc.com/\");\nExample:\n<?php\n $request = $_SERVER['REQUEST_URI'];\n $request = trim($request, '/');\n\n //there can be no output before this line\n header(\"Lo...
[ 2, 1 ]
[]
[]
[ "javascript", "php", "python", "redirect", "url" ]
stackoverflow_0005241545_javascript_php_python_redirect_url.txt
Q: Python ftplib can't get size of file before download? I'm using ftplib to transfer files. Everything is working great. Now I'm trying to get the size of the target file before downloading. First, I tried just getting size with ftp.size(filename). Server complained that I can't do that in ascii mode. Then I tri...
Python ftplib can't get size of file before download?
I'm using ftplib to transfer files. Everything is working great. Now I'm trying to get the size of the target file before downloading. First, I tried just getting size with ftp.size(filename). Server complained that I can't do that in ascii mode. Then I tried setting binary mode using ftp.sendcmd("binary") and ftp....
[ "Very late reply, but here's the correct answer. This works with ProFTPD.\nftp.sendcmd(\"TYPE i\") # Switch to Binary mode\nftp.size(\"/some/file\") # Get size of file\n\n", "Ftplib can get the size of a file before downloading. As the documentation says:\n\nFTP.size(filename)\n Request the size of\n the f...
[ 27, 4, 0 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0003231910_ftplib_python.txt
Q: print referred variable from object in django/python In the below python code ,can the object know that the template tag is referring a variable and get that in a python variable newemp is the object that i am passing from the views and the template is trying to access a variable as {{newemp.get_names.emp_add}} ,n...
print referred variable from object in django/python
In the below python code ,can the object know that the template tag is referring a variable and get that in a python variable newemp is the object that i am passing from the views and the template is trying to access a variable as {{newemp.get_names.emp_add}} ,now in the python code can the object print this variable i...
[ "No. The access is done once the appropriate object has been returned from get_names() so there is no direct way to know within the method what is being accessed.\n", "If you are asking whether you can write to a variable within a template, and then access that value back within your Python code, I do not believe...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005241883_django_django_models_django_templates_django_views_python.txt
Q: Where can I find good discussions of PHP vs Ruby vs Python? Do you know about any good articles that discuss the differences between the languages? So far I've mostly found very non-neutral stuff or technical benchmarking of function X vs function Y. Again, I'm not asking for arguments here for one language over a...
Where can I find good discussions of PHP vs Ruby vs Python?
Do you know about any good articles that discuss the differences between the languages? So far I've mostly found very non-neutral stuff or technical benchmarking of function X vs function Y. Again, I'm not asking for arguments here for one language over another. I see there are a lot of similar questions, where the ans...
[ "\nPython <-> Ruby: What does ruby have that python doesnt and vice versa\nPython <-> PHP: is switching from php to python worth the trouble\n\n" ]
[ 3 ]
[]
[]
[ "php", "python", "ruby" ]
stackoverflow_0005241961_php_python_ruby.txt
Q: Python: How to transform a 'flat' sequence into a sequence of tuples? I needed to make a list of 2-tuples out of a one-dimensional list of coordinates, for example [1, 2, 1, 5] needed to become [(1, 2), (1, 5)]. As it happens I've already found the fastest, most general way to do this, at Activestate, but the co...
Python: How to transform a 'flat' sequence into a sequence of tuples?
I needed to make a list of 2-tuples out of a one-dimensional list of coordinates, for example [1, 2, 1, 5] needed to become [(1, 2), (1, 5)]. As it happens I've already found the fastest, most general way to do this, at Activestate, but the code listed there is opaque to a relative Python newbie: def group3(lst, n): ...
[ "The itertools.islice function can produce a slice from any iterable. The statement:\nitertools.islice(lst, 0, None, 2)\n\nIn simplified terms means \"return an iterator which, when evaluated, will return every other element in lst starting with the element at 0\". The 0 arg is the starting point and 2 is the step ...
[ 2, 1 ]
[]
[]
[ "forms", "list", "python", "tuples" ]
stackoverflow_0005241391_forms_list_python_tuples.txt
Q: Web.py on dotcloud with wsgi I'm trying to deploy my web.py app on dotcloud, but can't figure out how to do it. I went through this tutorial fine: http://docs.dotcloud.com/static/tutorials/firststeps/ And then I looked at http://docs.dotcloud.com/static/components/python/ ... The python service can host any pyth...
Web.py on dotcloud with wsgi
I'm trying to deploy my web.py app on dotcloud, but can't figure out how to do it. I went through this tutorial fine: http://docs.dotcloud.com/static/tutorials/firststeps/ And then I looked at http://docs.dotcloud.com/static/components/python/ ... The python service can host any python web application compatible wi...
[ "I am fellow user of web.py and I work at DotCloud by the way :-)\nWe use uWSGI to run your WSGI application. The point is that uWSGI is looking for a variable named \"application\".\nHere is what I usually do:\napp = web.application(urls, globals())\n\nif __name__ == '__main__':\n app.run()\nelse:\n web.conf...
[ 12 ]
[]
[]
[ "python", "web.py", "wsgi" ]
stackoverflow_0005241291_python_web.py_wsgi.txt
Q: how to get the current thing in this code this is my code : class a(): def __init__(self): self.a="aaa" self.b='bbb' aa=a() x=['a','b','c'] for i in x: print aa.get(i) it show error : Traceback (most recent call last): File "a.py", line 10, in <module> print aa['a'] AttributeError: ...
how to get the current thing in this code
this is my code : class a(): def __init__(self): self.a="aaa" self.b='bbb' aa=a() x=['a','b','c'] for i in x: print aa.get(i) it show error : Traceback (most recent call last): File "a.py", line 10, in <module> print aa['a'] AttributeError: a instance has no attribute '__getitem__' what...
[ "Perhaps you are looking for getattr(aa, i) ?\n", "You'll have to use the getattr function or define a __getitem__ method for class a (though to implement it, you'll probably end up using getattr). \nIt looks like the error message was generated by different code where you were trying aa[i] rather than aa.get(i),...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005242264_python.txt
Q: File renaming; Can I get some feedback Background: A friend of mine, who just might have some OCD issues, was telling me a story of how he was not looking forward to the hours of work he was about to invest into renaming tons of song files that had the words An, The, Of and many more capitalized. Criteria: He gav...
File renaming; Can I get some feedback
Background: A friend of mine, who just might have some OCD issues, was telling me a story of how he was not looking forward to the hours of work he was about to invest into renaming tons of song files that had the words An, The, Of and many more capitalized. Criteria: He gave me a list of words, omitted here because y...
[ "Repeated code is usually considered bad style (DRY is the buzzword). Also I usually try not to interleave functionality.\nFor the \"design\" of this little script I would first walk the directories and create a large list of all audio files and directories. Then I write a function handling the changing of one the ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005242495_python.txt
Q: how to change jquery ui autocomplete function suitable for python Instead of using search.php within this example, how can i use a python method to return the data? example: is this valid: $.getJSON( "{{ data }}", { term: extractLast( request.term ) }, response ); ...
how to change jquery ui autocomplete function suitable for python
Instead of using search.php within this example, how can i use a python method to return the data? example: is this valid: $.getJSON( "{{ data }}", { term: extractLast( request.term ) }, response ); $(function() { function split( val ) { return val.split( /...
[ "You will need to have your python script print a JSON formatted string for a data array. I would be willing to bet the python has a library you may load for converting objects, array, strings, etc into JSON formatted strings. Simple turn the appropriate array into a JSON string and your JavaScript will load it, no...
[ 0, 0 ]
[]
[]
[ "jquery", "python" ]
stackoverflow_0005240997_jquery_python.txt
Q: how to print right thing in 'a' when loop 'b' this is my code : a ={ 'power':'力', 'magic':'魔', 'skill':'技' } b =['power','wwwww'] for i in b : #print getattr(a,i) print a[i] or 'default string' and it show error : Traceback (most recent call last): File "a.py", line 13, in <m...
how to print right thing in 'a' when loop 'b'
this is my code : a ={ 'power':'力', 'magic':'魔', 'skill':'技' } b =['power','wwwww'] for i in b : #print getattr(a,i) print a[i] or 'default string' and it show error : Traceback (most recent call last): File "a.py", line 13, in <module> print a[i] or 'default string' KeyError:...
[ "You can use .get()\nfor i in b:\n print a.get(i, \"default string\")\n\n", "You can use a conditional expression:\nprint a[i] if i in a else 'default string'\n\n", "if i in a:\n st = a[i]\nelse:\n st = \"default string\"\nprint st\n\n" ]
[ 7, 3, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0005242732_loops_python.txt
Q: Python: MySQLdb Installation Problems Mysql version 5.0.77 Python version 2.5 #easy_install MySQL-python When I try to install, I get the following errors: _mysql.c:2331: error: â_mysql_ConnectionObjectâ has no member named âopenâ _mysql.c:2338: error: â_mysql_ConnectionObjectâ has no member named âconverterâ _mys...
Python: MySQLdb Installation Problems
Mysql version 5.0.77 Python version 2.5 #easy_install MySQL-python When I try to install, I get the following errors: _mysql.c:2331: error: â_mysql_ConnectionObjectâ has no member named âopenâ _mysql.c:2338: error: â_mysql_ConnectionObjectâ has no member named âconverterâ _mysql.c:2345: error: â_mysql_ConnectionObjectâ...
[ "yum install mysql-devel\nThen,\neasy_install MySQL-python\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005242362_python.txt
Q: top down friction in pymunk Been struggling with this for a couple of days, hard to find code examples on the net. I'm making a topdown game and having trouble getting the player to move on key press. At the moment i'm using add_force or add_impulse to move the player in a direction, but the player doesn't stop. I...
top down friction in pymunk
Been struggling with this for a couple of days, hard to find code examples on the net. I'm making a topdown game and having trouble getting the player to move on key press. At the moment i'm using add_force or add_impulse to move the player in a direction, but the player doesn't stop. I've read about using surface fric...
[ "Joe crossposted the question to the Chipmunk/pymunk forum, and it got a couple of more answers there. http://www.slembcke.net/forums/viewtopic.php?f=1&t=1450&start=0&st=0&sk=t&sd=a\nIve pasted/edited in parts of my answer from the forum below:\n#As pymunk is python and not C, the constructor to PivotJoint is defin...
[ 1, 0 ]
[]
[]
[ "chipmunk", "pymunk", "python" ]
stackoverflow_0005215518_chipmunk_pymunk_python.txt
Q: How to write a python program to print out a column of records in database I need to write a python program to print out the data in a column of a table within database. The database I'm using is postgreSQL. The path of the table would be: server-datastation-data. Now in the table named "data", I have a column nam...
How to write a python program to print out a column of records in database
I need to write a python program to print out the data in a column of a table within database. The database I'm using is postgreSQL. The path of the table would be: server-datastation-data. Now in the table named "data", I have a column name say "column". What should I do to access the database and all the way to the c...
[ " import psycopg \n\n #fill in < > with relevant values\n pgconnection = psycopg.connect('dbname=datastation', 'user=<user>') \n\n curs=pgconnection.cursor() \n\n statement = 'SELECT column FROM data'\n\n curs.execute(statement)\n\n records = curs.fetchall()\n\n for record in records:\n print record\n\n" ]
[ 2 ]
[]
[]
[ "database", "python" ]
stackoverflow_0005242563_database_python.txt
Q: What was the motivation for doing lists augmented assignment (+=) in place in python? >>> list1 = [] >>> list2 = list1 >>> list2 += [1] >>> print list1 [1] Comparing this to >>> list1 = [] >>> list2 = list1 >>> list2 = list2 + [1] >>> print list1 [] Is there a reason why the '+='-operation modifies the original ...
What was the motivation for doing lists augmented assignment (+=) in place in python?
>>> list1 = [] >>> list2 = list1 >>> list2 += [1] >>> print list1 [1] Comparing this to >>> list1 = [] >>> list2 = list1 >>> list2 = list2 + [1] >>> print list1 [] Is there a reason why the '+='-operation modifies the original list? EDIT: just to make my question a bit clearer In most of the languages that I know the...
[ "Lists in Python as stored by reference.\nThis means that when you do list2 = list1, you are not making a copy of the list - you are merely saying \"list2 refers to the same thing list1 does,\" namely, the list you originally created when you did list1 = [].\nPython specifies += to mean \"append in place\" for list...
[ 10, 7, 5, 4, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005242933_python.txt
Q: Form generation/validation libraries in Python I'm a developer in Python coming from a PHP background. In PHP most frameworks included a decent form generation/validation API (Zend and CakePHP come to mind). At my new company we try to stay away from Django and use Werkzeug extensively. I've looked at FormEnco...
Form generation/validation libraries in Python
I'm a developer in Python coming from a PHP background. In PHP most frameworks included a decent form generation/validation API (Zend and CakePHP come to mind). At my new company we try to stay away from Django and use Werkzeug extensively. I've looked at FormEncode and Formular. Formular seems better to me, but t...
[ "There's also WTForms, which is a fairly minimal forms library that integrates well with Werkzeug in my experience.\n", "FormEncode is more a validation library and not very good at generating forms. \nPersonally, I don't like to intermix output generation (forms) and validation. As I see some shortcomings in For...
[ 3, 1 ]
[]
[]
[ "code_generation", "forms", "python", "validation" ]
stackoverflow_0003373174_code_generation_forms_python_validation.txt
Q: python module to password protect existing pdf files is there a python module to password protect existing pdf files? A: Try pyPDF, the PdfFileWriter has a encrypt method.
python module to password protect existing pdf files
is there a python module to password protect existing pdf files?
[ "Try pyPDF, the PdfFileWriter has a encrypt method.\n" ]
[ 4 ]
[]
[]
[ "password_protection", "pdf", "python" ]
stackoverflow_0005242956_password_protection_pdf_python.txt
Q: Python: reduce lightness of a RGB color Is there a simple way to change the lightness of a color given as RGB string? E.g. in_RGB = '#FF0000' --> out_RGB = '#CC0000' A: It's not that hard to convert a hex string to an RGB 3-tuple. Once you've done that, you can use the colorsys module (or if you prefer to imple...
Python: reduce lightness of a RGB color
Is there a simple way to change the lightness of a color given as RGB string? E.g. in_RGB = '#FF0000' --> out_RGB = '#CC0000'
[ "It's not that hard to convert a hex string to an RGB 3-tuple.\nOnce you've done that, you can use the colorsys module (or if you prefer to implement it yourself, the equations here) to convert from RGB to HSL, then do the manipulation you want, and then convert back from HSL to RGB.\nThen just convert back to hex,...
[ 3 ]
[]
[]
[ "colors", "hsl", "python", "rgb" ]
stackoverflow_0005243073_colors_hsl_python_rgb.txt
Q: Python: Writing/appending to a file inside a thread class error Im trying to periodcally write some measurements into a txt file. (some sorta logging). To periodically run a function, there is a RepeatTimer class. And to run the function of updating the file I have a VTlog() function as below. class RepeatTimer(Th...
Python: Writing/appending to a file inside a thread class error
Im trying to periodcally write some measurements into a txt file. (some sorta logging). To periodically run a function, there is a RepeatTimer class. And to run the function of updating the file I have a VTlog() function as below. class RepeatTimer(Thread): def __init__(self, interval, function, iterations=0, args=...
[ "I think you should check if open() was done correctly and a file handle was in fact returned or an error occured before making any calls to write() or close() for that file handle.\n------------CORRECTION-----------\nYou should check if open() was done correctly but not for the reson I mentioned above. open() will...
[ 0 ]
[]
[]
[ "file", "io", "multithreading", "python" ]
stackoverflow_0005243379_file_io_multithreading_python.txt
Q: Convert a database ID to a standard format of Alphabets I have a database called room and each room record has an incremental id and I am using this id as an identifier for people to join that room. But I dont want the user to have id's like 50,51 etc so I was thinking to convert them to a more standard format (m...
Convert a database ID to a standard format of Alphabets
I have a database called room and each room record has an incremental id and I am using this id as an identifier for people to join that room. But I dont want the user to have id's like 50,51 etc so I was thinking to convert them to a more standard format (maybe 8 characters) and convert them into real id's while work...
[ "You could use a Linear congruential generator to produce a pseudorandom sequence of id numbers (instead of the incremental sequence), and convert them to strings using base64.b32encode().\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005241522_google_app_engine_python.txt
Q: Python kludge to read UCS-2 (UTF-16?) as ASCII I'm in a little over my head on this one, so please pardon my terminology in advance. I'm running this using Python 2.7 on Windows XP. I found some Python code that reads a log file, does some stuff, then displays something. What, that's not enough detail? Ok, here's...
Python kludge to read UCS-2 (UTF-16?) as ASCII
I'm in a little over my head on this one, so please pardon my terminology in advance. I'm running this using Python 2.7 on Windows XP. I found some Python code that reads a log file, does some stuff, then displays something. What, that's not enough detail? Ok, here's a simplified version: #!/usr/bin/python import re ...
[ "codecs.open() will allow you to open a file using a specific encoding, and it will produce unicodes. You can try a few, going from most likely to least likely (or the tool could just always produce UTF-16LE but ha ha fat chance).\nAlso, \"Unicode In Python, Completely Demystified\".\n", "works.log appears to be ...
[ 6, 3, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0005241909_encoding_python.txt
Q: object properties in python class test: a="hi" def msg(self): print the variable for which the object is referring to t= test() print t.b From the above code is there any way to tell that the object is referring to a variable b which does not exist A: Use the __getattr__ method...
object properties in python
class test: a="hi" def msg(self): print the variable for which the object is referring to t= test() print t.b From the above code is there any way to tell that the object is referring to a variable b which does not exist
[ "Use the __getattr__ method, see documentation:\nIn [1]: class test(object):\n ...: a = 'hi'\n ...: def __getattr__(self, val):\n ...: print 'you are accessing ', val\n ...: \n ...: \n\nIn [2]: t = test()\n\nIn [3]: t.b\nyou are accessing b\n\nIn [4]: t.c\nyou are accessin...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005242003_python.txt
Q: update mysql data through django I have read the django tutorial, bit can't understand how to update a mysql record in django. My model and code is show below. I'm trying to update all values which are entered by user in form. class PatientInfo(models.Model): name = models.CharField(max_length=200) uhid = ...
update mysql data through django
I have read the django tutorial, bit can't understand how to update a mysql record in django. My model and code is show below. I'm trying to update all values which are entered by user in form. class PatientInfo(models.Model): name = models.CharField(max_length=200) uhid = models.CharField(max_length=200) a...
[ "see the docs at - http://docs.djangoproject.com/en/dev/topics/db/queries/#saving-changes-to-objects\nIf you wanted to change the name of a patient_edit\npatient_edit = PatientInfo.objects.get(id=patient_id) # object to update\npatient_edit.name = 'New name' # update name\npatient_edit.save() # save object\n\nor ba...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005243587_django_python.txt
Q: Problem with ropemacs when opening file in jython-mode I use ropemacs to write python source and here is the related portion of .emacs: (defun my-python-hook-mode () (interactive) (require 'pymacs) (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) ...
Problem with ropemacs when opening file in jython-mode
I use ropemacs to write python source and here is the related portion of .emacs: (defun my-python-hook-mode () (interactive) (require 'pymacs) (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-...
[ "It appears from your description, that, jython-mode has its own hooks that are run after running the hooks for python-mode. This is what M-x describe-function jython-mode shows as well. It is likely that this function is executed through these two hooks.\nEntering a comment the first line of the file to indicate...
[ 0 ]
[]
[]
[ "emacs", "jython", "python", "ropemacs" ]
stackoverflow_0005233784_emacs_jython_python_ropemacs.txt
Q: Why is 00100 = 64 in python? Why, like in the following python code, does 00100 equal 64? >>> i = 00100 >>> i 64 >>> type(00100) <type 'int'> >>> str(00100) '64' >>> str("00100") '00100' >>> int(str("00100")) 100 >>> A: its an octal value because of leading zeros http://www.translatorscafe.com/cafe/units-conver...
Why is 00100 = 64 in python?
Why, like in the following python code, does 00100 equal 64? >>> i = 00100 >>> i 64 >>> type(00100) <type 'int'> >>> str(00100) '64' >>> str("00100") '00100' >>> int(str("00100")) 100 >>>
[ "its an octal value because of leading zeros\nhttp://www.translatorscafe.com/cafe/units-converter/numbers/calculator/octal-to-decimal/\n^calculator (hard to summarize)\n", "In Python (and other languages too) when a number begin with 0 is interpreted as an octal number.\n", "It's octal. http://en.wikipedia.org/...
[ 9, 2, 1 ]
[]
[]
[ "int", "python" ]
stackoverflow_0005243968_int_python.txt
Q: The best way to get embedded documents in pymongo? I has in MongoDB documents like this: { "user": ObjectID("4d71076b26ab7b032800009f") "pages" : [ { "name" : "Main", "content" : [ { "id" : ObjectId("4d71076b26ab7b052800009f") }, { ...
The best way to get embedded documents in pymongo?
I has in MongoDB documents like this: { "user": ObjectID("4d71076b26ab7b032800009f") "pages" : [ { "name" : "Main", "content" : [ { "id" : ObjectId("4d71076b26ab7b052800009f") }, { "id" : ObjectId("4d61269b1deb5a3fce000004"), ...
[ "Yes you are right. In mongodb you can't load embedded document without parent. You can load parent document by some property of child document. \npages.find({\"pages.name\", \"Main\"}); //should load all document that contains pages collection and at least one item in embedded collection with name 'Main'.\n\nThan...
[ 2, 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0005204961_mongodb_pymongo_python.txt
Q: Django: how to read the db_column name of a model field I need to know the db_column name of various model fields. On a few models the name is explicitly set by "db_column='foo'", but most of the models/fields have the name automatically generated by Django. How can I retrieve the column_name for all fields from w...
Django: how to read the db_column name of a model field
I need to know the db_column name of various model fields. On a few models the name is explicitly set by "db_column='foo'", but most of the models/fields have the name automatically generated by Django. How can I retrieve the column_name for all fields from within a model's instance?
[ "There is an undocumented _meta API that's widely used throughout Django for introspecting models. It stores your model options on the type and provides about two dozen methods and attributes to inspect your model and it's fields. You can use it to get all the model fields and then from the fields you can get the c...
[ 31, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005243222_django_python.txt
Q: Text editors show python created UTF-8 files as gibberish this is my first question here and if its format is not what is expected here, sorry in advance. I have a small utility that reads ISO-8859-9 text files and produces its UTF-8 copies. The method I found is the usage of encode and decode methods, when I impl...
Text editors show python created UTF-8 files as gibberish
this is my first question here and if its format is not what is expected here, sorry in advance. I have a small utility that reads ISO-8859-9 text files and produces its UTF-8 copies. The method I found is the usage of encode and decode methods, when I implement the way of the elders, text editors show the unicode char...
[ "I've solved the problem. This is a mixed issue of OSX resource forks, TextEdit and a bit of PEBKAC. Here's how I solved it:\nI copied the files to my (fat32) flash disk, so I get the resource forks as \".filename\" . The thing I noticed that the file I wrote with python has come with no resource forks. Interesting...
[ 1, 0, 0 ]
[]
[]
[ "encoding", "file", "python", "save", "unicode" ]
stackoverflow_0005227146_encoding_file_python_save_unicode.txt
Q: Searching for an object This is how I have been searching for objects in python. Is there any more efficient (faster, simpler) way of doing it? Obs: A is a known object. for i in Very_Long_List_Of_Names: if A == My_Dictionary[i]: print: "The object you are looking for is ", i break A: The one...
Searching for an object
This is how I have been searching for objects in python. Is there any more efficient (faster, simpler) way of doing it? Obs: A is a known object. for i in Very_Long_List_Of_Names: if A == My_Dictionary[i]: print: "The object you are looking for is ", i break
[ "The one liner would be: (i for i in List_of_names if A == My_dictionary[i]).next(). \nThis throws a KeyError if there is an item in List_of_names that is not a key in My_dictionary and a StopIteration if the item is not found, else returns the key where it finds A.\n", "I assume you're looking for an object in t...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005244190_python.txt
Q: How to delete a row of CSV file using csv reader in Python? I want to process each row of a csv file and store into database. After that row is stored I want to delete that row in the csv file. I have written code for fetching and storing the row. But I got stuck on deleting a row on csv file. My code: import csv ...
How to delete a row of CSV file using csv reader in Python?
I want to process each row of a csv file and store into database. After that row is stored I want to delete that row in the csv file. I have written code for fetching and storing the row. But I got stuck on deleting a row on csv file. My code: import csv entries = csv.reader(open('/opt/workspace/jup/juppro/media/docs...
[ "\nRead the CSV into memory e.g. a list.\nSave the relevant rows to the database and remove them from the list.\nSave the remaining rows in the list back to the CSV file.\n\n", "I propose you this code\nimport csv\nfrom os.path import getsize\nfrom itertools import islice\n\nprint 'size of file :',getsize('/opt/w...
[ 1, 0 ]
[]
[]
[ "csv", "django", "python" ]
stackoverflow_0005243778_csv_django_python.txt
Q: Restricting access to Ajax services using django.contrib.auth In a web application already using django.contrib.auth for authentication, I'm looking for the "standard" approach for restricting access to Ajax services to authenticated users only. Using the @login_required decorator won't do, because that just red...
Restricting access to Ajax services using django.contrib.auth
In a web application already using django.contrib.auth for authentication, I'm looking for the "standard" approach for restricting access to Ajax services to authenticated users only. Using the @login_required decorator won't do, because that just redirects unauthenticated users to a login page. For a service, we sh...
[ "That's an example that will work great if the AJAX services are consumed by your front-end clients only. I do that all the time, because the same design gets used for pushing all other kinds of data to the client through the response for which the client needs to perform additional actions or otherwise provide som...
[ 3 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0005244097_django_django_authentication_python.txt
Q: how to write dict data in table format How to write below data in below table output format ? list of dict data=[{'date': datetime.date(2011, 2, 8), 'user': u'xxx', 'status': u'P'}, {'date': datetime.date(2011, 2, 8), 'user': u'yyy', 'status': u'P'}, {'date': datetime.date(2011, 2, 8), 'user': u'zzz', 'status': u...
how to write dict data in table format
How to write below data in below table output format ? list of dict data=[{'date': datetime.date(2011, 2, 8), 'user': u'xxx', 'status': u'P'}, {'date': datetime.date(2011, 2, 8), 'user': u'yyy', 'status': u'P'}, {'date': datetime.date(2011, 2, 8), 'user': u'zzz', 'status': u'P'}, {'date': datetime.date(2011, 2, 9), 'u...
[ "I'm a bit conflicted about writing answers like these - it seems like just producing a complete solution with very little didactic value, but I've tried to make it as generally helpful as possible...\nIf I understand what you're trying to do correctly, you want to turn your data into CSV where there is one row for...
[ 18 ]
[]
[]
[ "python" ]
stackoverflow_0005243623_python.txt
Q: Sensible small Python example using locks with threads I am searching for a sensible (i.e. it should really be useful in terms of efficiency) example using python threads & locks. I know many standard small examples but they are all missing at least one of the properties "small", "sensible" or "using locks" -- for...
Sensible small Python example using locks with threads
I am searching for a sensible (i.e. it should really be useful in terms of efficiency) example using python threads & locks. I know many standard small examples but they are all missing at least one of the properties "small", "sensible" or "using locks" -- for example: Testing a list of URLs to check availability (sen...
[ "Doug Hellmann's page is always a good address to get some examples:\nFor threading in general:\nhttp://www.doughellmann.com/PyMOTW/threading/index.html\nOr if you may prefer multiprocessing (e.g. the GIL hits you, or you like to distribute your load over multiple processors):\nhttp://www.doughellmann.com/PyMOTW/mu...
[ 3, 1 ]
[]
[]
[ "multithreading", "parallel_processing", "python", "python_multithreading" ]
stackoverflow_0005244211_multithreading_parallel_processing_python_python_multithreading.txt
Q: Multiple pluralisable variables in internationalized django template I am internationalizing (i18n) our django project, i.e. adding {% blocktrans %} to our templates. I know about using count and {% plural %} to have different strings for varaibles. However I have a string that has two variables that each need to ...
Multiple pluralisable variables in internationalized django template
I am internationalizing (i18n) our django project, i.e. adding {% blocktrans %} to our templates. I know about using count and {% plural %} to have different strings for varaibles. However I have a string that has two variables that each need to be pluralized, i.e. 4 possible options. For example, my string is "You hav...
[ "After doing some more research and reading, specifically about gettext, I don't think this is possible. gettext documentation only allows one variable to control the pluralization. There are probably problems with having 2 variable pluralization, since in arabic, you'd have to have 36 different strings to translat...
[ 4 ]
[]
[]
[ "django", "gettext", "internationalization", "python", "translation" ]
stackoverflow_0005196084_django_gettext_internationalization_python_translation.txt
Q: django - how to get model objects from another process instead of database I have a TCP server, a Python app, that gets the information from the connected devices. This information I am trying to show using Django web app. So, basically my model objects reside within the TCP server process. I can modify the TCP se...
django - how to get model objects from another process instead of database
I have a TCP server, a Python app, that gets the information from the connected devices. This information I am trying to show using Django web app. So, basically my model objects reside within the TCP server process. I can modify the TCP server to put the information into SQLite database and have my Django web app take...
[ "You may be able to serialise your model and pass the serialised data.\n", "i think better to use `memcached (http://memcached.org/) in mem cached server and each server see this server\nalso you can serialize your data and send it like udp and other method\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_models", "python", "web_applications" ]
stackoverflow_0005242230_django_django_models_python_web_applications.txt
Q: Appending a dictionary to a list - I see a pointer like behavior I tried the following in the python interpreter: >>> a = [] >>> b = {1:'one'} >>> a.append(b) >>> a [{1: 'one'}] >>> b[1] = 'ONE' >>> a [{1: 'ONE'}] Here, after appending the dictionary b to the list a, I'm changing the value corresponding to the ke...
Appending a dictionary to a list - I see a pointer like behavior
I tried the following in the python interpreter: >>> a = [] >>> b = {1:'one'} >>> a.append(b) >>> a [{1: 'one'}] >>> b[1] = 'ONE' >>> a [{1: 'ONE'}] Here, after appending the dictionary b to the list a, I'm changing the value corresponding to the key 1 in dictionary b. Somehow this change gets reflected in the list to...
[ "You are correct in that your list contains a reference to the original dictionary.\na.append(b.copy()) should do the trick.\nBear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.\n", "Also with dict\na = []\nb = {1:'one'}\n\na.append(dict(b))\nprint a\nb...
[ 165, 40, 3 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0005244810_dictionary_list_python.txt
Q: What should I use for a python program to do stuff with tables of data? I want to be able to add daily info to each object and want to have the ability to delete info x days old easily. With the tables I need to look at the trends and do stuff like selecting objects which match some criteria. Edit: I asked this be...
What should I use for a python program to do stuff with tables of data?
I want to be able to add daily info to each object and want to have the ability to delete info x days old easily. With the tables I need to look at the trends and do stuff like selecting objects which match some criteria. Edit: I asked this because I'm not able to think of a way to implement deleting old data easily be...
[ "Using sqlite would it be the best option, is file based, easy to use, you can use Lookups with SQL and it's builtin on python you don't need to install anything.\n→ http://docs.python.org/library/sqlite3.html\n", "If your question means that you are just going to be using \"table like data\" but not bound to a d...
[ 1, 0, 0, 0 ]
[]
[]
[ "database", "python" ]
stackoverflow_0005245522_database_python.txt
Q: How can I create a user-password login webpage using python bottle when I run the following code it ended in Import error:cannot import name route Can anyone help me?? from bottle import route, run @route('/:name') def index(name='World'): return '<b>Hello %s!</b>' % name run(host='localhost', port=8080) A:...
How can I create a user-password login webpage using python bottle
when I run the following code it ended in Import error:cannot import name route Can anyone help me?? from bottle import route, run @route('/:name') def index(name='World'): return '<b>Hello %s!</b>' % name run(host='localhost', port=8080)
[ "That example program is awful. It contains a cross-site scripting attack.\nMy guess is that you named the file you put your program in bottle.py. Either that or you haven't installed bottle.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005245361_python.txt
Q: How do I get the Google AdWords API Python Client Library to work? Is there an up-to-date tutorial available for using the Python adwords client, or failing that does anyone know enough to unpick the following? Have I made some configuration error, or perhaps is Python 2.6 unsupported? On Windows I've installed: ...
How do I get the Google AdWords API Python Client Library to work?
Is there an up-to-date tutorial available for using the Python adwords client, or failing that does anyone know enough to unpick the following? Have I made some configuration error, or perhaps is Python 2.6 unsupported? On Windows I've installed: Python 2.6 setuptools-0.6c11.win32-py2.6.exe PyXML-0.8.4 SOAPpy-0.12.4 Z...
[ "Have you tried with ZSI-2.0? This issue report looks similar to http://code.google.com/p/google-api-adwords-python-lib/issues/detail?id=141. Please append your info to the bug report, if you continue to see this issue.\nAs for tutorial code being out of date, good catch! I'll have it fixed shortly. Please track at...
[ 2 ]
[]
[]
[ "google_ads_api", "python" ]
stackoverflow_0005236024_google_ads_api_python.txt
Q: Find out if the form was submited or the page was refreshed I am using a form to search for some date. The form uses GET method for date retrieval. <form action="" method="GET"> ... <div id="search_button"><input type="submit" value={% trans 'Search' %} name="search"></div> </form> How could I know whether th...
Find out if the form was submited or the page was refreshed
I am using a form to search for some date. The form uses GET method for date retrieval. <form action="" method="GET"> ... <div id="search_button"><input type="submit" value={% trans 'Search' %} name="search"></div> </form> How could I know whether the submit button was pressed or the page was refresed?
[ "If someone submits the form then there'll be parameters in the query string named after your form fields. Of course, if someone then refreshes that page, I'm not sure that you'd be able to tell the difference between that and a form-submit.\nIf it's important that you can tell the difference, you should probably a...
[ 0, 0 ]
[]
[]
[ "django", "forms", "python", "refresh", "submit" ]
stackoverflow_0005243451_django_forms_python_refresh_submit.txt
Q: Can't configure node.js on windows 7 I have problem with configuring NODE.JS. I was trying to install node.js with this tutorial, but when i typed: ./configure I got error: I will be very thankful for any help! A: The unable to remap error you've encounted is often an indication that you need to run the reba...
Can't configure node.js on windows 7
I have problem with configuring NODE.JS. I was trying to install node.js with this tutorial, but when i typed: ./configure I got error: I will be very thankful for any help!
[ "The unable to remap error you've encounted is often an indication that you need to run the rebaseall program. Rerun the setup file you used to install the your cygwin environment, then run rebaseall -v and that should fix it. You'll need to make sure that no cygwin programs are running when you run rebaseall.\n", ...
[ 6, 0, 0 ]
[]
[]
[ "cygwin", "node.js", "python", "windows" ]
stackoverflow_0005233404_cygwin_node.js_python_windows.txt
Q: Removing duplicate element from a list and the element itself I know this question has been asked lots of times, but I am not asking how to remove duplicate elements from a list only, I want to remove the duplicated element as well. For example, if I have a list: x = [1, 2, 5, 3, 4, 1, 5] I want the list to be: x...
Removing duplicate element from a list and the element itself
I know this question has been asked lots of times, but I am not asking how to remove duplicate elements from a list only, I want to remove the duplicated element as well. For example, if I have a list: x = [1, 2, 5, 3, 4, 1, 5] I want the list to be: x = [2, 3, 4] # removed 1 and 5 since they were repeated I can't us...
[ "This should be done with a Counter object. It's trivial.\nfrom collections import Counter\nx = [k for k, v in Counter([1, 2, 5, 3, 4, 1, 5]).iteritems() if v == 1]\nprint x\n\nOutput:\n[2, 3, 4]\n\n", "Maybe this way:\n[_ for _ in x if x.count(_) == 1]\n\nEDIT: This is not the best way in term of time complexity...
[ 10, 3, 0, 0 ]
[]
[]
[ "list", "python", "unique" ]
stackoverflow_0005245872_list_python_unique.txt
Q: Python float to string: how to get '0.03' but '-.03' Is there a quick way to convert a floating point number between -0.99 and +0.99 such that it always takes up 4 characters: ie positive values go to e.g. '0.03' but negative values to e.g. '-.03', without the leading zero? Obviously I could do s = '%4.2f' % n if ...
Python float to string: how to get '0.03' but '-.03'
Is there a quick way to convert a floating point number between -0.99 and +0.99 such that it always takes up 4 characters: ie positive values go to e.g. '0.03' but negative values to e.g. '-.03', without the leading zero? Obviously I could do s = '%4.2f' % n if s[0] == '-': s = '-%s' % s[2:] but perhaps some stack...
[ "Well, you could do this:\n\"{0: 3.2f}\".format(n)\n\nThe space indicates that for positive numbers, a space should be printed, and for negative numbers the sign. This way, they always take the same width.\n", "s = ('%4.2f' % n).replace('-0','-')\n\n" ]
[ 5, 2 ]
[]
[]
[ "floating_point", "python", "string" ]
stackoverflow_0005244041_floating_point_python_string.txt
Q: How can I keep figure size constant with matplotlib although using pyplot.show()? Look at the following python example: import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['figure.figsize'] = [8.27, 11.69] fig = plt.figure() plt.show() # This line causes problems with figsize fig.savefig('test.pd...
How can I keep figure size constant with matplotlib although using pyplot.show()?
Look at the following python example: import matplotlib as mpl import matplotlib.pyplot as plt mpl.rcParams['figure.figsize'] = [8.27, 11.69] fig = plt.figure() plt.show() # This line causes problems with figsize fig.savefig('test.pdf') If I use "plt.show()" the figure size of test.pdf changes a lot (from 210 x 297 [...
[ "There's a good demo on adjusting image size in matplotlib figures on the SciPy site.\nThe effect of show() on the figure size will depend upon which matplotlib backend is used. For example, when I used the TkAgg backend (the default on my system) it added about 12 pixels to the width and height of the figure. But ...
[ 6 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005242628_matplotlib_python.txt
Q: psycopg2, SELECT, and schemas I'm trying to do a simple select statement on a table that's part of the "dam_vector" schema. The error I get is: psycopg2.ProgrammingError: relation "dam_vector.parcels_full" does not exist LINE 1: SELECT * FROM "dam_vector.parcels_full" I can't figure this out and know I'm m...
psycopg2, SELECT, and schemas
I'm trying to do a simple select statement on a table that's part of the "dam_vector" schema. The error I get is: psycopg2.ProgrammingError: relation "dam_vector.parcels_full" does not exist LINE 1: SELECT * FROM "dam_vector.parcels_full" I can't figure this out and know I'm missing something obvious. Any help ...
[ "Double quotes makes whatever is in them an identifier, so query\nSELECT * FROM \"dam_vector.parcels_full\";\n\nhits table dam_vector.parcels_full (period interpreted as part of table name) from schama public (or anything in search path).\nAs Adam said, you don't need quotes with names without some special characte...
[ 5, 1 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0004835477_psycopg2_python.txt
Q: How to override English labels inserted by Sphinx I use the Sphinx Python documentation generator. Creating PDF documents is very easy and simple, but I have one problem. All generated PDF documents have English words like "chapter", "release", and "part". How can I override these English labels in another langu...
How to override English labels inserted by Sphinx
I use the Sphinx Python documentation generator. Creating PDF documents is very easy and simple, but I have one problem. All generated PDF documents have English words like "chapter", "release", and "part". How can I override these English labels in another language, or remove them completely?
[ "In your conf.py, there is the following paragraph (around line 57 in a conf.py created by sphinx-quickstart):\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = None\n\nIn my case, I changed it to:\nlanguage = nl # bug!\n\nWhich of co...
[ 11, 8 ]
[]
[]
[ "internationalization", "pdf", "pdf_generation", "python", "python_sphinx" ]
stackoverflow_0002251450_internationalization_pdf_pdf_generation_python_python_sphinx.txt
Q: How to create a new property in google app engine I'm new to google apps engine. I want to have a something like: class demo(db.model) user = db.UserProperty() date = db.DateProperty(auto_now=False, auto_now_add=False) weekly = SomeNewProperty() ... How do I create this "SomeNew" property? I read some docs a...
How to create a new property in google app engine
I'm new to google apps engine. I want to have a something like: class demo(db.model) user = db.UserProperty() date = db.DateProperty(auto_now=False, auto_now_add=False) weekly = SomeNewProperty() ... How do I create this "SomeNew" property? I read some docs about it but didnt understand what to do. Thanks
[ "The different property types specify the type of the property. You can't easily define your own types (and I don't think that this is what you're after).\nTake a look at this page to see a list of different property classes.\nFor example to add a new boolean property weekly you'd write:\nweekly = db.BooleanPropert...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "properties", "python" ]
stackoverflow_0005243532_google_app_engine_properties_python.txt
Q: Querying a table from sqlalchemy I'm pretty new to sqlalchemy and oracle. I'm trying to perform a query on a pre existing table(schema or whatever they call it) in an oracle database. However, I get the following error: Couldn't find any column information for table prefix.tablename from sqlalchemy import create_e...
Querying a table from sqlalchemy
I'm pretty new to sqlalchemy and oracle. I'm trying to perform a query on a pre existing table(schema or whatever they call it) in an oracle database. However, I get the following error: Couldn't find any column information for table prefix.tablename from sqlalchemy import create_engine, MetaData, Table from sqlalchemy...
[ "use schema=prefix as an argument to Table\ne.g.\n\nnetc = Table(tablename, metadata, autoload=True, schema=prefix)\n\n" ]
[ 1 ]
[]
[]
[ "oracle", "python", "sqlalchemy" ]
stackoverflow_0005237742_oracle_python_sqlalchemy.txt
Q: How to query filtering by a ByteString field in Google App Engine? I have class Map(db.Model): urlHash= db.ByteStringProperty() hasher = hashlib.sha256() hasher.update(staticMapUrl) urlHash = hasher.digest() query = db.Query(models.Map) query = query.filter('urlHash =', urlHash) results = query.fetch(1) and...
How to query filtering by a ByteString field in Google App Engine?
I have class Map(db.Model): urlHash= db.ByteStringProperty() hasher = hashlib.sha256() hasher.update(staticMapUrl) urlHash = hasher.digest() query = db.Query(models.Map) query = query.filter('urlHash =', urlHash) results = query.fetch(1) and this type of query tries to decode the urlHash to a string, throwing an...
[ "Looks like it will work if you explicitly make the hash into a ByteString:\nfrom google.appengine.api.datastore_types import ByteString\n\nhasher = hashlib.sha256()\nhasher.update('http://www.google.com/')\nurlHash = hasher.digest()\nbs = ByteString(urlHash)\n\nm = Map(urlHash=bs).put()\n\nquery = db.Query(Map)\nq...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005237465_google_app_engine_python.txt
Q: Android HttpPost not working with python CGI server I'm buliding an android app and need to submit data to my python CGI server. I'm usually pulling data off the server with HttpGet and all those calls work correctly and quickly. When I try to push data with HttpPost, the program hangs indefinitely until I long pr...
Android HttpPost not working with python CGI server
I'm buliding an android app and need to submit data to my python CGI server. I'm usually pulling data off the server with HttpGet and all those calls work correctly and quickly. When I try to push data with HttpPost, the program hangs indefinitely until I long press the return button on the emulator and force quit the ...
[ "The error sounds like the given IP is not reachable or port 8000 is blocked by the ISP or firewalled.\n", "I changed \nHttpClient httpclient = new DefaultHttpClient();\nHttpParams params = httpclient.getParams();\nHttpConnectionParams.setConnectionTimeout(params, 5000);\nHttpConnectionParams.setSoTimeout(params,...
[ 0, 0 ]
[]
[]
[ "android", "cgi", "http_post", "python" ]
stackoverflow_0005231575_android_cgi_http_post_python.txt
Q: How to custom handle iteration in python dictionary? Supposing that we have a dictinary: links={"foo":"url1","bar":"url2","baz":"url3",} I would like by running one for loop if it is possible like: for link in links: ... print(next_dictinary_value) to print the next value of dictionaly, for the last one ...
How to custom handle iteration in python dictionary?
Supposing that we have a dictinary: links={"foo":"url1","bar":"url2","baz":"url3",} I would like by running one for loop if it is possible like: for link in links: ... print(next_dictinary_value) to print the next value of dictionaly, for the last one I want to print the first. The purpose is every dictinary ...
[ "I think you're asking for something like the following:\nkeys = links.keys()\nn = len(keys)\nfor i in range(n):\n thisKey = keys[i]\n nextKey = keys[(i + 1) % n]\n nextValue = links[nextKey]\n print thisKey, nextValue\n\nBut be aware that a dictionary is not sorted, so you could get back the keys in an...
[ 3, 2 ]
[ "You could get all the keys with keys = links.keys(). Then use them to iterate over the dictionary using the keys. Example:\n>>> links={\"foo\":\"url1\",\"bar\":\"url2\",\"baz\":\"url3\",}\n>>> k = links.keys()\n>>> for i in range(0, len(k)):\n... print(links[ k[i] ])\n... \nurl3\nurl1\nurl2\n\nVariable i conta...
[ -1 ]
[ "dictionary", "python" ]
stackoverflow_0005243967_dictionary_python.txt
Q: wxPython handling events (button and radio button) between different methods I'm learning wxpython for one of my project, and I have a problem.. How do I store the value of the RadioButton once I click my button? I have a class SerialFrame(wx.Frame): inside that I have def __init__(self, parent, title): su...
wxPython handling events (button and radio button) between different methods
I'm learning wxpython for one of my project, and I have a problem.. How do I store the value of the RadioButton once I click my button? I have a class SerialFrame(wx.Frame): inside that I have def __init__(self, parent, title): super(SerialFrame, self).__init__(parent, title=title, ...
[ "i'm assuming you have UI. radio button are used to select Baud rate. \n baudRadioButton1 = wx.RadioButton(mypanel, -1, '9600', style=wx.RB_GROUP)\n\nhere 9600 is only printed on GUI. you can put your name instead of 9600.\nYou have to understand that nothing is happening automatically. we have to tell wxpython how...
[ 3 ]
[]
[]
[ "oop", "python", "user_interface", "wxpython" ]
stackoverflow_0005246998_oop_python_user_interface_wxpython.txt
Q: Calling a C function with a timeout - ctypes I use ctypes in a python project where I need to call some C functions which can take some hours for giving response. My problem is that I want to kill the function (from the python code) after a certain time even if the function has not finish the calculation. I tried...
Calling a C function with a timeout - ctypes
I use ctypes in a python project where I need to call some C functions which can take some hours for giving response. My problem is that I want to kill the function (from the python code) after a certain time even if the function has not finish the calculation. I tried with multithread but it doesn't stop the C functi...
[ "That can't work because the Python code can't see into the C code to stop it running. That approach could only work with pure Python code.\nEven if it would work, it would be the wrong way to stop a threads. You should think of threading as a co-operative endeavour. If you want a thread to stop, then you need to a...
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005247353_ctypes_python.txt
Q: printing out individuals for each concept in an ontology using rdflib I have and ontology written in OWL/RDF(using Protege). This ontology has been already populated with some individuals for each concept. I have ported it in to python using rdflib and FuXi packages. And I can successfully parse my Ontology and pu...
printing out individuals for each concept in an ontology using rdflib
I have and ontology written in OWL/RDF(using Protege). This ontology has been already populated with some individuals for each concept. I have ported it in to python using rdflib and FuXi packages. And I can successfully parse my Ontology and put in a graph. Now the only thing that I need to to do is that to print out ...
[ "When you say all the individuals for each concept I guess that you mean all the resources of rdf:type an specific class. With rdflib you can easily do that by traversing the graph:\nfrom rdflib import Graph\nfrom rdflib import URIRef\ng = Graph()\ng.parse(\"ontology.owl\")\naClass = URIRef(\"http://www.someuri.org...
[ 4 ]
[]
[]
[ "ontology", "python", "rdf", "rdflib", "semantic_web" ]
stackoverflow_0005247059_ontology_python_rdf_rdflib_semantic_web.txt
Q: code using nltk and python I want a code for tagging idioms in a given sentence or text using NLTK and Python. A: Depends what you mean by an "idiom". Joe's suggestion of POS tagging is probably a good start - and might be what you are really after. If so, go read "Natural Language Processing with Python" by ...
code using nltk and python
I want a code for tagging idioms in a given sentence or text using NLTK and Python.
[ "Depends what you mean by an \"idiom\". Joe's suggestion of POS tagging is probably a good start - and might be what you are really after. If so, go read \"Natural Language Processing with Python\" by Bird et al. It is published by O'Reilly but is also available online under a Creative Commons license. This will ge...
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005217260_nltk_python.txt
Q: Python datetime.strptime month specifier doesn't seem to work The month format specifier doesn't seem to work. from datetime import datetime endDate = datetime.strptime('10 3 2011', '%j %m %Y') print endDate 2011-01-10 00:00:00 endDate = datetime.strptime('21 5 1987', '%j %m %Y') print endDate 1987-01-21 00:00:0...
Python datetime.strptime month specifier doesn't seem to work
The month format specifier doesn't seem to work. from datetime import datetime endDate = datetime.strptime('10 3 2011', '%j %m %Y') print endDate 2011-01-10 00:00:00 endDate = datetime.strptime('21 5 1987', '%j %m %Y') print endDate 1987-01-21 00:00:00 Now, according to the manual the manual: %m = Month as a decim...
[ "You can't mix the %j with others format code like %m because if you look in the table that you linked %j is the Day of the year as a decimal number [001,366] so 10 correspondent to the 10 day of the year so it's 01 of January ... \nSo you have just to write :\n>>> datetime.strptime('10 2011', '%j %Y')\ndatetime.da...
[ 6, 3, 2 ]
[]
[]
[ "datetime", "python", "python_3.x" ]
stackoverflow_0005247582_datetime_python_python_3.x.txt
Q: Manipulate PDF files (read, split, combine, move) I'm trying to figure out a way to deal with scanned pdf's with either Python or PHP. I need to be able to open a multiple page PDF, read the contents, and move the pages to individual PDF files (or one file if they are to be grouped) based on an identifier in the t...
Manipulate PDF files (read, split, combine, move)
I'm trying to figure out a way to deal with scanned pdf's with either Python or PHP. I need to be able to open a multiple page PDF, read the contents, and move the pages to individual PDF files (or one file if they are to be grouped) based on an identifier in the text. I downloaded and have played around a little bit ...
[ "I've used pypdf with success on small projects.\n", "Have you tried PyPdf? See: http://pybrary.net/pyPdf/\nAnd here is a recipe using PyPdf to extract the text: http://code.activestate.com/recipes/511465-pure-python-pdf-to-text-converter/\n" ]
[ 2, 2 ]
[]
[]
[ "pdf", "php", "python" ]
stackoverflow_0005247924_pdf_php_python.txt
Q: python global names I'm having trouble with python. I keep getting the same error: Traceback (most recent call last): File "F:\test4", line 21, in <module> graph = dict([(label, node(label))] for label in node_labels) File "F:\test4", line 21, in <genexpr> graph = dict([(label, node(label))] fo...
python global names
I'm having trouble with python. I keep getting the same error: Traceback (most recent call last): File "F:\test4", line 21, in <module> graph = dict([(label, node(label))] for label in node_labels) File "F:\test4", line 21, in <genexpr> graph = dict([(label, node(label))] for label in node_labels) ...
[ "In the last line you are calling node(label). Have you defined the function node?\n", "Why should it?\nnode is nowhere defined in the code you showed... maybe you forgot an import?\n" ]
[ 2, 2 ]
[]
[]
[ "global_variables", "python" ]
stackoverflow_0005248080_global_variables_python.txt
Q: Plone: Using the default skin for administration I'm developing a skin for Plone 3.x. The skin have a lot of differences from the default theme, and i would like to keep the default skin in administration mode. I read some solutions like this http://maurits.vanrees.org/weblog/archive/2008/01/switch-your-skin-based...
Plone: Using the default skin for administration
I'm developing a skin for Plone 3.x. The skin have a lot of differences from the default theme, and i would like to keep the default skin in administration mode. I read some solutions like this http://maurits.vanrees.org/weblog/archive/2008/01/switch-your-skin-based-on-the-url . But I cannot use subdomains in my web, s...
[ "This doesn't answer your question directly, but you might want to take a look at \"Editskin switcher\". \n", "Finally, I used this solution. The condition to detect if you are authenticated is tal:condition=\"not: here/portal_membership/isAnonymousUser\". So, you can use a stylesheet only for visitors and other ...
[ 1, 1, 1 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0003114602_plone_python.txt
Q: How to trigger datastore update if condition is met? (Google App Engine - Python) In my application I have a column display with values y or n. Default value is n and the item is not displayed. When payment is received the value is changed to y and the item is displayed. If the item is not renewed in a month I wou...
How to trigger datastore update if condition is met? (Google App Engine - Python)
In my application I have a column display with values y or n. Default value is n and the item is not displayed. When payment is received the value is changed to y and the item is displayed. If the item is not renewed in a month I would like to change it to n. How do I do this?
[ "Schedule a cron job to periodically check and update your data. See http://code.google.com/appengine/docs/python/config/cron.html\n", "The tricky part if calculating the dates; I assume that you know how to change the value itself.\nYou'll need to store the date of renewal, and check them periodically using Sche...
[ 4, 2 ]
[]
[]
[ "datastore", "google_app_engine", "python" ]
stackoverflow_0005248222_datastore_google_app_engine_python.txt
Q: Splitting string on white characters? I'm using python and I'm simply trying to split a string on white characters (white spaces, tab, new line, etc.) and put it on an array. If I use: result_array = result.split("\s+") it doesn't works. What I'm doing wrong? A: If you want to split on whitespace itself just us...
Splitting string on white characters?
I'm using python and I'm simply trying to split a string on white characters (white spaces, tab, new line, etc.) and put it on an array. If I use: result_array = result.split("\s+") it doesn't works. What I'm doing wrong?
[ "If you want to split on whitespace itself just use split() with no arguments. The split() for strings doesn't take a regular expression, though there is an re.split() function that will allow you to split based on a regular expression if you need.\n", "Just use\nresult_array = result.split()\n\nstr.split() spli...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005248345_python.txt
Q: Deleting equal elements from a list Can I check out if one single list has two or more equal elements and then delete them, even if I don't know what specific elements I'm looking for ? Or check the different elements when comparing two lists, like A-B, in set theory. Getting elements in A that doesn't exist in B....
Deleting equal elements from a list
Can I check out if one single list has two or more equal elements and then delete them, even if I don't know what specific elements I'm looking for ? Or check the different elements when comparing two lists, like A-B, in set theory. Getting elements in A that doesn't exist in B.
[ "If you don't care about the order of the items, just use the Python set data type instead of lists:\ns = set([1, 2, 3, 3])\nt = set([2, 4, 6])\nprint s\nprint t\nprint s - t\n\nprints\nset([1, 2, 3])\nset([2, 4, 6])\nset([1, 3])\n\n", "For the Or check ... part of your questions:\nIn []: A, B= {1, 2, 3, 4}, {2, ...
[ 2, 1, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0005248436_arrays_list_python.txt
Q: how to run Django application in apache2 Hi All i am not able to run a django application in apache2 webserver. I have went through all the document but it still did not work for me.This is my Apache2's httpd.conf file <Location "/mysite/"> SetHandler python-program PythonHandler django.core.handlers.modpython...
how to run Django application in apache2
Hi All i am not able to run a django application in apache2 webserver. I have went through all the document but it still did not work for me.This is my Apache2's httpd.conf file <Location "/mysite/"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settin...
[ "\nDownload and install http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz\nAdd to the /etc/httpd/conf.d/ directory\n\n\n<VirtualHost *:80>\n ServerName --insert--\n\n ErrorLog /home/djangotest/mysite/error_log\n CustomLog /home/djangotest/mysite/access_log combined\n\n UseCanonicalName Off\n\n WSGIScrip...
[ 2, 1, 0 ]
[]
[]
[ "apache2", "django", "python" ]
stackoverflow_0005246181_apache2_django_python.txt
Q: In app engine, is there any way to programmatically get a list of pending tasks in a given queue? Couldn't find a method that does that in the GAE python docs... A: No. Because of the way taskqueues work in App Engine, there is no way to do this using the built-in taskqueue library. Unfortunately, that's just t...
In app engine, is there any way to programmatically get a list of pending tasks in a given queue?
Couldn't find a method that does that in the GAE python docs...
[ "No.\nBecause of the way taskqueues work in App Engine, there is no way to do this using the built-in taskqueue library. Unfortunately, that's just the way it is.\nSee the Task Queue Python API Overview for details on the built-in taskqueues.\nYou can manage your queues in the Administration Console:\n\n\nManage t...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "queue" ]
stackoverflow_0005248626_google_app_engine_python_queue.txt
Q: String to Datetime I found this question which answered most of my question, however I have a .[dot] at the end of my string: 2011-03-09T09:58:28.649615 What %[a-z] do I need to use and were can I find more information on this. I know it's related to c. thanks! A: the part after the dot are probably microsecond...
String to Datetime
I found this question which answered most of my question, however I have a .[dot] at the end of my string: 2011-03-09T09:58:28.649615 What %[a-z] do I need to use and were can I find more information on this. I know it's related to c. thanks!
[ "the part after the dot are probably microseconds...\n datetime.datetime.strptime(\"2011-03-09T09:58:28.649615\",\"%Y-%m-%dT%H:%M:%S.%f\") \nreference: Python documentation\n" ]
[ 3 ]
[]
[]
[ "datetime", "formatting", "json", "python" ]
stackoverflow_0005248756_datetime_formatting_json_python.txt
Q: creating a list from a text file in python I have a text file that looks something like this where the first column is a student's name, the second column is the number of credits, and the third is the number of points (grade times hours). john 5 15 bill 9 30 ted 7 22 I want to create a class ...
creating a list from a text file in python
I have a text file that looks something like this where the first column is a student's name, the second column is the number of credits, and the third is the number of points (grade times hours). john 5 15 bill 9 30 ted 7 22 I want to create a class that extracts the relevant information and calcu...
[ "This is not an error. It is regular output. You should override the __str__ and __repr__ methods of the Student class, to tell python how to print Student objects.\nSome help on your code, this is much better:\ndef readStudents(filename):\n with open(filename) as student_file:\n return [Student(*line.spl...
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005246605_list_python.txt
Q: What should I use - Mako or Django? I'm making a website that mail users when a movie or a pc game has released. It isn't too complex - users can sign up, choose movies/music or a genre and save the settings. When the movie/music is released - it mails the user. Some other functionality too but this is the jist. N...
What should I use - Mako or Django?
I'm making a website that mail users when a movie or a pc game has released. It isn't too complex - users can sign up, choose movies/music or a genre and save the settings. When the movie/music is released - it mails the user. Some other functionality too but this is the jist. Now, I've been working with Python for a b...
[ "Ask yourself this question: What are you getting out of this project? What do you want to learn?\nIf you want to know the nuts and bolts of a web server the hard way: concoct your own web framework using Mako and other useful building blocks as needed. As @pulegium says, you'll have to choose how to handle the HTT...
[ 4, 2, 0 ]
[]
[]
[ "django", "mako", "python", "template_engine" ]
stackoverflow_0002562167_django_mako_python_template_engine.txt
Q: Binding a null value to a date field in pyodbc Using pyodbc, if I try and execute this code on a date field: cursor.execute('insert into test VALUES (?)', None) ... I get pyodbc.Error: ('HY000', '[HY000] [SAS][SAS ODBC Driver][SAS Server]ERROR: Value 1 of VALUES clause 1 does not match the data type of the corres...
Binding a null value to a date field in pyodbc
Using pyodbc, if I try and execute this code on a date field: cursor.execute('insert into test VALUES (?)', None) ... I get pyodbc.Error: ('HY000', '[HY000] [SAS][SAS ODBC Driver][SAS Server]ERROR: Value 1 of VALUES clause 1 does not match the data type of the corresponding column in (-1) (SQLExecDirectW)'), while if ...
[ "In my source (Python 2.71 / pyodbc 2.1.8), with a MS Access base, the following code is OK \nst_dt=None\nsql = 'insert into COM(poste,mydate) values (?,?)'\ncursor.execute(sql,'1254',st_dt)\ncnxn.commit()\n\nWhere mydate is a Timestamp column with no default value.\n" ]
[ 2 ]
[]
[]
[ "pyodbc", "python" ]
stackoverflow_0002900524_pyodbc_python.txt
Q: Serializing SQLAlchemy models for a REST API while respecting access control? Currently, the way our, as well as most web frameworks', serialization works is there's some type of method invocation which dumps the model into some type of format. In our case, we have a to_dict() method on every model that constructs...
Serializing SQLAlchemy models for a REST API while respecting access control?
Currently, the way our, as well as most web frameworks', serialization works is there's some type of method invocation which dumps the model into some type of format. In our case, we have a to_dict() method on every model that constructs and returns a key-value dictionary with the key being the field name and the value...
[ "establish the \"serialization\" contract via a mixin:\nclass Serializer(object):\n __public__ = None\n \"Must be implemented by implementors\"\n\n __internal__ = None\n \"Must be implemented by implementors\"\n\n def to_serializable_dict(self):\n # do stuff with __public__, __internal__\n ...
[ 7 ]
[]
[]
[ "aop", "python", "serialization" ]
stackoverflow_0005232461_aop_python_serialization.txt
Q: Checking if for-loop variable resides at two indexes of a list This may be difficult to explain. I want to specify two indexes, and then run a for loop. If the current x being checked in the loop is the exact same item specified at the location of the two indexes, then it should return a message. array = [ [1,1,1,...
Checking if for-loop variable resides at two indexes of a list
This may be difficult to explain. I want to specify two indexes, and then run a for loop. If the current x being checked in the loop is the exact same item specified at the location of the two indexes, then it should return a message. array = [ [1,1,1,1], [2,2,2,2], [3,3,3,3], [4,4,4,4] ] Again, here's my array. I wan...
[ "I think what you're asking is how to test object identity rather than object equality.\nIn Python you can do this with the is operator, i.e.\nif x is y:\n\nRather than:\nif x == y:\n\nHowever, you're going have problems with ints and strings because the Python runtime automatically re-uses objects it creates for t...
[ 1, 0, 0, 0 ]
[]
[]
[ "for_loop", "indexing", "loops", "match", "python" ]
stackoverflow_0005248057_for_loop_indexing_loops_match_python.txt
Q: How to deal with file in python without nested exceptions I'm writing a python script to perform some basic CM functions like tagging in subversion. The only error checking I know how to do in python is by catching exceptions. As write code to tests for existence of various files and directories, I get all these n...
How to deal with file in python without nested exceptions
I'm writing a python script to perform some basic CM functions like tagging in subversion. The only error checking I know how to do in python is by catching exceptions. As write code to tests for existence of various files and directories, I get all these nested try/except blocks. try: os.stat("dist") print "mv " ...
[ "The other approach is to check to see if the file exists before attempting to perform operations on it, which may help eliminate some of your try/except blocks. You can use os.path.exists() for that. There are other functions in os.path which you may find useful as well. \nThat being said, Python is designed to wo...
[ 2, 0 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0005249400_exception_handling_python.txt
Q: My MySQL transaction didn't complete, and it's stuck in the middle Now I'm getting errors like: OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction') A: Try killing the process that may be responsible for locking the table.
My MySQL transaction didn't complete, and it's stuck in the middle
Now I'm getting errors like: OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction')
[ "Try killing the process that may be responsible for locking the table.\n" ]
[ 0 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0005250003_database_django_mysql_python.txt
Q: Decode image file to extract image header information and modify it (with python) I'm reading an image file of dpx format, and want to extract the "Orientation" in the image section of the header, and also modify it. I have never tried to interpret binary data, so I'm a bit at a loss. I'm trying to use the struct ...
Decode image file to extract image header information and modify it (with python)
I'm reading an image file of dpx format, and want to extract the "Orientation" in the image section of the header, and also modify it. I have never tried to interpret binary data, so I'm a bit at a loss. I'm trying to use the struct module, but I really don't know how to do it properly. The file header specification is...
[ "There seems to be a constant offset to the Orientation so if this is all you want to change then I wouldn't bother trying to parse it all, just work out the offset (which I think is just the size of the GENERICFILEHEADER plus one byte for the high byte of the orientation word) and read / manipulate it directly.\nU...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005249748_python.txt
Q: Does mimetools.py module working on Google App Engine I got this error message .. what is the problem ? Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__ handler.post(*groups) File "/base/data/home/apps/refac...
Does mimetools.py module working on Google App Engine
I got this error message .. what is the problem ? Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__ handler.post(*groups) File "/base/data/home/apps/refacingme/1.348883430619943894/main.py", line 187, in post ...
[ "The socket library is not supported under AppEngine. See the docs.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005249970_google_app_engine_python.txt
Q: Django query filter, return object if attr delete is false (i.e if it hasn't been deleted) I have the following: PHONE_CHOICES = ( ('home', 'Home'), ('home2', 'Home 2'), ('mobi', 'Mobile'), ('mobi2', 'Mobile 2'), ('work', 'Work'), ('work2', 'Work 2'), ) phones = [] for k, v in PHONE_CHOICE...
Django query filter, return object if attr delete is false (i.e if it hasn't been deleted)
I have the following: PHONE_CHOICES = ( ('home', 'Home'), ('home2', 'Home 2'), ('mobi', 'Mobile'), ('mobi2', 'Mobile 2'), ('work', 'Work'), ('work2', 'Work 2'), ) phones = [] for k, v in PHONE_CHOICES: try: phones.append(ClientPhone.objects.filter(client=clientKEY, phone_type=k).lat...
[ "It is somewhat difficult to tell what you are asking, but I think you want something like this:\nphones = []\nfor k, v in PHONE_CHOICES:\n try:\n current = ClientPhone.objects.filter(client=clientKEY, phone_type=k)\n if current.deleted is None:\n phones.append(current.latest('id'))\n ...
[ 2 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0005250223_django_django_queryset_python.txt
Q: Ubuntu development: Sass, Coffeescript, Nose in my current Django project I have Sass, Coffeescript and Nose. Now all of these have watch options but I would like to automate this so I don't have to turn them all one by one each time I start working. What's a recommend approach for doing this? It's a Django projec...
Ubuntu development: Sass, Coffeescript, Nose
in my current Django project I have Sass, Coffeescript and Nose. Now all of these have watch options but I would like to automate this so I don't have to turn them all one by one each time I start working. What's a recommend approach for doing this? It's a Django project so something Pythony would be great.
[ "I'm not a Python/Django guy, myself, but some searching finds these potentially useful plugins:\n\nhttps://github.com/ashchristopher/django-sass (Django plugin for Sass)\nhttps://github.com/dsc/coffeecup (WSGI middleware for CoffeeScript)\n\n" ]
[ 1 ]
[]
[]
[ "coffeescript", "nose", "python", "sass", "ubuntu" ]
stackoverflow_0005246165_coffeescript_nose_python_sass_ubuntu.txt
Q: python method return string rather than instancemethod I got a class and a few method in it class ThisClass: def method1(self): text1 = 'iloveyou' return text1 def method2(self): text2 = self.method1 print str(text2) thisObj = ThisClass() thisObj.method2 the result i get...
python method return string rather than instancemethod
I got a class and a few method in it class ThisClass: def method1(self): text1 = 'iloveyou' return text1 def method2(self): text2 = self.method1 print str(text2) thisObj = ThisClass() thisObj.method2 the result i get is something like <bound method thisclass.method2 of <__ma...
[ "Missing the () for the method call. Without the () you are printing the string representation of the method object which is also true for all callables including free functions.\nMake sure you do it for all your method calls ( self.method1 and thisObj.method2 )\nclass ThisClass:\n\n def method1(self):\n ...
[ 9, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005250235_oop_python.txt
Q: Why is my django password change not sticking? I have a profile model I use to supplement the built in User model. I've made a function to reset the password of a user as follows: def _reset_password(self): import random, string password = ''.join(random.choice(string.letters+string.digits) for i in range(...
Why is my django password change not sticking?
I have a profile model I use to supplement the built in User model. I've made a function to reset the password of a user as follows: def _reset_password(self): import random, string password = ''.join(random.choice(string.letters+string.digits) for i in range(10)) u = self.user u.set_password(password) ...
[ "I haven't tested this, but it seems that your user object u is stale, because you retrieved it before you actually change the password. Try to \nu = User.objects.get(profile = p)\n\nafter you reset the password and it should work. \n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005250230_django_python.txt
Q: converting a simple list to a dictionary (in python) I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? list = ['first_key', 'first_value', 's...
converting a simple list to a dictionary (in python)
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? list = ['first_key', 'first_value', 'second_key', 'second_value'] Thanks in advance!
[ "The most concise way is\nsome_list = ['first_key', 'first_value', 'second_key', 'second_value']\nd = dict(zip(*[iter(some_list)] * 2))\n\n", "myDict = dict(zip(myList[::2], myList[1::2]))\n\nPlease do not use 'list' as a variable name, as it prevents you from accessing the list() function.\nIf there is much data...
[ 4, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005249353_python.txt
Q: Current user in django admin I've tried numerous methods of finding the current user ID in django's administration. I've tried pulling the user ID via SessionKey and request.user (HTTPRequest) to no avail. My latest incarnation is: def save(self, request, obj, form, change): if getattr(obj, 'submitter', None) ...
Current user in django admin
I've tried numerous methods of finding the current user ID in django's administration. I've tried pulling the user ID via SessionKey and request.user (HTTPRequest) to no avail. My latest incarnation is: def save(self, request, obj, form, change): if getattr(obj, 'submitter', None) is None: obj.submitter = r...
[ "From the looks of your snippet, you are trying to save the currently logged in user to your model field in a ModelAdmin\nIt looks like you meant to override save_model\nhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model\nclass AppAdmin(admin.ModelAdmin):\n def sav...
[ 8 ]
[]
[]
[ "admin", "django", "httprequest", "python" ]
stackoverflow_0005250419_admin_django_httprequest_python.txt