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: C++ library for python - linking problems I have written a c++ library, and I'm trying to make python bindings to it with boost::python. This is simplified version of file, where I define them: #include <boost/python.hpp> #include <matrix.h> #include <string> using namespace boost::python; class MatrixForPython ...
C++ library for python - linking problems
I have written a c++ library, and I'm trying to make python bindings to it with boost::python. This is simplified version of file, where I define them: #include <boost/python.hpp> #include <matrix.h> #include <string> using namespace boost::python; class MatrixForPython : public Matrix{ public: MatrixForPython(...
[ "\nundefined symbol: _ZN6MatrixC2ERKS_\n\nThis is because you are missing the Matrix::Matrix(const Matrix&) copy constructor in your shared library:\nsamm@mac ~> echo _ZN6MatrixC2ERKS_ | c++filt \nMatrix::Matrix(Matrix const&)\nsamm@mac ~> \n\n" ]
[ 2 ]
[]
[]
[ "boost", "c++", "cmake", "python" ]
stackoverflow_0008467102_boost_c++_cmake_python.txt
Q: importing matplotlib in eclipse I'm running pydev in Ecplise (Python 2.7). Numpy and tkinter work fine, but I installed matplotlib and for some reason when I try from matplotlib import * I get the response it's not found. I added the folder with the module to PythonPath but keep getting same message. What am I doi...
importing matplotlib in eclipse
I'm running pydev in Ecplise (Python 2.7). Numpy and tkinter work fine, but I installed matplotlib and for some reason when I try from matplotlib import * I get the response it's not found. I added the folder with the module to PythonPath but keep getting same message. What am I doing wrong?
[ "from pydev tutorial (in my experience, the two most common cases related with your problem):\n1)\n\nThe most common error is having a problem in the environment variables\n used from the shell that spawned Eclipse, in a way that for some\n reason when getting the variables of one interpreter, it gathers the\n i...
[ 6 ]
[]
[]
[ "matplotlib", "pydev", "python" ]
stackoverflow_0008467583_matplotlib_pydev_python.txt
Q: Execute script from within python I have a playgame.cmd file I would like to exceute from within my python code. It is a genetic algorithm that runs the game (input is individual), waits for the game to run with that individual, then parses data from the game log to output the fitness of that individual. Inside th...
Execute script from within python
I have a playgame.cmd file I would like to exceute from within my python code. It is a genetic algorithm that runs the game (input is individual), waits for the game to run with that individual, then parses data from the game log to output the fitness of that individual. Inside the .cmd file (shouldn't matter I don't t...
[ "If you want to launch a .cmd file from within a Python script which then launches two more copies of Python within the .cmd, I think you need to slow down, take a step back, and think about how to just get all this stuff to run within one Python interpreter. But, the direct answer to your question is to use os.sy...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008467839_python.txt
Q: How to call functions/methods inside objects in python Here is my code. How do I execute the print_point line? Edited to work. Thank you class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def distance_from_origin(self): return ((self.x **2) + (self.y **2)) **.5 de...
How to call functions/methods inside objects in python
Here is my code. How do I execute the print_point line? Edited to work. Thank you class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def distance_from_origin(self): return ((self.x **2) + (self.y **2)) **.5 def print_point(p): print '(%s, %s)' % (str(p.x), str(...
[ "It's not clear what you want, since you've got the indentation wrong. Is print_point part of the class?\nIf so, you got self right in distance_from_origin, but perhaps not in print_point:\ndef print_point(self):\n print '(%f, %f)' % (self.x, self.y)\n\nIt is legal, but a bad idea, to use a different name for th...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008467683_python.txt
Q: Python - Change the socket address of existing .exe application How do I with python change the port and address information of a client .exe application? So instead of programming your own client where you assign it initially, you change the ip information of an already existing client using python. An ip-changer...
Python - Change the socket address of existing .exe application
How do I with python change the port and address information of a client .exe application? So instead of programming your own client where you assign it initially, you change the ip information of an already existing client using python. An ip-changer, I suppose :) (Windows, python 2.6)
[ "If your application has a host name buried in it that it tries to contact, your simplest approach is to leave the port alone and modify your /etc/hosts file (C:/Windows/ System32/drivers/etc/hosts on Windows) so that the host name resolves to 127.0.0.1.\nFor instance:\n127.0.0.1 tibia.com\n\n" ]
[ 0 ]
[]
[]
[ "client", "ip", "python", "sockets", "windows" ]
stackoverflow_0008467791_client_ip_python_sockets_windows.txt
Q: Possible to use conditional execution in Fabric? Is it possible to ask fabric to perform actions conditionally? This should be fairly trivial, because it's "just Python", but I'm not 100% sure how to run commands and capture their return code or output. As an example, how would I have behaviour that is conditional...
Possible to use conditional execution in Fabric?
Is it possible to ask fabric to perform actions conditionally? This should be fairly trivial, because it's "just Python", but I'm not 100% sure how to run commands and capture their return code or output. As an example, how would I have behaviour that is conditional on the value of an environment variable in the host?
[ "It's pretty straightforward:\n@hosts('host.example.com')\ndef task():\n if run('echo $SOME_VAR') == 'some value':\n run('some_other_command.sh')\n\n" ]
[ 6 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0008467856_fabric_python.txt
Q: how to read a file that can be saved as either ansi or unicode in python? I have to write a script that support reading of a file which can be saved as either Unicode or Ansi (using MS's notepad). I don't have any indication of the encoding format in the file, how can I support both encoding formats? (kind of a ge...
how to read a file that can be saved as either ansi or unicode in python?
I have to write a script that support reading of a file which can be saved as either Unicode or Ansi (using MS's notepad). I don't have any indication of the encoding format in the file, how can I support both encoding formats? (kind of a generic way of reading files with out knowing the format in advanced).
[ "MS Notepad gives the user a choice of 4 encodings, expressed in clumsy confusing terminology:\n\"Unicode\" is UTF-16, written little-endian. \"Unicode big endian\" is UTF-16, written big-endian. In both UTF-16 cases, this means that the appropriate BOM will be written. Use utf-16 to decode such a file.\n\"UTF-8\"...
[ 16, 3 ]
[]
[]
[ "ansi", "python", "unicode", "utf_8" ]
stackoverflow_0008466460_ansi_python_unicode_utf_8.txt
Q: urllib2.urlopen() returning error 500 on a particular URL with GAE I'm having trouble using the urllib2.urlopen on a particular URL on GAE. When I run the same code on using Eclipse, I'm able to retrieve the website data, but when I try it with a GAE implementation, I get 'Status 500 Internal Server Error'. On the...
urllib2.urlopen() returning error 500 on a particular URL with GAE
I'm having trouble using the urllib2.urlopen on a particular URL on GAE. When I run the same code on using Eclipse, I'm able to retrieve the website data, but when I try it with a GAE implementation, I get 'Status 500 Internal Server Error'. On the ordinary Python app, I have the following code that works fine. query2 ...
[ "As the exception indicates, it's failing because the outgoing HTTP request timed out. Instead of using urllib2, use URLFetch directly, and pass the deadline argument to the fetch function with a longer deadline.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008458539_google_app_engine_python.txt
Q: Display posts from Wordpress blog in webpage hosted on google app engine I am trying to display titles of the posts (along with date and link to the post) from my wordpress blog on my webpage which is hosted on google app engine. Can I import python's xmlrpc module and use getRecentPosts function to get the list o...
Display posts from Wordpress blog in webpage hosted on google app engine
I am trying to display titles of the posts (along with date and link to the post) from my wordpress blog on my webpage which is hosted on google app engine. Can I import python's xmlrpc module and use getRecentPosts function to get the list of the posts? How can I get the date and link of the post and display it on my ...
[ "From: http://ttm.appspot.com/blog/2008/12/20/wordpress-xml-rpc-getrecentposts-behaviour/\nHere's some code that will call getRecentPosts and output it in the response:\nusername = 'yourUser'\npassword = 'yourPassword'\nxmlrpc_url = \"http://www.yourblog.net/wordpress/xmlrpc.php\"\nsp = xmlrpclib.ServerProxy(xmlrpc...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python", "wordpress" ]
stackoverflow_0008456836_google_app_engine_python_wordpress.txt
Q: How can a zope.interface.Interface require implementation of a list of objects that implement another interface? In the following example, I want objects implementing IParentInterface to be required to supply a mycollection attribute that is a list of objects implementing IChildInterface. from zope.schema import T...
How can a zope.interface.Interface require implementation of a list of objects that implement another interface?
In the following example, I want objects implementing IParentInterface to be required to supply a mycollection attribute that is a list of objects implementing IChildInterface. from zope.schema import Text, List from zope.interface import Interface class IChildInterface(Interface): someField = Text() class IParen...
[ "This should work:\nfrom zope.schema import Text, List, Object\nfrom zope.interface import Interface\n\nclass IChildInterface(Interface):\n someField = Text()\n\nclass IParentInterface(Interface):\n mycollection = List(value_type=Object(title=u'Child',\n schema=IChildI...
[ 4 ]
[]
[]
[ "interface", "python", "schema", "validation", "zope" ]
stackoverflow_0008467922_interface_python_schema_validation_zope.txt
Q: In Python, when iterating through items in list, how to start at 0 if end is reached? I am iterating through a list in Python. mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] i = 0 while i <= 27: print mylist[i] i +=1 I am looking for a simple / elegant solutition so that when i is 11, it...
In Python, when iterating through items in list, how to start at 0 if end is reached?
I am iterating through a list in Python. mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] i = 0 while i <= 27: print mylist[i] i +=1 I am looking for a simple / elegant solutition so that when i is 11, it grabs 'a' from mylist. I'd rather not use a complex set of if statments to check if the e...
[ "Try modulo math:\nmylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']\ni = 0\nwhile i <= 27:\n print mylist[i % len(mylist)]\n i +=1\n\n", "http://docs.python.org/library/itertools.html#itertools.cycle\n", "In the spirit of Falmarri's answer, I can't resist adding this:\ndef modrange(first, ...
[ 10, 4, 0 ]
[]
[]
[ "iteration", "list", "loops", "python" ]
stackoverflow_0008468082_iteration_list_loops_python.txt
Q: Python: os.chdir() not working within a for loop? I'm trying to get a homemade path navigation function working - basically I need to go through one folder, and explore every folder within it, running a function within each folder. I reach a problem when I try to change directories within a for loop. I've got this...
Python: os.chdir() not working within a for loop?
I'm trying to get a homemade path navigation function working - basically I need to go through one folder, and explore every folder within it, running a function within each folder. I reach a problem when I try to change directories within a for loop. I've got this "findDirectories" function: def findDirectories(list):...
[ "Well, you don't post the traceback of the actual error but clearly it doesn't work as you have specified y as a relative path.\nThus it may be able to change to y in the first iteration of the loop, but in the second it will be trying to change to a subdirectory of y that is also called y\nWhich you probably do no...
[ 2, 1 ]
[]
[]
[ "chdir", "python" ]
stackoverflow_0008468630_chdir_python.txt
Q: Create model instance from another model's instance in Django without link to original instance source I'm making a game. The player's inventory holds weapons. The weapons are instances of the Weapon model. When a new weapon is created a weapon template is selected at random from the Template model instances. Than...
Create model instance from another model's instance in Django without link to original instance source
I'm making a game. The player's inventory holds weapons. The weapons are instances of the Weapon model. When a new weapon is created a weapon template is selected at random from the Template model instances. Than all fields are copied to create the weapon instance. To do so I use this function: class ItemModel(models.M...
[ "I think you should not use inheritance between weapon and weapontemplate, django treats inheritance as OneToOneRelationship. If you want to make your code more DRY you may try to make things that way:\nfrom django.db import models\nfrom django.db.models.manager import Manager\n\n\nclass WeaponBase(models.Model):\n...
[ 0 ]
[]
[]
[ "database_design", "django", "django_models", "python" ]
stackoverflow_0008466502_database_design_django_django_models_python.txt
Q: A more pythonic way to build a class based on a string (how not to use eval) OK. So I've got a database where I want to store references to other Python objects (right now I'm using to store inventory information for person stores of beer recipe ingredients). Since there are about 15-20 different categories of ing...
A more pythonic way to build a class based on a string (how not to use eval)
OK. So I've got a database where I want to store references to other Python objects (right now I'm using to store inventory information for person stores of beer recipe ingredients). Since there are about 15-20 different categories of ingredients (all represented by individual SQLObjects) I don't want to do a bunch of ...
[ "To get the value of a global by name; Use:\nglobals()[self.inventory_type]\n\n" ]
[ 3 ]
[]
[]
[ "python", "sqlobject" ]
stackoverflow_0008468691_python_sqlobject.txt
Q: Why is PyGILState_Release throwing Fatal Python Errors ANSWERED Ok, I solved this issue. Its all in how you initialize the thread state. You don't need to use ReleaseLock at all. Simply add InitThreads call to your module definition: BOOST_PYTHON_MODULE(ModuleName) { PyEval_InitThreads(); ... } Ok, I hav...
Why is PyGILState_Release throwing Fatal Python Errors
ANSWERED Ok, I solved this issue. Its all in how you initialize the thread state. You don't need to use ReleaseLock at all. Simply add InitThreads call to your module definition: BOOST_PYTHON_MODULE(ModuleName) { PyEval_InitThreads(); ... } Ok, I have attempted to diagnose this problem for hours and poured t...
[ "Ok, I solved this issue. Its all in how you initialize the thread state. You don't need to use ReleaseLock at all. Simply add InitThreads call to your module definition:\nBOOST_PYTHON_MODULE(ModuleName)\n{\n PyEval_InitThreads();\n\n ...\n}\n\n" ]
[ 9 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0008451334_boost_boost_python_c++_python.txt
Q: python map string split list I am trying to map the str.split function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with map in python? For example let's assume we have a list like this: a = ['2011-12-22 46:31:11','2011-...
python map string split list
I am trying to map the str.split function to an array of string. namely, I would like to split all the strings in a string array that follow the same format. Any idea how to do that with map in python? For example let's assume we have a list like this: a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09...
[ "Though it isn't well known, there is a function designed just for this purpose, operator.methodcaller:\n>>> from operator import methodcaller\n>>> a = ['2011-12-22 46:31:11','2011-12-20 20:19:17', '2011-12-20 01:09:21']\n>>> list(map(methodcaller(\"split\", \" \"), a))\n[['2011-12-22', '46:31:11'], ['2011-12-20', ...
[ 59, 40, 10, 9, 2 ]
[]
[]
[ "functional_programming", "parsing", "python", "string" ]
stackoverflow_0008461230_functional_programming_parsing_python_string.txt
Q: How do I store a Python object in memory for use by different processes? Here's the situation: I have a massive object that needs to be loaded into memory. So big that if it is loaded in twice it will go beyond the available memory on my machine (and no, I can't upgrade the memory). I also can't divide it up into ...
How do I store a Python object in memory for use by different processes?
Here's the situation: I have a massive object that needs to be loaded into memory. So big that if it is loaded in twice it will go beyond the available memory on my machine (and no, I can't upgrade the memory). I also can't divide it up into any smaller pieces. For simplicity's sake, let's just say the object is 600 MB...
[ "http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes\nLook for shared memory, or Server process. After re-reading your post Server process sounds closer to what you want.\nhttp://en.wikipedia.org/wiki/Shared_memory\n", "\nThere must be someway to store a Python object in memory (a...
[ 5, 2, 1 ]
[]
[]
[ "memory", "python", "python_internals", "web" ]
stackoverflow_0008469272_memory_python_python_internals_web.txt
Q: Formatting json converted datetime string returned from github v3 in python I have a python application that decodes json from github api v3. After the decode, my unicode date/time string looks like this: u'2011-12-11T22:37:18Z' How do I format this using something like strftime or the like? A: import datetime d...
Formatting json converted datetime string returned from github v3 in python
I have a python application that decodes json from github api v3. After the decode, my unicode date/time string looks like this: u'2011-12-11T22:37:18Z' How do I format this using something like strftime or the like?
[ "import datetime\ndatetime.datetime.strptime('2011-12-11T22:37:18Z', '%Y-%m-%dT%H:%M:%SZ')`\n\n" ]
[ 3 ]
[]
[]
[ "python", "strftime" ]
stackoverflow_0008469629_python_strftime.txt
Q: Handling numbers that are prices with GAE + WTForms I use Google app engine (python) and Jinja2 and I'd like to take advantage of webapp2's feature for currency internationalization and localization ie store prices as a number and make the correct formatting using the builtin i18n method of webapp2. Then first I m...
Handling numbers that are prices with GAE + WTForms
I use Google app engine (python) and Jinja2 and I'd like to take advantage of webapp2's feature for currency internationalization and localization ie store prices as a number and make the correct formatting using the builtin i18n method of webapp2. Then first I must have the correct data type for my prices. I'm migrat...
[ "Please have a look at the issue number 6595 and also this. If your problem lies in this area it could be solved by the patch else I would suggest to capture the area in an except block and dump the variable esp the individual ordinal number's to make sure, what is passed to the Decimal is a legitimate acceptable c...
[ 1 ]
[]
[]
[ "google_app_engine", "internationalization", "jinja2", "money_format", "python" ]
stackoverflow_0008469605_google_app_engine_internationalization_jinja2_money_format_python.txt
Q: What should when a parent has a static class and a child does not? I have code that looks like this: Class Parent: def someMethod(self): return 42 Class Child(Parent): def someMethod(self): print self.answer The parent has a method that could be static, and (to get rid of Pylint warnings)...
What should when a parent has a static class and a child does not?
I have code that looks like this: Class Parent: def someMethod(self): return 42 Class Child(Parent): def someMethod(self): print self.answer The parent has a method that could be static, and (to get rid of Pylint warnings) I want to add a @staticmethod decorator, but then I would want to remov...
[ "If you want to be able to pass a Child when a Parent is expected, then the overriding method should accept the same argument list as the parent's method. It just happens that this specific Parent implementation that method could be made static. \nUse a # pylint: disable=X0123 (replace with the appropriate warning ...
[ 4 ]
[]
[]
[ "class", "inheritance", "methods", "python" ]
stackoverflow_0008469792_class_inheritance_methods_python.txt
Q: Mimicking functionality of built-in types I am curious if there is a way to mimic the same kind of functionality as built-in types with custom classes. The best way to explain what I am looking for is with an example. class MyClass(object): def __init__(self, val): self._returnVal = val myObject = My...
Mimicking functionality of built-in types
I am curious if there is a way to mimic the same kind of functionality as built-in types with custom classes. The best way to explain what I am looking for is with an example. class MyClass(object): def __init__(self, val): self._returnVal = val myObject = MyClass('test') print myObject Rather than the a...
[ "You could override the __repr__ method:\nclass MyClass(object):\n def __init__(self, val):\n self._returnVal = val\n def __repr__(self):\n return self._returnVal\n\nNow if I instantiate the class I get:\n>>> myObject = MyClass('test')\n>>> print myObject\ntest\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008469918_python.txt
Q: Ignore "certificate unknown" alert I have the following simple Python script: import socket import ssl if __name__ == "__main__": s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind("", 443) s.listen(1) (conn, addr) = s.accept() sslconn = ssl.wrap_socket(conn, server_side=True, certfi...
Ignore "certificate unknown" alert
I have the following simple Python script: import socket import ssl if __name__ == "__main__": s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind("", 443) s.listen(1) (conn, addr) = s.accept() sslconn = ssl.wrap_socket(conn, server_side=True, certfile="server.crt", keyfile="server.key", c...
[ "Try catching the exception and ignoring it. It is supposed to be non-fatal.\nsslconn = ssl.wrap_socket(conn, server_side=True, certfile=\"server.crt\",\n keyfile=\"server.key\", cert_reqs=ssl.CERT_NONE,\n do_handshake_on_connect=False)\ntry:\n sslconn.do_handsha...
[ 3 ]
[]
[]
[ "openssl", "python" ]
stackoverflow_0008468337_openssl_python.txt
Q: Convert a decimal matrix to a binary matrix in SciPy Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples. My question: is th...
Convert a decimal matrix to a binary matrix in SciPy
Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples. My question: is there a fast, convenient way to reduce the decimal matrix to...
[ "Apply the scipy.sign function to every cell in the matrix.\n[EDIT] Cudos to speciousfool:\nIf x is your matrix then scipy.sign(x) gives you the binary matrix.\n", "You can do the following:\n>>> import scipy\n>>> a = scipy.array((12, 0, -1, 23, 0))\narray([12, 0, -1, 23, 0])\n>>> (a != 0).astype(int)\narray([1...
[ 2, 2, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0001524023_python_scipy.txt
Q: Efficiency of display lists in OpenGL with Python? I have been teaching myself OpenGL programming using the Python wrapper PyOpenGL, and am now working on my first project with it. This project is a music visualizer (not dissimilar to whitecap) using many independently moving and independently colored cubes. My c...
Efficiency of display lists in OpenGL with Python?
I have been teaching myself OpenGL programming using the Python wrapper PyOpenGL, and am now working on my first project with it. This project is a music visualizer (not dissimilar to whitecap) using many independently moving and independently colored cubes. My current method is to have a display list for one cube and...
[ "It is like the common sense was wrong. You manually restore the transformation (glTranslatef(-x,-y,-z)) after drawing the cube, this way glPopMatrix is not only called twice for no reason, but it is also useless because you did all the work for it.\nCorrect code would like like so:\nfor x in xrange(...):\n for ...
[ 1 ]
[]
[]
[ "opengl", "performance", "pyopengl", "python" ]
stackoverflow_0008469034_opengl_performance_pyopengl_python.txt
Q: Find (start:end) positions that sublists occur within a list . Python If one had a long list of numbers: example=['130','90','150','123','133','120','160','45','67','55','34'] and sub lists within the list like sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']] how would you generate a function ...
Find (start:end) positions that sublists occur within a list . Python
If one had a long list of numbers: example=['130','90','150','123','133','120','160','45','67','55','34'] and sub lists within the list like sub_lists=[['130','90','150'],['90','150'],['120','160','45','67']] how would you generate a function that takes these sublists and gives you the positions that they occurred in...
[ "This should handle almost any case, including a sublist being present more than once:\nexample=['130','90','150','123','133','120','160','45','67','55','34']\nsub_lists=[['130','90','150'],['90','150'],['120','160','45','67']]\n\nfor i in range(len(example)):\n for li in sub_lists:\n length = len(li)\n ...
[ 3, 2 ]
[]
[]
[ "find", "list", "position", "python", "sublist" ]
stackoverflow_0008470852_find_list_position_python_sublist.txt
Q: Python - Run a simple command-line program with prompted I/O and "proxy" it, on Windows I have a simple command-line binary program hello which outputs to STDOUT: What is your name? and waits for the user to input it. After receiving their input it outputs: Hello, [name]! and terminates. I want to use Python to ...
Python - Run a simple command-line program with prompted I/O and "proxy" it, on Windows
I have a simple command-line binary program hello which outputs to STDOUT: What is your name? and waits for the user to input it. After receiving their input it outputs: Hello, [name]! and terminates. I want to use Python to run computations on the final output of this program ("Hello, [name]!"), however before the f...
[ "You could try winpexpect (not tested):\nimport re\nfrom winpexpect import winspawn\n\np = winspawn('hello')\nprompt = \"What is your name?\"\np.expect(re.escape(prompt))\nname = raw_input(prompt)\np.sendline(name)\np.expect(\"Hello, .*!\")\noutput = p.after\n# ... \n\n" ]
[ 1 ]
[]
[]
[ "console", "interactive", "python", "subprocess", "windows" ]
stackoverflow_0008470559_console_interactive_python_subprocess_windows.txt
Q: django built in comments I am using djangos built in comments framework presented in this example: https://docs.djangoproject.com/en/1.3/ref/contrib/comments/example/ And there is a sample code of how to implement a basic comment submission form {% render_comment_form for entry %} and when I use this code i get an...
django built in comments
I am using djangos built in comments framework presented in this example: https://docs.djangoproject.com/en/1.3/ref/contrib/comments/example/ And there is a sample code of how to implement a basic comment submission form {% render_comment_form for entry %} and when I use this code i get an error that my news model does...
[ "Did you added comments in urls.py?\nlike so:\nurl(r'^comments/', include('django.contrib.comments.urls')),\n\n", "You probably have an error in urls.py file in your \"news\" app. It seems like one of URL patterns there is referring to a non-existing \"add_comment\" function.\n" ]
[ 0, 0 ]
[]
[]
[ "comments", "django", "frameworks", "python" ]
stackoverflow_0008465828_comments_django_frameworks_python.txt
Q: Python regular expression There is one problem bother me for a long time. In Python, the regex always match the longest string in the content. For example, the content is below: <test> A <br> B <br> If I use the regex re.compile('/<test/>(\w\s)+/<br/>'), python match longest string which means <test> A <br> B <br...
Python regular expression
There is one problem bother me for a long time. In Python, the regex always match the longest string in the content. For example, the content is below: <test> A <br> B <br> If I use the regex re.compile('/<test/>(\w\s)+/<br/>'), python match longest string which means <test> A <br> B <br> How can I match the shortest ...
[ "Your regex looks really strange. I think you mean:\nre.compile('/<test>[\\w\\s]+<br>/')\n\nAnd in that case you can make it 'non-greedy' using a question mark:\nre.compile('/<test>[\\w\\s]+?<br>/')\n\n", "From the docs:\n\n*?, +?, ??\n The '*', '+', and '?' qualifiers are all greedy; they match as much text...
[ 4, 3, 2 ]
[ "re.compile('/<test/>(\\w\\s)+?/<br/>')\n\nNotice the ? after (\\w\\s)+\nFor more detail, see http://docs.python.org/howto/regex.html#greedy-versus-non-greedy\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0008471584_python_regex.txt
Q: pip is not installing my data_files. But easy_install does This is going to be a short question. The source is here: https://github.com/exhuma/grc And the title explains my problem ;) I registered and uploaded the package to pypi. Now if I run easy_install grc, it works as expected. But if I run pip install grc, i...
pip is not installing my data_files. But easy_install does
This is going to be a short question. The source is here: https://github.com/exhuma/grc And the title explains my problem ;) I registered and uploaded the package to pypi. Now if I run easy_install grc, it works as expected. But if I run pip install grc, it installs properly, but does not install the data_files. I don'...
[ "Maybe the files aren't installed in the path you expect. In Ubuntu 11.10, I see them under /usr/local/configs as it can be seen in pip uninstall output:\n$ sudo pip uninstall grc\nUninstalling grc:\n /usr/local/bin/grc\n /usr/local/configs/apache_access.yml\n /usr/local/configs/aptitude.yml\n /usr/local/config...
[ 5 ]
[]
[]
[ "easy_install", "pip", "python", "setup.py" ]
stackoverflow_0008471507_easy_install_pip_python_setup.py.txt
Q: String/Binary data to Bytes Am new to Python. I want to convert a char array to byte buffer i.e. Is there any way to convert data which could be string or binary data to byte buffer. Eg: if str = 'apple' I need buffer = bytes values of 'apple' which I can access like buffer[i] and buffer[:j] If i use map(ord,'app...
String/Binary data to Bytes
Am new to Python. I want to convert a char array to byte buffer i.e. Is there any way to convert data which could be string or binary data to byte buffer. Eg: if str = 'apple' I need buffer = bytes values of 'apple' which I can access like buffer[i] and buffer[:j] If i use map(ord,'apple') this returns a list but I ne...
[ "Try bytearray. Which will convert the source string to an array of byte. There is an optional encoding parameter which you need to specify in case if the default encoding is not the current default string encoding.\nExample\n>>> s = 'apple'\n>>> arr=bytearray(s)\n>>> [x for x in arr]\n[97, 112, 112, 108, 101]\n>>>...
[ 3, 0 ]
[]
[]
[ "arrays", "binary", "bytebuffer", "python" ]
stackoverflow_0008471616_arrays_binary_bytebuffer_python.txt
Q: HTML debug pretty-printing for Python After using the excellent Krumo package for PHP (perhaps most famous for its use in Drupal), I was wondering if there is something similar for Python. Specifically, I'm looking for a package that does the following: turns arbitrary (or almost arbitrary) Python variables into t...
HTML debug pretty-printing for Python
After using the excellent Krumo package for PHP (perhaps most famous for its use in Drupal), I was wondering if there is something similar for Python. Specifically, I'm looking for a package that does the following: turns arbitrary (or almost arbitrary) Python variables into themed HTML/CSS. Javascript component to col...
[ "Since I was unable to find any existing libraries, I wrote Pymo. It functions very similarly to Krumo, rendering any Python variable into html which can be printed or saved to a file for viewing in a web browser, with javascript and CSS to make it readable.\nPlease take a look at it and submit bug reports or featu...
[ 4, 0 ]
[]
[]
[ "html", "pretty_print", "python", "python_3.x" ]
stackoverflow_0008352513_html_pretty_print_python_python_3.x.txt
Q: How to include category in the product url in Satchmo? I am porting an existing web site to django/satchmo. I want to keep the same url schema than the existing site. This url schema includes the category of the product. Someting like : /parent-category/category/sub-category/product.html AFAIK, Satchmo doesn't g...
How to include category in the product url in Satchmo?
I am porting an existing web site to django/satchmo. I want to keep the same url schema than the existing site. This url schema includes the category of the product. Someting like : /parent-category/category/sub-category/product.html AFAIK, Satchmo doesn't give the possibility to insert the category in the product ur...
[ "It seems that it is not possible. I finally decided to change the url schemas and to redirect old pages to new ones.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0006359333_django_python_satchmo.txt
Q: Python project explanation this might be the "again-python-project" one topic, but I am interested how to make a project, for example a simple game, which will have an installer so the user can just double clcik and install a working game in some dir (specified later). I was looking for setup.py, distutils, easy_i...
Python project explanation
this might be the "again-python-project" one topic, but I am interested how to make a project, for example a simple game, which will have an installer so the user can just double clcik and install a working game in some dir (specified later). I was looking for setup.py, distutils, easy_install and pip, but mu projects ...
[ "If I understand your question, you need a way to distribute a Python project and all it's dependencies. \nDid you try PyInstaller already. It allows you to \"freeze\" your (and all needed) Python modules into one executable. It also provides mechanisms to set up the environment as needed.\n", "Under GNU/Linux, t...
[ 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0008471935_linux_python.txt
Q: Python callback inside class I'm registering pysvn.Client.callback_get_login callback, but I want my callback to be defined under my class, as method, rather then global function. So, in my class I want to have something like: self.client = pysvn.Client() self.client.callback_get_login = self.get_login instead: s...
Python callback inside class
I'm registering pysvn.Client.callback_get_login callback, but I want my callback to be defined under my class, as method, rather then global function. So, in my class I want to have something like: self.client = pysvn.Client() self.client.callback_get_login = self.get_login instead: self.client = pysvn.Client() self.c...
[ "I encountered the same problem and solve it by creating a closure for my login func : \nclass DummyClient:\n def __init__(self):\n def callback_get_login(realm, username, may_save):\n name = raw_input(\"Enter your svn login : \")\n password = getpass.getpass(\"Enter your svn password :\")\n ...
[ 6 ]
[]
[]
[ "callback", "class", "function", "methods", "python" ]
stackoverflow_0008472299_callback_class_function_methods_python.txt
Q: buttons for sending a 1 byte character to an ip address I am new to python and I am looking for a way to send a 1 byte character (for example: the letter "D") to an ip address. This is used to control a robot so all I need are forward, backward, left and right. I've done some research online and it suggests using ...
buttons for sending a 1 byte character to an ip address
I am new to python and I am looking for a way to send a 1 byte character (for example: the letter "D") to an ip address. This is used to control a robot so all I need are forward, backward, left and right. I've done some research online and it suggests using sockets to connect to the ip address but it seems kind of con...
[ "Sockets are easy, especially in Python! :)\nThis is a simple program to send a single letter to some ip-address:\nimport socket\n\n# Each address on the Internet is identified by an ip-address\n# and a port number.\nrobot_ip_address = \"192.168.0.12\" # Change to applicable\nrobot_port = 3000 # C...
[ 1 ]
[]
[]
[ "ip", "python" ]
stackoverflow_0008472007_ip_python.txt
Q: Tornado - Non Blocking calls which return values on GET? when trying to fetch data from a tornado GET method, if we need a result to be returned, the call has to be a blocking call which returns a value to the client (if we're fetching data from some third party, the result gets all the more delayed and the call i...
Tornado - Non Blocking calls which return values on GET?
when trying to fetch data from a tornado GET method, if we need a result to be returned, the call has to be a blocking call which returns a value to the client (if we're fetching data from some third party, the result gets all the more delayed and the call is blocked till then). Is there a way I could return processed ...
[ "As suggested by Sushant Khurana, you could \"monkey patch\" urllib2. Fortunately, you don't have to do it yourself: someone else has done it for you!\nCheck out eventlet: http://eventlet.net/doc/index.html\nIt basically implements its own asynchronous versions of socket, urllib2, asyncore, etc.\nCheck out its docu...
[ 0 ]
[]
[]
[ "python", "tornado", "webserver" ]
stackoverflow_0008164522_python_tornado_webserver.txt
Q: Add utc time to filename python How can i get the current time in UTC time (Zulu style for hours and minutes: 0100Z) , and add it to a string so i can concatenate it This gives me cannot concatenate string: import datetime utc_datetime = datetime.datetime.utcnow() utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result...
Add utc time to filename python
How can i get the current time in UTC time (Zulu style for hours and minutes: 0100Z) , and add it to a string so i can concatenate it This gives me cannot concatenate string: import datetime utc_datetime = datetime.datetime.utcnow() utc_datetime.strftime("%Y-%m-%d-%H%MZ") //Result: '2011-12-12-0939Z' filename = '/Som...
[ "What you want to do is probably : \nimport datetime\nutc_datetime = datetime.datetime.utcnow()\nformated_string = utc_datetime.strftime(\"%Y-%m-%d-%H%MZ\") //Result: '2011-12-12-0939Z'\nfilename = '/SomeDirectory/AnotherDirectory/FilePrefix_%s.txt'% formated_string\n\nor in a one-liner way :\nfilename = '/SomeDire...
[ 6, 1, 0 ]
[]
[]
[ "datetime", "python", "string" ]
stackoverflow_0008472413_datetime_python_string.txt
Q: Why is my python script forking a copy of itself when it creates threads? I have a simple python script which calls 6 threads and for some reason it creates those threads and forks a copy of itself. When I try to join all the threads it gets stuck forever. How do I fix this? def backup_function(): for todo_lis...
Why is my python script forking a copy of itself when it creates threads?
I have a simple python script which calls 6 threads and for some reason it creates those threads and forks a copy of itself. When I try to join all the threads it gets stuck forever. How do I fix this? def backup_function(): for todo_list in master_list: worker_thread = maint_tasker(todo_list) threa...
[ "The forking is being done by thepopen call, not the thread creation, so seems to be perfectly acceptable.\nCan't debug your join problem without more information. What does the thread return when asked is_alive()?\nEdit: Mixing threads and forks may be bad. See this article and blog link in my comment below.\n" ]
[ 3 ]
[]
[]
[ "debugging", "fork", "multithreading", "python" ]
stackoverflow_0008472371_debugging_fork_multithreading_python.txt
Q: Why is this for statement appending twice? Python alpha_sum = [2396, 780, 2022, 596] alpha_b_sum = [2206, 828, 1962, 597] results_alpha = [[145, 142, 142, 111, 121, 151, 111, 113, 121, 106, 67, 151, 57, 111, 106, 101, 111, 98, 142, 106, 83], [142, 106, 83, 69, 145, 121, 114], [69, 145, 121, 114, 57, 121, 111, 121,...
Why is this for statement appending twice? Python
alpha_sum = [2396, 780, 2022, 596] alpha_b_sum = [2206, 828, 1962, 597] results_alpha = [[145, 142, 142, 111, 121, 151, 111, 113, 121, 106, 67, 151, 57, 111, 106, 101, 111, 98, 142, 106, 83], [142, 106, 83, 69, 145, 121, 114], [69, 145, 121, 114, 57, 121, 111, 121, 151, 77, 121, 77, 101, 113, 142, 77, 113, 108, 83], [1...
[ "Like Noah1989 said the values are iterated over but never used.\nBecause two values from alpha happened to be larger than their corresponding match in alpha_b the loop happened twice.\nTry this\n>>> for i in range(len(values_alpha)):\n... for element in results_alpha:\n... length = len(element)\n... ...
[ 2 ]
[]
[]
[ "append", "for_loop", "if_statement", "python", "sum" ]
stackoverflow_0008472461_append_for_loop_if_statement_python_sum.txt
Q: apply a regex to retrieve a string this might be a rookie question, but how would you efficiently apply regex expressions on strings to retrieve parts of the string ? I have a concrete parsing to solve as an example. If I have the string : STRING[(val1)-{val2}-!val3!] or STRING[{val2}-!val3!-(val1)] or STRING[!...
apply a regex to retrieve a string
this might be a rookie question, but how would you efficiently apply regex expressions on strings to retrieve parts of the string ? I have a concrete parsing to solve as an example. If I have the string : STRING[(val1)-{val2}-!val3!] or STRING[{val2}-!val3!-(val1)] or STRING[!val3!-(val1)-{val2}] etc... (All 8 perm...
[ "You can use lookahead assertions with capturing groups to find matches in any order:\nimport re\ndef matchany(subject):\n match = re.match(\n r\"\"\"\n (?=.*\\(([^()]*)\\)) # Find match between () --> group 1\n (?=.*\\{([^{}]*)\\}) # Find match between {} --> group 2\n (?=.*!([^!...
[ 4, 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008472318_python_regex.txt
Q: how to add log-in in main_page django Possible Duplicate: Putting a django login form on every page how can I add a log-in in my main_page in django? let us say that in my main_page i just want to have a log-in. for example, in my www.example.com, i have a log-in division for any user who visit the site. here is...
how to add log-in in main_page django
Possible Duplicate: Putting a django login form on every page how can I add a log-in in my main_page in django? let us say that in my main_page i just want to have a log-in. for example, in my www.example.com, i have a log-in division for any user who visit the site. here is my urls.py urlpatterns = patterns('', ...
[ "had this issue before , i think code here does exactly what you need \nhttp://www.nerdydork.com/django-login-form-on-every-page.html\n\nthat explains how to put login on every page( by passing it to the base template )\nif you want it only in the main page .. pass it to the main page instead of the base template\n...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008472507_django_python.txt
Q: How can I specify form validation errors when they occur? I'm quite new to Django Forms, and I'm facing a problem that I cannot solve. I've been googling and reading the docs, but I can't find the place where this is explained. My problem is that I have an Animal Model and a ModelForm: class Animal(models.Model): ...
How can I specify form validation errors when they occur?
I'm quite new to Django Forms, and I'm facing a problem that I cannot solve. I've been googling and reading the docs, but I can't find the place where this is explained. My problem is that I have an Animal Model and a ModelForm: class Animal(models.Model): name = models.CharField(max_length=300) age = models.Po...
[ "The way you have written your view, to display form errors, in your web/error.html template, simply output the errors:\n{%if e %}\n You had some errors in your submission!<br />\n {{ e }}\n{% endif %}\n\nHowever, you don't have explicitly pass the errors list, it is part of the form itself. A bit of simplificati...
[ 4, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0008465475_django_django_forms_python.txt
Q: How to use Django decorators for Piston handler methods? Is it possible to use Django (and self-made) view decorators with Piston handler methods? The problem is that with the methods, the first argument is self (the handler) and the second the request, while for the methods the first argument is the request. Basi...
How to use Django decorators for Piston handler methods?
Is it possible to use Django (and self-made) view decorators with Piston handler methods? The problem is that with the methods, the first argument is self (the handler) and the second the request, while for the methods the first argument is the request. Basically I'd like to do something like this: from piston.handler ...
[ "from django.utils.decorators import method_decorator\n\nclass MyHandler(BaseHandler):\n @method_decorator(permission_required(lambda u: u.is_staff or u.is_superuser))\n def read(self, request, foo, bar):\n # do something\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0008473554_django_django_piston_python.txt
Q: Regular expression: Match string between two slashes if the string itself contains escaped slashes I'm trying to build a regular expression that matches regular expressions between two forward slashes. My main problem is that regular expressions themselves can contain forward slashes, escaped by a backslash. I try...
Regular expression: Match string between two slashes if the string itself contains escaped slashes
I'm trying to build a regular expression that matches regular expressions between two forward slashes. My main problem is that regular expressions themselves can contain forward slashes, escaped by a backslash. I try to filter them out with a negative lookbehind assertion (only match the closing slash if there is no ba...
[ "Try this:\npattern = re.compile(r\"^/(?:\\\\.|[^/\\\\])*/\")\n\nExplanation:\n^ # Start of string\n/ # Match /\n(?: # Match either...\n \\\\. # an escaped character\n| # or\n [^/\\\\] # any character except slash/backslash\n)* # any number of times.\n/ # Match /\n\nFor your \"re...
[ 17 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008473853_python_regex.txt
Q: Leak in updating label I'm new to tkinter and have traced a memory leak in a project I'm doing down to a clock in my code. It turns out the memory leak happens when updating a label, the simplest example I've got it down to in code is: import Tkinter as tk class Display: def __init__(self, master): se...
Leak in updating label
I'm new to tkinter and have traced a memory leak in a project I'm doing down to a clock in my code. It turns out the memory leak happens when updating a label, the simplest example I've got it down to in code is: import Tkinter as tk class Display: def __init__(self, master): self.master = master s...
[ "The problem is that tick keeps creating new labels. There's no reason to create more than one label in a loop like this unless you really do need an ever increasing number of labels. You can update the text of a label widget by using the configure method. \nFor example:\ndef tick(self):\n self.label.configure(t...
[ 4, 0 ]
[]
[]
[ "python", "tk_toolkit", "tkinter" ]
stackoverflow_0008468198_python_tk_toolkit_tkinter.txt
Q: Python: accessing DLL function using ctypes -- access by function *name* fails myPythonClient (below) wants to invoke a ringBell function (loaded from a DLL using ctypes). However, attempting to access ringBell via its name results in an AttributeError. Why? RingBell.h contains namespace MyNamespace { cla...
Python: accessing DLL function using ctypes -- access by function *name* fails
myPythonClient (below) wants to invoke a ringBell function (loaded from a DLL using ctypes). However, attempting to access ringBell via its name results in an AttributeError. Why? RingBell.h contains namespace MyNamespace { class MyClass { public: static __declspec(dllexport) int ri...
[ "Your C++ compiler is mangling the names of all externally visible objects to reflect (as well as their underlying names) their namespaces, classes, and signatures (that's how overloading becomes possible).\nIn order to avoid this mangling, you need an extern \"C\" on externally visible names that you want to be v...
[ 12, 11, 7 ]
[]
[]
[ "attributeerror", "ctypes", "dll", "python" ]
stackoverflow_0001088085_attributeerror_ctypes_dll_python.txt
Q: use multiprocessing as local IPC I'm considering using Python's multiprocessing package for messaging between local python programs. This seems like the right way to go IF: The programs will always run locally on the same machine (and same OS instance) The programs' implementation will remain in Python Speed is i...
use multiprocessing as local IPC
I'm considering using Python's multiprocessing package for messaging between local python programs. This seems like the right way to go IF: The programs will always run locally on the same machine (and same OS instance) The programs' implementation will remain in Python Speed is important Is it possible in case the p...
[ "See Listeners and Clients\n", "\nThe programs will always run locally on the same machine (and same OS instance)\n\nMultiprocessing allows to have remote concurrency.\n\nThe programs' implementation will remain in Python\n\nYes and no. You could wrap another command in a python function. This will work, for exam...
[ 2, 1 ]
[]
[]
[ "messaging", "multiprocessing", "python" ]
stackoverflow_0008466383_messaging_multiprocessing_python.txt
Q: How define a Traverse for neo4j with Python? I need to traverse a neo4j graph using Python27. From the manual I've seen that I can define a Traversal and include a Evaluator and I got something similar to that. def my_evaluator(path): if (path.end['type'] == 'STOP') or (path.end['type'] == 'BUS_STOP'): ...
How define a Traverse for neo4j with Python?
I need to traverse a neo4j graph using Python27. From the manual I've seen that I can define a Traversal and include a Evaluator and I got something similar to that. def my_evaluator(path): if (path.end['type'] == 'STOP') or (path.end['type'] == 'BUS_STOP'): return Evaluation.EXCLUDE_AND_CONTINUE else: ...
[ "You can chain multiple evaluators to achieve this. To skip the start node, add an evaluator that looks something like this:\ndef exclude_start_node(path):\n if len(path) == 0:\n return Evaluation.EXCLUDE_AND_CONTINUE\n\n return Evaluation.INCLUDE_AND_CONTINUE\n\nAnd to stop at some given depth, someth...
[ 0 ]
[]
[]
[ "neo4j", "neo4j.py", "python" ]
stackoverflow_0008231705_neo4j_neo4j.py_python.txt
Q: Defining both post and get method under same request handler I'm using python to develop a web app. I defined both "get" and "post" method in the same request handler to serve different purpose. That is, I use "get" method to present a form to user, and "post" method to handle the submitted form. It works fine, bu...
Defining both post and get method under same request handler
I'm using python to develop a web app. I defined both "get" and "post" method in the same request handler to serve different purpose. That is, I use "get" method to present a form to user, and "post" method to handle the submitted form. It works fine, but is this approach appropriate? Or should I better define get and ...
[ "Your approach is appropriate. According to the newest documentation you can even define post and get as functions outside request handler and just as other functions in your module and that's a way I would choose since it eliminates problems that can happen when instanciating request handlers.\nIf starting a new a...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "webapp2" ]
stackoverflow_0008473712_google_app_engine_python_webapp2.txt
Q: Accessing a function from a module I cant figure out how to add my simple function to my main program file. why not ? when i do this: import print_text echothis("this is text") exit() cant understand why people think this is such a bad question. this doesnt work either: print_text.echothis("this is text") same...
Accessing a function from a module
I cant figure out how to add my simple function to my main program file. why not ? when i do this: import print_text echothis("this is text") exit() cant understand why people think this is such a bad question. this doesnt work either: print_text.echothis("this is text") same thing happens if i type any of the answ...
[ "EDIT: You're actually not having a python issue but a bash one. You're running your python script as if it were bash (hence the 'from: can't read from'), did you put #!/usr/bin/env python at the beginning of the file you're running (not print_text.py, the other one)? You could alternatively call it that way: pytho...
[ 1, 0 ]
[]
[]
[ "class", "definition", "python" ]
stackoverflow_0008474462_class_definition_python.txt
Q: Pythonic way to combine datetime.date and datetime.time objects I have two objects that represent the same event instance --- one holds the date, the other the time of this event, and I want to create a datetime object. Since one can't simply add date and time objects (following call fails): datetime.date(2011,...
Pythonic way to combine datetime.date and datetime.time objects
I have two objects that represent the same event instance --- one holds the date, the other the time of this event, and I want to create a datetime object. Since one can't simply add date and time objects (following call fails): datetime.date(2011, 01, 01) + datetime.time(10, 23)
[ "It's in the python docs.\nimport datetime\ndatetime.datetime.combine(datetime.date(2011, 1, 1), \n datetime.time(10, 23))\n\nreturns\ndatetime.datetime(2011, 1, 1, 10, 23)\n\n" ]
[ 446 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008474670_datetime_python.txt
Q: Loop in ManyToMany Fields in django model I have a model like this: class MyProfile(models.Model): club = models.ManyToManyField(Club, default=None) city = models.ManyToManyField(City, default=None) . . In view: user = User.objects.get(pk=id) profile = MyProfile.objects.select_related().ge...
Loop in ManyToMany Fields in django model
I have a model like this: class MyProfile(models.Model): club = models.ManyToManyField(Club, default=None) city = models.ManyToManyField(City, default=None) . . In view: user = User.objects.get(pk=id) profile = MyProfile.objects.select_related().get(user=user) With for example profile.club.sel...
[ "This fields are the same as \"objects\" field in MyProfile class. Adding .all() and casting it to list. \nfields = [car, club]\nfor f in fields:\n z = getattr(profile, f)\n print list(z.all())\n\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008474013_django_python.txt
Q: Access standalone GUI application through Web Is it possible to access a standalone GUI-based application over the Web? The concerned application is an event animator, which displays the animation based on custom textual inputs. I don't wish to access that software through any remote desktop connection (or web mee...
Access standalone GUI application through Web
Is it possible to access a standalone GUI-based application over the Web? The concerned application is an event animator, which displays the animation based on custom textual inputs. I don't wish to access that software through any remote desktop connection (or web meeting) like option. I actually intend to integrate t...
[ "The only way to make something like that possible would be to load the application into memory, interact with it and render the presentation. Consider something like having a application that can parse a HTML document, instantiate and provides access to the DOM elements in memory so that you can modify their prope...
[ 1 ]
[]
[]
[ "django", "python", "user_interface", "web" ]
stackoverflow_0008472282_django_python_user_interface_web.txt
Q: unable to update (PUT) and delete (delete) data in django-piston i just followed this tutorial and the example is great. http://weblog.mattdorn.com/content/restful-web-apps-with-django-piston-and-ext-js/ but when i create on my own, the add method is ok but the delete and update is not. here is the console of my r...
unable to update (PUT) and delete (delete) data in django-piston
i just followed this tutorial and the example is great. http://weblog.mattdorn.com/content/restful-web-apps-with-django-piston-and-ext-js/ but when i create on my own, the add method is ok but the delete and update is not. here is the console of my runserver: [16/Nov/2011 00:11:17] "DELETE /api/phonebooks/10 HTTP/1.1" ...
[ "Make sure you put in the trailing slashes in your request URL.\nRight now, since the trailing slash is missing, your request is being auto forwarded by Django to the address which includes the trailing slash - and in that case, the requests are being converted to 'GET' rather than the original 'PUT' or 'DELETE'.\n...
[ 0 ]
[]
[]
[ "django", "django_piston", "extjs", "jquery", "python" ]
stackoverflow_0008147542_django_django_piston_extjs_jquery_python.txt
Q: How can I use the OAuth2Decorator with Google Cloud Storage? I am following this instructions in order to connect my app engine python web service with Google storage and specifically to be able to use files API. I went through the buzz example but doesn't seem to work for me. I need the web service to authorize i...
How can I use the OAuth2Decorator with Google Cloud Storage?
I am following this instructions in order to connect my app engine python web service with Google storage and specifically to be able to use files API. I went through the buzz example but doesn't seem to work for me. I need the web service to authorize in the background in order to be able to retrieve my files from sto...
[ "This may not be the most direct answer, but have you explored the built in Google Storage API on App Engine?\nhttp://code.google.com/appengine/docs/python/googlestorage/\nThis lets you bypass the native API all together.\n", "I managed to get it running properly by using the gslite.py script from the au-to-do go...
[ 1, 1 ]
[ "If you are using the apiclient along with the native REST API, it would look something like this...\nfrom apiclient.discovery import build\nimport httplib2\nfrom oauth2client.appengine import OAuth2Decorator\n\ndecorator = OAuth2Decorator(client_id=YOUR_GOOGLE_CLIENT_ID,\n client_secret=...
[ -1 ]
[ "google_api_python_client", "google_app_engine", "google_cloud_storage", "python" ]
stackoverflow_0008325142_google_api_python_client_google_app_engine_google_cloud_storage_python.txt
Q: Extracting ID string from GDataEntry I am playing around with Google's gdata API in python. More specificalyl, I am using the YouTube API, but I do not believe it will be relevant to this question. I now have an object which is a subclass of GDataEntry and I am trying to get its id. print entry.id this fails as i...
Extracting ID string from GDataEntry
I am playing around with Google's gdata API in python. More specificalyl, I am using the YouTube API, but I do not believe it will be relevant to this question. I now have an object which is a subclass of GDataEntry and I am trying to get its id. print entry.id this fails as it cannot convert and Id object to a string...
[ "I'm pretty sure, that entry.id is of the type atom.Id which provides a ToString method and a text accessor. See the documentation here.\nSo you'd like to write:\nprint entry.id.text\n\n" ]
[ 2 ]
[]
[]
[ "gdata", "gdata_api", "python" ]
stackoverflow_0008474922_gdata_gdata_api_python.txt
Q: Django aggregation and following foreign key relations Models: class Item(models.Model): name = models.CharField(max_length=100) # More stuff. class Sale(models.Model): sale_date = models.DateField(auto_now_add=True) item = models.ForeignKey(Item) # More stuff. View: class TodaySales(ListView)...
Django aggregation and following foreign key relations
Models: class Item(models.Model): name = models.CharField(max_length=100) # More stuff. class Sale(models.Model): sale_date = models.DateField(auto_now_add=True) item = models.ForeignKey(Item) # More stuff. View: class TodaySales(ListView): # Stuff in here. def get_queryset(self): s...
[ "This will do. Try:\nItem.objects.filter(\n sale__sale_date=date.today()\n).annotate(\n count = Count('sale')\n)\n\n", "As you care about getting extra data from the Item, rather than the Sale, you could query on that class:\nmodels.Item.objects.filter(sale__sale_date=date.today()).annotate(Count('id'))\n\n...
[ 8, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008473648_django_python.txt
Q: Scrolling windows with wxPython I am making a frame with a scrollbar and some images inside. The scrollbar works fine when the frame is empty. However, when I add a picture in, the scrollbars seem to get pushed up into the top left corner of the frame. How can I implement my code so that the scrollbars stay where ...
Scrolling windows with wxPython
I am making a frame with a scrollbar and some images inside. The scrollbar works fine when the frame is empty. However, when I add a picture in, the scrollbars seem to get pushed up into the top left corner of the frame. How can I implement my code so that the scrollbars stay where they are after I add pictures? Workin...
[ "If you want your images inside the scrolled window panel, then you have to put your static bipmap and gifImage inside it. So the parent of your images should not be self (the wx.Frame instance) but self.scroll.\nModify the 4 lines indicated:\n ...................\n wx.StaticBitmap(self.scroll, -1, background...
[ 2 ]
[]
[]
[ "image", "python", "scroll", "wxpython" ]
stackoverflow_0008471040_image_python_scroll_wxpython.txt
Q: Python name of iterable that can be iterated many times I'm trying to improve my documentation. I want to say that this function accepts something that is a collections.Iterable, but the code will iterate over the iterable many times. A "list" is too specific, and an "iterable" doesn't work because some iterable...
Python name of iterable that can be iterated many times
I'm trying to improve my documentation. I want to say that this function accepts something that is a collections.Iterable, but the code will iterate over the iterable many times. A "list" is too specific, and an "iterable" doesn't work because some iterables can only be iterated once. Is there a name for a thing? "R...
[ "You probably want the term \"sequence\". A sequence in Python is something that has a length and supports item access by index.\n", "I can't think of anything appropriate. Reiterable sounds like a nice term, why not define it clearly in your documentation then use it?\n" ]
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008475252_python.txt
Q: How can I improve this many-to-many Django ORM query and model set? I have a Django query and some Python code that I'm trying to optimize because 1) it's ugly and it's not as performant as some SQL I could use to write it, and 2) because the hierarchical regrouping of the data looks messy to me. So, 1. Is it poss...
How can I improve this many-to-many Django ORM query and model set?
I have a Django query and some Python code that I'm trying to optimize because 1) it's ugly and it's not as performant as some SQL I could use to write it, and 2) because the hierarchical regrouping of the data looks messy to me. So, 1. Is it possible to improve this to be a single query? 2. How can I improve my Python...
[ "When you have sql query, that is hard to write using orm - you can use postgresql views. Not sure about mysql. In this case you will have:\nRaw SQL like: \nCREATE VIEW photo_urls AS\nSelect\nphoto.id, --pseudo primary key for django mapper\nGallery.id as gallery_id, \nPhotoSize.PhotoURL as photo_url\nFrom PhotoSiz...
[ 3, 1, 1 ]
[]
[]
[ "django", "django_models", "postgresql", "python", "sql" ]
stackoverflow_0008369172_django_django_models_postgresql_python_sql.txt
Q: Holiday Calendars, File Formats, et al I'm looking for a way to figure out whether a given date is a "holiday," given some holiday calendar. Specifically, you might say is_holiday (datetime.date, "USA") which would answer whether the given date is a holiday for the calendar named "USA." I recognize that there's n...
Holiday Calendars, File Formats, et al
I'm looking for a way to figure out whether a given date is a "holiday," given some holiday calendar. Specifically, you might say is_holiday (datetime.date, "USA") which would answer whether the given date is a holiday for the calendar named "USA." I recognize that there's no trivial way of doing this for all holidays...
[ "Mozilla has a set of user-contributed holiday files in .ics format. That may get you started. Unfortunately they go out to different date ranges. iCalShare also has holiday calendars in .ics format.\nNote:\n\nSome holidays are state or region-related, rather than country-related.\n\nI've found in the past that a h...
[ 6, 2, 2, 0 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0001986207_calendar_python.txt
Q: parsing to an expression tree in python I have a genetic program that prints the expression tree to a file (it can easily switch between pre/post/in-fix) It seems like pre-fix would be the easiest to parse so I am currently using that. How would I go about parsing this string using python 2.7? For example, how wou...
parsing to an expression tree in python
I have a genetic program that prints the expression tree to a file (it can easily switch between pre/post/in-fix) It seems like pre-fix would be the easiest to parse so I am currently using that. How would I go about parsing this string using python 2.7? For example, how would I parse the string +(*(2,1),*(4,3)) ...
[ "For one thing, prefix notation won't require any parentheses - you control the precedence of operations purely by the ordering of elements in the string. For instance, if you wanted 2*(1+4)*3 instead, your prefix expression would become \"* * 2 + 1 4 3\".\n2*1+4*3 would become \"+ * 2 1 * 4 3\". Using split(), thi...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008471611_python.txt
Q: FileObject read works like write Let's see simple piece of code: import os f = open('test.bin', 'wb') f.write('X') f.close() # test.bin - X f = open('test.bin', 'r+b') f.seek(0, os.SEEK_END) f.write('AB') # test.bin - XAB f.seek(0, os.SEEK_SET) f.write('Y') # test.bin - YAB print f.read(1) # test.bin - YBB an...
FileObject read works like write
Let's see simple piece of code: import os f = open('test.bin', 'wb') f.write('X') f.close() # test.bin - X f = open('test.bin', 'r+b') f.seek(0, os.SEEK_END) f.write('AB') # test.bin - XAB f.seek(0, os.SEEK_SET) f.write('Y') # test.bin - YAB print f.read(1) # test.bin - YBB and prints B 0_o whhyyy? f.close() Why...
[ "If you put \nf.flush()\n\nafter you write 'Y' subsequent read(1) reads the correct value (in this case 'A'). \nSo my guess is that on windows read() doesn't force buffers flush while on *nix it does. \n" ]
[ 3 ]
[]
[]
[ "file_io", "python", "seek" ]
stackoverflow_0008474394_file_io_python_seek.txt
Q: urllib2.urlopen don't work with separate threads I'm working on an application to download the code of a web page and captures the links. It works, but if I connect the program to a GUI, it locks the corresponding button until the download is completed. If I trigger the download via a separate thread, to avoid the...
urllib2.urlopen don't work with separate threads
I'm working on an application to download the code of a web page and captures the links. It works, but if I connect the program to a GUI, it locks the corresponding button until the download is completed. If I trigger the download via a separate thread, to avoid the button lock, it just freezes and does not complete ex...
[ "I just called gtk.gdk.threads_init() before gtk.main() and everything worked perfectly without any changes.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008386317_python.txt
Q: fastest way to iterate in python I've never had to concern myself with this problem so far but now I need to use some large number of vertices that need to be buffered by PyOpenGL and it seems like the python iteration is the bottleneck. Here is the situation. I have an array of 3D points vertices, and at each ste...
fastest way to iterate in python
I've never had to concern myself with this problem so far but now I need to use some large number of vertices that need to be buffered by PyOpenGL and it seems like the python iteration is the bottleneck. Here is the situation. I have an array of 3D points vertices, and at each step I have to compute a 4D array of colo...
[ "\nTo make this code faster, you need to \"vectorise\" it: replace all explicit Python loops with implicit loops, using NumPy's broadcasting rules. I can try and give a vectorised version of your loop:\nif self.color_array is None:\n self.color_array = numpy.empty((len(activity), 4))\ndiff_activity = (activit...
[ 13, 6 ]
[]
[]
[ "numpy", "pyopengl", "python" ]
stackoverflow_0008475807_numpy_pyopengl_python.txt
Q: How can I get rid of ft2font import error from matplotlib on a Windows XP source installation? So today I tried building matplotlib from source (git clone) on a Windows XP box. First I downloaded and compiled the dependencies (zlib, libpng, freetype2) as per this blog entry. I then edited setup.cfg to make the mat...
How can I get rid of ft2font import error from matplotlib on a Windows XP source installation?
So today I tried building matplotlib from source (git clone) on a Windows XP box. First I downloaded and compiled the dependencies (zlib, libpng, freetype2) as per this blog entry. I then edited setup.cfg to make the matplotlib installation aware of the installations of the dependencies. Lastly, python setup.py build a...
[ "I finally figured it out. Opening ft2font.pyd in Dependency Walker showed that libfreetype-6.dll was missing as a dependency. Turns out I had forgot to copy bin\\libfreetype-6.dll to the system32 folder. After I'd copied it over matplotlib worked without a hitch.\n" ]
[ 3 ]
[]
[]
[ "importerror", "matplotlib", "python", "windows_xp" ]
stackoverflow_0008474419_importerror_matplotlib_python_windows_xp.txt
Q: Redirecting python output to file prints two lines Using the advice of another stack overflow question I wrote my own LogWriter class: class LogWriter: def __init__(self, output, filename): self.output = output self.logfile = file(filename, 'a') def write(self, text): n...
Redirecting python output to file prints two lines
Using the advice of another stack overflow question I wrote my own LogWriter class: class LogWriter: def __init__(self, output, filename): self.output = output self.logfile = file(filename, 'a') def write(self, text): now = datetime.now() stamp = now.strftime("%Y...
[ "Try:\n>>>print \"test\",\n\nPossibly you are getting the implicit newline from print as a separate call to write(). Either way, the problem is that you're getting multiple calls to write() (as there is no guarantee how a caller uses write() - it could call it for every character if it liked).\n", "You should no...
[ 4, 2 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008476523_logging_python.txt
Q: Issue in webpy db select query In webpy db module I have a query: db().query("select * from table where column in ($ERROR_LIST)", vars=dict(ERROR_LIST=ERROR_LIST)).list() There is no issue with this query if the ERROR_LIST is just a variable. But my requirement is that the ERROR_LIST must be list of error va...
Issue in webpy db select query
In webpy db module I have a query: db().query("select * from table where column in ($ERROR_LIST)", vars=dict(ERROR_LIST=ERROR_LIST)).list() There is no issue with this query if the ERROR_LIST is just a variable. But my requirement is that the ERROR_LIST must be list of error values. Is there a way to handle list ...
[ "If you have a variable error_listthat holds a list of the values, let webpy convert everything for you and don't add the () arround the variable either:\ndb.query(\"SELECT * FROM table WHERE column IN $ERROR_LIST\", vars(dict(ERROR_LIST,error_list)))\n\nSince I believe reparam uses the same methods, this seems to ...
[ 1 ]
[]
[]
[ "database", "mysql", "python", "web.py" ]
stackoverflow_0008443641_database_mysql_python_web.py.txt
Q: looping through the rows of a matrix in sage I am trying to program a Graham-Schmidt process in sage and cannot figure out how to loop through the rows of an array. def graham_schmidt(W): a=0 U=W for i in W.dims()[0]:# this is the not working part print w a=a+1 for j in xrange(...
looping through the rows of a matrix in sage
I am trying to program a Graham-Schmidt process in sage and cannot figure out how to loop through the rows of an array. def graham_schmidt(W): a=0 U=W for i in W.dims()[0]:# this is the not working part print w a=a+1 for j in xrange(0,-2): a=a+1 U[i]=U[i]-(tr...
[ "You're making things far too complicated. If W is not a sparse matrix, you can just do\nfor row in W:\n\nSince you also need the row index, you can use Python's built-in enumerate:\nfor i, row in enumerate(W):\n\nor (uglier)\nfor i in xrange(len(W.shape[0])):\n\n" ]
[ 5 ]
[]
[]
[ "matrix", "numpy", "python", "sage" ]
stackoverflow_0008475498_matrix_numpy_python_sage.txt
Q: Logging execution time on Pyramid I'm trying to log how much time my webapp takes to answer each request. Right now I have a metaclass for Handlers that wraps each action and calculates the time passed between entering the method and exiting. This works fine, except that the logged times do not include the time sp...
Logging execution time on Pyramid
I'm trying to log how much time my webapp takes to answer each request. Right now I have a metaclass for Handlers that wraps each action and calculates the time passed between entering the method and exiting. This works fine, except that the logged times do not include the time spent rendering the templates... How coul...
[ "This is the purpose of a tween. It is middleware that wraps the Pyramid application, so it has access to both the ingress and egress of a request within Pyramid. Note that there is already the debug toolbar which displays how long the entire request took. This is also a good application for WSGI middleware of whic...
[ 8 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008476171_pyramid_python.txt
Q: compare datetime var to str var I'm trying to compare a datetime.datetime.now() variable to a calendar.itermonthdates() variable. According to the errors I'm getting, the datetime.now is a datetime.date() type, whereas the itermonthdates is a string. how can I convert the datetime date to a string for compariso...
compare datetime var to str var
I'm trying to compare a datetime.datetime.now() variable to a calendar.itermonthdates() variable. According to the errors I'm getting, the datetime.now is a datetime.date() type, whereas the itermonthdates is a string. how can I convert the datetime date to a string for comparison? and will string comparison work fo...
[ "According to the python documentation, calendar.itermonthdates should return a datetime.date object :\n\nReturn an iterator for the month month (1-12) in the year year. This\n iterator will return all days (as datetime.date objects) for the month\n and all days before the start of the month or after the end of t...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008477157_python.txt
Q: Understanding the Namespace in Python I need help understanding a practice exam problem for a CS class in python. The problem deals with the python namespace. Here is the question: Which of the following are true in Python? i. Every function has access to the names in the builtin namespace. ii. Every invocation o...
Understanding the Namespace in Python
I need help understanding a practice exam problem for a CS class in python. The problem deals with the python namespace. Here is the question: Which of the following are true in Python? i. Every function has access to the names in the builtin namespace. ii. Every invocation of a function creates a new namespace nested...
[ "For 2: The new function's namespace isn't within the calling function's namespace: it's completely separate. An inner function has no access to the variables used in the outer one. The invocation makes a new namespace, but it's not nested within that of the calling function.\nI didn't know 3, but it makes sense. T...
[ 1 ]
[]
[]
[ "namespaces", "python" ]
stackoverflow_0008477258_namespaces_python.txt
Q: python : use optparse on given list rather than on system command line arguments within the frame of a python application, I need to make calls to several of my scripts that were largely using optparse. They all have an entry point of this form : if __name__ == '__main__': mains(sys.argv) I just called my mai...
python : use optparse on given list rather than on system command line arguments
within the frame of a python application, I need to make calls to several of my scripts that were largely using optparse. They all have an entry point of this form : if __name__ == '__main__': mains(sys.argv) I just called my main function mains thinking that my problem initially came from there. Then, the mains a...
[ "You left out the call to parse your options:\nparser.parse_args(argv)\n\nparse_args takes an optional argument which will be used for parsing rather than sys.argv.\n", "Although others have answered your immediate question, I would strongly recommend putting all your argument-parsing stuff in the if __name__ == ...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008475967_python.txt
Q: What is the relationship between COM and windows DLLs? Numpty question alert. Is COM one type of DLL interface, or are DLLs one type of COM interface? If I call a Native (not .net) C++ DLL from Python using ctypes, is that using COM? A: Is COM one type of DLL interface, or are DLLs one type of COM interface?...
What is the relationship between COM and windows DLLs?
Numpty question alert. Is COM one type of DLL interface, or are DLLs one type of COM interface? If I call a Native (not .net) C++ DLL from Python using ctypes, is that using COM?
[ "\nIs COM one type of DLL interface, or are DLLs one type of COM interface? \n\nYes and no. Per-se COM has nothing to do with DLL exports as such, but it is often implemented through one or more DLL entry points for inproc servers.\nIn this case the registry holds some book-keeping information so that the DLL can b...
[ 4 ]
[]
[]
[ "com", "ctypes", "dll", "python" ]
stackoverflow_0008477595_com_ctypes_dll_python.txt
Q: Displaying icon in mac statusbar with python I have a script that just returns true/false depending on some conditions, and I need to display this status in the status bar/some topmost window, the script is written in python. I tried to find a way to display a status bar icon with python but seems all existing wra...
Displaying icon in mac statusbar with python
I have a script that just returns true/false depending on some conditions, and I need to display this status in the status bar/some topmost window, the script is written in python. I tried to find a way to display a status bar icon with python but seems all existing wrappers are outdated. I feel that it is not very goo...
[ "Have found out that\nimport objc, from Foundation import *\nfrom AppKit import *\nfrom PyObjCTools import AppHelper\n\nsolves my problem\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "statusbar" ]
stackoverflow_0008000255_macos_python_statusbar.txt
Q: Flattening a list of dicts of lists of dicts (etc) of unknown depth in Python (nightmarish JSON structure) I'm dealing with a JSON structure which is output to me in structures like this: [{u'item': u'something', u'data': { u'other': u'', u'else': [ { ...
Flattening a list of dicts of lists of dicts (etc) of unknown depth in Python (nightmarish JSON structure)
I'm dealing with a JSON structure which is output to me in structures like this: [{u'item': u'something', u'data': { u'other': u'', u'else': [ { u'more': u'even more', u'argh': { ...
[ "Since the depth of your data is arbitrary, it is easier to resort to recursion to flatten it. This function creates a flat dictionary, with the path to each data item composed as the key, in order to avoid collisions. \nYou can retrieve its contents later with for key in sorted(dic_.keys()), for example.\nI didn'...
[ 11 ]
[]
[]
[ "dictionary", "json", "list", "python", "recursion" ]
stackoverflow_0008477550_dictionary_json_list_python_recursion.txt
Q: Why does this Django form rendering taking forever? I have a ModelForm based on a gigantic 300 fields model. Actually one model with 150 fields inheriting from another one with 150 other. I was expecting the model to cause some issues at syncdb or save(), but it works fine. However, calling the form based on this ...
Why does this Django form rendering taking forever?
I have a ModelForm based on a gigantic 300 fields model. Actually one model with 150 fields inheriting from another one with 150 other. I was expecting the model to cause some issues at syncdb or save(), but it works fine. However, calling the form based on this model as_p() method just take forever. I can wait 10 minu...
[ "if you have foreign keys to tables with a large number of rows, it's worth remembering that the default widget for each is a dropdown (<select>) with each row ('s unicode) as a choice. these often get enormous and it's worth looking at options (like the admin's raw_id_field)\n", "I found something like this in t...
[ 1, 1 ]
[]
[]
[ "django", "forms", "html_rendering", "python" ]
stackoverflow_0008477860_django_forms_html_rendering_python.txt
Q: NumPy C-API: convert type object to type number The function PyObject* PyArray_TypeObjectFromType(int); converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object. How do you do the opposite conversion, from the type object for a NumPy scalar type to the correspond...
NumPy C-API: convert type object to type number
The function PyObject* PyArray_TypeObjectFromType(int); converts the type number for a NumPy scalar type (NPY_BOOL, NPY_BYTE, ...) to the corresponding type object. How do you do the opposite conversion, from the type object for a NumPy scalar type to the corresponding type number? Edit: The following code is based on...
[ "If you can get PyArray_Descr structs rather than PyArray_TypeObjects, you can simply look at the type_num field. The descr structs can be acquired via the type number using PyArray_DescrFromType. If you look at that link, there are also a few more functions for converting various things into descr structs. They're...
[ 4 ]
[]
[]
[ "c", "numpy", "python", "python_c_api" ]
stackoverflow_0008477122_c_numpy_python_python_c_api.txt
Q: Using urllib2 with SOCKS proxy Is it possible to fetch pages with urllib2 through a SOCKS proxy on a one socks server per opener basic? I've seen the solution using setdefaultproxy method, but I need to have different socks in different openers. So there is SocksiPy library, which works great, but it has to be use...
Using urllib2 with SOCKS proxy
Is it possible to fetch pages with urllib2 through a SOCKS proxy on a one socks server per opener basic? I've seen the solution using setdefaultproxy method, but I need to have different socks in different openers. So there is SocksiPy library, which works great, but it has to be used this way: import socks import sock...
[ "Try with pycurl:\nimport pycurl\nc1 = pycurl.Curl()\nc1.setopt(pycurl.URL, 'http://www.google.com')\nc1.setopt(pycurl.PROXY, 'localhost')\nc1.setopt(pycurl.PROXYPORT, 8080)\nc1.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)\n\nc2 = pycurl.Curl()\nc2.setopt(pycurl.URL, 'http://www.yahoo.com')\nc2.setopt(pycurl.P...
[ 17, 11, 0, 0, 0, 0 ]
[ "You could do you it by setting evironmental variable HTTP_PROXY in following format:\nuser:pass@proxy:port\nor if you use bat/cmd, add before calling script:\nset HTTP_PROXY=user:pass@proxy:port\nI am using such cmd-file to make easy_install work under proxy.\n" ]
[ -3 ]
[ "python", "socks", "urllib2" ]
stackoverflow_0002537726_python_socks_urllib2.txt
Q: How redirect a shell command output to a Python script input ? This is probably something really basic, but I can not find a good solution for it. I need to write a python script that can accept input from a pipe like this: $ some-linux-command | my_script.py something like this: cat email.txt | script.py Or it ...
How redirect a shell command output to a Python script input ?
This is probably something really basic, but I can not find a good solution for it. I need to write a python script that can accept input from a pipe like this: $ some-linux-command | my_script.py something like this: cat email.txt | script.py Or it will just be piped by my .forward file directly from sendmail. This ...
[ "Use sys.stdin to read the input . Example :\nExample content of s.py : \nimport sys\ndata = sys.stdin.readlines()\nprint data\n\n-- Running :\n user@xxxxxxx:~$ cat t.txt\n alpha\n beta\n gamma\n\n user@xxxxxxx:~$ cat t.txt | python ./s.py\n ['alpha\\n', 'beta\\n', 'gamma\\n']\n\nYou can also make...
[ 28, 3 ]
[]
[]
[ "input", "pipe", "python", "shell" ]
stackoverflow_0008478137_input_pipe_python_shell.txt
Q: pyqt4 QComboBox setEditable(True) - How to setMaxLength? I have a QComboBox that is tied to database VARCHAR(45) field. The QComboBox dropdown list provides a set of default values but it is EDIT enabled and user can enter anything in it. I want to limit the user entry length to max of 45 chars QComboBox does not ...
pyqt4 QComboBox setEditable(True) - How to setMaxLength?
I have a QComboBox that is tied to database VARCHAR(45) field. The QComboBox dropdown list provides a set of default values but it is EDIT enabled and user can enter anything in it. I want to limit the user entry length to max of 45 chars QComboBox does not have a setMaxLength(int) like QLineEdit does. Anyone have any ...
[ "If a combo-box is editable, its lineEdit method will give access to its line-edit widget:\nself.myDropDown = QComboBox()\nself.myDropDown.setEditable(True)\nself.myDropDown.lineEdit().setMaxLength(45)\n\n" ]
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qcombobox" ]
stackoverflow_0008477837_pyqt_pyqt4_python_qcombobox.txt
Q: Lambda function in sorting function There is this code: lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lam...
Lambda function in sorting function
There is this code: lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lambda x,y: y > x) # sort descending print l...
[ "The second example doesn't work because the function you're giving it isn't a valid comparator.\nA valid comparator is supposed to\n\nreturn a negative, zero or positive number depending on whether the\n first argument is considered smaller than, equal to, or larger than\n the second argument.\n\nThe function la...
[ 21, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008478958_python.txt
Q: Python IndentationError: too many levels of indentation I've a part of my python program which is generated, the generated codes contains a lot of nested if / else, my problem is that a lot can be too much and I got this Error when running my code: IndentationError: too many levels of indentation I've read that ...
Python IndentationError: too many levels of indentation
I've a part of my python program which is generated, the generated codes contains a lot of nested if / else, my problem is that a lot can be too much and I got this Error when running my code: IndentationError: too many levels of indentation I've read that this was some limitation defined on the low level of the pyth...
[ "Your generator is producing bad code. You should treat this exactly as you would if it were producing syntactically invalid code. \nUse functions, dictionary dispatching and any other thing that might occur to you to reduce the depth. \nOTOH, thanks for showing me that Python does really have a maximum depth. I di...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008439572_python.txt
Q: Dictionaries and listing positions of word in a list I need to take a list and use a dictionary to catalogue where a particular item occurs in a list, as an example: L = ['a', 'b', 'c', 'b', 'c', 'a', 'e'] the dictionary needs to contain the following: D = {'a': 0, 5 , 'b': 1, 3 , 'c': 2, 4 , 'e': 6} However i...
Dictionaries and listing positions of word in a list
I need to take a list and use a dictionary to catalogue where a particular item occurs in a list, as an example: L = ['a', 'b', 'c', 'b', 'c', 'a', 'e'] the dictionary needs to contain the following: D = {'a': 0, 5 , 'b': 1, 3 , 'c': 2, 4 , 'e': 6} However if I use what I wrote: for i in range(len(word_list)): ...
[ "if D.has_key('word_list[i]') == False:\n\nUh, what?\nAt the very least, you should drop the quotes:\nif D.has_key(word_list[i]) == False:\n\nBut you're also misusing a number of Python structures:\n\nWhy are summing up the indices? \nWhy are you comparing to False?\nShouldn't you be using setdefault\n\nLike this:\...
[ 6, 4, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008478983_dictionary_python.txt
Q: How to make Python code write once, run anywhere? I am learning Python. My intentions are: to write a webapp in Python/Django create an android app (using Jython) write some python scripts for unix box I was under (incorrect) impression that because Python has been implemented in Java (Jython) and .NET (IronPyth...
How to make Python code write once, run anywhere?
I am learning Python. My intentions are: to write a webapp in Python/Django create an android app (using Jython) write some python scripts for unix box I was under (incorrect) impression that because Python has been implemented in Java (Jython) and .NET (IronPython), I could simply write my Python code and run it thr...
[ "print 'Hello, World!'\n\nThis works just fine on any Python implementation worthy of the name. So will most other pure-Python code. Where it gets tricky is when using libraries, as Jython and IronPython are missing some standard library modules and don't support C extensions. Dealing with platform-specific code ca...
[ 2 ]
[ "Please be more specific about what you are trying to do. What is your regular Python code ? What does not work with it as you expected ?\nAccording to the Jython FAQ, Jython is an implementation of the Python language. The same Python code should produce the same result on Jython or CPython.\n" ]
[ -1 ]
[ "ironpython", "jython", "python" ]
stackoverflow_0008472264_ironpython_jython_python.txt
Q: Python map() function output into Pandas DataFrame I utilize python's map() function to pass parameters to a trading model and output the results. I use itertools.product to find all the possible combinations of the two parameters, then pass the combination to my function named "run". The function run returns a ...
Python map() function output into Pandas DataFrame
I utilize python's map() function to pass parameters to a trading model and output the results. I use itertools.product to find all the possible combinations of the two parameters, then pass the combination to my function named "run". The function run returns a pandas dataframe of returns. The Column header is a tup...
[ "I think all you need to do is:\ndata = DataFrame(dict(test1))\nthat will result in a DataFrame whose columns are the elements like\n(1.1, 175, -12.118290962161304)\nin pandas 0.6.1 (to be released soon) you'll also be able to do:\ndata = DataFrame.from_items(test1)\n" ]
[ 4 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0008451327_pandas_python.txt
Q: How to create a new window button PySide/PyQt? I'm having problems with a "New Window" function in PyQt4/PySide with Python 2.7. I connected a initNewWindow() function, to create a new window, to an action and put it in a menu bar. Once a common function in desktop software. Instead of giving me a new persistent w...
How to create a new window button PySide/PyQt?
I'm having problems with a "New Window" function in PyQt4/PySide with Python 2.7. I connected a initNewWindow() function, to create a new window, to an action and put it in a menu bar. Once a common function in desktop software. Instead of giving me a new persistent window alongside the other one the new window pops up...
[ "If a function creates a PyQt object that the application needs to continue using, you will have to ensure that a reference to it is kept somehow. Otherwise, it could be deleted by the Python garbage collector immediately after the function returns.\nSo either give the object a parent, or keep it as an attribute of...
[ 5, 3 ]
[]
[]
[ "pyqt", "pyside", "python", "windows" ]
stackoverflow_0008478210_pyqt_pyside_python_windows.txt
Q: Change values of a python dictionary contigent on the other values of the dictionary Is there a possibility to make the default input-values dependent on one of the input-values? I tried this: def getHigh(pricedata, start=min(pricedata), end=max(pricedata)): ## do something But it doesn't work, because priced...
Change values of a python dictionary contigent on the other values of the dictionary
Is there a possibility to make the default input-values dependent on one of the input-values? I tried this: def getHigh(pricedata, start=min(pricedata), end=max(pricedata)): ## do something But it doesn't work, because pricedata is not yet defined.
[ "Keep it simple :)\ndef getHigh(pricedata, start=None, end=None):\n start = min(pricedata) if start is None else start\n end = max(pricedata) if end is None else end\n\n", "In the general case, you can do this using None and testing for it.\ndef getHigh(pricedata, start=None, end=None):\n start = min(pri...
[ 6, 3, 2 ]
[]
[]
[ "default_value", "python" ]
stackoverflow_0008479424_default_value_python.txt
Q: Moving object across screen in Pygame So I am trying to move this random jumble of two polygons, a circle, and a line across the screen, any direction, and when it reaches the end of the screen is is placed back on the screen and moves again. Simply put, I want to move those shapes across the screen. I cannot re...
Moving object across screen in Pygame
So I am trying to move this random jumble of two polygons, a circle, and a line across the screen, any direction, and when it reaches the end of the screen is is placed back on the screen and moves again. Simply put, I want to move those shapes across the screen. I cannot really figure out how, I am new to pygame so ...
[ "You probably want to clear the screen each time you redraw.\nwhile True:\n windowSurface.fill(WHITE) #This clears the screen on each redraw\n pygame.draw.polygon(windowSurface,BLUE,((0+x,250+y),(120+x,120+y),(55+x,55+y)))\n pygame.draw.polygon(windowSurface,RED,((0+x,150+y),(85+x,85+y),(100+x,175+y),(0+x,...
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008452357_pygame_python.txt
Q: Finer control over Django timeuntil output possible? I'm currently using the timeuntil tag to show an items expiration date. It's currently spitting out... {{rental_till|timeuntill}} Which produces... 3 months, 1 week Is it possible to get it to just show, the months, for example? Or any type of finer control ov...
Finer control over Django timeuntil output possible?
I'm currently using the timeuntil tag to show an items expiration date. It's currently spitting out... {{rental_till|timeuntill}} Which produces... 3 months, 1 week Is it possible to get it to just show, the months, for example? Or any type of finer control over the output format, similar to the date tags.
[ "To only show months, you could write a simple template filter that splits the string on the comma, and returns the first item of the resulting list. The filter code would look like this:\nfrom django.template import Library\nregister = Library()\n\n@register.filter\ndef split_timeuntil(duration):\n return durat...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008477989_django_python.txt
Q: grouping with topology I apologize if this question has already been answered in: Topological Sort with Grouping However, I do not completely understand the answer as I am new to graph theory. I have the following items: c01,a11,b12,a21, b22,c23, c31,b32, a33. Each of these is a three tuple. Tup[0]: 'letter to gr...
grouping with topology
I apologize if this question has already been answered in: Topological Sort with Grouping However, I do not completely understand the answer as I am new to graph theory. I have the following items: c01,a11,b12,a21, b22,c23, c31,b32, a33. Each of these is a three tuple. Tup[0]: 'letter to group by' Tup[1]: 'group numbe...
[ "This is my solution\n>>> data\n['c01', 'a11', 'b12', 'a21', 'b22', 'c23', 'c31', 'b32', 'a33']\n>>> data=\"c01,a11,b12,a21, b22,c23, c31,b32, a33\"\n>>> data=[x.strip() for x in data.split(\",\")]\n>>> data=sorted(data,key=operator.itemgetter(0))\n>>> data=sorted(data,key=operator.itemgetter(1))\n>>> data=sorted(d...
[ 0 ]
[]
[]
[ "graph_theory", "grouping", "python", "topological_sort" ]
stackoverflow_0008478487_graph_theory_grouping_python_topological_sort.txt
Q: using python urllib how to avoid non HTML content I am using urllib (note not urllib2) and getting title of pages from user supplied urls. Unfortunately sometimes the url is not an HTML but some huge file or some very long running process on the remote site. I have checked the python docs but urllib is limited an...
using python urllib how to avoid non HTML content
I am using urllib (note not urllib2) and getting title of pages from user supplied urls. Unfortunately sometimes the url is not an HTML but some huge file or some very long running process on the remote site. I have checked the python docs but urllib is limited and looking at the source it seems I could change it but ...
[ "Here, it states that the info() method returns meta-information associated with the URL. You could use this to get the headers, and see what the Content-Type is (text/html), and if it's not what you want, discard the request.\n>>> import urllib\n>>> d = urllib.urlopen('http://www.google.com/')\n>>> try:\n... i...
[ 7 ]
[]
[]
[ "content_type", "limits", "python", "urllib" ]
stackoverflow_0008479736_content_type_limits_python_urllib.txt
Q: How to evenly distribute tasks among nodes with Celery? I am using Celery with Django to manage a task que and using one (or more) small(single core) EC2 instances to process the task. I have some considerations. My task eats 100% CPU on a single core. - uses whatever CPU available but only in one core If 2 tasks...
How to evenly distribute tasks among nodes with Celery?
I am using Celery with Django to manage a task que and using one (or more) small(single core) EC2 instances to process the task. I have some considerations. My task eats 100% CPU on a single core. - uses whatever CPU available but only in one core If 2 tasks are in progress on the same core, each task will be slowed d...
[ "it's actually easy: you start one celery-instance per ec2-instance. set concurrency to the number of cores per ec2-instance.\nnow the tasks don't interfere and distribute nicely among you instances.\n(the above assumes that your tasks are cpu bound)\n" ]
[ 2 ]
[]
[]
[ "celery", "django", "django_celery", "python" ]
stackoverflow_0008479320_celery_django_django_celery_python.txt
Q: Best (most "pythonic") way to temporarily unzip a file I need to temporarily create an unzipped version of some files. I've seen people do zcat somefile.gz > /tmp/somefile in bash, so I made this simple function in python: from subprocess import check_call def unzipto(zipfile, tmpfile): with open(tmpfile, 'wb'...
Best (most "pythonic") way to temporarily unzip a file
I need to temporarily create an unzipped version of some files. I've seen people do zcat somefile.gz > /tmp/somefile in bash, so I made this simple function in python: from subprocess import check_call def unzipto(zipfile, tmpfile): with open(tmpfile, 'wb') as tf: check_call(['zcat', zipfile], stdout=tf) B...
[ "gzip.open(zipfile).read() will give you the contents of the file in a single string.\nwith open(tmpfile, \"wb\") as tmp:\n shutil.copyfileobj(gzip.open(zipfile), tmp)\n\nwill put the contents in a temporary file.\n", "Have you considered using zlib or gzip or tarfile.\n" ]
[ 17, 6 ]
[]
[]
[ "gzip", "python" ]
stackoverflow_0008479827_gzip_python.txt
Q: editing QTableView cell value how could i make QTableView cell keep its original value when editing it? when i start editing cell it is cleared out automatically. I searched all over the place and i can not find any pointers that would lead somewhere. My implementation of model view: class BlockViewModel(QAbstrac...
editing QTableView cell value
how could i make QTableView cell keep its original value when editing it? when i start editing cell it is cleared out automatically. I searched all over the place and i can not find any pointers that would lead somewhere. My implementation of model view: class BlockViewModel(QAbstractTableModel): def __init__(sel...
[ "The data method is responsible for displaying your data all the time. While editing, it uses EditRole. So modify your data method to show values in EditRole same as DisplayRole like below:\ndef data(self, index, role):\n if role == Qt.DisplayRole or role == Qt.EditRole:\n try:\n row = index.ro...
[ 9 ]
[]
[]
[ "datamodel", "pyside", "python", "qt", "qtableview" ]
stackoverflow_0008479799_datamodel_pyside_python_qt_qtableview.txt
Q: PyAudio raise exception on buffer under/overflow PyAudio is based on PortAudio. Is there anyway to detect a buffer under/overflow for writing/reading from an audio stream in PyAudio? A: According to the documentation you can raise an exception on underflow when doing a write on a Stream class: Stream.write(self,...
PyAudio raise exception on buffer under/overflow
PyAudio is based on PortAudio. Is there anyway to detect a buffer under/overflow for writing/reading from an audio stream in PyAudio?
[ "According to the documentation you can raise an exception on underflow when doing a write on a Stream class:\nStream.write(self, frames, num_frames=None, exception_on_underflow=True)\n" ]
[ 2 ]
[]
[]
[ "audio", "portaudio", "pyaudio", "python" ]
stackoverflow_0004717238_audio_portaudio_pyaudio_python.txt
Q: using ctypes methods in python gives unexpected error I'm pretty new to python and ctypes. I'm trying to accomplish a seemingly easy task but am getting unexpected results. I'm trying to pass a string to a c function so I'm using the c_char_p type but it's giving me an error message. To simply it, this is whats ...
using ctypes methods in python gives unexpected error
I'm pretty new to python and ctypes. I'm trying to accomplish a seemingly easy task but am getting unexpected results. I'm trying to pass a string to a c function so I'm using the c_char_p type but it's giving me an error message. To simply it, this is whats happening: >>>from ctypes import * >>>c_char_p("hello world...
[ "In Python 3.x, the \"text literal\" is really a unicode object. You want to use the byte-string literal like b\"byte-string literal\"\n>>> from ctypes import *\n>>> c_char_p('hello world')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: string or integer address expected in...
[ 8 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0008480376_ctypes_python.txt
Q: comparing times with datetime I'm new to python, and I'm trying to use a time in a while statement. while hours_left is greater than 0:00 { do some stuff decrement hours_left } is what I'm trying to achieve. however I can't just say hours_left > 0 because it's an int. any ideas how I can type 0:00 as dat...
comparing times with datetime
I'm new to python, and I'm trying to use a time in a while statement. while hours_left is greater than 0:00 { do some stuff decrement hours_left } is what I'm trying to achieve. however I can't just say hours_left > 0 because it's an int. any ideas how I can type 0:00 as datetime? Thanks!
[ "You want a timedelta object.\nimport datetime\ncurrent_time = datetime.datetime(2011,12,12,12,0,0) # High Noon!\nend_time = datetime.datetime(2011,12,25,0,0,0) # Santa?\nwhile end_time-current_time > datetime.timedelta(0):\n do_stuff()\n current_time = current_time - datetime.timedelta(hours=1)\n\n", ...
[ 2, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008480408_datetime_python.txt
Q: replacing a thread instance while still isAlive I have a python thread, assigned to a variable name xx, which, when it completes its' run function triggers a callback. The callback eventually tries to create a new instance of that thread with variable name xx, effectively restarting the thread. Of course, checking...
replacing a thread instance while still isAlive
I have a python thread, assigned to a variable name xx, which, when it completes its' run function triggers a callback. The callback eventually tries to create a new instance of that thread with variable name xx, effectively restarting the thread. Of course, checking xx.isAlive() returns True (since it initiated the ca...
[ "Without understanding the details of your situation, my knee-jerk reaction is to say, Don't recreate the thread -- reuse the established one. It takes less time to reuse the established thread than it would to shut it down and start a new one.\n", "I voted for unubtu's answer. But in case this scenario is not po...
[ 4, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008479596_multithreading_python.txt
Q: How to respond to HTTP OPTIONS request on a JSON-RPC server My JSON-RPC client (browser using dojo JSON-RPC) makes a JSON-RPC request (dojo.callRemote) to my JSON-RPC server on myserver.com/12345 (Python 2.5, SimpleJSONRPCServer). The server then gets a HTTP request with header "OPTIONS / HTTP/1.1", which it can'...
How to respond to HTTP OPTIONS request on a JSON-RPC server
My JSON-RPC client (browser using dojo JSON-RPC) makes a JSON-RPC request (dojo.callRemote) to my JSON-RPC server on myserver.com/12345 (Python 2.5, SimpleJSONRPCServer). The server then gets a HTTP request with header "OPTIONS / HTTP/1.1", which it can't handle by default, so I wrote a custom handler for this request...
[ "add code and try, it work fine for me:\nclass CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):\n...\n...\n def do_OPTIONS(self):\n self.send_response(200, \"ok\")\n self.send_header('Access-Control-Allow-Origin', self.headers.dict['origin'])\n self.send_header('Access-Contr...
[ 3, 2, 1 ]
[]
[]
[ "dojo", "http", "json_rpc", "python" ]
stackoverflow_0002580461_dojo_http_json_rpc_python.txt