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: Why is printing to stdout so slow? Can it be sped up? I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for ...
Why is printing to stdout so slow? Can it be sped up?
I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for the terminal to process the results. Can writing to stdout ...
[ "\nHow can it be that writing to physical disk is WAY faster than writing to the \"screen\" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null?\n\nCongratulations, you have just discovered the importance of I/O buffering. :-)\nThe disk appears to be faster, becaus...
[ 186, 109, 14, 4, 3, 2 ]
[]
[]
[ "linux", "printing", "python", "stdout", "tty" ]
stackoverflow_0003857052_linux_printing_python_stdout_tty.txt
Q: Generate a list of length n with m possible elements I need to generate a ton of lists in Python. Every list is of length 13, and I have 4 possible values that can go into each element. These are [1, -1, i, -i], but it could be whatever. Thus I should get 4 * 4 * 4 ... * 4 = 4^13 = 67,108,864 lists, or more genera...
Generate a list of length n with m possible elements
I need to generate a ton of lists in Python. Every list is of length 13, and I have 4 possible values that can go into each element. These are [1, -1, i, -i], but it could be whatever. Thus I should get 4 * 4 * 4 ... * 4 = 4^13 = 67,108,864 lists, or more generally, m^n, given the info in the subject. I tried the combi...
[ "I think you want\ny = itertools.product((1, -1, 1j, -1j), repeat=13)\n\n\nThen, btw, print sum(1 for x in y) prints, 67108864, as you expect.\n" ]
[ 7 ]
[]
[]
[ "combinations", "permutation", "python", "python_itertools" ]
stackoverflow_0003860267_combinations_permutation_python_python_itertools.txt
Q: Is it ok to return None from __new__? In general, is it reasonable to return None from a __new__ method if the user of the class knows that sometimes the constructor will evaluate to None? The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__ is not going to be calle...
Is it ok to return None from __new__?
In general, is it reasonable to return None from a __new__ method if the user of the class knows that sometimes the constructor will evaluate to None? The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__ is not going to be called, None not being an instance of the custom...
[ "It's not illegal. If nothing weird is done with the result, it will work.\n", "You should avoid this. The documentation doesn't exhaustively list the things you shouldn't do, but it says what __new__ should do: return an instance of the class.\nIf you don't want to return a new object in some cases, raise an e...
[ 7, 3 ]
[]
[]
[ "new_operator", "python" ]
stackoverflow_0003860469_new_operator_python.txt
Q: about python datetime type What's the equivalent type in types module for datetime? Example: import datetime import types t=datetime.datetime.now() if type(t)==types.xxxxxx: do sth I didn't find the relevent type in types module for the datetime type; could any one help me? A: >>> type(t) <type 'datetime.da...
about python datetime type
What's the equivalent type in types module for datetime? Example: import datetime import types t=datetime.datetime.now() if type(t)==types.xxxxxx: do sth I didn't find the relevent type in types module for the datetime type; could any one help me?
[ ">>> type(t)\n<type 'datetime.datetime'>\n>>> type(t) is datetime.datetime\nTrue\n\nIs that the information you're looking for? I don't think you'll be able to find the relevant type within the types module since datetime.datetime is not a builtin type.\nEdit to add: Another note, since this is evidently what you w...
[ 14 ]
[]
[]
[ "datetime", "python", "types" ]
stackoverflow_0003860482_datetime_python_types.txt
Q: How to parse and print fields from CSV data in python I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text. This is an example of the text: {"This is an example", "of what I...
How to parse and print fields from CSV data in python
I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text. This is an example of the text: {"This is an example", "of what I what I have to deal with. ", "Please pick up th following...
[ "import csv\nwith open('test') as f:\n for row in csv.reader(f):\n for item in row:\n item=item.strip('{} \"')\n print(item)\n\nThe strip method removes the specified characters from the left or right end of the string item.\n", "Please explain what you have got to start with.\nx =...
[ 1, 1, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003860095_csv_python.txt
Q: Python: Dictionary of list of lists def makecounter(): return collections.defaultdict(int) class RankedIndex(object): def __init__(self): self._inverted_index = collections.defaultdict(list) self._documents = [] self._inverted_index = collections.defaultdict(makecounter) def index_dir(self, ba...
Python: Dictionary of list of lists
def makecounter(): return collections.defaultdict(int) class RankedIndex(object): def __init__(self): self._inverted_index = collections.defaultdict(list) self._documents = [] self._inverted_index = collections.defaultdict(makecounter) def index_dir(self, base_path): num_files_indexed = 0 ...
[ "First, use a factory. Start with:\ndef makecounter():\n return collections.defaultdict(int)\n\nand later use\nself._inverted_index = collections.defaultdict(makecounter)\n\nand as the for term in tokens: loop,\n for term in tokens: \n self._inverted_index[term][docnumber] +=1\n\nThis lea...
[ 6, 1, 0 ]
[]
[]
[ "information_retrieval", "python" ]
stackoverflow_0003860568_information_retrieval_python.txt
Q: Decorators applied to class definition with Python Compared to decorators applied to a function, it's not easy to understand the decorators applied to a class. @foo class Bar(object): def __init__(self, x): self.x = x def spam(self): statements What's the use case of decorators to a class...
Decorators applied to class definition with Python
Compared to decorators applied to a function, it's not easy to understand the decorators applied to a class. @foo class Bar(object): def __init__(self, x): self.x = x def spam(self): statements What's the use case of decorators to a class? How to use it?
[ "It replaces the vast majority of classic good uses for custom metaclasses in a much simpler way.\nThink about it this way: nothing that's directly in the class body can refer to the class object, because the class object doesn't exist until well after the body's done running (it's the metaclass's job to create the...
[ 23, 6 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0003860539_decorator_python.txt
Q: Any free debug softwares that would allow me to peek into the workings of a compiled pyexe file? I am trying to learn more about the mechanics of executable files, but I have no background in assembler code. Is there any program I can use for this purpose? I would like to be able to pause a program in real time an...
Any free debug softwares that would allow me to peek into the workings of a compiled pyexe file?
I am trying to learn more about the mechanics of executable files, but I have no background in assembler code. Is there any program I can use for this purpose? I would like to be able to pause a program in real time and read its memory dump at that instant. Is there anything like that for windows 7 32? What about for w...
[ "I would suggest that you beef up on assembly programming.\nAlso read about and around windows executable format\n\nhttp://msdn.microsoft.com/en-us/magazine/cc301805.aspx\nhttp://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx\n\nOthers\n - http://www.slideshare.net/rety61/a-handson-introduction-to-the-...
[ 1, 1 ]
[]
[]
[ "debugging", "executable", "python" ]
stackoverflow_0003860732_debugging_executable_python.txt
Q: Python regex: how to extract inner data from regex I want to extract data from such regex: <td>[a-zA-Z]+</td><td>[\d]+.[\d]+</td><td>[\d]+</td><td>[\d]+.[\d]+</td> I've found related question extract contents of regex but in my case I shoud iterate somehow. A: As paprika mentioned in his/her comment, you nee...
Python regex: how to extract inner data from regex
I want to extract data from such regex: <td>[a-zA-Z]+</td><td>[\d]+.[\d]+</td><td>[\d]+</td><td>[\d]+.[\d]+</td> I've found related question extract contents of regex but in my case I shoud iterate somehow.
[ "As paprika mentioned in his/her comment, you need to identify the desired parts of any matched text using ()'s to set off the capture groups. To get the contents from within the td tags, change:\n<td>[a-zA-Z]+</td><td>[\\d]+.[\\d]+</td><td>[\\d]+</td><td>[\\d]+.[\\d]+</td> \n\nto:\n<td>([a-zA-Z]+)</td><td>([\\d]+...
[ 7, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003860881_html_python_regex.txt
Q: How do I modify a single character in a string, in Python? How do I modify a single character in a string, in Python? Something like: a = "hello" a[2] = "m" 'str' object does not support item assignment. A: Strings are immutable in Python. You can use a list of characters instead: a = list("hello") When you ...
How do I modify a single character in a string, in Python?
How do I modify a single character in a string, in Python? Something like: a = "hello" a[2] = "m" 'str' object does not support item assignment.
[ "Strings are immutable in Python. You can use a list of characters instead:\na = list(\"hello\")\n\nWhen you want to display the result use ''.join(a):\na[2] = 'm'\nprint ''.join(a)\n\n", "In python, string are immutable. If you want to change a single character, you'll have to use slicing:\na = \"hello\"\na = a[...
[ 15, 12, 8, 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003861026_python_string.txt
Q: Chaining operator functions in Python's filter I have a list of objects and want to filter them according to some criteria. I can do it with list comprehension: import datetime, pytz # let's have a range of 100 hourly datetimes (just an example!): dates = [ datetime.datetime(2010, 10, 1, 0, 0, 0, 0, pytz.utc) + da...
Chaining operator functions in Python's filter
I have a list of objects and want to filter them according to some criteria. I can do it with list comprehension: import datetime, pytz # let's have a range of 100 hourly datetimes (just an example!): dates = [ datetime.datetime(2010, 10, 1, 0, 0, 0, 0, pytz.utc) + datetime.timedelta(hours=i) for i in xrange(100) ] # ...
[ "One way is to use a custom lambda function. This one is verbose for clarity.\nfilter(lambda dt: hasattr(dt, 'hour') and dt.hour % 6, dates)\n\nThe hasattr check is only necessary if you are expecting non date objects in the dates sequence. \nI'd like to add a note that list comprehensions are preferred to map and ...
[ 4, 1 ]
[]
[]
[ "filter", "operators", "python" ]
stackoverflow_0003861263_filter_operators_python.txt
Q: Read contents of a pdf file Is there a commandline tool to read a pdf file on linux.Please indicate the appropriate urls for this. Thanks.. A: Xpdf and Poppler contain the commandline-utility pdftotext wich converts PDF files to plain text. A: Not a command line tool but a pdf reading and generation framework ...
Read contents of a pdf file
Is there a commandline tool to read a pdf file on linux.Please indicate the appropriate urls for this. Thanks..
[ "Xpdf and Poppler contain the commandline-utility pdftotext wich converts PDF files to plain text.\n", "Not a command line tool but a pdf reading and generation framework\n\nhttp://www.reportlab.com/software/opensource/\n\nyou should also be able to write a simple reader using\n\nhttp://pybrary.net/pyPdf/\nhttp:/...
[ 5, 0, 0 ]
[]
[]
[ "command_line", "linux", "pdf", "python", "shell" ]
stackoverflow_0003861158_command_line_linux_pdf_python_shell.txt
Q: Combining two lists of objects based on an attribute Every example of list or set usage in Python seems to include trivial cases of integers but I have two lists of objects where the name attribute defines whether two objects instances are "the same" or not (other attributes might have different values). I can cre...
Combining two lists of objects based on an attribute
Every example of list or set usage in Python seems to include trivial cases of integers but I have two lists of objects where the name attribute defines whether two objects instances are "the same" or not (other attributes might have different values). I can create a list that contains all items from both lists, sorted...
[ "Sounds to me like you might be better off with a dict instead of a list, using the name as the key, and the rest of the object as value. Then you can simply dict1.update(dict2).\n>>> dict1 = {\"Harry\": 18, \"Mary\": 27, \"Tim\": 7}\n>>> dict2 = {\"Harry\": 22, \"Mary\": 27, \"Frank\": 40}\n>>> dict1.update(dict2)...
[ 5, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003861491_list_python.txt
Q: A data-structure for 1:1 mappings in python? I have a problem which requires a reversable 1:1 mapping of keys to values. That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. x = D[y] y == D.inverse[x] Th...
A data-structure for 1:1 mappings in python?
I have a problem which requires a reversable 1:1 mapping of keys to values. That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. x = D[y] y == D.inverse[x] The obvious solution is to simply invert the diction...
[ "\nThe other alternative is to make a new\n class which unites two dictionaries,\n one for each kind of lookup. That\n would most likely be fast but would\n use up twice as much memory as a\n single dict.\n\nNot really. Have you measured that? Since both dictionaries would use references to the same objects as...
[ 28, 11, 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0000863935_data_structures_python.txt
Q: AppEngine: Query datastore for records with no condition for a specific property i want to do a query that a user may or may not select a filter, but i don't want to create 2 indexes (tables). value=self.request.get('filter') if value: results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter...
AppEngine: Query datastore for records with no condition for a specific property
i want to do a query that a user may or may not select a filter, but i don't want to create 2 indexes (tables). value=self.request.get('filter') if value: results=Entity.all().filter('p1 =','v1').filter('p2 =','v2').filter('filter_property =',value) else: results=Entity.all().filter('p1 =','v1').filter('p2 =','...
[ "It sounds like you've got a good handle on the alternatives. You can add order clauses to replace filters if you want the datastore to use the same index for each; otherwise, you're stuck with having multiple indexes.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003860097_google_app_engine_google_cloud_datastore_python.txt
Q: how to know on which platform is remote machine running using python code I just wanted to know that how can we fetch the platform on which a remote machine is running using Python? A: Frankly, i'd use python to launch an nmap executable and parse the result. nmap can detect accurately what platform it's talking...
how to know on which platform is remote machine running using python code
I just wanted to know that how can we fetch the platform on which a remote machine is running using Python?
[ "Frankly, i'd use python to launch an nmap executable and parse the result. nmap can detect accurately what platform it's talking with based on little variations and details in the packets exchanged.\n", "I don't quite know how to interpret your question, but samy has answered the case of \"how to use Python to f...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003861654_python.txt
Q: Split string by number of words with python How do I split up a string into several parts of a number of words in python. For example, turn a 10,000 word string into ten 1,000 word strings. Thanks. A: def splitter(n, s): pieces = s.split() return (" ".join(pieces[i:i+n]) for i in range(0, len(pieces), n)...
Split string by number of words with python
How do I split up a string into several parts of a number of words in python. For example, turn a 10,000 word string into ten 1,000 word strings. Thanks.
[ "def splitter(n, s):\n pieces = s.split()\n return (\" \".join(pieces[i:i+n]) for i in range(0, len(pieces), n)\n\nfor piece in splitter(1000, really_long_string):\n print(piece)\n\nWhere n is number of words; s is the long string.\nThis will yield ten 1000 word strings from a 10000 word string like you as...
[ 5, 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003861674_python_string.txt
Q: How to prevent boost::python::extract from accepting int I'm using boost::python::extract<> to convert the items in a boost::python::list to floats. My problem is with int's in python - extract<float> seems to regard int->float as a valid conversion, however I only want true float objects. Is there a way to force ...
How to prevent boost::python::extract from accepting int
I'm using boost::python::extract<> to convert the items in a boost::python::list to floats. My problem is with int's in python - extract<float> seems to regard int->float as a valid conversion, however I only want true float objects. Is there a way to force extract<> to be more conservative? extract<float> value(o); if...
[ "I'm pretty sure that you can't tell extract<float> not to convert intergers to floats. \nWhat you could do is to query the wrapped PyObject:\nconst PyObject* pyo = o.ptr();\nif (PyFloat_Check(pyo))\n{\n // True only for floats.\n a = extract<float>(o);\n}\n\n" ]
[ 1 ]
[]
[]
[ "boost_python", "python" ]
stackoverflow_0003861496_boost_python_python.txt
Q: Pickling objects I need to pickle object [wxpython frame object] and send it as a prameter to this function apply_async on multiproccessing pool module could someone provide me an example how can I do it I tried the following and get an error message : myfile = file(r"C:\binary.dat", "w") pickle.dump(self, myfil...
Pickling objects
I need to pickle object [wxpython frame object] and send it as a prameter to this function apply_async on multiproccessing pool module could someone provide me an example how can I do it I tried the following and get an error message : myfile = file(r"C:\binary.dat", "w") pickle.dump(self, myfile) myfile.close() se...
[ "I don't believe that wxPython objects can be pickled. They are just wrappers around C objects, which contain lots of pointers and other stateful stuff. The pickle module doesn't know enough about them to be able to restore their state afterwards.\n", "You can not serialize a widget for use in another process. I ...
[ 1, 1 ]
[]
[]
[ "pickle", "python", "wxpython" ]
stackoverflow_0003862331_pickle_python_wxpython.txt
Q: Setting model level permissions in code for Django admin panel Is there a way to implement the permissions for models through the code? I have a large set of models and I want some of the models to be just viewable by the admin and not the ability to add them. Please suggest. A: You can set permissions through t...
Setting model level permissions in code for Django admin panel
Is there a way to implement the permissions for models through the code? I have a large set of models and I want some of the models to be just viewable by the admin and not the ability to add them. Please suggest.
[ "You can set permissions through the admin site itself. For instructions, see the \"Users, Groups and Permissions\" section in the django book chapter:\n\nThe Django Administration Site \n\n", "Found the solution here: http://code.djangoproject.com/wiki/RowLevelPermissions \nworks the way I needed.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003828084_django_django_admin_python.txt
Q: send commands to a backgrounded jobs stdin I have a java server application that, when its running, you can interact with it sending commands via stdin. I want to write a web interface that can send these commands to it. In order to do that I need some way of getting commands from php to the stdin for this backgr...
send commands to a backgrounded jobs stdin
I have a java server application that, when its running, you can interact with it sending commands via stdin. I want to write a web interface that can send these commands to it. In order to do that I need some way of getting commands from php to the stdin for this backgrounded job. Is there a way to do this from conso...
[ "You could connect its stdin to a FIFO and then have another daemon also connect to the FIFO and send commands. It might be better to have the control daemon start the Java daemon though, so that the Java daemon doesn't shut down if the control daemon does for some reason.\n", "You can use python subprocess modul...
[ 0, 0, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003862332_php_python.txt
Q: Can I safely use hashes of tuples containing 64 bit integers (longs) as unique keys in a python dictionary? I have to store objects that have two attributes (ida and idb) inside a dict. Both attributes are 64 bit positive integers and I can only store one object for a unique arrangement(combination in which the or...
Can I safely use hashes of tuples containing 64 bit integers (longs) as unique keys in a python dictionary?
I have to store objects that have two attributes (ida and idb) inside a dict. Both attributes are 64 bit positive integers and I can only store one object for a unique arrangement(combination in which the order matters) of ida and idb. For example: obj1 = SomeClass(ida=5223372036854775807, idb=2) obj2 = SomeClass(ida=2...
[ "In [33]: hash?\n\n\nReturn a hash value for the object. Two objects with the same\n value have the same hash value. The reverse is not necessarily true, but\n likely.\n\nWhy not just use the tuple (ida,idb) as the key?\nimport pprint\nclass SomeClass(object):\n def __init__(self,ida,idb):\n self.ida=...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "hash", "hashtable", "python", "tuples" ]
stackoverflow_0003863753_dictionary_hash_hashtable_python_tuples.txt
Q: python nose and twisted I am writing a test for a function that downloads the data from an url with Twisted (I know about twisted.web.client.getPage, but this one adds some extra functionality). Either ways, I want to use nosetests since I am using it throughout the project and it doesn't look appropriate to use T...
python nose and twisted
I am writing a test for a function that downloads the data from an url with Twisted (I know about twisted.web.client.getPage, but this one adds some extra functionality). Either ways, I want to use nosetests since I am using it throughout the project and it doesn't look appropriate to use Twisted Trial only for this pa...
[ "Are you sure your getPage function is parsing the URL correctly? The error message seems to suggest that it is using the hostname and port together when doing the dns lookup.\nYou say your getPage is similar to twisted.web.client.getPage, but that works fine for me when I use it in this complete script:\n#!/usr/bi...
[ 2 ]
[]
[]
[ "nose", "python", "twisted" ]
stackoverflow_0003863374_nose_python_twisted.txt
Q: How to write tag deleter script in python I want to implement a file reader (folders and subfolders) script which detects some tags and delete those tags from the files. The files are .cpp, .h .txt and .xml And they are hundreds of files under same folder. I have no idea about python, but people told me that I can...
How to write tag deleter script in python
I want to implement a file reader (folders and subfolders) script which detects some tags and delete those tags from the files. The files are .cpp, .h .txt and .xml And they are hundreds of files under same folder. I have no idea about python, but people told me that I can do it easily. EXAMPLE: My main folder is A: C:...
[ "The general solution would be to:\n\nuse the os.walk() function to traverse the directory tree. \nIterate over the filenames and use fn_name.endswith('.cpp') with if/elseif to determine which file you're working with\nUse the re module to create a regular expression you can use to determine if a line contains your...
[ 3, 1 ]
[]
[]
[ "directory", "parsing", "python", "tags" ]
stackoverflow_0003856160_directory_parsing_python_tags.txt
Q: Cancel a group of HTTP requests in twisted I'm making several HTTP requests with twisted.web.client.getPage, and would like to be able to cancel some of them at the user's request. Ideally I would like to do something like: # Pseudocode, getPage doesn't work like this: getPage(url1, "group1") getPage(url2, "group1...
Cancel a group of HTTP requests in twisted
I'm making several HTTP requests with twisted.web.client.getPage, and would like to be able to cancel some of them at the user's request. Ideally I would like to do something like: # Pseudocode, getPage doesn't work like this: getPage(url1, "group1") getPage(url2, "group1") getPage(url3, "group1") ... # Later on react...
[ "You are describing two separate issues. First, can an HTTP request made with getPage be cancelled at all? No, it can't. Second, can operations be grouped together so that they can all be cancelled simultaneously. Sure, that doesn't involve anything very special:\ndef cancel(group):\n for job in group:\n ...
[ 1, 0 ]
[]
[]
[ "http", "python", "twisted" ]
stackoverflow_0003862129_http_python_twisted.txt
Q: WSGI request and response wrappers I'm looking for WSGI request and response wrappers for having a more convenient interface than the plain WSGI environ and start_response callback. I want something like WebOb or Werkzeug. But I don't like WebOb's PHP-like usage of GET and POST for parameter dictionaries, because ...
WSGI request and response wrappers
I'm looking for WSGI request and response wrappers for having a more convenient interface than the plain WSGI environ and start_response callback. I want something like WebOb or Werkzeug. But I don't like WebOb's PHP-like usage of GET and POST for parameter dictionaries, because HTTP is not limited to GET and POST and ...
[ "WebOb allows you to access POST & GET parameters jointly by accessing Request.str_params attribute. Additionally, Request.method gives you acces to the HTTP request type which is not limited to POST or GET.\n" ]
[ 1 ]
[]
[]
[ "http", "httprequest", "httpresponse", "python", "wsgi" ]
stackoverflow_0003862966_http_httprequest_httpresponse_python_wsgi.txt
Q: Installing psycopg2 in virtualenv (Ubuntu 10.04, Python 2.5) I had problems installing psycopg2 in a virtualenv. I tried different things explained there: http://www.saltycrane.com/blog/2009/07/using-psycopg2-virtualenv-ubuntu-jaunty/ The last thing I tried is this... I created a virtualenv with -p python2.5 --no-...
Installing psycopg2 in virtualenv (Ubuntu 10.04, Python 2.5)
I had problems installing psycopg2 in a virtualenv. I tried different things explained there: http://www.saltycrane.com/blog/2009/07/using-psycopg2-virtualenv-ubuntu-jaunty/ The last thing I tried is this... I created a virtualenv with -p python2.5 --no-site-packages I installed libpq-dev: apt-get install libpq-dev In...
[ "From python-list: \n\nDiez:\n Install the python-dev-package. It\n contains the Python.h file, which the\n above error message pretty clearly\n says. Usually, it's a good idea to\n search package descriptions of\n debian/ubuntu packages for missing\n header files to know what to install.\n\nPascal:\n It...
[ 6 ]
[]
[]
[ "psycopg2", "python", "virtualenv" ]
stackoverflow_0003847536_psycopg2_python_virtualenv.txt
Q: How to get IP when using SimpleXMLRPCDispatcher in Django Having a code inspired from http://code.djangoproject.com/wiki/XML-RPC : from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5 def rpc_h...
How to get IP when using SimpleXMLRPCDispatcher in Django
Having a code inspired from http://code.djangoproject.com/wiki/XML-RPC : from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5 def rpc_handler(request): """ the actual handler: if you set...
[ "Ok I could do it ... with some nifty tips ...\nFirst, I created my own copy of SimpleXMLRPCDispatcher which inherit everything from it and overides 2 methods :\nclass MySimpleXMLRPCDispatcher (SimpleXMLRPCDispatcher) :\n def _marshaled_dispatch(self, data, dispatch_method = None, request = None):\n # cop...
[ 0 ]
[]
[]
[ "django", "ip_address", "python", "simplexmlrpcserver", "xml_rpc" ]
stackoverflow_0003777449_django_ip_address_python_simplexmlrpcserver_xml_rpc.txt
Q: Python SocketServer How can I call shutdown() in a SocketServer after receiving a certain message "exit"? As I know, the call to serve_forever() will block the server. Thanks! A: Use the source, Luke! Excerpt from SocketServer.py: def serve_forever(self, poll_interval=0.5): """Handle one request at a ...
Python SocketServer
How can I call shutdown() in a SocketServer after receiving a certain message "exit"? As I know, the call to serve_forever() will block the server. Thanks!
[ "Use the source, Luke!\nExcerpt from SocketServer.py:\n def serve_forever(self, poll_interval=0.5):\n \"\"\"Handle one request at a time until shutdown.\n\n Polls for shutdown every poll_interval seconds. Ignores\n self.timeout. If you need to do periodic tasks, do them in\n another th...
[ 6, 4 ]
[]
[]
[ "python", "sockets", "socketserver" ]
stackoverflow_0003863281_python_sockets_socketserver.txt
Q: Adding or merging python dictionaries without loss I'm trying to count up ip addresses found in a log file on two servers and then merge the dictionary stats together without loosing elements or counts. I found a partial solution in another stack overflow question but as you can see it drops the '10.10.0.1':7 pair...
Adding or merging python dictionaries without loss
I'm trying to count up ip addresses found in a log file on two servers and then merge the dictionary stats together without loosing elements or counts. I found a partial solution in another stack overflow question but as you can see it drops the '10.10.0.1':7 pair. >>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12'...
[ "If you have Python 2.7+, try collections.Counter\nOtherwise try the following:\na = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}\nb = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}\nc = {}\nfor dictionary in (a,b):\n for k,v in dictionary.iteritems():\n c[k] = c.get(k, 0) + v\n\n",...
[ 5, 5, 5, 2, 1, 1 ]
[]
[]
[ "add", "count", "dictionary", "merge", "python" ]
stackoverflow_0003864517_add_count_dictionary_merge_python.txt
Q: in numpy what is the multi dimensional equivalent of take I have this bit of code def build_tree_base(blocks, x, y, z): indicies = [ (x ,z ,y ), (x ,z+1,y ), (x ,z ,y+1), (x ,z+1,y+1), (x+1,z ,y ), (x+1,z+1,y ), (x+1,z ,y+1), (x+1,z+1,y...
in numpy what is the multi dimensional equivalent of take
I have this bit of code def build_tree_base(blocks, x, y, z): indicies = [ (x ,z ,y ), (x ,z+1,y ), (x ,z ,y+1), (x ,z+1,y+1), (x+1,z ,y ), (x+1,z+1,y ), (x+1,z ,y+1), (x+1,z+1,y+1), ] children = [blocks[i] for i in indicies] ret...
[ "Numpy indexing make this quite easy... You should be able to to something like this:\ndef build_tree_base(blocks, x, y, z):\n idx = [x, x, x, x, x+1, x+1, x+1, x+1]\n idz = [z, z+1, z, z+1, z, z+1, z, z+1]\n idy = [y, y, y+1, y+1, y, y, y+1, y+1]\n children = blocks[idx, idz, idy]\n return Node(chil...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003813344_numpy_python.txt
Q: about python __doc__ docstring i want to show docstring of my function, but if i use like this @cost_time def func(): "define ...." blabla print func.__doc__ it will not show the docstring,just because i use some meta programming tricky, how can fix this? A: Your wrapped function returned from the cost_...
about python __doc__ docstring
i want to show docstring of my function, but if i use like this @cost_time def func(): "define ...." blabla print func.__doc__ it will not show the docstring,just because i use some meta programming tricky, how can fix this?
[ "Your wrapped function returned from the cost_time decorator must have the docstring instead of func. Therefore, use functools.wraps which correctly sets __name__ and __doc__:\nfrom functools import wraps\n\ndef cost_time(fn):\n @wraps(fn)\n def wrapper():\n return fn()\n\n return wrapper\n\n", "U...
[ 12, 2 ]
[]
[]
[ "doc", "docstring", "python" ]
stackoverflow_0003865254_doc_docstring_python.txt
Q: Python3 decorating conditionally? Is it possible to decorate a function based on a condition? a'la: if she.weight() == duck.weight(): @burn def witch(): pass I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn? If not, is it possible...
Python3 decorating conditionally?
Is it possible to decorate a function based on a condition? a'la: if she.weight() == duck.weight(): @burn def witch(): pass I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn? If not, is it possible to create a condition within the decor...
[ "You can create a 'conditionally' decorator: \n>>> def conditionally(dec, cond):\n def resdec(f):\n if not cond:\n return f\n return dec(f)\n return resdec\n\nUsage example follows:\n>>> def burn(f):\n def blah(*args, **kwargs):\n print 'hah'\n return f(*args, **kwarg...
[ 13, 7, 5 ]
[]
[]
[ "conditional_statements", "decorator", "python" ]
stackoverflow_0003773555_conditional_statements_decorator_python.txt
Q: HTML form POST to a python script? Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script? A: For a very basic CGI script, you can use the cgi module. Check out the following article from the Python documentation for a very basic example on how to hand...
HTML form POST to a python script?
Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script?
[ "For a very basic CGI script, you can use the cgi module. Check out the following article from the Python documentation for a very basic example on how to handle an HTML form submitted through POST:\n\nWeb Programming in Python : CGI Scripts\n\nExample from the above article:\n#!/usr/bin/env python\n\nimport cgi\ni...
[ 9, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0003862788_html_python.txt
Q: sorting by first group element in python I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item. order group 3 1 4 2 2 2 1 1 After sort order group 1 1 3 1 2 2 4 2 Python list unordered ...
sorting by first group element in python
I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item. order group 3 1 4 2 2 2 1 1 After sort order group 1 1 3 1 2 2 4 2 Python list unordered = [(3, 1), (4, 2), (2, 2), (1, 1)]
[ "I assume you meant unordered = [(3, 1), (4, 2), (2, 2), (1, 1)] because that part of your example as you typed it is incompatible with the other two, right?\nIf so, then\n>>> import operator\n>>> sorted(unordered, key=operator.itemgetter(1,0))\n[(1, 1), (3, 1), (2, 2), (4, 2)]\n\nor similarly unordered.sort(key=op...
[ 16 ]
[]
[]
[ "python" ]
stackoverflow_0003865779_python.txt
Q: Nautilus extensions written in Python does not run when it calls gtk.main() I'm developing a nautilus extension and I have the following code: #!/usr/local/bin/python # -*- coding: utf-8 -*- import urllib import gtk import pygtk import nautilus import gconf import gtk.glade class Slide (nautilus.MenuProvider): ...
Nautilus extensions written in Python does not run when it calls gtk.main()
I'm developing a nautilus extension and I have the following code: #!/usr/local/bin/python # -*- coding: utf-8 -*- import urllib import gtk import pygtk import nautilus import gconf import gtk.glade class Slide (nautilus.MenuProvider): f = None def __init__(self): self.client = gconf.client_get_default() ...
[ "Try only commenting gtk.main(). If it still runs after that I'm guessing that since nautilus is already running, calling gtk.main() launches a new gtk application. separate from nautilus. All you need to do is connect to nautilus and hit window.show(), which you do in your oi method.\n" ]
[ 1 ]
[]
[]
[ "gnome", "nautilus", "pygtk", "python" ]
stackoverflow_0003860021_gnome_nautilus_pygtk_python.txt
Q: Translating PHP’s preg_match_all to Python Can I have a translation of PHP’s preg_match_all('/(https?:\/\/\S+)/', $text, $links) in Python, please? (ie) I need to get the links present in the plain text argument in an array. A: This will do it: import re links = re.findall('(https?://\S+)', text) If you plan to...
Translating PHP’s preg_match_all to Python
Can I have a translation of PHP’s preg_match_all('/(https?:\/\/\S+)/', $text, $links) in Python, please? (ie) I need to get the links present in the plain text argument in an array.
[ "This will do it:\nimport re\nlinks = re.findall('(https?://\\S+)', text)\n\nIf you plan to use this multiple times than you can consider doing this:\nimport re\nlink_re = re.compile('(https?://\\S+)')\nlinks = link_re.findall(text)\n\n" ]
[ 16 ]
[]
[]
[ "php", "python", "regex" ]
stackoverflow_0003865896_php_python_regex.txt
Q: What are the full implications of not using the default 'id' primary_key in your Django model? Consider the case where a CHAR field primary_key is required in order to define a ForeignKey relationship. After some initial investigation I have identified the following possibilities, each with their own drawbacks: 1)...
What are the full implications of not using the default 'id' primary_key in your Django model?
Consider the case where a CHAR field primary_key is required in order to define a ForeignKey relationship. After some initial investigation I have identified the following possibilities, each with their own drawbacks: 1) Using 'primary_key=True'. Example 1: class Collection(models.Model): code = models.CharField(pr...
[ "GenericForeignKeys would suffer since they all need to use the same type for a foreign PK. As long as you stay away from them, you should be fine.\n", "I had troubles in the django admin application when using char field as primary key. See unicode error when saving an object in django admin for details\nRestori...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_models", "orm", "python" ]
stackoverflow_0003862739_django_django_models_orm_python.txt
Q: Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate? Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate? #!/usr/bin/env python import operato...
Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate?
Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate? #!/usr/bin/env python import operator import doctest class Stack: """A stack is a collection, meaning that it is a data structure that co...
[ "General suggestions:\n\nAvoid unnecessary type checks, and rely on default exception behavior.\nhas_key() has long been deprecated in favor of the in operator: use that instead.\nProfile your program, before attempting any performance optimization. For a zero-effort profiling run of any given code, just run: pytho...
[ 10, 3, 2 ]
[]
[]
[ "postfix_notation", "python", "rpn" ]
stackoverflow_0003865939_postfix_notation_python_rpn.txt
Q: IronPython & WPF: Binding a checkbox's IsChecked property to a class member variable I've seen many similar questions on how to get data binding working with a checkbox, but all of the examples I've seen are in C# and I can't seem to make the leap to convert it to IronPython. I have a checkbox defined in a window ...
IronPython & WPF: Binding a checkbox's IsChecked property to a class member variable
I've seen many similar questions on how to get data binding working with a checkbox, but all of the examples I've seen are in C# and I can't seem to make the leap to convert it to IronPython. I have a checkbox defined in a window thusly: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ...
[ "The property should use INotifyPropertyChanged interface. See my blog for an example how to implement it in IronPython.\nAlso note there is a Silverlight bug in .NET or IronPython causing an error when anything else than string should be propagated back into viewmodel.\n" ]
[ 3 ]
[]
[]
[ "binding", "ironpython", "python", "visual_studio_2010", "wpf" ]
stackoverflow_0003856905_binding_ironpython_python_visual_studio_2010_wpf.txt
Q: django error: 'unicode' object is not callable im attempting to do the django tutorial from the django website, and ive run into a bit of an issue: ive got to adding my __unicode__ methods to my models classes, but when ever i try to return the objects of that model i get the following error: in __unicode__ re...
django error: 'unicode' object is not callable
im attempting to do the django tutorial from the django website, and ive run into a bit of an issue: ive got to adding my __unicode__ methods to my models classes, but when ever i try to return the objects of that model i get the following error: in __unicode__ return self.question() TypeError: 'unicode' object is ...
[ "self.choice is a string value, but the code is trying to call it like a function. Just remove the () after it.\n" ]
[ 29 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003866577_django_python.txt
Q: understanding zip function All discussion is about python 3.1.2; see Python docs for the source of my question. I know what zip does; I just don't understand why it can be implemented like this: def zip(*iterables): # zip('ABCD', 'xy') --> Ax By iterables = map(iter, iterables) while iterables: ...
understanding zip function
All discussion is about python 3.1.2; see Python docs for the source of my question. I know what zip does; I just don't understand why it can be implemented like this: def zip(*iterables): # zip('ABCD', 'xy') --> Ax By iterables = map(iter, iterables) while iterables: yield tuple(map(next, iterables...
[ "It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop.\nAnd the latest version of the documentation has the same problem: http://docs.python.org/release/3.1.2/library/functions.html\nLooks like change 61361 was the problem, as ...
[ 9, 7 ]
[]
[]
[ "iterator", "python", "python_3.x", "zip" ]
stackoverflow_0003865640_iterator_python_python_3.x_zip.txt
Q: How to extract the bitrate and other statistics of a video file with Python I am trying to extract the prevailing bitrate of a video file (e.g. .mkv file containing a movie) at a regular sampling interval of between 1-10 seconds under conditions of normal playback. Kind of like you may see in vlc, during playback ...
How to extract the bitrate and other statistics of a video file with Python
I am trying to extract the prevailing bitrate of a video file (e.g. .mkv file containing a movie) at a regular sampling interval of between 1-10 seconds under conditions of normal playback. Kind of like you may see in vlc, during playback of the file in the statistics window. Can anyone suggest the best way to bootstr...
[ "Something like these:\nhttp://code.google.com/p/pyffmpeg/\nhttp://pymedia.org/\n", "You should be able to do this with gstreamer. http://pygstdocs.berlios.de/pygst-tutorial/seeking.html has an example of a simple media player. It calls\npos_int = self.player.query_position(gst.FORMAT_TIME, None)[0]\n\nperiodical...
[ 1, 0 ]
[]
[]
[ "analysis", "ffmpeg", "python", "video_processing" ]
stackoverflow_0003863432_analysis_ffmpeg_python_video_processing.txt
Q: Python error when running script - "IndentationError: unindent does not match any outer indentation" I'm getting an error when I try to run my script Error:"IndentationError: unindent does not match any outer indentation" Code snipet that throws the error: def update(): try: lines = open("vbvuln.txt"...
Python error when running script - "IndentationError: unindent does not match any outer indentation"
I'm getting an error when I try to run my script Error:"IndentationError: unindent does not match any outer indentation" Code snipet that throws the error: def update(): try: lines = open("vbvuln.txt", "r").readlines() except(IOError): print "[-] Error: Check your phpvuln.txt path and permis...
[ "Put a space before sys.exit(1) or remove space before print \"[-] Error: Check your phpvuln.txt path and permissions\" and print \"[-] Update Failed\\n\".\n", "As others have mentioned, you need to make sure that each code block has the exact same indentation.\nWhat they haven't mentioned is that the widely adop...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "indentation", "python", "syntax" ]
stackoverflow_0001124823_indentation_python_syntax.txt
Q: Clicking links by regexp in python selenium I've been looking around and trying to find a way to click on a link in selenium that's matched by a regexp. Here is the code that works; from selenium import selenium sel = selenium("localhost", 4444, "*chrome", "http://www.ncbi.nlm.nih.gov/") sel.start() sel.open('/pub...
Clicking links by regexp in python selenium
I've been looking around and trying to find a way to click on a link in selenium that's matched by a regexp. Here is the code that works; from selenium import selenium sel = selenium("localhost", 4444, "*chrome", "http://www.ncbi.nlm.nih.gov/") sel.start() sel.open('/pubmed') sel.type("search_term", "20032207[uid]") se...
[ "sel.click can take an XPath as an argument. Using Firebug I found (what I believe is) the XPath to \"linkout-icon-unknown-vir_full\" link:\nsel.click(\"//*[@id='linkout-icon-unknown-vir_full']\")\n\nUsing the above command takes me to this page. \n\nI wasn't able to get matches to work -- I'm not sure why -- but t...
[ 2, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0003865678_python_selenium.txt
Q: MySQL: Get dates with and without category/subcategory in ONE query (and sorted) I have a database with 4 tables with this structure: categories subcategories dates events We have events, that can have multiple dates. Events are categorized in categories and subcategories, but can have only a category and no sub...
MySQL: Get dates with and without category/subcategory in ONE query (and sorted)
I have a database with 4 tables with this structure: categories subcategories dates events We have events, that can have multiple dates. Events are categorized in categories and subcategories, but can have only a category and no subcategory, too. I tried this query: SELECT t.id as sortid, t.numprint, s.t...
[ "OK, last shot:\nif you want all kapitels, regardless of whether they have an event.\nSELECT * \nFROM kapitel k\n\nLEFT JOIN seminare s\nON s.kapitel = k.id\n AND s.aktiv = 1\n\nLEFT JOIN termine t\nON t.parent = s.id\n\nLEFT JOIN unterkapitel u\nON u.parent = k.id\n AND s.unterkapitel = u.id\n\nIf you want o...
[ 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003866329_mysql_python.txt
Q: Resampling irregularly spaced data to a regular grid in Python I need to resample 2D-data to a regular grid. This is what my code looks like: import matplotlib.mlab as ml import numpy as np y = np.zeros((512,115)) x = np.zeros((512,115)) # Just random data for this test: data = np.random.randn(512,115) # fillin...
Resampling irregularly spaced data to a regular grid in Python
I need to resample 2D-data to a regular grid. This is what my code looks like: import matplotlib.mlab as ml import numpy as np y = np.zeros((512,115)) x = np.zeros((512,115)) # Just random data for this test: data = np.random.randn(512,115) # filling the grid coordinates: for i in range(512): y[i,:]=np.arang...
[ "Comparing your code example to your question's title, I think you're a bit confused... \nIn your example code, you're creating regularly gridded random data and then resampling it onto another regular grid. You don't have irregular data anywhere in your example...\n(Also, the code doesn't run as-is, and you shoul...
[ 75 ]
[]
[]
[ "matplotlib", "python", "resampling" ]
stackoverflow_0003864899_matplotlib_python_resampling.txt
Q: Descriptor that auto-detects the name of another attribute passed to it? Can a descriptor auto-detect the name of an object passed to it? class MyDecorator( object ): def __init__(self, wrapped): # Detect that wrapped's name is 'some_attr' here pass class SomeClass( object ): some_attr = d...
Descriptor that auto-detects the name of another attribute passed to it?
Can a descriptor auto-detect the name of an object passed to it? class MyDecorator( object ): def __init__(self, wrapped): # Detect that wrapped's name is 'some_attr' here pass class SomeClass( object ): some_attr = dict() wrapper = MyDecorator( some_attr )
[ "No, not really. You can hack something together with introspection of call frames, but it's not a nice -- or robust -- solution. (What would you do if SomeClass had two descriptors, some_attr=MyDecorator() and someother_attr=some_attr??)\nIt's better to be explicit:\ndef mydecorator(attr):\n class MyDecorator( ...
[ 2 ]
[ "(Answering my own question for posterity.)\nThis is the best I've come up with so far:\nclass MyDecorator( object ): \n def __init__(self, wrapped): \n import inspect ...
[ -1 ]
[ "descriptor", "metaprogramming", "python" ]
stackoverflow_0003867472_descriptor_metaprogramming_python.txt
Q: How do I abort object instance creation in Python? I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the __new__ method: class a(): def __new__(cls, x): if x == Tru...
How do I abort object instance creation in Python?
I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the __new__ method: class a(): def __new__(cls, x): if x == True: return cls else: rais...
[ "When you override __new__, dont forget to call to super!\n>>> class Test(object):\n... def __new__(cls, x):\n... if x:\n... return super(Test, cls).__new__(cls)\n... else:\n... raise ValueError\n... \n>>> obj1 = Test(True)\n>>> obj2 = Test(False)\nTraceback (most recent ...
[ 22, 7 ]
[]
[]
[ "object", "python" ]
stackoverflow_0003867718_object_python.txt
Q: MatplotLib - Displaying Data under Graph / Plot My graph has Xticks Yticks , Xlabels , Ylabels . My Code firmwareList = self.firmware # Gets the list of all firmwares , this is a list I need to put this firmware data under each bar . Basically i need to put the build version below the X axis for each bar. Exa...
MatplotLib - Displaying Data under Graph / Plot
My graph has Xticks Yticks , Xlabels , Ylabels . My Code firmwareList = self.firmware # Gets the list of all firmwares , this is a list I need to put this firmware data under each bar . Basically i need to put the build version below the X axis for each bar. Example | | | | |...
[ "Maybe I'm misunderstanding things, but based on your comments to @ars, simply putting appending \\n and the firmware version to your xticklabels should do what you want... (I'm posting this as an answer so that I can include an example image) E.g.:\nimport matplotlib.pyplot as plt\nplt.bar(range(3), [10,20,30], a...
[ 2, 1 ]
[]
[]
[ "bar_chart", "graph", "matplotlib", "python" ]
stackoverflow_0003860549_bar_chart_graph_matplotlib_python.txt
Q: Is there a design pattern for this: hide certain methods from certain classes I'm writing a simulation in Python for a dice game, and am trying to find the best way to handle the following situation in an Object Oriented manner. I have a Dice class that handles rolling the dice and reporting things about the dice....
Is there a design pattern for this: hide certain methods from certain classes
I'm writing a simulation in Python for a dice game, and am trying to find the best way to handle the following situation in an Object Oriented manner. I have a Dice class that handles rolling the dice and reporting things about the dice. This class's methods include a roll() method which modifies the dice values, and ...
[ "Have the Player ask the Turn to roll, by calling e.g. turn.roll_dice(). The Turn can then decide whether to roll the dice or e.g. to raise NotYourTurnError.\nYou can't prevent the Player class directly calling die.roll(), although you can make roll private by renaming it __roll. However, since I assume the player ...
[ 1 ]
[]
[]
[ "design_patterns", "oop", "python" ]
stackoverflow_0003867945_design_patterns_oop_python.txt
Q: imageData function in OpenCV with Python I am trying to make some transformations on an image with OpenCV and Python. I started by reading the image with cvLoadImage function, and then I got the image data with imageData function. img = highgui.cvLoadImage("x.png",1) data = img.imageData The problem is, the image...
imageData function in OpenCV with Python
I am trying to make some transformations on an image with OpenCV and Python. I started by reading the image with cvLoadImage function, and then I got the image data with imageData function. img = highgui.cvLoadImage("x.png",1) data = img.imageData The problem is, the imageData function returns a string data and when I...
[ "As you've said, the imageData property returns a binary string containing the \"raw image data\" (I don't recall what format, though). Instead, you should access the image data by indexing into the img object:\n>>> img = cv.CreateImage((10, 10), 8, 1)\n>>> img[0, 0]\n0.0\n>>> img[0, 3] = 1.3\n>>>\n\n", "If you'r...
[ 1, 0, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0003859902_opencv_python.txt
Q: Newbie Confusion regarding classes I have been trying, without success, to control an object within a class from without such class. These are the important bits (not the whole thing!) def GOGO(): ################################################ VFrame.SetStatusText("Ok") # ----> THIS IS WH...
Newbie Confusion regarding classes
I have been trying, without success, to control an object within a class from without such class. These are the important bits (not the whole thing!) def GOGO(): ################################################ VFrame.SetStatusText("Ok") # ----> THIS IS WHAT I AM TRYING TO FIX # ...
[ "You need to instantiate your VFrame class.\nframe = VFrame(parent)\nframe.SetStatusText(\"OK\")\n\nThis is mostly syntactic sugar for\nframe = VFrame(parent)\nVFrame.SetStatusText(frame, \"OK\")\n\nEssentially, you have to tell the computer which VFrame's status text you want to set.\n" ]
[ 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003868019_class_python.txt
Q: how to make a Command Line Interface from a given data model used for GUI HI, guys. I am developing a GUI to configure and call several external programs with Python and I use wxPython for the GUI toolkits. Basically, instead of typing commands and parameters in each shell for each application (one application via...
how to make a Command Line Interface from a given data model used for GUI
HI, guys. I am developing a GUI to configure and call several external programs with Python and I use wxPython for the GUI toolkits. Basically, instead of typing commands and parameters in each shell for each application (one application via one shell), the GUI is visualizing these parameters and call them as subproces...
[ "If you can call your data model's methods from your GUI and they don't depend on anything in the GUI, then yes, you should be able to call those same methods from another GUI, be it CLI, pyGTK or whatever.\n", "Is it possible to have the CLI and GUI at the same time? I mean, can I take the CLI as another view of...
[ 1, 1 ]
[]
[]
[ "command_line_interface", "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0003867500_command_line_interface_python_user_interface_wxpython_wxwidgets.txt
Q: Trouble with Emacs pdb and breakpoints in multi-threaded Python code I am running Emacs 23.2 with python.el and debugging some Python code with pdb. My code spawns a sibling thread using the threading module and I set a breakpoint at the start of the run() method, but the break is never handled by pdb even though...
Trouble with Emacs pdb and breakpoints in multi-threaded Python code
I am running Emacs 23.2 with python.el and debugging some Python code with pdb. My code spawns a sibling thread using the threading module and I set a breakpoint at the start of the run() method, but the break is never handled by pdb even though the code definitely runs and works for all intents and purposes. I was u...
[ "See http://heather.cs.ucdavis.edu/~matloff/158/PLN/ParProcBook.pdf, there's a section on multithreaded debugging.\n\n3.6.1 Using PDB to Debug Threaded Programs\nUsing PDB is a bit more complex when threads are involved. One cannot, for instance, simply do something\nlike this:\npdb.py buggyprog.py\nbecause the chi...
[ 1, 1 ]
[]
[]
[ "emacs", "multithreading", "pdb", "python" ]
stackoverflow_0003867892_emacs_multithreading_pdb_python.txt
Q: Please Help: IPython for Emacs on Windows crashes Questions Update: Why there is no In[1]: prompt? Please see the following output of IPython command line in Emacs. Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0...
Please Help: IPython for Emacs on Windows crashes
Questions Update: Why there is no In[1]: prompt? Please see the following output of IPython command line in Emacs. Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Int...
[ "Installing pyreadline should help.\n" ]
[ 3 ]
[]
[]
[ "emacs", "ipython", "python", "windows" ]
stackoverflow_0003867236_emacs_ipython_python_windows.txt
Q: Pylons + Mako -- Access POST data from templates How can I access my request.params post data from my Mako template with Pylons? A: Same as in the controller. ${request.params['my_param']} or preferably: ${request.params.get('my_param', '')}
Pylons + Mako -- Access POST data from templates
How can I access my request.params post data from my Mako template with Pylons?
[ "Same as in the controller.\n${request.params['my_param']}\n\nor preferably:\n${request.params.get('my_param', '')}\n\n" ]
[ 2 ]
[]
[]
[ "mako", "pylons", "python", "templates" ]
stackoverflow_0003867426_mako_pylons_python_templates.txt
Q: Is it possible to generate variables from a list? Is it possible to generate variables on the fly from a list? In my program I am using the following instruction: for i in re.findall(r"...(?=-)", str(vr_ctrs.getNodeNames())): tmp_obj = vr_ctrs.getChild(i+"-GEODE") TMP.append([tmp_obj.getPosition(viz.ABS_G...
Is it possible to generate variables from a list?
Is it possible to generate variables on the fly from a list? In my program I am using the following instruction: for i in re.findall(r"...(?=-)", str(vr_ctrs.getNodeNames())): tmp_obj = vr_ctrs.getChild(i+"-GEODE") TMP.append([tmp_obj.getPosition(viz.ABS_GLOBAL)[0], tmp_obj.getPosition(viz.ABS_...
[ "I would suggest that instead of creating variables, that you capture these entries in a dict, using what you would have used as the variable name for the dict keys. Then you can easily navigate through the parsed data by accessing dict.keys(), and you wont have to sort out your variables from other local or globa...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003868191_python.txt
Q: Setuptools : how to use the setup() function within a script (no setup specific command line argument) I'm writing a tool to automatically generate .egg files from python projects. The tool basically discovers some properties to guess the setup options (such as version number etc). Now I would like to call the set...
Setuptools : how to use the setup() function within a script (no setup specific command line argument)
I'm writing a tool to automatically generate .egg files from python projects. The tool basically discovers some properties to guess the setup options (such as version number etc). Now I would like to call the setup() function, with the context bdist_egg. I do as such : if __name__ == '__main__' project_dir = _get_d...
[ "setup(script_args=['bdist_egg'], **config)\n" ]
[ 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0003863082_python_setuptools.txt
Q: How do I replace the current working MySQL database with a .sql file? I'm trying to restore the current working database to the data stored in a .sql file from within Django. Whats the best way to do this? Does django have an good way to do this or do I need to grab the connection string from the settings.py file ...
How do I replace the current working MySQL database with a .sql file?
I'm trying to restore the current working database to the data stored in a .sql file from within Django. Whats the best way to do this? Does django have an good way to do this or do I need to grab the connection string from the settings.py file and send command line mysql commands to do this? Thanks for your help.
[ "Django doesn't have any built-in commands for loading SQL fixtures. If you happen to have it in some sort of serialized file, like JSON, you can use the loaddata command of django-admin or manage.py.\nYou can read about it here.\n", "You can't import sql dumps through django; import it through mysql directly, if...
[ 1, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003866989_django_mysql_python.txt
Q: Creating User Profiles In Python I'm making a small python game with pygame. I'd like to be able to have multiple profiles with different stats, upgrades, etc. My biggest problem is storing this information persistently. I've already thought about MySql but I don't know how I could connect to it and I would pre...
Creating User Profiles In Python
I'm making a small python game with pygame. I'd like to be able to have multiple profiles with different stats, upgrades, etc. My biggest problem is storing this information persistently. I've already thought about MySql but I don't know how I could connect to it and I would prefer some way to be able to distribute ...
[ "You can use the sqlite3 module which comes with python or you could use the shelve module\nYou can use the shelve module as an object database and just save the user classes directly.\nThe sqlite3 module will let you store a relational database in a file. It's used by firefox for example.\n", "sqllite3 will prob...
[ 3, 2 ]
[]
[]
[ "pygame", "python", "user_profile" ]
stackoverflow_0003868385_pygame_python_user_profile.txt
Q: Web.py template error: 'sum' does not exist I use the built in 'sum' function in a web.py templator template and I get the following error: global name 'sum' is not defined Source code is below: $if profs: $for prof in profs: $sum([1, 2, 3]) I can use 'sum' just fine at a Python REPL in the terminal. W...
Web.py template error: 'sum' does not exist
I use the built in 'sum' function in a web.py templator template and I get the following error: global name 'sum' is not defined Source code is below: $if profs: $for prof in profs: $sum([1, 2, 3]) I can use 'sum' just fine at a Python REPL in the terminal. What could be the issue? Thanks, Jacob
[ "Add the functions in a dict and pass as the globals argument to render:\nrender = web.template.render('templates/', globals={'sum': sum})\n\nThen in your template you can just use it:\n$def with (numbers)\n\n<h1>Numbers add to $sum(numbers)</h1>\n\n", "Not all python code is available in template notation, try s...
[ 4, 0 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0001741022_python_web.py.txt
Q: programmatically find and replace content dynamically in a string in python i need to find and replace patterns in a string with a dynamically generated content. lets say i want to find all strings within '' in the string and double the string. a string like: my 'cat' is 'white' should become my 'catcat' is 'whit...
programmatically find and replace content dynamically in a string in python
i need to find and replace patterns in a string with a dynamically generated content. lets say i want to find all strings within '' in the string and double the string. a string like: my 'cat' is 'white' should become my 'catcat' is 'whitewhite' all matches could also appear twice in the string. thank you
[ "Make use of the power of regular expressions. In this particular case:\nimport re\n\ns = \"my 'cat' is 'white'\"\n\nprint re.sub(\"'([^']+)'\", r\"'\\1\\1'\", s) # prints my 'catcat' is 'whitewhite'\n\n\\1 refers to the first group in the regex (called $1 in some other implementations).\n", "It's also pretty eas...
[ 7, 1 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0003868330_python_replace.txt
Q: Grepping for Python processes I'm running a script that executes either: ./ide.py # or python ./ide.py After that I use pstree -p | grep ide.py to check, but I only found a Python process. If I have many Python scripts running, how can I distinguish them from each other? A: Use the -a switch: pstree -p -a to ...
Grepping for Python processes
I'm running a script that executes either: ./ide.py # or python ./ide.py After that I use pstree -p | grep ide.py to check, but I only found a Python process. If I have many Python scripts running, how can I distinguish them from each other?
[ "Use the -a switch:\npstree -p -a\n\nto show process command line arguments.\n", "You need to run the pstree command with the \"-a\" switch to show command line arguments. Here's why:\nAll python scripts are run through the python interpreter... Even if you run them directly (i.e. ./ide.py).\n" ]
[ 2, 0 ]
[]
[]
[ "pid", "process", "python" ]
stackoverflow_0003868792_pid_process_python.txt
Q: Omit iterator in list comprehension? Is there a more elegant way to write the following piece of Python? [foo() for i in range(10)] I want to accumulate the results of foo() in a list, but I don't need the iterator i. A: One way to do this is to use _: [foo() for _ in range(10)] This means exactly the same thi...
Omit iterator in list comprehension?
Is there a more elegant way to write the following piece of Python? [foo() for i in range(10)] I want to accumulate the results of foo() in a list, but I don't need the iterator i.
[ "One way to do this is to use _:\n[foo() for _ in range(10)]\n\nThis means exactly the same thing, but by convention the use of _ indicates to the reader that the index isn't actually used for anything.\nPresumably foo() returns something different every time you call it. If it doesn't, and it returns the same thin...
[ 5, 0 ]
[ "By no means more elegant, but:\n[x() for x in [foo]*10]\n\nI think beyond that you have to go to Ruby ;)\n", "map(lambda _ : foo(), range(10))\nalthough this trades your problem with a meaningless iterator i with a new meaningless argument to the lambda expression.\n" ]
[ -1, -2 ]
[ "list_comprehension", "python" ]
stackoverflow_0003868752_list_comprehension_python.txt
Q: Google App Engine-Ajax refresh from datastore using python I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax. Ajax function <script type="text/javascript" src="http://ajax...
Google App Engine-Ajax refresh from datastore using python
I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax. Ajax function <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> ...
[ "The call to load('/refresh') replaces the contents of the responsecontainer div with the loaded HTML.\nYou therefore need the RefreshPage handler to just return that HTML, and not the whole page. For example, it should use a template which just contains this:\n{% for greeting in greetings %} \n {% if greeting.aut...
[ 8 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003868710_google_app_engine_google_cloud_datastore_python.txt
Q: Sort by 2 fields? is there any hacks or with index.yaml? or geoPT? q = WorldObject.all() # define boundaries # left q.filter('x >=', x) # right q.filter('x <', x + width) # top q.filter('y >=', y) # bottom q.filter('y <', y + height) #q.filter('world', world_key) wobjects = q.fetch(1000) I got an error saying I...
Sort by 2 fields? is there any hacks or with index.yaml? or geoPT?
q = WorldObject.all() # define boundaries # left q.filter('x >=', x) # right q.filter('x <', x + width) # top q.filter('y >=', y) # bottom q.filter('y <', y + height) #q.filter('world', world_key) wobjects = q.fetch(1000) I got an error saying I can't use multiple sorts q = WorldObject.all() q.filter('xy >=', db.Ge...
[ "google's datastore indexes are sequential. furthermore, the datastore refuses to satisfy range queries that require more than one index. You can either implement a GiS index on top of the datastore (hard) or just do the range query on one axis and exclude out of range results in your application code (easy).\nSo...
[ 2, 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003852532_google_app_engine_python.txt
Q: Passing variables between modules I'm wonder why this simple code doesn't work. In main.py I have def foo(): HTTPHelper.setHost("foo") host = HTTPHelper.host() and in HTTPHelper.py: _host = None def setHost(host): _host = host def host(): return _host But when I step through foo() host becomes No...
Passing variables between modules
I'm wonder why this simple code doesn't work. In main.py I have def foo(): HTTPHelper.setHost("foo") host = HTTPHelper.host() and in HTTPHelper.py: _host = None def setHost(host): _host = host def host(): return _host But when I step through foo() host becomes NoneType, even though I set it on the lin...
[ "Glenn's answer will fix your immediate issue from within a module, but for the sake of giving a man a fishing pole rather than a fish:\nShort Description of the Scoping Rules?\nYou'd do well reading on scopes and Python's LEGB rule.\nScope and domain of existence concepts also apply to programming and analysis in ...
[ 9, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003868928_python.txt
Q: Convert Python string to its ASCII representants How do I convert a string in Python to its ASCII hex representants? Example: I want to result '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' in 001bd47da4f3. A: >>> text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.rstrip('\0'...
Convert Python string to its ASCII representants
How do I convert a string in Python to its ASCII hex representants? Example: I want to result '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' in 001bd47da4f3.
[ ">>> text = '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'.rstrip('\\0')\n>>> print \"\".join(\"%02x\" % ord(c) for c in text)\n001bd47da4f3\n\nAs per martineau's comment, here is the Python 3 way:\n>>> \"\".join(format(ord(c),\"02x\") for c in text)\n\n", "With python 2.x you can ...
[ 6, 5, 4, 2 ]
[ "binascii.hexlify():\nimport binascii\n\nbyte_string = '\\x00\\x1b\\xd4}\\xa4\\xf3\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00' \nprint binascii.hexlify(byte_string.rstrip('\\x00'))\n\n# -> 001bd47da4f3\n\nSee @John Machin's answer.\n" ]
[ -4 ]
[ "python" ]
stackoverflow_0003850531_python.txt
Q: SQL templating engine to mix SQL with dynamic language? (similar to Ruby's erb) Has anyone comes across a SQL templating engine which allows one to mix SQL with a dynamic language like Ruby or Python? I'm looking for something similar to Ruby erb templates. For example, in Ruby on Rails you can have various templa...
SQL templating engine to mix SQL with dynamic language? (similar to Ruby's erb)
Has anyone comes across a SQL templating engine which allows one to mix SQL with a dynamic language like Ruby or Python? I'm looking for something similar to Ruby erb templates. For example, in Ruby on Rails you can have various templates for a view: customers.html.erb (html + ruby) customers.js.erb (javascript + ruby)...
[ "Well, I found out that Ruby's erb works just fine for a SQL template. I was able to use it very easily in my Rails 3 project.\nI also found that Python has a templating engine, Cheetah, which can do the same thing.\nReferences\n\nAn Introduction to ERB Templating\n\nClass: ERB (RDoc Documentation)\n\nCheetah - The...
[ 0 ]
[]
[]
[ "erb", "python", "ruby_on_rails", "sql", "templates" ]
stackoverflow_0003866421_erb_python_ruby_on_rails_sql_templates.txt
Q: Python: Overwriting a directory with another directory containing the same files I'm trying to overwrite a directory with another directory that contains the same files. I've tried using distutils.dir_util.copy_tree(src, dst) but it tried to make a directory for dst instead. The objective is to overwrite the direc...
Python: Overwriting a directory with another directory containing the same files
I'm trying to overwrite a directory with another directory that contains the same files. I've tried using distutils.dir_util.copy_tree(src, dst) but it tried to make a directory for dst instead. The objective is to overwrite the directory and its contents silently. Is there any other way to do so?
[ "Edit: This rigamarole is apparently not necessary; see the OP's answer for the reason.\nYou'll probably want to first rename the destination directory to something else. If that goes okay, then copy the source directory to the original name of the destination directory. Then, if that worked, delete the destinati...
[ 1, 0 ]
[]
[]
[ "copy", "overwrite", "python", "windows" ]
stackoverflow_0003869280_copy_overwrite_python_windows.txt
Q: Python: 2.6 and 3.1 string matching inconsistencies I wrote my module in Python 3.1.2, but now I have to validate it for 2.6.4. I'm not going to post all my code since it may cause confusion. Brief explanation: I'm writing a XML parser (my first interaction with XML) that creates objects from the XML file. There ...
Python: 2.6 and 3.1 string matching inconsistencies
I wrote my module in Python 3.1.2, but now I have to validate it for 2.6.4. I'm not going to post all my code since it may cause confusion. Brief explanation: I'm writing a XML parser (my first interaction with XML) that creates objects from the XML file. There are a lot of objects, so I have a 'unit test' that manual...
[ "You are printing i[1:-3] but comparing i[1:-2] in the loop.\n\nVery Important Question\nWhy are you writing code to parse XML when lxml will do all that for you? The point of unit tests is to test your code, not to ensure that the libraries you are using work!\n", "repr() and %r format are your friends ... they ...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003868006_python_string.txt
Q: How do I modify variables in the SocketServer server instance from within a RequestHandler handler instance in Python? Here's the code in question: class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer): __slots__ = ("loaded") class Handler(SocketServer.StreamRequestHandler): def handle(sel...
How do I modify variables in the SocketServer server instance from within a RequestHandler handler instance in Python?
Here's the code in question: class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer): __slots__ = ("loaded") class Handler(SocketServer.StreamRequestHandler): def handle(self): print self.server.loaded # Prints "False" at every call, why? self.server.loaded = True print se...
[ "Forking creates a new process, so you can't modify the server's variables in the original process. Try the ThreadingTCPServer instead:\nimport SocketServer\n\nclass Server(SocketServer.ThreadingTCPServer):\n __slots__ = (\"loaded\")\n\nclass Handler(SocketServer.StreamRequestHandler):\n def handle(self):\n ...
[ 4, 2 ]
[]
[]
[ "python", "python_2.7", "sockets", "socketserver" ]
stackoverflow_0003868132_python_python_2.7_sockets_socketserver.txt
Q: Python: I'm not allowed to raise exception. Are there other elegant python ways? My work place has imposed a rules for no use of exception (catching is allowed). If I have code like this def f1() if bad_thing_happen(): raise Exception('bad stuff') ... return something I could change it to def f1() if bad...
Python: I'm not allowed to raise exception. Are there other elegant python ways?
My work place has imposed a rules for no use of exception (catching is allowed). If I have code like this def f1() if bad_thing_happen(): raise Exception('bad stuff') ... return something I could change it to def f1() if bad_thing_happen(): return [-1, None] ... return [0, something] f1 caller would ...
[ "Exceptions in python are not something to be avoided, and are often a straightforward way to solve problems. Additionally, an exception carries a great deal of information with it that can help quickly locate (via stack trace) and identify problems (via exception class or message).\nWhoever has come up with this b...
[ 3, 1, 1 ]
[]
[]
[ "exception", "python", "raise" ]
stackoverflow_0003869326_exception_python_raise.txt
Q: Simple Image Manipulation with Python What I'm trying to do: I want to give the user the ability to upload a picture that is any size. This image is then resized if it is over 1024 wide or over 768 high. It then resizes the image to be within those bounds, but keeping proportions. Then it adds a semi-transparent w...
Simple Image Manipulation with Python
What I'm trying to do: I want to give the user the ability to upload a picture that is any size. This image is then resized if it is over 1024 wide or over 768 high. It then resizes the image to be within those bounds, but keeping proportions. Then it adds a semi-transparent watermark to the lower right corner, and sav...
[ "\nAs far as resizing goes, I was hoping\nit would have a way to do smart\nresizing (keep proportions).\n\nSeeing as this is probably one or two lines in Python, I don't see why this needs to be in the interface of the library.\n\nAlso, I didn't seem to have much\ncontrol over the quality level when\nsaving it as a...
[ 4, 1, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0003869517_image_python_python_imaging_library.txt
Q: HTTP Proxy Server in Python (with authentication) I needed a simple HTTP proxy server written in Python so I began googling around and found this page. Not all the proxies were working and so I settled for this or this. ..but neither of them support authentication. Has anyone come across a HTTP Proxy Server writte...
HTTP Proxy Server in Python (with authentication)
I needed a simple HTTP proxy server written in Python so I began googling around and found this page. Not all the proxies were working and so I settled for this or this. ..but neither of them support authentication. Has anyone come across a HTTP Proxy Server written in Python that supports authentication? Thanks.
[ "\nUseful for NTLM based authentication\n on windows\n\n\nhttp://ntlmaps.sourceforge.net/\n\n\nSortable comparison of open source\n proxies in Python\n\n\nhttp://proxies.xhaus.com/python/\n\n" ]
[ 1 ]
[]
[]
[ "http", "proxy_server", "python" ]
stackoverflow_0003869839_http_proxy_server_python.txt
Q: how do I monitor stdout with subprocess in python? I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do...
how do I monitor stdout with subprocess in python?
I have a linux application that runs interactively from commandline using stdin to accept commands. I've written a wrapper using subprocess to access stdin while the application is backgrounded. I can now send commands to it using p.stdin.write(command) but how do I go about monitoring its responses?
[ "Read from p.stdout to access the output of the process.\nDepending on what the process does, you may have to be careful to ensure that you do not block on p.stdout while p is in turn blocking on its stdin. If you know for certain that it will output a line every time you write to it, you can simply alternate in a ...
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003869834_python_subprocess.txt
Q: Ruby or Python instead of PHP? I'm considering learning a new language as an alternative to PHP. I'm considering Python and Ruby. Which one is a better language based on the following four criteria, and any other qualifiers you may have? Which is more stable? Which is more scaleable? Which is more secure? Which i...
Ruby or Python instead of PHP?
I'm considering learning a new language as an alternative to PHP. I'm considering Python and Ruby. Which one is a better language based on the following four criteria, and any other qualifiers you may have? Which is more stable? Which is more scaleable? Which is more secure? Which is easier to learn? EDIT: Keeping th...
[ "Both are stable \nBoth are scalable \nboth are as secure \nBoth are easier to learn !!\n\nSo what matters?\nYour taste. Taste them both and proceed with one that seems more palatable :)\n", "These two languages are so similar that any strong preference will be mostly subjective. They are both the correct answer...
[ 19, 3, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "php", "programming_languages", "python", "ruby" ]
stackoverflow_0003809981_php_programming_languages_python_ruby.txt
Q: how to decode a non unicode character in python? I have a string say s = 'Chocolate Moelleux-M\xe8re' When i am doing: In [14]: unicode(s) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) UnicodeDecodeError: 'as...
how to decode a non unicode character in python?
I have a string say s = 'Chocolate Moelleux-M\xe8re' When i am doing: In [14]: unicode(s) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20: ordi...
[ "I have had to face this problem one too many times. The problem that I had contained strings in different encoding schemes. So I wrote a method to decode a string heuristically based on certain features of different encodings. \ndef decode_heuristically(string, enc = None, denc = sys.getdefaultencoding()):\n \"...
[ 11, 4 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003870084_python_unicode.txt
Q: python mechanize javascript submit button problem! im making some script with mechanize.browser module. one of problem is all other thing is ok, but when submit() form,it not working, so i was found some suspicion source part. in the html source i was found such like following. im thinking, loginCheck(this) makin...
python mechanize javascript submit button problem!
im making some script with mechanize.browser module. one of problem is all other thing is ok, but when submit() form,it not working, so i was found some suspicion source part. in the html source i was found such like following. im thinking, loginCheck(this) making problem when submit form. but how to handle this kind ...
[ "You can go through the login process by hand in your browser and check (using e.g. Firebug in firefox, Developer Tools in Chrome etc.) what requests are sent to the site when you hit the OK button. Usually this is a POST request with data taken from the login form. Check what data are sent in this request and exec...
[ 4 ]
[]
[]
[ "mechanize", "python", "urlopen" ]
stackoverflow_0003798550_mechanize_python_urlopen.txt
Q: Django on IronPython I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas? A: Besides the Jeff Hardy blog post on Dj...
Django on IronPython
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
[ "Besides the Jeff Hardy blog post on Django + IronPython mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is Solving the zlib problem which discusses the absence of zlib for IronPython; hence, no eas...
[ 26, 8, 5, 2 ]
[]
[]
[ "django", "ironpython", "python" ]
stackoverflow_0000425990_django_ironpython_python.txt
Q: Python drawing cumulative plot (matplotlib) I have not used matplotlib, but looks like it is main library for drawing plots. I want to draw CPU usage plot. I have background processes each minute making record (date, min_load, avg_load, max_load). date could be timestamp or nice formatted date. I want to draw diag...
Python drawing cumulative plot (matplotlib)
I have not used matplotlib, but looks like it is main library for drawing plots. I want to draw CPU usage plot. I have background processes each minute making record (date, min_load, avg_load, max_load). date could be timestamp or nice formatted date. I want to draw diagram which show min_load, avg_load and max_load on...
[ "Try:\nfrom matplotlib.dates import strpdate2num, epoch2num\nimport numpy as np\nfrom pylab import figure, show, cm\n\ndatefmt = \"%a %b %d %H:%M:%S CEST %Y\"\ndatafile = \"cpu.dat\"\n\ndef parsedate(x):\n global datefmt\n try:\n res = epoch2num( int(x) )\n except:\n try:\n res = s...
[ 2 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0003869866_matplotlib_plot_python.txt
Q: I'm looking for an example on how to use select.select() with subprocess to monitor stdout Basically, I have an application that is loaded using p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) I can send it commands using p.stdin.write() without any trouble, but I...
I'm looking for an example on how to use select.select() with subprocess to monitor stdout
Basically, I have an application that is loaded using p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) I can send it commands using p.stdin.write() without any trouble, but I need to monitor stdout for server responses. this whole thing is running inside a tcp server, s...
[ "A non-None timeout parameter will make sure that select() doesn't block.\n" ]
[ 0 ]
[]
[]
[ "python", "select", "subprocess" ]
stackoverflow_0003870453_python_select_subprocess.txt
Q: Google App Engine Python: How to display textarea value in mail I have a html form with <textarea name="message"></textarea> and I get the value by message = self.request.get('message'). Then I do mail api message = mail.EmailMessage(sender="abc@domain.com", subject="Testing") message.to = 'bcd@domain.com' messag...
Google App Engine Python: How to display textarea value in mail
I have a html form with <textarea name="message"></textarea> and I get the value by message = self.request.get('message'). Then I do mail api message = mail.EmailMessage(sender="abc@domain.com", subject="Testing") message.to = 'bcd@domain.com' message.html = """The Message: %s """ % (message) message.send() The probl...
[ "You're using the variable name 'message' for both the original text in the textarea, and the email you're sending. Try this:\ntext = self.request.get('message')\nmessage = mail.EmailMessage(sender=\"abc@domain.com\", subject=\"Testing\") \nmessage.to = 'bcd@domain.com' \nmessage.html = \"\"\"The Message: %s \"\"\"...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003870279_google_app_engine_python.txt
Q: How to parse xsd:dateTime format? Values of type xsd:dateTime can have a variety of forms, as described in RELAX NG. How can I parse all the forms into either time or datetime objects? A: It's actually a pretty restricted format, especially compared to all of ISO 8601. Using a regex is mostly the same as using ...
How to parse xsd:dateTime format?
Values of type xsd:dateTime can have a variety of forms, as described in RELAX NG. How can I parse all the forms into either time or datetime objects?
[ "It's actually a pretty restricted format, especially compared to all of ISO 8601. Using a regex is mostly the same as using strptime plus handling the offset yourself (which strptime doesn't do).\nimport datetime\nimport re\n\ndef parse_timestamp(s):\n \"\"\"Returns (datetime, tz offset in minutes) or (None, Non...
[ 2, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002211362_python_xml.txt
Q: Trouble getting code parameter on facebook oauth callback I'm writing a Django app requesting permission to post on facebook. I can access authorization and callback, but I can't get the parameter 'code' that facebook needs to continue with oauth. def connect_fb(request): return redirect("https://graph.facebook.co...
Trouble getting code parameter on facebook oauth callback
I'm writing a Django app requesting permission to post on facebook. I can access authorization and callback, but I can't get the parameter 'code' that facebook needs to continue with oauth. def connect_fb(request): return redirect("https://graph.facebook.com/oauth/authorize?" +"client_id=MY_ID&" ...
[ "I've used django-facebook-oauth in the past, but if you really want to roll your own solution then I'd suggest just looking through their source.\nFrom just glancing through it, the only thing I can see you doing differently is the\n&type=user_agent&display=popup\n\nin the URL. The app I linked you to doesn't appe...
[ 1, 0 ]
[]
[]
[ "django", "facebook", "oauth", "python" ]
stackoverflow_0003866263_django_facebook_oauth_python.txt
Q: How to handle call to __setattr__ from __init__? I have written a class that will be used to store parameters in a convenient way for pickling. It overloads __setattr__ for convenient access. It also uses a list to remember the order in which attributes where added, so that the iteration order is predictable and c...
How to handle call to __setattr__ from __init__?
I have written a class that will be used to store parameters in a convenient way for pickling. It overloads __setattr__ for convenient access. It also uses a list to remember the order in which attributes where added, so that the iteration order is predictable and constant. Here it is: class Parameters(object): def...
[ "yes.\nhave it call super(Parameters, self).__setattr__() instead.\nclass Parameters(object):\n def __init__(self):\n super(Parameters, self).__setattr__('paramOrder', [])\n\n # etc.\n\nOr am I missing something?\nAnother alternative is to just go straight to __dict__\nclass Parameters(object):\n de...
[ 12, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003870982_python.txt
Q: Pylons - Handling GET and POST requests What's the best way to handle form POST data in my Pylons app? I've tried: Having a seperate GET method and a POST method with a rest.restrict('post') decorator. Problem -- if there were validation errors then you can't redisplay the form with the data which the user entere...
Pylons - Handling GET and POST requests
What's the best way to handle form POST data in my Pylons app? I've tried: Having a seperate GET method and a POST method with a rest.restrict('post') decorator. Problem -- if there were validation errors then you can't redisplay the form with the data which the user entered because you have to redirect back to the GE...
[ "\nHaving it all in one method, and detecting if the form has been posted via a check on request.method. This works okay, but it seems clumsy to have if request.method == 'post': ... else: ...\n\nI am not sure why you describe this as clumsy. Switching on request method is a valid idiom in the web app world across ...
[ 2 ]
[]
[]
[ "pylons", "python", "validation" ]
stackoverflow_0003871145_pylons_python_validation.txt
Q: What security issues need to be addressed when working with Google App Engine? I've been considering using Google App Engine for a few hobby projects. While they won't be handling any sensitive data, I'd still like to make them relatively secure for a number of reasons, like learning about security, legal, etc. Wh...
What security issues need to be addressed when working with Google App Engine?
I've been considering using Google App Engine for a few hobby projects. While they won't be handling any sensitive data, I'd still like to make them relatively secure for a number of reasons, like learning about security, legal, etc. What security issues need to be addressed when working with Google App Engine? Are the...
[ "“Sanitising” input is not the way to avoid query-injection and markup-injection problems. Using the correct form of escaping at the output stage is... or, even better, using a higher-level tool that deals with it for you.\nSo for preventing query-injection against GQL, use the parameter-binding interface of GqlQue...
[ 7 ]
[ "In general there are the same issues. In addition google \"knows\" your code and can in theory monitor anything what the code is doing. Therefore it is very difficult if you want to prevent them from reading your data.\nBut i don't believe they have time and resources to monitor your code and data that close.\n" ]
[ -2 ]
[ "google_app_engine", "python", "security", "web_applications" ]
stackoverflow_0003871012_google_app_engine_python_security_web_applications.txt
Q: Is there a way to emulate the __prepare__ special method of a Python 3-metaclass in Python 2.5? In my project I have to stick to Python 2.5 (Google App Engine). Somewhere in the application (actually a framework), I have to keep track which variables are defined and in which order they are defined, in other words ...
Is there a way to emulate the __prepare__ special method of a Python 3-metaclass in Python 2.5?
In my project I have to stick to Python 2.5 (Google App Engine). Somewhere in the application (actually a framework), I have to keep track which variables are defined and in which order they are defined, in other words I would like to intercept whenever an assignment operator is processed. Using Python 3, I would defin...
[ "You can wrap the variables you populate your classes with with a wrapper that internally keeps a counter and assigns an increasing value. The wrapper may be subclassed for tagging or to add behaviour to the variables. You would use the variable value to order them and a regular Python 2 metaclass to intercept the ...
[ 3 ]
[ "One place to start is by looking at PEP-3115 and reading about the \"current\" behavior, e.g. the behavior that was current before Python 3 was implemented.\n" ]
[ -1 ]
[ "metaclass", "python", "python_3.x" ]
stackoverflow_0003870282_metaclass_python_python_3.x.txt
Q: Reading from a file using pickle and for loop in python I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. ...
Reading from a file using pickle and for loop in python
I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. actually I noticed that it only load the my first list into m...
[ "How about this:\nlists = []\ninfile = open('yourfilename.pickle', 'r')\nwhile 1:\n try:\n lists.append(pickle.load(infile))\n except (EOFError, UnpicklingError):\n break\ninfile.close()\n\n" ]
[ 10 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0003871388_pickle_python.txt
Q: Avoid OpenERP audittrail bug I'd like to manage OpenERP user's activity by installing the audittrail module. After creating some rules ( define which user, which object and which activity (create, update..) will be monitored). I update a product to see it works. When I've tried to update a product i got the syste...
Avoid OpenERP audittrail bug
I'd like to manage OpenERP user's activity by installing the audittrail module. After creating some rules ( define which user, which object and which activity (create, update..) will be monitored). I update a product to see it works. When I've tried to update a product i got the system error. Seeing the log, I get [20...
[ "t would be important to see the source code to understand whats going on.\nBut from what you have posted it looks like the previous cursor was not closed explicitly.\ncr = sqldb.db_connect(dbname).cursor()\n.........\ncr.close()\ncr = None\n\nI would suggest that you hack audittrail.py to find where ever you are c...
[ 4, 2, 1 ]
[]
[]
[ "audit_trail", "openerp", "python" ]
stackoverflow_0003606418_audit_trail_openerp_python.txt
Q: HttpLib2 throws error when trying to do a request to couchdb I'm building an application in Python2.6 that needs to get data from CouchDb. I'm using CouchDB-0.8-py2.6 to connect to the database. I'm using this code: import couchdb server = couchdb.Server(url='http://localhost:5984/', full_commit=True, session=None...
HttpLib2 throws error when trying to do a request to couchdb
I'm building an application in Python2.6 that needs to get data from CouchDb. I'm using CouchDB-0.8-py2.6 to connect to the database. I'm using this code: import couchdb server = couchdb.Server(url='http://localhost:5984/', full_commit=True, session=None) db = server['databaseName'] doc = db['docId'] value = doc['value...
[ "You're using a different version of CouchDB on the server - CouchDB-0.7dev_r199. CouchDB does not use httplib2 anymore, so if you get your development and server environments roughly the same the problem is quite likely to disappear.\n" ]
[ 1 ]
[]
[]
[ "couchdb", "httplib2", "python" ]
stackoverflow_0003871464_couchdb_httplib2_python.txt
Q: Django model inheritance problem. How to solve? I have an existing app with the following model class Contact(models.Model): lastname = models.CharField(max_length=200) firstname = models.CharField(max_length=200) ... class Journalist(Contact): pass I have a Contact in my database and I would...
Django model inheritance problem. How to solve?
I have an existing app with the following model class Contact(models.Model): lastname = models.CharField(max_length=200) firstname = models.CharField(max_length=200) ... class Journalist(Contact): pass I have a Contact in my database and I would like that it becomes a Journalist. In raw sql, it s...
[ "One way to solve this is (without changing your model structure) to set the contact_ptr attribute of the Journalist instance to the appropriate Contact instance. For e.g.\ncontact = Contact.objects.get(pk = 25624)\njournalist = Journalist(contact_ptr = contact)\njournalist.save()\n\nThis becomes easier to understa...
[ 3, 2, 0 ]
[]
[]
[ "django", "django_models", "django_orm", "inheritance", "python" ]
stackoverflow_0003871094_django_django_models_django_orm_inheritance_python.txt
Q: Alternate ways of saving a list into a file in Python I am trying to a save a list into a file in a way that when I load and read the file again I get my lists as they are. In other words,the datatype doesn't change while saving and loading. Because right now, I use "write" to save my list into a file, and when I ...
Alternate ways of saving a list into a file in Python
I am trying to a save a list into a file in a way that when I load and read the file again I get my lists as they are. In other words,the datatype doesn't change while saving and loading. Because right now, I use "write" to save my list into a file, and when I try to load it back into memory I get strings rather than r...
[ "If your data is only a list whose items are basic types (e.g. str, unicode, int, float) and lists or dicts whose elements are etc etc, then you can use json; this is portable across languages (is that your problem with pickle?).\nUpdate after question edited \"\"\"my problem with pickle is that I have to add my li...
[ 4, 1, 0 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0003868675_file_list_python.txt
Q: Python: Check when a cmd command completes its job When I execute a python script using subprocess.Popen(script, shell=True) in another python script, is it possible to alert python when the script completes running before executing other functions? On a side note, can I get real-time output of the executed pyth...
Python: Check when a cmd command completes its job
When I execute a python script using subprocess.Popen(script, shell=True) in another python script, is it possible to alert python when the script completes running before executing other functions? On a side note, can I get real-time output of the executed python script? I can only get output from it doing command>o...
[ "When you create a subprocess with Popen, it returns a subprocess.Popen object that has several methods for accessing subprocess status and data:\n\nYou can use poll() to determine whether a subprocess has finished. None indicates that the process has ended.\nOutput from a script while its running can be retrieved ...
[ 3, 1 ]
[]
[]
[ "python", "real_time" ]
stackoverflow_0003871209_python_real_time.txt
Q: Python's StringIO for Clojure Is there something equivalent to Python's StingIO for Clojure? I'm trying to write a report generating/literate programming system similar to Sweave and Pweave for Clojure. I'm currently using a temp file, but I'd prefer using something similar to StringIO. A: with-out-str is pretty...
Python's StringIO for Clojure
Is there something equivalent to Python's StingIO for Clojure? I'm trying to write a report generating/literate programming system similar to Sweave and Pweave for Clojure. I'm currently using a temp file, but I'd prefer using something similar to StringIO.
[ "with-out-str is pretty handy.\n(let [foo (with-out-str (println \"Hello world!\"))] \n foo)\n\nMore documentation here\n", "java.io.StringWriter: http://download.oracle.com/javase/6/docs/api/java/io/StringWriter.html\n" ]
[ 5, 2 ]
[]
[]
[ "clojure", "python", "stringio" ]
stackoverflow_0003863921_clojure_python_stringio.txt
Q: Django admin site: how to create a single page for global settings? I would like to create a single page in the admin site of django where I can change some global variables of the website (title of the website, items in the navigation menu, etc). At the moment I have them coded as context processors but I would l...
Django admin site: how to create a single page for global settings?
I would like to create a single page in the admin site of django where I can change some global variables of the website (title of the website, items in the navigation menu, etc). At the moment I have them coded as context processors but I would like to make them editable. Something similar to what happens in WordPress...
[ "django-preferences does exactly what you are looking for. The implementation is a bit hacky (particularly the setting of __module__ on the model class to trick Django into thinking it was loaded from a different app), but it works.\n", "This sounds like what the sites framework is intended to help with.\nhttp://...
[ 5, 3, 2 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0003868939_django_django_admin_django_forms_python.txt
Q: Parsing facebook oauth access_token string Facebook returns access tokens in the form of a string: 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375' Is there a way to parse the access_token without using regex? I'm afraid using regex wou...
Parsing facebook oauth access_token string
Facebook returns access tokens in the form of a string: 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375' Is there a way to parse the access_token without using regex? I'm afraid using regex would be unaccurate since I don't know what FB uses...
[ "Facebook access_token and expires are returned as key=value pairs. One way to parse them is to use the parse_qs function from the urlparse module. \n>>> import urlparse\n>>> s = 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'\n>>> urlpars...
[ 2 ]
[]
[]
[ "facebook", "google_app_engine", "oauth", "python", "regex" ]
stackoverflow_0003872648_facebook_google_app_engine_oauth_python_regex.txt
Q: How to update status with myspace python api I'm using myspace python api to post update status, but its return 401, Can't figure it out ,How to deal with that. A: HTTP 401 status code suggests that you need some credentials to perform that POST operation.
How to update status with myspace python api
I'm using myspace python api to post update status, but its return 401, Can't figure it out ,How to deal with that.
[ "HTTP 401 status code suggests that you need some credentials to perform that POST operation.\n" ]
[ 1 ]
[]
[]
[ "api", "myspace", "python" ]
stackoverflow_0003872894_api_myspace_python.txt