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: python compilation error am using Python brisa Framework to implement UpnP protocols. I was trying to make a device but while executing it in ubuntu linux env, it throws me an error.What does thsi eror mean? DO i need to change the framework files?? /usr/local/lib/python2.6/dist-packages/cherrypy/lib/cptools.py:4:...
python compilation error
am using Python brisa Framework to implement UpnP protocols. I was trying to make a device but while executing it in ubuntu linux env, it throws me an error.What does thsi eror mean? DO i need to change the framework files?? /usr/local/lib/python2.6/dist-packages/cherrypy/lib/cptools.py:4: DeprecationWarning: the md5 m...
[ "That's not an error, it's a warning. You're using code written for python 2.5 or earlier, before there was a hashlib module.\n" ]
[ 0 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0004902366_networking_python.txt
Q: how to install setuptools for Python 2.7.1 on Mac OS X Tiger? i've got a problem when trying to install setuptools on Mac OS X Tiger the current version of python is 2.7.1 ...:~/Desktop usrusr$ python -V Python 2.7.1 i downloaded this egg setuptools-0.6c11-py2.7.egg, and followed the instructions. unfortunately i...
how to install setuptools for Python 2.7.1 on Mac OS X Tiger?
i've got a problem when trying to install setuptools on Mac OS X Tiger the current version of python is 2.7.1 ...:~/Desktop usrusr$ python -V Python 2.7.1 i downloaded this egg setuptools-0.6c11-py2.7.egg, and followed the instructions. unfortunately i'm getting an error: ...:~/Desktop usrusr$ sudo sh setuptools-0.6c1...
[ "When you installed python, you didn't end up with a python2.7 symlink to your python binary for some reason. Creating one somewhere in your path should work.\n" ]
[ 1 ]
[]
[]
[ "macos", "python", "setuptools" ]
stackoverflow_0004902373_macos_python_setuptools.txt
Q: Faster alternative/usage of os.walk to only find all subdirs in Python From what I've read around the interwebs and here on SO, os.walk is one of the best bets for finding all subdirs and files in a directory, but the question I have is, if I only want to recursively find all the subdirectories, is os.walk the fas...
Faster alternative/usage of os.walk to only find all subdirs in Python
From what I've read around the interwebs and here on SO, os.walk is one of the best bets for finding all subdirs and files in a directory, but the question I have is, if I only want to recursively find all the subdirectories, is os.walk the fastest solution? I suppose in addition my question is since the call to os.wal...
[ "I'm not 100% for certain on all aspects of this but from my understanding:\nIn general the file listing is already included in the directory metadata so when you look up a directory the data is already there (Linux, not sure bout windows). So this means that os.walk is probably the fastest/simplest way of doing t...
[ 2 ]
[]
[]
[ "os.walk", "python", "subdirectory" ]
stackoverflow_0004902237_os.walk_python_subdirectory.txt
Q: python grep look for a pattern and then a number of lines before I'm looking to do the equivalent of _grep -B14 MMA I have a URL that I open and it spits out many lines. I want to find the line that has 'MMa' then print the 14th line before it I don't even know where to begin with this. import urllib import...
python grep look for a pattern and then a number of lines before
I'm looking to do the equivalent of _grep -B14 MMA I have a URL that I open and it spits out many lines. I want to find the line that has 'MMa' then print the 14th line before it I don't even know where to begin with this. import urllib import urllib2 url = "https://longannoyingurl.com" opts = { 'action': 'D...
[ "Instead of just doing a bare read on the response object, call readlines instead, and then run a regular expression through each line. If the line matches, print the 14th line before it, but check to see that you're not negative indexing. E.g.\nimport re\n\nlines = response.readlines()\n\nr = re.compile(r'MMa')\nf...
[ 8, 1, 0 ]
[]
[]
[ "grep", "lines", "python" ]
stackoverflow_0004902259_grep_lines_python.txt
Q: How to get transparent background in window with PyGTK and PyCairo? I've been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I can't get it to work. I've tried a lot of different ways, they all failed, t...
How to get transparent background in window with PyGTK and PyCairo?
I've been trying really hard to create a window with no decoration and a transparent background using PyGTK. I would then draw the content of the window with Cairo. But I can't get it to work. I've tried a lot of different ways, they all failed, this is one of them #!/usr/bin/env python import pygtk pygtk.require('2.0...
[ "So, I actually figured this out myself.\nThis is a working example. I've commented the relevant parts just in case somebody else is interested in how to do this.\n#!/usr/bin/env python\n\nimport pygtk\npygtk.require('2.0')\nimport gtk, sys, cairo\nfrom math import pi\n\ndef expose (widget, event):\n cr = widget...
[ 9, 0 ]
[]
[]
[ "cairo", "gtk", "pycairo", "pygtk", "python" ]
stackoverflow_0004889045_cairo_gtk_pycairo_pygtk_python.txt
Q: GetThreadContext() returns error 18 - There are no more files GetThreadContext() returns error 18 - There are no more files. I've searched all over the place and cannot find explanation to the error. Could someone clarify this for me? Big thanks. A: Rob Kennedyand Hans Passant answered my question below. I wante...
GetThreadContext() returns error 18 - There are no more files
GetThreadContext() returns error 18 - There are no more files. I've searched all over the place and cannot find explanation to the error. Could someone clarify this for me? Big thanks.
[ "Rob Kennedyand Hans Passant answered my question below. I wanted to just quote Rob and Hans here as an answer:\nHans Passant\nFirst verify that it [GetThreadContext()] returned FALSE, you won't get a valid error code from GetLastError() if it [GetThreadContext()] returned TRUE.\nRob Kennedy\nThe return value from ...
[ 1 ]
[]
[]
[ "c++", "ctypes", "python", "winapi" ]
stackoverflow_0004901889_c++_ctypes_python_winapi.txt
Q: How to set-up generic views in an application's urls.py? Let's say I have a project's urlconf which includes myapp's urlconf: urlpatterns = patterns('', (r'^myapp', include(myapp.urls)), ) and a myapp/urls.py with some routes defined: urlpatterns = patterns('myapp.views', (r'^manager$', 'manager_view'), )...
How to set-up generic views in an application's urls.py?
Let's say I have a project's urlconf which includes myapp's urlconf: urlpatterns = patterns('', (r'^myapp', include(myapp.urls)), ) and a myapp/urls.py with some routes defined: urlpatterns = patterns('myapp.views', (r'^manager$', 'manager_view'), ) I want to use generic views in myapp (i.e. to display an ite...
[ "You don't need to use the prefix at all - you can specify the full path to each of your views for each url:\nurlpatterns = patterns('',\n (r'^manager$', 'myapp.views.manager_view'),\n (r'^items/(?P<page>[0-9]+)$', 'django.views.generic.list_detail.object_list',\n items_list),\n)\n\nAlternatively, you ...
[ 3 ]
[]
[]
[ "django", "django_generic_views", "python", "urlconf" ]
stackoverflow_0004902506_django_django_generic_views_python_urlconf.txt
Q: Tiny python executable? I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb). Is there any way to create even smaller Python executables? For example using a shri...
Tiny python executable?
I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb). Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something ...
[ "If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c...
[ 10, 3, 1 ]
[]
[]
[ "executable", "pyinstaller", "python" ]
stackoverflow_0000254635_executable_pyinstaller_python.txt
Q: Regex to match double underscores? I'm trying to extend the python.lang file so that it will make methods like __init__ highlighted. I've been trying to come up with a Regex that will match all __privateMethods(). The python.lang is a XML file containing all of the highlighting rules for python files. Ex: <context...
Regex to match double underscores?
I'm trying to extend the python.lang file so that it will make methods like __init__ highlighted. I've been trying to come up with a Regex that will match all __privateMethods(). The python.lang is a XML file containing all of the highlighting rules for python files. Ex: <context id="special-variables" style-ref="speci...
[ "It should rather be:\n(__[a-zA-Z0-9_]*(__)?)\n\nIn order to match all of the following: \n__hello()\n__init__()\n__this_is_a_function()\n__this_is_also_a_function__()\n__a_URL2_function__()\n\n", "Match your previous case piped with the following (rubular example):\n(^__[a-z]*__$)\n\n" ]
[ 5, 1 ]
[]
[]
[ "gedit", "python", "regex", "xml" ]
stackoverflow_0004902509_gedit_python_regex_xml.txt
Q: Considerations for moving our web app to an appliance We have developed a web application running on Linux that is quite popular. We now wish to release it as an appliance so customers can run it internally on their own networks. We are unsure of the best approach. We are flexible on areas such as: the Linux dist...
Considerations for moving our web app to an appliance
We have developed a web application running on Linux that is quite popular. We now wish to release it as an appliance so customers can run it internally on their own networks. We are unsure of the best approach. We are flexible on areas such as: the Linux distro, whether it's a hardware or software only appliance. Doe...
[ "I know when Github needed to do something similar, they contracted with a company who specializes in building installers called BitRock. \nIf you want to develop the solution yourself, you can't go wrong building a Debian package (or RPM if you prefer). That's what most linux system admins would be comfortable wit...
[ 1, 0 ]
[]
[]
[ "appliance", "python" ]
stackoverflow_0004872722_appliance_python.txt
Q: Pymongo AssertionError: ids don't match I use: MongoDB 1.6.5 Pymongo 1.9 Python 2.6.6 I have 3 types of daemons. 1st load data from web, 2nd analyze it and save result, and 3rd group result. All of them working with Mongodb. At some time 3rd daemon throws many exceptions like this(mostly when there are big amoun...
Pymongo AssertionError: ids don't match
I use: MongoDB 1.6.5 Pymongo 1.9 Python 2.6.6 I have 3 types of daemons. 1st load data from web, 2nd analyze it and save result, and 3rd group result. All of them working with Mongodb. At some time 3rd daemon throws many exceptions like this(mostly when there are big amount of data in DB): Traceback (most recent call...
[ "This is likely a threading problem related to how you are using worker threads with gevent coroutines. It seems like the pymongo connection object is reading a response for a request it didn't make.\n" ]
[ 4 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0004817431_mongodb_pymongo_python.txt
Q: need help with intermediate/advanced caching in django, with memcached and friends So: I always deploy my Django apps with memcached running alongside. For my purposes, they're always running on the same instance. I'm enabling the cache with these lines in settings.py: CACHE_BACKEND = 'memcached://127.0.0.1:11211/...
need help with intermediate/advanced caching in django, with memcached and friends
So: I always deploy my Django apps with memcached running alongside. For my purposes, they're always running on the same instance. I'm enabling the cache with these lines in settings.py: CACHE_BACKEND = 'memcached://127.0.0.1:11211/' CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = "the_name_of_the_app" SESS...
[ "Memcache isn't going to magically make your website faster. The absolute first thing you are going to need to do is figuring out what is expensive. A simple way to do this is to decorate your views or other functions to see how long they generally take to execute, for example:\ndef print_latency(f):\n def wrapp...
[ 2 ]
[]
[]
[ "caching", "django", "memcached", "optimization", "python" ]
stackoverflow_0004170992_caching_django_memcached_optimization_python.txt
Q: Which methods should be overridden to implement automatic locking and unlocking records in Django How can I modify the behaviour of models in Django to perform automatic locking and unlocking records in database on selecting them and make this behaviour transparent for a programmer? I already know how to lock and ...
Which methods should be overridden to implement automatic locking and unlocking records in Django
How can I modify the behaviour of models in Django to perform automatic locking and unlocking records in database on selecting them and make this behaviour transparent for a programmer? I already know how to lock and unlock a record (database record locking) but we'd like to know where this code should be placed in Dja...
[ "You'll want to obtain the lock during the model __init__(); this can be implemented fairly simply through inheritance. The model's Manager will have a QuerySet instantiated for that model and your lock will be obtained as soon as the retrieved model is added to the query _result_cache[] or when the query's iterato...
[ 2 ]
[]
[]
[ "concurrency", "django", "locking", "postgresql", "python" ]
stackoverflow_0004901861_concurrency_django_locking_postgresql_python.txt
Q: python setup path problem ** cd Python-2.5.5 ./configure --prefix=/usr/local/python2.5 make make test sudo make install sudo ln -s /usr/local/python2.5/bin/python /usr/bin/python2.5 ** I followed the above steps to download python 2.5 on Obuntu where python 2.6 was already installed. Then I changed one the file ...
python setup path problem
** cd Python-2.5.5 ./configure --prefix=/usr/local/python2.5 make make test sudo make install sudo ln -s /usr/local/python2.5/bin/python /usr/bin/python2.5 ** I followed the above steps to download python 2.5 on Obuntu where python 2.6 was already installed. Then I changed one the file and tried to install it with th...
[ "I'm guessing that the build process created some files with root ownership when you ran this:\nsudo make install\n\nWhen running as a non-root user, you don't have permission to delete those files.\nYou may need to run this if you want to be able to build as a non-root user again:\nsudo make clean\n\n", "You nee...
[ 0, 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0004903413_installation_python.txt
Q: Python sys.argv[1:] not picking up command line options Update/Solution: the answer is below, from Zack. The problem was, indeed, DOS line endings on the script file itself, clenotes.cmd. Since I futzed with the various files so much, I deleted the whole directory and then re-downloaded a fresh copy from HERE. I r...
Python sys.argv[1:] not picking up command line options
Update/Solution: the answer is below, from Zack. The problem was, indeed, DOS line endings on the script file itself, clenotes.cmd. Since I futzed with the various files so much, I deleted the whole directory and then re-downloaded a fresh copy from HERE. I ran Zack's perl script on the file just like so: perl -pi.bak ...
[ "I think your problem is that clenotes.cfg has DOS line endings, which Python is misinterpreting. Try changing this line of clenotes.py\nconfig.readfp(open('%sconfig/clenotes.cfg' % System.getProperty('jython.home')))\n\nto read\nconfig.readfp(open('%sconfig/clenotes.cfg' % System.getProperty('jython.home'), \"rU\"...
[ 5, 3 ]
[]
[]
[ "command_line", "jython", "linux", "lotus_notes", "python" ]
stackoverflow_0004893010_command_line_jython_linux_lotus_notes_python.txt
Q: is there an easy way of fetching the sent headers of an http request for pycurl/curl? Right now I'm using a proxy where I can see the headers that are sent. I'm wondering if there's a simpler pycurl method of grabbing the headers that were sent in an http request. Ive tried using HEADERFUNCTION already but it give...
is there an easy way of fetching the sent headers of an http request for pycurl/curl?
Right now I'm using a proxy where I can see the headers that are sent. I'm wondering if there's a simpler pycurl method of grabbing the headers that were sent in an http request. Ive tried using HEADERFUNCTION already but it gives you the response headers and not the ones i'm looking for.
[ "libcurl itself provides this data in the DEBUGFUNCTION callback, so if there's no current support for that in pycurl I figure it should be added and it shouldn't be too hard to do it...\n", "There is indeed support for the debugfunction callback. Alternatively, if you just need the data for debugging purposes, s...
[ 1, 0 ]
[]
[]
[ "curl", "http_headers", "pycurl", "python" ]
stackoverflow_0004839670_curl_http_headers_pycurl_python.txt
Q: Not enough arguments error in Python, what should I do to fix this? Error: Traceback (most recent call last): File "C:\Python26\Lib\idlelib\full_rpg.py", line 145, in <module> Commands[c](p) File "C:\Python26\Lib\idlelib\full_rpg.py", line 57, in status print "%s's Level:" % (self.name, self.level) Typ...
Not enough arguments error in Python, what should I do to fix this?
Error: Traceback (most recent call last): File "C:\Python26\Lib\idlelib\full_rpg.py", line 145, in <module> Commands[c](p) File "C:\Python26\Lib\idlelib\full_rpg.py", line 57, in status print "%s's Level:" % (self.name, self.level) TypeError: not all arguments converted during string formatting Code line w...
[ "You need to provide another place to put the second string. From the python docs:\n\nIf format requires a single argument,\n values may be a single non-tuple\n object. [4] Otherwise, values must be\n a tuple with exactly the number of\n items specified by the format string,\n or a single mapping object (for\...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0004903744_python.txt
Q: Using Selenium's Python API - How do I get the number of rows in a table? How do I get the number of rows in an HTML table using Selenium's Python API? I'd have a 2 column table of Keys and Values and I'd like to read it into a dictionary. Something like: browser = Selenium(...) ... rows = ? (this is what I need) ...
Using Selenium's Python API - How do I get the number of rows in a table?
How do I get the number of rows in an HTML table using Selenium's Python API? I'd have a 2 column table of Keys and Values and I'd like to read it into a dictionary. Something like: browser = Selenium(...) ... rows = ? (this is what I need) for r = range(row): key = browser.get_table('tablename.' + r + '.0') va...
[ "from the driver:\ndef get_xpath_count(self,xpath):\n \"\"\"\n Returns the number of nodes that match the specified xpath, eg. \"//table\" would give\n the number of tables.\n\n 'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you.\n ...
[ 2, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0004903144_python_selenium.txt
Q: Python - Acquiring a count of file extensions across all directories we have a hardrive with hundreds of thousands of files i need to figure out how many of every file extension we have how can i do this with python? i need it to go through every directory. this lawyers at my company need this. it can be a total f...
Python - Acquiring a count of file extensions across all directories
we have a hardrive with hundreds of thousands of files i need to figure out how many of every file extension we have how can i do this with python? i need it to go through every directory. this lawyers at my company need this. it can be a total for the entire hardrive it does not have to be broken down by directory exa...
[ "Have a look at os.walk call in the os module and traverse through the entire directory tree. Get the extension using os.path.splitext. Maintain a dictionary where key the extension.lower() and increment the count of each extension that you encounter.\nimport os\nimport collections\nextensions = collections.default...
[ 10, 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004903878_python.txt
Q: python variable function definition First, please don't shoot me if this has already been asked - I have looked around but to no avail. I have a python file (named rpc.py) containing many functions serving AJAX requests. For example: def test(self, vars): return vars['id'] def test2(self, vars): return va...
python variable function definition
First, please don't shoot me if this has already been asked - I have looked around but to no avail. I have a python file (named rpc.py) containing many functions serving AJAX requests. For example: def test(self, vars): return vars['id'] def test2(self, vars): return vars['id']+1 And it is called with a URL l...
[ "You can use\ngetattr(server, vars[\"fnc\"])(vars)\n\nbut I'd also suggest adding a prefix to the service names (e.g. \"do_test\") to avoid malicious code that would be able to call any of the methods of the server object simply by passing their names (including ones you think it shouldn't). In this case it would b...
[ 6 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0004904073_eval_python.txt
Q: Execute a block of python code with exec, capturing all its output? What's a good way to exec a bunch of python code, like exec mycode, and capture everything it prints to stdout into a string? A: Try replacing the default sys.stdout, like in this snippet: import sys from StringIO import StringIO buffer = Strin...
Execute a block of python code with exec, capturing all its output?
What's a good way to exec a bunch of python code, like exec mycode, and capture everything it prints to stdout into a string?
[ "Try replacing the default sys.stdout, like in this snippet:\nimport sys\nfrom StringIO import StringIO\n\nbuffer = StringIO()\nsys.stdout = buffer\n\nexec \"print 'Hello, World!'\"\n\n#remember to restore the original stdout!\nsys.stdout = sys.__stdout__\n\nprint buffer.getvalue()\n\n" ]
[ 11 ]
[]
[]
[ "dynamic", "exec", "io", "python" ]
stackoverflow_0004904079_dynamic_exec_io_python.txt
Q: How to parse an ical file and export event to a list? I have an iCal file. I would like to be able to extract all events into a list. Is there any tools or library that can do it easily? (e.g. handle the time zone info) Python is the preferred language, but any interpretive language is OK. A: http://sourceforge....
How to parse an ical file and export event to a list?
I have an iCal file. I would like to be able to extract all events into a list. Is there any tools or library that can do it easily? (e.g. handle the time zone info) Python is the preferred language, but any interpretive language is OK.
[ "http://sourceforge.net/projects/dday-ical/ is quite a good .net library for ical. the object model is really good as well \n" ]
[ 2 ]
[]
[]
[ "icalendar", "python" ]
stackoverflow_0004904198_icalendar_python.txt
Q: Python / Django - Get List Value With Index From Object Variable Value I have a list that is passed into a template. I want to access a value with a specific index. Problem is the list is accessed with dot notation in the template... For example: object = { id: 1 } list = [ "zero", "one" ] print list[ object.id ...
Python / Django - Get List Value With Index From Object Variable Value
I have a list that is passed into a template. I want to access a value with a specific index. Problem is the list is accessed with dot notation in the template... For example: object = { id: 1 } list = [ "zero", "one" ] print list[ object.id ] ## one Once the list is in the template you access values by index with d...
[ "I don't think this is possible with Django's template language. It is pretty limited by design.\nYou can do this by putting that code in the view, and passing the value of list[object.id] down to the template when you render it.\n", "I don't quite agree it's impossible.\nYou can create template tag, which will a...
[ 2, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004902227_django_django_templates_python.txt
Q: Error while loading a file in Python-Set Up path Problem The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/usr/local/lib/python2.6/dist-packages/test-easy-install-20294.pth' The installation directory you specified (via --install-d...
Error while loading a file in Python-Set Up path Problem
The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/usr/local/lib/python2.6/dist-packages/test-easy-install-20294.pth' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /us...
[ "The easiest way is to run the command with administrator privileges. It looks like you're using some form of Linux. In Ubuntu or similar, use:\nsudo easy_install <package>\n\nOtherwise, you can use an option:\neasy_install -d /home/<username>/wherever <package>\n\nThen you'll need to make sure that the directory m...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004904312_python.txt
Q: How to read in binary data after ascii header in Python I have some imaging data that's stored in a file that contains an ascii text header, ending with a null character, followed by the binary data. The ascii headers vary in length, and I'm wondering what's the best way to open the file, read the header and find ...
How to read in binary data after ascii header in Python
I have some imaging data that's stored in a file that contains an ascii text header, ending with a null character, followed by the binary data. The ascii headers vary in length, and I'm wondering what's the best way to open the file, read the header and find the null character, and then load the binary data (in Python)...
[ "Probably ought to start with something like this.\nwith open('some file','rb') as input:\n aByte= input.read(1)\n while aByte and ord(aByte) != 0: aByte= input.read(1)\n # At this point, what's left is the binary data.\n\nPython version numbers matter a lot for this kind of thing. The issue is the result...
[ 2, 1, 1 ]
[]
[]
[ "ascii", "binary", "file_io", "python" ]
stackoverflow_0004904184_ascii_binary_file_io_python.txt
Q: How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly? I'm currently trying to escape a variable using django templating filters as below. I use a jinja2 template engine instead of just django's primary templateing engine {{ my_variable|escape|linebreaks }} the output of a string with ne...
How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?
I'm currently trying to escape a variable using django templating filters as below. I use a jinja2 template engine instead of just django's primary templateing engine {{ my_variable|escape|linebreaks }} the output of a string with newlines is as follows: Lorem ipsum <br /> dolor sit amet <br />rg srg gs rgsr rsg serg<...
[ "So you are using django's linebreaks filter in a jinja2 template? In that case, I would assume that the way django marks a string safe may not be compatible with jinja2, therefore escaping the tags added by django (if autoescape is active).\nWhat if you added the safe filter from jinja2 to the end?\n{{ my_variable...
[ 5, 2 ]
[]
[]
[ "django", "django_templates", "html", "jinja2", "python" ]
stackoverflow_0004901483_django_django_templates_html_jinja2_python.txt
Q: Creating Schema for Users with Friends without many to many relationship? I'm working on my first Django app and trying to create the models for it but am stuck on how to create what I think should be a simple model relationship. I want to create a model for a user, with typical attributes like username, password...
Creating Schema for Users with Friends without many to many relationship?
I'm working on my first Django app and trying to create the models for it but am stuck on how to create what I think should be a simple model relationship. I want to create a model for a user, with typical attributes like username, password(hash of course), date joined, etc. Then would like to be able to link this use...
[ "First, I would recommend you not create your own User model, instead use the one that comes built in Django. It takes care of all the fields that you're looking for.\nSecond, I would also create a \"profile\" model and store my friends in that. Have a look here on what profiles are: http://docs.djangoproject.com/e...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "mysql", "python", "sql" ]
stackoverflow_0004904891_django_django_models_mysql_python_sql.txt
Q: Python convert String to Tuple for REST API I'm trying to build a REST API using django-piston and in the library, I can specify the fields to display using a tuples. fields = ('id', 'title', ('author', 'username',),) Hence, I would like to allow the developer to request the data format via GET operation such as:...
Python convert String to Tuple for REST API
I'm trying to build a REST API using django-piston and in the library, I can specify the fields to display using a tuples. fields = ('id', 'title', ('author', 'username',),) Hence, I would like to allow the developer to request the data format via GET operation such as: http://localhost/api/users?attr=(id,title,(autho...
[ "I would just use regular string methods for parsing, and whatever syntax you find suitable. In my opinion, it's totally uncool to expose your inner gears like that.\n", "You didn't specify the Python version you are using, but here's a solution that works in Python 2.6 and doesn't use eval.\nimport ast\n\ndef pa...
[ 1, 1 ]
[]
[]
[ "api", "python" ]
stackoverflow_0004904446_api_python.txt
Q: Access a URL (w/ cookies) using sockets? I'm trying to write a program that uses sockets to connect to a website and save data from it. The issue I have is that I can't figure out how to connect to something besides index.php. Like, say I want to connect to page1.php instead of index.php. Can anyone help me with t...
Access a URL (w/ cookies) using sockets?
I'm trying to write a program that uses sockets to connect to a website and save data from it. The issue I have is that I can't figure out how to connect to something besides index.php. Like, say I want to connect to page1.php instead of index.php. Can anyone help me with that? Also, is there a way to get all the data ...
[ "You need to be using the urllib2 and cookielib modules. Here's an example from the Python Cookbook (see more).\n" ]
[ 0 ]
[]
[]
[ "cookies", "python", "sockets", "urllib2" ]
stackoverflow_0004905111_cookies_python_sockets_urllib2.txt
Q: aapt: Do not skip (null) files when packaging I am developing an Android application that uses a number of python scripts in res/raw that are deployed via SL4A and included in the app's APK. As the scripts make use of python packages, their directories contain a number of 0byte sized __init__.py files that are nec...
aapt: Do not skip (null) files when packaging
I am developing an Android application that uses a number of python scripts in res/raw that are deployed via SL4A and included in the app's APK. As the scripts make use of python packages, their directories contain a number of 0byte sized __init__.py files that are necessary for python to recognize the directories as p...
[ "If this is your only problem you can just add a comment '#' inside the __init__.py files.\nIf you find more problems as the directory structure you can use a tar or zip and expand it after APK installation.\n" ]
[ 0 ]
[]
[]
[ "aapt", "android", "python" ]
stackoverflow_0004904321_aapt_android_python.txt
Q: Socket Programming Issue - Python Alright, I've spent about three hours fiddling with socket programming in Python trying to make a simple chat program. I've gotten the client to send text to the server and then, from then client, it repeats the message to it's self. However, I want the message to be sent to the s...
Socket Programming Issue - Python
Alright, I've spent about three hours fiddling with socket programming in Python trying to make a simple chat program. I've gotten the client to send text to the server and then, from then client, it repeats the message to it's self. However, I want the message to be sent to the server and then the server, not the clie...
[ "Right now your app is instantiating the MyUDPHandler class for each client connection. When the connection is opened you need to store that instance to a static array or queue. Then when the handle() call is made it can loop through all those sockets and send a copy of the data to each of them.\nI'd checkout the...
[ 1, 1 ]
[]
[]
[ "connection", "python", "sockets" ]
stackoverflow_0004904567_connection_python_sockets.txt
Q: calling __coerce__() method on derived classes results in an error My trial was like below, but it didn't work. class MyNum: def __init__(self , n): self.n = n class MyNum2(MyNum): def __coerce__(self , y): return self, y def __radd__(self, y): print 'radd called' return self....
calling __coerce__() method on derived classes results in an error
My trial was like below, but it didn't work. class MyNum: def __init__(self , n): self.n = n class MyNum2(MyNum): def __coerce__(self , y): return self, y def __radd__(self, y): print 'radd called' return self.n + y.n I typed on the python command line: >>> x = MyNum(20) >>> y = M...
[ "Based on the error message, your __coerce__ implementation actually had\nreturn self.y\ninstead of the\nreturn self,y\nas you've written in the example code.\nYour code above works for me, and you don't actually even need the __coerce__ method here. Just having the __radd__ is sufficient in your example.\n" ]
[ 1 ]
[]
[]
[ "coerce", "derived_class", "inheritance", "python" ]
stackoverflow_0004905344_coerce_derived_class_inheritance_python.txt
Q: Python Numpy Matrix - Return the value contained in the matrix? I have a 1x1 matrix that contains a value. I want just the value. matrix([[-0.16666667+0.66666667j]]) I want the complex number inside that matrix. How do I get it? A: >>> m = matrix([[-1.0/6 + (2.0j/3)]]) >>> m matrix([[-0.16666667+0.66666667j]]) >...
Python Numpy Matrix - Return the value contained in the matrix?
I have a 1x1 matrix that contains a value. I want just the value. matrix([[-0.16666667+0.66666667j]]) I want the complex number inside that matrix. How do I get it?
[ ">>> m = matrix([[-1.0/6 + (2.0j/3)]])\n>>> m\nmatrix([[-0.16666667+0.66666667j]])\n>>> m.shape\n(1, 1)\n>>> m[0,0]\n(-0.16666666666666666+0.66666666666666663j)\n>>> m[(0,0)]\n(-0.16666666666666666+0.66666666666666663j)\n\nor, while we're at it:\n>>> m.tolist()[0][0] # seldom useful, though\n(-0.16666666666666666+0...
[ 9, 6 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0004905381_matrix_numpy_python.txt
Q: Python SqlAlchemy Pass Query to View Serialization Issue What is the best way to pass a sqlalchemy query's result to the view? I have a declaratively declared table such as: class Greeting(Base): __tablename__ = 'greetings' id = Column(Integer, primary_key=True) author = Column(String) content = Column(Te...
Python SqlAlchemy Pass Query to View Serialization Issue
What is the best way to pass a sqlalchemy query's result to the view? I have a declaratively declared table such as: class Greeting(Base): __tablename__ = 'greetings' id = Column(Integer, primary_key=True) author = Column(String) content = Column(Text) date = Column(DateTime) def __init__(self, author, co...
[ "Take a look at http://www.sqlalchemy.org/docs/core/serializer.html.\n\nSerializer/Deserializer objects for usage with SQLAlchemy query structures, allowing “contextual” deserialization.\nAny SQLAlchemy query structure, either based on sqlalchemy.sql.* or sqlalchemy.orm.* can be used. The mappers, Tables, Columns, ...
[ 0 ]
[]
[]
[ "json", "python", "serialization", "sqlalchemy" ]
stackoverflow_0004905320_json_python_serialization_sqlalchemy.txt
Q: How to use python io library to write on to an external file I am currently using the python io library to write in to an external file. Below is a sample piece of code which i am trying to execute: import io output=io.StringIO output.write('\n Hello world ') output.close() print output.getvalue() when I run thi...
How to use python io library to write on to an external file
I am currently using the python io library to write in to an external file. Below is a sample piece of code which i am trying to execute: import io output=io.StringIO output.write('\n Hello world ') output.close() print output.getvalue() when I run this piece of code i get an error. Can any one tell me where I am goi...
[ "StringIO is for writing to strings, treating them as in-memory streams.\nIf you want to write to file, do this:\nf = open('yourfile', 'w')\nf.write('Hello, world.')\nf.close()\n\nNo need to use StringIO for this.\nYou did not even get an instance of the class, because there aren't parentheses () after StringIO, so...
[ 6, 2, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004900511_file_io_python.txt
Q: How do I receive mail using Python? I am trying to make a program on my computer at home that will constantly check a certain gmail address; The purpose being the only email this address receives is from me. I would just like to be able to Check for mail Download mail (presumably to a string, though a file is acc...
How do I receive mail using Python?
I am trying to make a program on my computer at home that will constantly check a certain gmail address; The purpose being the only email this address receives is from me. I would just like to be able to Check for mail Download mail (presumably to a string, though a file is acceptable), and Delete the mail from the we...
[ "As Gabi points out, you should check out libgmail. You might also want to check out twisted python. They have some powerful modules for SMTP, POP3, IMAP, and many more that have nothing to do with email.\n", "If you want to write a program to just process incoming e-mail, take a look at Pythomnic framework: http...
[ 2, 1 ]
[]
[]
[ "email", "python" ]
stackoverflow_0004905441_email_python.txt
Q: Using 'in' to match an attribute of Python objects in an array I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, foo in iter_attr(array of python objects, attribute name) I've looked over the docs but this kind of thing doesn't fall under any o...
Using 'in' to match an attribute of Python objects in an array
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, foo in iter_attr(array of python objects, attribute name) I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
[ "Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search.\nThe temporary list can be avoiding by using a gene...
[ 49, 12, 10, 7, 6, 5, 3, 0 ]
[]
[]
[ "arrays", "iteration", "python" ]
stackoverflow_0000000683_arrays_iteration_python.txt
Q: Convert a text file from UTF-8 to ASCII to avoid python UnicodeEncodeError? I'm getting an encoding error from a script, as follows: from django.template import loader, Context t = loader.get_template(filename) c = Context({'menus': menus}) print t.render(c) File "../django_to_html.py", line 45, in <module> ...
Convert a text file from UTF-8 to ASCII to avoid python UnicodeEncodeError?
I'm getting an encoding error from a script, as follows: from django.template import loader, Context t = loader.get_template(filename) c = Context({'menus': menus}) print t.render(c) File "../django_to_html.py", line 45, in <module> print t.render(c) UnicodeEncodeError: 'ascii' codec can't encode character u'...
[ "How to find ALL the nasties in your file:\nimport unicodedata as ucd\nimport sys\nwith open(sys.argv[1]) as f:\n for linex, line in enumerate(f):\n uline = line.decode('UTF-8')\n bad_line = False\n for charx, char in enumerate(uline):\n if char <= u'\\xff': continue\n ...
[ 3, 2, 1, 0 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0004903067_character_encoding_python.txt
Q: split utf8 strings into parts with regexp I need to find in text strings, which start with =? and ends with ?= and translate them. I ended with such an expression : re.sub('=\?[\w\?\-\/=\+\:\;_\,\[\]\(\)\<\>]+\?=', decode_match, string) It works in 95% cases, but it fails with similar strings: =?utf-8asdfaDDS23=e...
split utf8 strings into parts with regexp
I need to find in text strings, which start with =? and ends with ?= and translate them. I ended with such an expression : re.sub('=\?[\w\?\-\/=\+\:\;_\,\[\]\(\)\<\>]+\?=', decode_match, string) It works in 95% cases, but it fails with similar strings: =?utf-8asdfaDDS23=eFF?=-=?utf-8?eadf-,=?= Can someone try to help...
[ "Does str.split('=?') do the trick?\n", "You need the case where you have ? without matching a ?= in your pattern\n'=\\?(?:[^?]|\\?[^=])+\\?='\n\n", "why don't you write ? :\nre.sub('=\\?.+?\\?=', decode_match, string)\n\nThis regex will match two times in '=?utf-8asdfaDDS23=eFF?=-=?utf-8?eadf-,=?='\n'=?utf-8as...
[ 0, 0, 0 ]
[]
[]
[ "python", "regex", "utf_8" ]
stackoverflow_0004905935_python_regex_utf_8.txt
Q: Publishing ics feeds in Django I'm attempting to publish an ICS feed using django + vobject. As a test run, I have the following view defined: def ical(request, user_id=None): cal = vobject.iCalendar() cal.add('method').value = 'PUBLISH' cal.add('calscale').value = 'GREGORIAN' cal.add('x-wr-calname...
Publishing ics feeds in Django
I'm attempting to publish an ICS feed using django + vobject. As a test run, I have the following view defined: def ical(request, user_id=None): cal = vobject.iCalendar() cal.add('method').value = 'PUBLISH' cal.add('calscale').value = 'GREGORIAN' cal.add('x-wr-calname').value = 'TestCal28' cal.add('...
[ "I doubt this will solve your problem (sounds like a server configuration issue), but I would suggest checking out django-cal for your feed generation. It works the same way as django.contrib's syndication feed framework (read: nicely)\n" ]
[ 4 ]
[]
[]
[ "apache", "django", "icalendar", "python" ]
stackoverflow_0003288048_apache_django_icalendar_python.txt
Q: Python Default Inheritance? If I define a class in Python such as: class AClass: __slots__ = ['a', 'b', 'c'] Which class does it inherit from? It doesn't seem to inherit from object. A: If you define a class and don't declare any specific parent, the class becomes a "classic class", which behaves a bit diffe...
Python Default Inheritance?
If I define a class in Python such as: class AClass: __slots__ = ['a', 'b', 'c'] Which class does it inherit from? It doesn't seem to inherit from object.
[ "If you define a class and don't declare any specific parent, the class becomes a \"classic class\", which behaves a bit differently than \"new-style classes\" inherited from object. See here for more details: http://docs.python.org/release/2.5.2/ref/node33.html\nClassic classes don't have a common root, so essenti...
[ 15, 10, 2, 2 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0004906014_class_inheritance_python.txt
Q: Testing all combinations in Python I have two sets of options: optionList1 = [a1,a2,a3,...,an] optionList2 = [b1,b2,b3,...,bn] The number of elements in the optionlists are not necessarily equal and I have to choose from the first optionlist twice. How do I ensure that I have tried every combination of 2 options ...
Testing all combinations in Python
I have two sets of options: optionList1 = [a1,a2,a3,...,an] optionList2 = [b1,b2,b3,...,bn] The number of elements in the optionlists are not necessarily equal and I have to choose from the first optionlist twice. How do I ensure that I have tried every combination of 2 options from the first list and one from the sec...
[ "Combine product and permutations from itertools assuming you don't want duplicates from the first list:\n>>> from itertools import product,permutations\n>>> o1 = 'a1 a2 a3'.split()\n>>> o2 = 'b1 b2 b3'.split()\n>>> for (a,b),c in product(permutations(o1,2),o2):\n... print a,b,c\n... \na1 a2 b1\na1 a2 b2\na1 a2...
[ 7, 6, 6, 3, 2 ]
[]
[]
[ "combinations", "python" ]
stackoverflow_0004906041_combinations_python.txt
Q: Problems saving Japanese characters to mysql via python-mysqldb I tried following the instructions here in my python script running on Ubuntu: http://www.dasprids.de/blog/2007/12/17/python-mysqldb-and-utf-8 But I can't seem to save japanese characters properly. They keep appearing as '?!?!?!' in the database. I ca...
Problems saving Japanese characters to mysql via python-mysqldb
I tried following the instructions here in my python script running on Ubuntu: http://www.dasprids.de/blog/2007/12/17/python-mysqldb-and-utf-8 But I can't seem to save japanese characters properly. They keep appearing as '?!?!?!' in the database. I can, however, save japanese characters from the mysql command line prom...
[ "With php, I have to execute the SET NAMES 'utf8' query before I execute queries containing Japanese correctly. Have you tried this?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004906672_python.txt
Q: how to get authentication provider from sharepoint through web services? How to get authentication provider from share point through web services?.. I am log in to share point from python application. I need to find the selected authentication provider from the share point site. how to get that?.. A: You cannot ...
how to get authentication provider from sharepoint through web services?
How to get authentication provider from share point through web services?.. I am log in to share point from python application. I need to find the selected authentication provider from the share point site. how to get that?..
[ "You cannot retrieve provider instance and then do something like Membership.ValidateUser(username, password).\nYou need to create a reference to the Authentication Web service, perform login operation (C# example below - you have to do something similar in Python):\nstring siteUrl = \"http://example.com/sites/hr\"...
[ 2 ]
[]
[]
[ "authentication", "provider", "python", "sharepoint", "web_services" ]
stackoverflow_0004906460_authentication_provider_python_sharepoint_web_services.txt
Q: Django: Can you upload a directory or multiple files in Admin site You can upload an individual file with the Admin site. However I have a need to upload at least 1 file, but potentially multiple files, for each object. Sometimes there will be sub-directories with these files that must also be uploaded. Is there a...
Django: Can you upload a directory or multiple files in Admin site
You can upload an individual file with the Admin site. However I have a need to upload at least 1 file, but potentially multiple files, for each object. Sometimes there will be sub-directories with these files that must also be uploaded. Is there a good way to do this in the Admin site? Or would you recommend simply sf...
[ "Maybe have a look at https://github.com/stefanfoulis/django-filer, it allows multiple files to be uploaded at once.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004907013_django_django_admin_python.txt
Q: Debugging djcelery's celeryd via pdb Have anybody tried debugging celeryd worker using pdb? Whenever a breakpoint is encountered (either by running celeryd via pdb, or by pdb.set_trace()), I hit the following error: Error while handling action event. Traceback (most recent call last): File "/home/jeeyo/workspace...
Debugging djcelery's celeryd via pdb
Have anybody tried debugging celeryd worker using pdb? Whenever a breakpoint is encountered (either by running celeryd via pdb, or by pdb.set_trace()), I hit the following error: Error while handling action event. Traceback (most recent call last): File "/home/jeeyo/workspace3/uwcr/subscriptions/tasks.py", line 79, i...
[ "I had the same problem. Try using Celery's remote debugger rdb instead:\nfrom celery import task\nfrom celery.contrib import rdb\n\n@task()\ndef add(x, y):\n result = x + y\n rdb.set_trace() # <- set break-point\n return result\n\nSee the user guide (link update 2017/5).\n" ]
[ 26 ]
[]
[]
[ "celery", "debugging", "django", "python" ]
stackoverflow_0004543967_celery_debugging_django_python.txt
Q: Python parsing boolean expressions with custom evaluations Hello Im working on a django project where i want to store a set of requirements for a course, but these requirements are not simple, they could be a combination of and / or ie, ((course1 or course2) and course3) I found this boolean parser, and have kin...
Python parsing boolean expressions with custom evaluations
Hello Im working on a django project where i want to store a set of requirements for a course, but these requirements are not simple, they could be a combination of and / or ie, ((course1 or course2) and course3) I found this boolean parser, and have kinda figured out how it works, the only hickup is that once it get...
[ "Try using Python expressions and the eval() function:\n>>> course1 = True\n>>> course2 = False\n>>> course3 = True\n>>> print eval('(course1 or course2) and course3')\nTrue\n\nBut if expressions can come from outside your app, you will have a security problem because folks could inject and execute arbitrary Python...
[ 2, 2 ]
[]
[]
[ "boolean", "django", "python" ]
stackoverflow_0004907418_boolean_django_python.txt
Q: Is there a prebuilt version of python 2.7 mySql db APIs to install and use with django or do i have to really build it from scratch? i want to install django and use mysql as the backend. i installed django and it worked fine. i am now following the first tutorial and created mysite. After putting the mysql bac...
Is there a prebuilt version of python 2.7 mySql db APIs to install and use with django or do i have to really build it from scratch?
i want to install django and use mysql as the backend. i installed django and it worked fine. i am now following the first tutorial and created mysite. After putting the mysql backend into into the settings.py, the web server no longer ran. I get the following error: raise ImproperlyConfigured("Error loading MySQLd...
[ "For windows you might try the binary installer from http://www.codegood.com/archives/129\nOn linux you would normally install it using the native package manager, e.g. sudo apt-get install mysql-python or via sudo easy_install mysqld.\nThe easy_install way will also work on windows provided you have installed the ...
[ 1 ]
[]
[]
[ "django", "installation", "mysql", "python", "windows_xp" ]
stackoverflow_0004906861_django_installation_mysql_python_windows_xp.txt
Q: Django: setting a max number of unique fields in a Model I'm using Django 1.2. I would like to make a model with 3 fields, as shown below: class Also_Viewed(models.Model): page = models.ForeignKey(Page) also_page = models.ForeignKey(Page) rank = models.IntegerField() class Meta: unique_toge...
Django: setting a max number of unique fields in a Model
I'm using Django 1.2. I would like to make a model with 3 fields, as shown below: class Also_Viewed(models.Model): page = models.ForeignKey(Page) also_page = models.ForeignKey(Page) rank = models.IntegerField() class Meta: unique_together = ('page', 'also_page') However for each unique page fie...
[ "If you're using your own views, you can use model validation as a place to put this code. (but remember you have to call clean yourself)\nhttp://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects\nIf you want this enforced in the admin, you'll need to override the admin forms.\nhttp://docs.djan...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004907924_django_django_models_python.txt
Q: highlighting a window in GNOME's window list In order to indicate activity, some applications (e.g. Pidgin) highlight their entry in GNOME's Window List panel widget (e.g. via bold font or flashing color). This indication is reset automatically when the window is activated. I have a terminal application for which ...
highlighting a window in GNOME's window list
In order to indicate activity, some applications (e.g. Pidgin) highlight their entry in GNOME's Window List panel widget (e.g. via bold font or flashing color). This indication is reset automatically when the window is activated. I have a terminal application for which I would like to achieve the same thing (preferably...
[ "In a GTK application, use gtk_window_set_urgency_hint(). If you have a terminal application, you can't really do that - with libwnck you can get information about other application's windows, but as far as I know you can't get a GtkWindow pointer to another application's window.\nMay I suggest using the terminal b...
[ 2, 1 ]
[]
[]
[ "gtk", "perl", "python" ]
stackoverflow_0004906424_gtk_perl_python.txt
Q: Does using python files in Jython require python classes? I am trying to implement Python code I've written in Java and I want to use Jython. There are a number of websites that provide information about how to build Jython object factories, but all of the examples use Python classes. For example: http://jythonpod...
Does using python files in Jython require python classes?
I am trying to implement Python code I've written in Java and I want to use Jython. There are a number of websites that provide information about how to build Jython object factories, but all of the examples use Python classes. For example: http://jythonpodcast.hostjava.net/jythonbook/en/1.0/JythonAndJavaIntegration.ht...
[ "If I understand what you're asking correctly (I take it you want to invoke a Python function from Java code), I think that is possible.\nThis is completely untested and a bit speculative, but it looks like Jython provides a Java object model that will allow you to do what you want. The important thing to understan...
[ 3 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0004906266_java_jython_python.txt
Q: How do I do multiple joins and aggregation with django ORM? Django/Python/ORM noob here! I'm having a hard time wrapping my head around how joins in the ORM work. Here are my models: class Courts(models.Model): id = models.AutoField(primary_key=True) location_name = models.CharField(max_length=100) num...
How do I do multiple joins and aggregation with django ORM?
Django/Python/ORM noob here! I'm having a hard time wrapping my head around how joins in the ORM work. Here are my models: class Courts(models.Model): id = models.AutoField(primary_key=True) location_name = models.CharField(max_length=100) number = models.IntegerField() def __unicode__(self): re...
[ "You have a couple of \"things\" there:\n\nDefining \"id\" primary fields is unnecessary and therefore confusing, Django generates them automatically\nIt's a good practice to name your models using singular forms (i.e. Match instead of Matches etc.) - this way you allow Django to provide proper singular vs plural h...
[ 5 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0004907479_database_django_python.txt
Q: Fastest way to do data type conversion using csv.DictReader in python I'm working with a CSV file in python, which will have ~100,000 rows when in use. Each row has a set of dimensions (as strings) and a single metric (float). As csv.DictReader or csv.reader return values as string only, I'm currently iterating ov...
Fastest way to do data type conversion using csv.DictReader in python
I'm working with a CSV file in python, which will have ~100,000 rows when in use. Each row has a set of dimensions (as strings) and a single metric (float). As csv.DictReader or csv.reader return values as string only, I'm currently iterating over all rows and converting the one numeric value to a float. for i in csvDi...
[ "I had first exploited the CSV file with a regex, but since the data in the file is very strictly arranged in each row, we can simply use the split() function \nimport gviz_api\n\nscheme = [('col1','string','SURNAME'),('col2','number','ONE'),('col3','number','TWO')]\ndata_table = gviz_api.DataTable(scheme)\n\n# --...
[ 2, 1, 1 ]
[]
[]
[ "csv", "dictionary", "python", "type_conversion" ]
stackoverflow_0004897935_csv_dictionary_python_type_conversion.txt
Q: Passing arguments in a nested For Range loop in Python 2.5 I'm just learning Python and am trying to figure out how to pass an argument in a 'for range' loop to a variable. In the code below, I would like the 'months' variable to be the names of the months (Jan, Feb, etc). Then I'm trying to get the user prompt ...
Passing arguments in a nested For Range loop in Python 2.5
I'm just learning Python and am trying to figure out how to pass an argument in a 'for range' loop to a variable. In the code below, I would like the 'months' variable to be the names of the months (Jan, Feb, etc). Then I'm trying to get the user prompt for the 'sales' variable to read 'Enter the sales for Jan'. The...
[ "Python's dict and list objects will take you far.\n>>> months = \"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\".split()\n>>> sales = {}\n>>> for num, name in enumerate(months, 1):\n print \"Sales for\", name\n sales[num] = 14.99 # get the sales here\n print \"Num:\", num\n\nSales for Jan\nNum: 1\nSale...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004904802_python.txt
Q: Does the python vm compiles method every time? If I have a function that is called in few places in my module, does the virtual machine compiles it to native code only the first time the function is executed and than use the cashed code on the other calls? (like .NET jit compiler) A: In CPython (the standard Pyt...
Does the python vm compiles method every time?
If I have a function that is called in few places in my module, does the virtual machine compiles it to native code only the first time the function is executed and than use the cashed code on the other calls? (like .NET jit compiler)
[ "In CPython (the standard Python implementation) the first time a Python module is imported, it's compiled to bytecode and stored in a .pyc file. From then on, the .pyc file is read and interpreted by the VM when needed. Once the .pyc is read into memory, the bytecode is in memory, and interpreted by the VM when ...
[ 8 ]
[]
[]
[ "python", "vm_implementation" ]
stackoverflow_0004908683_python_vm_implementation.txt
Q: python utf-8 japanese I have some Japanese words I wish to convert to utf-8, as shown below: jap_word1 = u'中山' jap_word2 = u'小倉' print jap_word1.encode('utf-8') # Doesn't work print jap_word2.encode('utf-8') # Prints properly Why is it that one word can be converted properly to utf-8 and printed to show the sam...
python utf-8 japanese
I have some Japanese words I wish to convert to utf-8, as shown below: jap_word1 = u'中山' jap_word2 = u'小倉' print jap_word1.encode('utf-8') # Doesn't work print jap_word2.encode('utf-8') # Prints properly Why is it that one word can be converted properly to utf-8 and printed to show the same characters but not the ot...
[ "Lots of things must align to print characters properly:\n\nWhat encoding is the script saved in?\nDo you have a # coding: xxxx statement in your script, where xxxx matches the encoding the file is saved in?\nDoes your output terminal support your encoding? import sys; print sys.stdout.encoding\na. If not, can you...
[ 1, 0 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0004908544_python_unicode_utf_8.txt
Q: How to use: while not in I'm trying to check if a list has no member as boolean operator AND, OR, NOT. I use: while ('AND' and 'OR' and 'NOT') not in list: print 'No boolean operator' However, when my input is: a1 c2 OR c3 AND, it prints 'No boolean operator', which means this list is considered no boolean oper...
How to use: while not in
I'm trying to check if a list has no member as boolean operator AND, OR, NOT. I use: while ('AND' and 'OR' and 'NOT') not in list: print 'No boolean operator' However, when my input is: a1 c2 OR c3 AND, it prints 'No boolean operator', which means this list is considered no boolean operator in it by using above loop...
[ "Using sets will be screaming fast if you have any volume of data\nIf you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.\nMyOper = set(['AND', 'OR', 'NOT'])\nMyList = set(['c1', 'c2', 'NOT', 'c3'])\n\nwhi...
[ 7, 4, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0004908666_python_while_loop.txt
Q: xml parse without the recursive search python This is driving me mental, and I've probably been hacking away at it for to long so would appreciate some help to prevent lose of/restore my sanity! The food based xml is only an example of what I wish to achieve. I have the following file which I am trying to put into...
xml parse without the recursive search python
This is driving me mental, and I've probably been hacking away at it for to long so would appreciate some help to prevent lose of/restore my sanity! The food based xml is only an example of what I wish to achieve. I have the following file which I am trying to put into a graph, so wheat and fruit are parents with a dep...
[ "Use lxml. In particular, XPath. You can get all layer elements, regardless of level, through \"//layer\" and the layer with the id id through \"//layer[id='{}'][0]\".format(id). The keyword elements directly under an element (or several elements) by \".../keyword\" (where ... is a query that yields the nodes whose...
[ 4, 2, 1, 0 ]
[]
[]
[ "dom", "python", "xml" ]
stackoverflow_0004908738_dom_python_xml.txt
Q: Python - write list list of lists in columns I have a list of lists with a various number of elements (int). I want to print/write it, but in columns rather than in rows. Example: l = [[1,2,3],[4,5],[6,7,8,9],[0]] Result: 1 4 6 0 2 5 7 . 3 . 8 . . . 9 . A: The easiest way to do this is to use itertools.izip_lon...
Python - write list list of lists in columns
I have a list of lists with a various number of elements (int). I want to print/write it, but in columns rather than in rows. Example: l = [[1,2,3],[4,5],[6,7,8,9],[0]] Result: 1 4 6 0 2 5 7 . 3 . 8 . . . 9 .
[ "The easiest way to do this is to use itertools.izip_longest():\nfor x in itertools.izip_longest(*l, fillvalue=\".\"):\n print \" \".join(str(i) for i in x)\n\n", "This:\nimport itertools\n\nl = [[1,2,3],[4,5],[6,7,8,9],[0]]\n\nfor t in itertools.izip_longest(*l):\n print \"\".join(\"%3d\" % x if x is not N...
[ 14, 3 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0004908987_csv_list_python.txt
Q: Best way to check multiple equalities? Preferably in Python, What's the best way to create a function that checks for multiple equalities? I want the function to return 1 if the input is equal to "f", "fall", "F", "Fall", "fa", etc. and if "fall" is in a dictionary. A: Generalizing a bit, it sounds like you have...
Best way to check multiple equalities?
Preferably in Python, What's the best way to create a function that checks for multiple equalities? I want the function to return 1 if the input is equal to "f", "fall", "F", "Fall", "fa", etc. and if "fall" is in a dictionary.
[ "Generalizing a bit, it sounds like you have a dictionary of words (commands?) and want to match the first entry that matches partial input, case-insensitive:\nD = dict(fall=None,stand=None)\ntrials = 'f fall F Fall fa foo Foo s ST stan'.split()\n\ndef check(t):\n for k in D:\n if k.startswith(t.lower()):...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004908870_python.txt
Q: Categorize book authors as fiction vs non-fiction For my own personal purposes, I have about ~300 authors (full name) of various books. I want to partition this list into "fiction authors" and "non-fiction authors". If an author writes both, then the majority gets the vote. I looked at Amazon Product Search API: ...
Categorize book authors as fiction vs non-fiction
For my own personal purposes, I have about ~300 authors (full name) of various books. I want to partition this list into "fiction authors" and "non-fiction authors". If an author writes both, then the majority gets the vote. I looked at Amazon Product Search API: I can search by author (in Python), but there is no way...
[ "Well, you can try another service - Google Book Search API. To use Python you can have a look at gdata-python-api. In its protocol, in result feed there is a node <dc:subject> - probably that's what you need:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\"\n xmlns:open...
[ 4, 2, 0 ]
[]
[]
[ "amazon", "api", "categorization", "python" ]
stackoverflow_0004905268_amazon_api_categorization_python.txt
Q: python - 2 math questions Hey, I'm using pyGame and I want to: A) make a function that returns the angle between two points. I've tried doing this with math.atan2 and I'm getting really wierd returns. I tried this with both (delta X, deltaY) and (deltaY, deltaX). Any suggestions? B) given a length and an angle, re...
python - 2 math questions
Hey, I'm using pyGame and I want to: A) make a function that returns the angle between two points. I've tried doing this with math.atan2 and I'm getting really wierd returns. I tried this with both (delta X, deltaY) and (deltaY, deltaX). Any suggestions? B) given a length and an angle, return a point using those two fr...
[ "math.atan2 returns radians. If you need degree, multiply the result by 180/π.\ndef A(dx, dy):\n return math.atan2(dy, dx) * 180 / math.pi\n\nSimilarly, all trigonometric functions in math operate in radians. If you input a degree, you need to multiply by π/180 first.\ndef LengthDir(length, angle):\n radian_angle...
[ 4, 1, 0 ]
[]
[]
[ "geometry", "math", "python" ]
stackoverflow_0004909016_geometry_math_python.txt
Q: What would cause Gdata Python Client to fail on call to YouTubeVideoQuery in appengine? The following use to work as expected on the local development server and on deployment. client = gdata.youtube.service.YouTubeService() gdata.alt.appengine.run_on_appengine(client,deadline=10) query = gdata.youtube.service.You...
What would cause Gdata Python Client to fail on call to YouTubeVideoQuery in appengine?
The following use to work as expected on the local development server and on deployment. client = gdata.youtube.service.YouTubeService() gdata.alt.appengine.run_on_appengine(client,deadline=10) query = gdata.youtube.service.YouTubeVideoQuery() query.vq = search_term query.orderby = 'viewCount' query.max_results = '5' ...
[ "Nevermind. I found my mistake. Forgot to add back developer key to revised code. Works locally, but gets quota errors when doing a query from the appengine servers.\n" ]
[ 1 ]
[]
[]
[ "gdata", "gdata_api", "google_app_engine", "python", "youtube_api" ]
stackoverflow_0004908905_gdata_gdata_api_google_app_engine_python_youtube_api.txt
Q: help with pylons routes url_for~ view-source:http://127.0.0.1:5000/admin/post/edit/2 : <form action="/admin/post/update_post/2" method="post"> view-source:http://xxx.com/admin/post/edit/2 <form action="/admin/post/edit/2/admin/post/update_post/2" method="post"> something was diffent between server url code and l...
help with pylons routes url_for~
view-source:http://127.0.0.1:5000/admin/post/edit/2 : <form action="/admin/post/update_post/2" method="post"> view-source:http://xxx.com/admin/post/edit/2 <form action="/admin/post/edit/2/admin/post/update_post/2" method="post"> something was diffent between server url code and localhost serve with the same code : ${...
[ "I believe the url should start with a /. Also, you've specified a controller of 'admin/post' and I'm thinking that is probably supposed to be either or. \nGive this a try\nurl('/admin/post/edit/' + request.urlvars['id'])\n\n" ]
[ 0 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0004907816_pylons_python_routes.txt
Q: Google App Engine - Use Task Queues or Deferred Jobs Google App Engine has two methods for running jobs at some later point, Task Queues and Deferred jops They support all the same features as far as I can tell (e.g. a deferred job can be placed on a particular task queue so you can throttle execution) - but the d...
Google App Engine - Use Task Queues or Deferred Jobs
Google App Engine has two methods for running jobs at some later point, Task Queues and Deferred jops They support all the same features as far as I can tell (e.g. a deferred job can be placed on a particular task queue so you can throttle execution) - but the deferred jobs look much easier to implement and more flexib...
[ "I'm not sure if you noticed it, but the documentation for deferreds has this section in the end:\n\nYou may be wondering when to use ext.deferred, and when to stick with the built-in task queue API. Here are our suggestions.\nYou may want to use the deferred library if:\n\nYou only use the task queue lightly.\nYou...
[ 11 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004909278_google_app_engine_python.txt
Q: How do I handle several submit forms with same handler? (google app engine-python) In AdminPage I've created several forms to edit the form fields in the database; all forms refer to the action=/adminpage <form name="submit_form" action="/adminpage" method="post"> then I created a def post(self): to handle each f...
How do I handle several submit forms with same handler? (google app engine-python)
In AdminPage I've created several forms to edit the form fields in the database; all forms refer to the action=/adminpage <form name="submit_form" action="/adminpage" method="post"> then I created a def post(self): to handle each form, for instance def post(self): .... handle first form def post(self): ... ...
[ "First of all, what's wrong with having a separate handler for each form? If you do decide you want to go down this path, you have a couple options. You could either check the referrer URL to see what page the user came from and infer what was submitted. Another option is to place a hidden field in each form that s...
[ 2, 2 ]
[]
[]
[ "forms", "google_app_engine", "python" ]
stackoverflow_0004909398_forms_google_app_engine_python.txt
Q: Cannot query using IDs - Django MongoDB Engine I am using django-nonrel and django-mongodb-engine I have a Django model stored on PostgreSQL: class Author(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I have a MongoDB stored model: class Post(mode...
Cannot query using IDs - Django MongoDB Engine
I am using django-nonrel and django-mongodb-engine I have a Django model stored on PostgreSQL: class Author(models.Model): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I have a MongoDB stored model: class Post(models.Model): title = models.CharField(max_length=1...
[ "I believe the \"mongo way\" would be to embed the author details in the post, as well as all comments, in Embedded Documents. Having multiple related collections (tables) isn't the best way to solve this problem in your case.\nReduce your foreignKey usage as much as possible, and just embed the data. I believe M...
[ 2, 0 ]
[ "It's impossible to mix those two engines. The simplest explanation for this is that MongoDB primary keys are string-like objects and *SQL pks are integers. You can't use both, chose one.\n" ]
[ -1 ]
[ "django", "django_nonrel", "mongodb", "python" ]
stackoverflow_0004854911_django_django_nonrel_mongodb_python.txt
Q: Insert/delete/retrieve elements of an array across threads without using globals This might be a silly question, but what's the best way to keep insert/delete/retrieve elements of an array in a multi-threaded Python application, but not keep the array global or assign an entire thread to keep track of the changes ...
Insert/delete/retrieve elements of an array across threads without using globals
This might be a silly question, but what's the best way to keep insert/delete/retrieve elements of an array in a multi-threaded Python application, but not keep the array global or assign an entire thread to keep track of the changes to that single array? It feels tiresome to pass the array to each function I use.
[ "If you can't use globals, maybe you can use Qt's QThread class. You can use signals to access to the thread.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004909665_python.txt
Q: Python: Multi-dimensional array of different types Is it possible to create a multi-dimensional array of different types in Python? The way I usually solve it is [([None] * n) for i in xrange(m)], but I don't want to use list. I want something which is really a continuous array of pointers in memory, not a list. (...
Python: Multi-dimensional array of different types
Is it possible to create a multi-dimensional array of different types in Python? The way I usually solve it is [([None] * n) for i in xrange(m)], but I don't want to use list. I want something which is really a continuous array of pointers in memory, not a list. (Each list itself is continuous, but when you make a list...
[ "If you're using numpy, by chance, numpy object arrays are \"continuous arrays of pointers in memory\".\nHowever, they defeat the usual purpose of numpy arrays, and often wind up being a bad answer to the problem at hand... \n(contiguous memory of the same type --> fast calculations on the entire array... Object ar...
[ 3, 2 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0004909748_arrays_python.txt
Q: efficient comparison of values in a python list I have a list made out of tuples such as the one below: (2809.3994479562093, 1032.5989696312365, 0.0), {'level': '2', 'id': '1'}) having a sett of different values for the level key in the dictionary(increasing, but not always integers i.e. 1, 2, 3, 3B, 4A, 5, 5A, ...
efficient comparison of values in a python list
I have a list made out of tuples such as the one below: (2809.3994479562093, 1032.5989696312365, 0.0), {'level': '2', 'id': '1'}) having a sett of different values for the level key in the dictionary(increasing, but not always integers i.e. 1, 2, 3, 3B, 4A, 5, 5A, 6, 7), the id increasing incrementally and consists o...
[ "Two notes:\n\nYou don't write for i in range(len(xs)): # use xs[i] in Python, as much as you don't write int i = 0; while (i < N) { /* use xs[i]; */ i++; } in C. You write for x in xs: # use x.\nConsider using a named tuple for descriptive names for the values. Also consider restructuring the data. For instance, y...
[ 2, 1 ]
[]
[]
[ "algorithm", "logic", "python" ]
stackoverflow_0004909761_algorithm_logic_python.txt
Q: List values from one to another list I am almost new to python and I am stuck with a seemingly simple problem. I got two lists L1 = [a,b,c] L2 = [1,2,3] now I want to replace the values from L2 to L1 becoming L1 = [1,2,3] Now this is where the fun comes in the length of L2 is always how many unique items there c...
List values from one to another list
I am almost new to python and I am stuck with a seemingly simple problem. I got two lists L1 = [a,b,c] L2 = [1,2,3] now I want to replace the values from L2 to L1 becoming L1 = [1,2,3] Now this is where the fun comes in the length of L2 is always how many unique items there can be in L1 eg. L2 = [1,2,3,4,5] than L1 ...
[ "You can replace slices of the list.\n>>> L1 = ['a','b','c','d','e','a','a','e','e','b','b']\n>>> L2 = [1,2,3,4,5]\n>>> length = len(L2)\n>>> L1[:length] = L2[:length]\n>>> print(L1)\n[1, 2, 3, 4, 5, 'a', 'a', 'e', 'e', 'b', 'b']\n\nJust in case I misinterpreted what you wanted and want to replace every instance of...
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "python", "replace" ]
stackoverflow_0004909808_dictionary_list_python_replace.txt
Q: How to if !something I'm just learning GAE, Python and Django and have a problem with my Django template. I understand the GAE version of Django is 0.96 and so predates a lot of the fancy {% if x == False %} stuff. All I want to do is: {% if NOT variable.approved %} This should render if the approved property is...
How to if !something
I'm just learning GAE, Python and Django and have a problem with my Django template. I understand the GAE version of Django is 0.96 and so predates a lot of the fancy {% if x == False %} stuff. All I want to do is: {% if NOT variable.approved %} This should render if the approved property is False {% end if %} The a...
[ "You can just do {% if not variable.approved %}. This is explained in, for example, the 1.1 documentation.\nNote that you can install Django 1.2 in GAE, if you want.\n" ]
[ 8 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004909891_django_google_app_engine_python.txt
Q: making list in python When i executed the following python script list= (1,2,3,4,1,2,7,8) for number in list: item1= number item2= list[list.index(item1)+2] couple= item1, item2 print couple the goal is to link each number with the second following I obtain this result (1, 3) (2, 4) (3, 1) (4, 2...
making list in python
When i executed the following python script list= (1,2,3,4,1,2,7,8) for number in list: item1= number item2= list[list.index(item1)+2] couple= item1, item2 print couple the goal is to link each number with the second following I obtain this result (1, 3) (2, 4) (3, 1) (4, 2) (1, 3) (2, 4) (and then ...
[ "list.index returns the offset of the first occurrence of the value in the list - thus if you do [1,1,1].index(1), the answer will always be 0, even though 1 and 2 are also valid answers.\nInstead, try:\nfrom itertools import islice, izip, ifilter\n\nmylist = [1,2,3,4,1,2,7,8]\nfor pair in ifilter(lambda x: x[0]==1...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004909878_list_python.txt
Q: lxml cssselect Parsing I have a document with the following data: <div class="ds-list"> <b>1. </b> A domesticated carnivorous mammal <i>(Canis familiaris)</i> related to the foxes and wolves and raised in a wide variety of breeds. </div> And I want to get everything within the class ds-list (wi...
lxml cssselect Parsing
I have a document with the following data: <div class="ds-list"> <b>1. </b> A domesticated carnivorous mammal <i>(Canis familiaris)</i> related to the foxes and wolves and raised in a wide variety of breeds. </div> And I want to get everything within the class ds-list (without <b> and <i> tags). Cur...
[ "Perhaps you are looking for the text_content method?:\nimport lxml.html as lh\ncontent='''\\\n<div class=\"ds-list\">\n <b>1. </b> \n A domesticated carnivorous mammal \n <i>(Canis familiaris)</i> \n related to the foxes and wolves and raised in a wide variety of breeds.\n</div>'''\ndoc=lh.fromstring(c...
[ 10, 1 ]
[]
[]
[ "css_selectors", "html", "lxml", "parsing", "python" ]
stackoverflow_0004909811_css_selectors_html_lxml_parsing_python.txt
Q: Modules or functions to obtain information from a network interface in Python I wrote a little application that I use from the terminal in Linux to keep track of the amount of data up and down that I consume in a session of Internet connection (I store the info in MongoDB). The data up and down I write by hand an...
Modules or functions to obtain information from a network interface in Python
I wrote a little application that I use from the terminal in Linux to keep track of the amount of data up and down that I consume in a session of Internet connection (I store the info in MongoDB). The data up and down I write by hand and read them (visually) from the monitor system, the fact is that I would like to au...
[ "Well I answer myself\nFound in the community PyAr this recipe to me me like a glove going to do what we wanted without having to use extra commands or other applications.\nSlightly modifying the code to better suit my application and add a function that comvierta of bytes to Megabytes leave it like this:\ndef byte...
[ 0 ]
[]
[]
[ "interface", "networking", "python" ]
stackoverflow_0004868167_interface_networking_python.txt
Q: Debugging Python in TextWrangler shows Terminal not Debugger When I am debugging python code in TextWrangler using the #! | Run in Debugger option the code is run in a terminal not in the python debugger. How do I configure TextWrangler to use the python debugger? BTW - Using TextWrangler v3.5 (2880) running on a ...
Debugging Python in TextWrangler shows Terminal not Debugger
When I am debugging python code in TextWrangler using the #! | Run in Debugger option the code is run in a terminal not in the python debugger. How do I configure TextWrangler to use the python debugger? BTW - Using TextWrangler v3.5 (2880) running on a Mac, python file has .py extension and is seen by TextWrangler as ...
[ "The terminal that TextWranger opens up when you click on #! | Run in Debugger is the debug environment provided by TextWrangler. It's a command-line utility similar to gdb (from the GNU toolchain) if you've ever used that before. When the terminal opens, if you see this prompt: (pdb) then that means you're in the ...
[ 1 ]
[]
[]
[ "python", "textwrangler" ]
stackoverflow_0004652893_python_textwrangler.txt
Q: Unable to solve sys path error; module said to be missing I keep throwing an exception saying a module isn't installed that is. Any help would be much appreciated. I've looked around and it's been suggested that this error could be solved by extending the sys path to include the app directory. Something I'm pretty...
Unable to solve sys path error; module said to be missing
I keep throwing an exception saying a module isn't installed that is. Any help would be much appreciated. I've looked around and it's been suggested that this error could be solved by extending the sys path to include the app directory. Something I'm pretty sure is taken care of by the sys.path directive in the WSGI fi...
[ "Can you post this middleware that's throwing the exception so we can see exactly what it's trying to import? \nSounds like it's importing markdown, and markdown isn't on your path. Normally, this would be installed in your site-packages directory and not so much inside of your project.\ntry pip install markdown\nU...
[ 0 ]
[]
[]
[ "apache", "django", "middleware", "python", "wsgi" ]
stackoverflow_0004910203_apache_django_middleware_python_wsgi.txt
Q: Matrix multiplication gives unsual result in Python (SciPy/PyLab) I'm new to Python, and a bit rusty with my linear algebra, so perhaps this is a simple question. I'm trying to implement a Taylor Series expansion on a Matrix to compute exp(A), where A is just a simple 3x3 matrix. The formula, BTW for this expansio...
Matrix multiplication gives unsual result in Python (SciPy/PyLab)
I'm new to Python, and a bit rusty with my linear algebra, so perhaps this is a simple question. I'm trying to implement a Taylor Series expansion on a Matrix to compute exp(A), where A is just a simple 3x3 matrix. The formula, BTW for this expansion is sum( A^n / n! ). My routine works alright up to n=9, but at n=10, ...
[ "Your matrix is created with elements of type int32 (32-bit integer). You can see this by printing the value of A.dtype. 32-bit integers can only hold values up to about 2 billion, so after that they will wrap around to negative values.\nIf 64-bit integers are large enough, you can use them instead:\nA = mat('[1 3 ...
[ 8, 3 ]
[]
[]
[ "linear_algebra", "matrix", "numpy", "python", "scipy" ]
stackoverflow_0004910453_linear_algebra_matrix_numpy_python_scipy.txt
Q: configurations eclipse I want to run php or python scripts from eclipse that will create folders and files and give them content. I think I know what to write for the php or python code but I am having trouble on what I need to do in eclipse to run my script. I would also like to provide my script with arguments s...
configurations eclipse
I want to run php or python scripts from eclipse that will create folders and files and give them content. I think I know what to write for the php or python code but I am having trouble on what I need to do in eclipse to run my script. I would also like to provide my script with arguments such as folder names through ...
[ "you shouldn't have to do anything to eclipse, or any editor, if php\\python is installed you can call them from the command line.\n" ]
[ 1 ]
[]
[]
[ "configuration", "eclipse", "php", "python" ]
stackoverflow_0004910541_configuration_eclipse_php_python.txt
Q: Why my regex with r'string' matches but not 'string' using Python? The way regex works in Python is so intensely puzzling that it makes me more furious with each passing second. Here's my problem: I understand that this gives a result: re.search(r'\bmi\b', 'grand rapids, mi 49505) while this doesn't: re.search('\...
Why my regex with r'string' matches but not 'string' using Python?
The way regex works in Python is so intensely puzzling that it makes me more furious with each passing second. Here's my problem: I understand that this gives a result: re.search(r'\bmi\b', 'grand rapids, mi 49505) while this doesn't: re.search('\bmi\b', 'grand rapids, mi 49505) And that's okay. I get that much of it...
[ "The anwser itself\nregex = '|'.join([r'\\b' + str(state) + r'\\b' for state in states])\n\nThe reason behind this is that the 'r' prefix tells Python to not analyze the string you pass to it. If you don't put an 'r' before the string, Python will try to turn any char preceding by '\\' into a special char, to allow...
[ 14, 4, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004909691_python_regex.txt
Q: PATH/PYTHONPATH is not working I've made a separate directory for my django modules. I've added this directory to my PATH variable. I've also created a new PYTHONPATH variable, since it wasn't there. I've added modules to settings.py. But when im trying to run manage.py syncdb for the new module it still says Erro...
PATH/PYTHONPATH is not working
I've made a separate directory for my django modules. I've added this directory to my PATH variable. I've also created a new PYTHONPATH variable, since it wasn't there. I've added modules to settings.py. But when im trying to run manage.py syncdb for the new module it still says Error: No module named my_module Why, o...
[ "PATH tells your shell where to find executables; it has nothing to do with Python. PYTHONPATH is a list of directories to search for Python modules. It should be edited to include the directory with my_module.\n", "Hard to tell you what the issue is with only that output, however this should solve the problem:...
[ 1, 0 ]
[]
[]
[ "django", "path", "python", "pythonpath" ]
stackoverflow_0004910275_django_path_python_pythonpath.txt
Q: How do I get the python package "gtk"? I can't import it right now, but my library imports it. I don't want the full Windows gtk thing. I just want the package that can be imported by this script: http://www.koders.com/python/fid798D591F71AC2C5F462B7BFFF0D84E1EA8D5759F.aspx?s=timer A: Go to the PyGTK website an...
How do I get the python package "gtk"?
I can't import it right now, but my library imports it. I don't want the full Windows gtk thing. I just want the package that can be imported by this script: http://www.koders.com/python/fid798D591F71AC2C5F462B7BFFF0D84E1EA8D5759F.aspx?s=timer
[ "Go to the PyGTK website and choose the all-in-one .msi that matches your Python version. Save it and then open the .msi to install GTK for Python.\n" ]
[ 3 ]
[]
[]
[ "gtk", "image", "python" ]
stackoverflow_0004910800_gtk_image_python.txt
Q: Python - efficient representation of pixels and associated values I'm using python to work with large-ish (approx 2000 x 2000) matrices, where each I, J point in the matrix represents a single pixel. The matrices themselves are sparse (ie a substantial portion of them will have zero values), but when they are upda...
Python - efficient representation of pixels and associated values
I'm using python to work with large-ish (approx 2000 x 2000) matrices, where each I, J point in the matrix represents a single pixel. The matrices themselves are sparse (ie a substantial portion of them will have zero values), but when they are updated they tend to be increment operations, to a large number of adjacent...
[ "The general rule is, get the code working first, then optimize if needed...\nIn this case, use a normal numpy 2000x2000 array, or 2000x2000x3 for RGB. This will be much easier and faster to work with, is only a small memory requirement, and has many other advantages, for example, you can use the standard image pr...
[ 4, 2, 0 ]
[]
[]
[ "data_structures", "matrix", "numpy", "python", "sparse_matrix" ]
stackoverflow_0004908957_data_structures_matrix_numpy_python_sparse_matrix.txt
Q: Python CSV search for specific values after reading into dictionary I need a little help reading specific values into a dictionary using Python. I have a csv file with User numbers. So user 1,2,3... each user is within a specific department 1,2,3... and each department is in a specific building 1,2,3... So I need ...
Python CSV search for specific values after reading into dictionary
I need a little help reading specific values into a dictionary using Python. I have a csv file with User numbers. So user 1,2,3... each user is within a specific department 1,2,3... and each department is in a specific building 1,2,3... So I need to know how can I list all the users in department one in building 1 then...
[ "A brute-force approach would look like\nimport csv\ncsvFile = csv.reader(open('myfile.csv'))\ndata = list(csvFile)\ndata.sort(key=lambda x: (x[2], x[1], x[0]))\n\nIt could then be extended to\nimport csv\nimport collections\n\ncsvFile = csv.reader(open('myfile.csv'))\ndata = collections.defaultdict(lambda: collect...
[ 2 ]
[]
[]
[ "csv", "dictionary", "python" ]
stackoverflow_0004911070_csv_dictionary_python.txt
Q: pygtk and native gtk_main(); mixing I'm trying to develop a C-based application which embeds one or more Python interpreters. I'm using gtk-things in the C-parts, and logically calling gtk_main() within that. The Python interpreters are created in separate pthreads using Py_NewInterpreter(), and basically running ...
pygtk and native gtk_main(); mixing
I'm trying to develop a C-based application which embeds one or more Python interpreters. I'm using gtk-things in the C-parts, and logically calling gtk_main() within that. The Python interpreters are created in separate pthreads using Py_NewInterpreter(), and basically running forever (a 'while True' loop is added to ...
[ "This is a situation where you are better off making one more Python interpreter and doing all your GTK work by sending Python snippets to that special GTK helper interpreter. That way your C code never uses GTK directly and you only need to worry about coordinating between the Python threads.\n", "This looks lik...
[ 0, 0 ]
[]
[]
[ "c", "gtk", "multithreading", "pygtk", "python" ]
stackoverflow_0004896434_c_gtk_multithreading_pygtk_python.txt
Q: How to call method from inside a method? class A: def a(self): print 'a' def b(self): print 'b' a() A: Class methods need their first argument to be self. You can then call the a method with self.a(): class A: def a(self): print 'a' def b(self): print 'b' self.a()
How to call method from inside a method?
class A: def a(self): print 'a' def b(self): print 'b' a()
[ "Class methods need their first argument to be self. You can then call the a method with self.a():\nclass A:\n def a(self):\n print 'a'\n def b(self):\n print 'b'\n self.a()\n\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004911231_python.txt
Q: how to match an image tag's link with regex i am working on a regex match function in python. i have the following code: def src_match(line, img): imgmatch = re.search(r'<img src="(?P<img>.*?)"', line) if imgmatch and imgmatch.groupdict()['img'] == img: print 'the match was:', imgmatch.groupdict(...
how to match an image tag's link with regex
i am working on a regex match function in python. i have the following code: def src_match(line, img): imgmatch = re.search(r'<img src="(?P<img>.*?)"', line) if imgmatch and imgmatch.groupdict()['img'] == img: print 'the match was:', imgmatch.groupdict()['img'] the above does not seem to operate corr...
[ "Rule #37: do not attempt parsing HTML with regex.\nUse the right tool for the job - in this case, BeautifulSoup.\nEdit:\ncut-and-pasting the function and testing as\n>>> src_match('this is <img src=\"my example\" />','my example')\nthe match was: my example\n\nso it appears to function; however it will fail on (pe...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004911199_python_regex.txt
Q: In Python's sqlite3 module, why can't cursor.rowcount() tell me the number of rows returned by a select statement So I've read the documentation and it says: Cursor.rowcount¶ Although the Cursor class of the sqlite3 module implements this attribute, the database engine’s own support for the determination of...
In Python's sqlite3 module, why can't cursor.rowcount() tell me the number of rows returned by a select statement
So I've read the documentation and it says: Cursor.rowcount¶ Although the Cursor class of the sqlite3 module implements this attribute, the database engine’s own support for the determination of “rows affected”/”rows selected” is quirky. This includes SELECT statements because we cannot determine the number ...
[ "SQLite does not \"fetch\" all the rows when initially processing the query. It returns a single row each time the prepared query is stepped.\nFrom the SQLite3 FAQ here\nQ) Which func could get the number of rows?\nA) There is no function to retrieve the number of rows in a result set. SQLite doesn't know the numbe...
[ 8 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0004911404_python_sql_sqlite.txt
Q: Using Python with a flexible remote library that resides in a different git repo? I work on a project that uses a lot of different git repos. Some are open source and some are closed source. Often times there is python code written that would be useful for both open and closed source sides of the project but it is...
Using Python with a flexible remote library that resides in a different git repo?
I work on a project that uses a lot of different git repos. Some are open source and some are closed source. Often times there is python code written that would be useful for both open and closed source sides of the project but it is not easy to share between the two. I am wondering if anyone has a slick general way t...
[ "Submodules\n" ]
[ 1 ]
[]
[]
[ "import", "python", "shared" ]
stackoverflow_0004911506_import_python_shared.txt
Q: files's binary data stored as variable inside python file Lets say a have program.exe , i will create a python script that will read program.exe in binary mode and save it in variable data open mypytonprog.py in binary append mode append data to mypythonprog.py (?) before this, mypythonprog.py would be prepared...
files's binary data stored as variable inside python file
Lets say a have program.exe , i will create a python script that will read program.exe in binary mode and save it in variable data open mypytonprog.py in binary append mode append data to mypythonprog.py (?) before this, mypythonprog.py would be prepared as: program_data=''' after it, mypythonprog.py would continue...
[ ">>> 'some binary data'.encode('base64')\n'c29tZSBiaW5hcnkgZGF0YQ==\\n'\n>>> 'c29tZSBiaW5hcnkgZGF0YQ==\\n'.decode('base64')\n'some binary data'\n\n", "import base64\n\nexe = 'c:/users/me/program.exe'\nscript = 'c:/users/me/newpython.py'\nchunksize = 6144\nlinelength = 80\n\nwith open(exe,'rb') as inf, open(script...
[ 3, 2 ]
[]
[]
[ "binary_data", "encoding", "exe", "python" ]
stackoverflow_0004911440_binary_data_encoding_exe_python.txt
Q: Why would os.path.exists("C:\\windows\\system32\\inetsrv\\metaback") return False even when it exists? I've got a python program which is supposed to clean up a number of directories and one of them is C:\windows\system32\inetsrv\metaback; however, os.path.exists() returns False on that directory even though it ex...
Why would os.path.exists("C:\\windows\\system32\\inetsrv\\metaback") return False even when it exists?
I've got a python program which is supposed to clean up a number of directories and one of them is C:\windows\system32\inetsrv\metaback; however, os.path.exists() returns False on that directory even though it exists (and I have permissions to access it). What's interesting also is that the tool windirstat completely ...
[ "This is redirection of system folders at work. When a 32-bit process is running on a 64-bit version of Windows and uses the path %WINDIR%\\System32, Windows substitutes %WINDIR%\\SysWow64.\nThe function is returning false to tell you that C:\\windows\\syswow64\\inetsrv\\metaback does not exist, and it most likely...
[ 26, 1 ]
[]
[]
[ "python", "windows", "wow64" ]
stackoverflow_0004911555_python_windows_wow64.txt
Q: Querying data from a specific related object in Django template I'm trying to use Django to display a table of information from across several models and I'm uncertain what the best practices for doing so are. Here's a stripped down version of my models.py: from django.contrib.auth.models import User class Widge...
Querying data from a specific related object in Django template
I'm trying to use Django to display a table of information from across several models and I'm uncertain what the best practices for doing so are. Here's a stripped down version of my models.py: from django.contrib.auth.models import User class Widget(models.Model): name = models.CharField(max_length=50) pass ...
[ "Updated answer based on need for passing in user object.\nThe easiest way is to deal with this in your view, but it has its problems.\nfor widget in widget_list:\n widget.latest_finished_widget = widget.finished_widget_set.filter(user=request.user).latest('created')\n\n{% for widget in widget_list %}\n <p>{{...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004911305_django_django_models_python.txt
Q: Finding first n primes? Possible Duplicate: Fastest way to list all primes below N in python Although I already have written a function to find all primes under n (primes(10) -> [2, 3, 5, 7]), I am struggling to find a quick way to find the first n primes. What is the fastest way to do this? A: Start with the ...
Finding first n primes?
Possible Duplicate: Fastest way to list all primes below N in python Although I already have written a function to find all primes under n (primes(10) -> [2, 3, 5, 7]), I am struggling to find a quick way to find the first n primes. What is the fastest way to do this?
[ "Start with the estimate g(n) = n log n + n log log n*, which estimates the size of the nth prime for n > 5.\nThen run a sieve on that estimate.\ng(n) gives an overestimate, which is okay because we can simply discard the extra primes generated which are larger than the desired n.\nThen consider the answers in \"Fa...
[ 8, 5, 2, 0, 0 ]
[]
[]
[ "math", "performance", "primes", "python" ]
stackoverflow_0004911777_math_performance_primes_python.txt
Q: Django Postgresql DatabaseError when filtering decimals Each time I filter/exclude against a decimal field I get a Database Error saying: "cant' adapt" This doesn't happen in my local enviroment. I am using Postgresql 8.3.11 in production and 8.4.5 in local enviroment. I have just recently migrated from MYSQL. (...
Django Postgresql DatabaseError when filtering decimals
Each time I filter/exclude against a decimal field I get a Database Error saying: "cant' adapt" This doesn't happen in my local enviroment. I am using Postgresql 8.3.11 in production and 8.4.5 in local enviroment. I have just recently migrated from MYSQL. (I migrated each database locally and then load a pg_dump in t...
[ "I have found my answer here:\nhttp://www.defitek.com/blog/2010/06/29/cant-adapt-type-decimal-error-with-django-apache-postgresql-psycopg2/\nI hope this helps to more people! :)\n" ]
[ 1 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0004080482_django_postgresql_python.txt
Q: Reading only root element in XML In many REST based API calls, we have this parameter called nextURL, using which we can query for the next URL. This is usually in the root element.(or may be the next one) In general how do you guys read this? In case you are using a standard XML parser, it reads and loads the en...
Reading only root element in XML
In many REST based API calls, we have this parameter called nextURL, using which we can query for the next URL. This is usually in the root element.(or may be the next one) In general how do you guys read this? In case you are using a standard XML parser, it reads and loads the entire XML and then you get to read the ...
[ "Python: You could use the ElementTree iterparse method ... provided the data you want is in an attribute, which will have been parsed by the time that you get the start event. If it's in the text or tail of the element, you will have to wait until the end event. It would be a good idea if you edited your question ...
[ 3, 0 ]
[]
[]
[ "java", "python", "xml" ]
stackoverflow_0004911929_java_python_xml.txt
Q: BEGIN call is polluting SQLAlchemy logs I'm using SQLAlchemy 0.6.3 with Pylons 1.0, and my sqlalchemy.log file is being polluted by "BEGIN" calls: 2011-01-14 10:15:17 SELECT /* redacted */ 2011-01-14 10:15:22 BEGIN 2011-01-14 10:15:27 BEGIN 2011-01-14 10:15:32 BEGIN 2011-01-14 10:15:37 BEGIN 2011-01-14 10:15:42 BE...
BEGIN call is polluting SQLAlchemy logs
I'm using SQLAlchemy 0.6.3 with Pylons 1.0, and my sqlalchemy.log file is being polluted by "BEGIN" calls: 2011-01-14 10:15:17 SELECT /* redacted */ 2011-01-14 10:15:22 BEGIN 2011-01-14 10:15:27 BEGIN 2011-01-14 10:15:32 BEGIN 2011-01-14 10:15:37 BEGIN 2011-01-14 10:15:42 BEGIN 2011-01-14 10:15:47 BEGIN 2011-01-14 10:1...
[ "One approach would be to figure out why SQLAlchemy is doing these, and see if they can be avoid.\nAnother would be to filter them out at logging level. Python's logging module supports filters.\nHere's a quick stand-alone example, adapted from this example from Python docs:\nimport logging\n\nclass BeginFilter(log...
[ 0 ]
[]
[]
[ "logging", "pylons", "python", "sqlalchemy" ]
stackoverflow_0004692603_logging_pylons_python_sqlalchemy.txt
Q: Django ManyToManyField In my model I have: class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) I'm trying to create the Poll object and store tags like so: Tags = [] for splitTag in splitTags: tag = Tag(name = splitTag.lower()) tag.save() Tags....
Django ManyToManyField
In my model I have: class Poll(models.Model): topic = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) I'm trying to create the Poll object and store tags like so: Tags = [] for splitTag in splitTags: tag = Tag(name = splitTag.lower()) tag.save() Tags.append(tag) How do I set th...
[ "Well, it should be more like this:\nmodels.py\n\nclass Tag(models.Model):\n name = models.CharField(max_length=200)\n\nclass Poll(models.Model):\n topic = models.CharField(max_length=200)\n tags = models.ManyToManyField(Tag)\n\nin views.py:\n\npoll = Poll(topic=\"My topic\")\npoll.save()\nfor splitTag in ...
[ 12, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004912223_django_python.txt
Q: How can I create controller routes in Pylons for multi-part IDs? By default the RESTful controller in Pylons supports single-part IDs for objects. This works for some kinds of objects, but my domain model has a set of objects that have composite identifiers, and I'd like to be able to build good URLs for those as ...
How can I create controller routes in Pylons for multi-part IDs?
By default the RESTful controller in Pylons supports single-part IDs for objects. This works for some kinds of objects, but my domain model has a set of objects that have composite identifiers, and I'd like to be able to build good URLs for those as well. This is what is currently supported: GET /advanis/saas/projects/...
[ "Your routes can have as many dynamic parts as you need. Read about route parts here.\nQuick example:\nIn config/routing.py:\nmap.connect('specific_key', '/advanis/saas/projects/{client}/{key}', \n controller='mycontroller',\n action='item')\n\nIn controllers/mycontroller.py:\ndef item(self, c...
[ 0 ]
[]
[]
[ "pylons", "python", "rest", "routes" ]
stackoverflow_0003416505_pylons_python_rest_routes.txt
Q: The best way to write initial settings data for custom CMS in Django I'm writing my own CMS and have the situation where the some initial settings information should be written in the database. I don't like the idea to write some XML/Json file with fixture data which will be imported when I will run syncdb. What I...
The best way to write initial settings data for custom CMS in Django
I'm writing my own CMS and have the situation where the some initial settings information should be written in the database. I don't like the idea to write some XML/Json file with fixture data which will be imported when I will run syncdb. What I'm thinking about is that I can create some cms_init.py file and run it be...
[ "Don't do it automatically/implicitly, make the user do it explicitly with a manage.py command, e.g.\npython manage.py your_cms init\n\nWhen running your CMS functionality check or rather try-except if the initialization has taken place and if not remind the user to run the init command first.\nDoing it explicitly ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004912184_django_python.txt
Q: Python programming max heapify? In python language: How to write a function that takes a heap structure (that violates the heap property) and returns None. It changes the array slot in the heap structure so that the heap property is satisfied. A: The function heapq.heapify from the standard library does this.
Python programming max heapify?
In python language: How to write a function that takes a heap structure (that violates the heap property) and returns None. It changes the array slot in the heap structure so that the heap property is satisfied.
[ "The function heapq.heapify from the standard library does this.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004912128_python.txt