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:
WSGI Middleware for OAuth authentication
I have build a very small web application using Flask. Now I would like to add very basic authentication to the site (I don't need authorization). As Flask does not support auth&auth out of the box, I'd like to plug in a WSGI middleware doing this job. The web-app is only u... | WSGI Middleware for OAuth authentication | I have build a very small web application using Flask. Now I would like to add very basic authentication to the site (I don't need authorization). As Flask does not support auth&auth out of the box, I'd like to plug in a WSGI middleware doing this job. The web-app is only used by roughly 10 people, all of them are on F... | [
"Flask has an OpenAuth extension that's written by the Armin Ronacher (Flask's author). It provides Flask with support for Open Auth 1.0. \n",
"You should take a look at repoze.who, which is authentication framework for WSGI application with plugins available for:\n\nHTTP basic/digest\nAuth via HTML forms with s... | [
7,
5,
1
] | [] | [] | [
"flask",
"middleware",
"oauth",
"python",
"wsgi"
] | stackoverflow_0004648838_flask_middleware_oauth_python_wsgi.txt |
Q:
File Parsing on the fly in Flask
I recently received some advice on a question regarding an easy to use web-framework to use for a simple project that I am helping a friend with and was suggested to use Flask.
Everything has been working out so far - however I am trying to figure out how to (or if it is possible) ... | File Parsing on the fly in Flask | I recently received some advice on a question regarding an easy to use web-framework to use for a simple project that I am helping a friend with and was suggested to use Flask.
Everything has been working out so far - however I am trying to figure out how to (or if it is possible) to read a file on the fly, and pass th... | [
"The documentation on the flask site (http://flask.pocoo.org/docs/patterns/fileuploads/) demonstrates how to properly and safely handle file uploads, I would start there. If you wish to parse the file before/instead of saving it, you should be able to use the stream property/attribute on the FileStorage object you'... | [
10,
1
] | [] | [] | [
"file",
"flask",
"parsing",
"python"
] | stackoverflow_0004949849_file_flask_parsing_python.txt |
Q:
How to deal with interactive API in python
I'm in a situation where I need to pass some texts to a prompt generate by a API (seems for API it's a pretty weird behavior, this is the first time I ran into this), like below:
kvm_cli = libvirt.open("qemu+ssh://han@10.0.10.8/system")
then a prompt shows up asking for ... | How to deal with interactive API in python | I'm in a situation where I need to pass some texts to a prompt generate by a API (seems for API it's a pretty weird behavior, this is the first time I ran into this), like below:
kvm_cli = libvirt.open("qemu+ssh://han@10.0.10.8/system")
then a prompt shows up asking for the ssh password (password for 10.0.10.8 is:), I... | [
"I am not a libvirt user, but I believe that the problem is not in the library, but in the connection method. You seem to be connecting via ssh, so you need to authenticate yourself.\nI've been reading the libvirt page on ArchWiki, and I think that you could try:\n\nsetting up the simple (TCP/IP socket) connection ... | [
4
] | [] | [] | [
"libvirt",
"python"
] | stackoverflow_0004954764_libvirt_python.txt |
Q:
Determining if an xlsx cell is date formatted for Excel 2007 spreadsheets
I'm working with some code that reads data from xlsx files by parsing the xml. It is all pretty straightforward, with the exception of date cell.
Dates are stored as integers and have an "s" attribute that is an index into the stylesheet, w... | Determining if an xlsx cell is date formatted for Excel 2007 spreadsheets | I'm working with some code that reads data from xlsx files by parsing the xml. It is all pretty straightforward, with the exception of date cell.
Dates are stored as integers and have an "s" attribute that is an index into the stylesheet, which can be used to get a date formatting string. Here are some examples from ... | [
"\nDates are stored as integers\n\nIn the Excel data model, there is really no such thing as an integer. Everything is a float. Dates and datetimes are floats, representing days and a fraction since a variable epoch. Times are fractions of a day.\n\nIt seems like the standard excel\n reading libraries are lacking ... | [
5,
0
] | [] | [] | [
"excel",
"openxml",
"python",
"xlsx"
] | stackoverflow_0004948998_excel_openxml_python_xlsx.txt |
Q:
Nodebox graph module
I did the Nodebox tutorial on the graph library:
http://nodebox.net/code/index.php/Graph#loading_the_library
I installed the library in Application Support
I pasted the following code:
graph = ximport("graph")
create(iterations=1000, distance=1.0, layout="spring", depth=True)
And I got this e... | Nodebox graph module | I did the Nodebox tutorial on the graph library:
http://nodebox.net/code/index.php/Graph#loading_the_library
I installed the library in Application Support
I pasted the following code:
graph = ximport("graph")
create(iterations=1000, distance=1.0, layout="spring", depth=True)
And I got this error message:
Traceback (... | [
"The problem is with your Path, as the tutorial link that you pointed to said:\nPut the graph library folder in the same folder as your script so NodeBox can find the library. You can also put it in ~/Library/Application Support/NodeBox/.\nOtherwise install content from the graph.zip\nand do\nimport graph\ngraph.cr... | [
0
] | [] | [] | [
"graph",
"nodebox",
"python"
] | stackoverflow_0004955071_graph_nodebox_python.txt |
Q:
Missing type to str.format() behavior
According to the Python docs here, when leaving the type out, it defaults to a type of 'g' for floating point arguments.
However,
print("{0:.2}".format(14.9))
prints "1.5e+01", while
print("{0:.2g}".format(14.9))
prints "15"
Is this simply an issue of the documentation bein... | Missing type to str.format() behavior | According to the Python docs here, when leaving the type out, it defaults to a type of 'g' for floating point arguments.
However,
print("{0:.2}".format(14.9))
prints "1.5e+01", while
print("{0:.2g}".format(14.9))
prints "15"
Is this simply an issue of the documentation being incorrect or is there another reason for ... | [
"According to the source code, this is a documentation bug. The correct description for the behaviour without a floating point specifier is \"like 'g', but always with at least one digit after the decimal point\".\n",
"You linked the documentation of Python 2.7, but you actually used Python 3.x. In the documenta... | [
4,
1
] | [] | [] | [
"format",
"printing",
"python"
] | stackoverflow_0004954074_format_printing_python.txt |
Q:
How to periodically create an HTTP POST request from windows
I need to install on one of my Windows PC's some software that will periodically send a short HTTP POST request to my remote development server. The request is always the same and should get sent every minute.
What would you recommend as the best approac... | How to periodically create an HTTP POST request from windows | I need to install on one of my Windows PC's some software that will periodically send a short HTTP POST request to my remote development server. The request is always the same and should get sent every minute.
What would you recommend as the best approach for that?
The things I considered are:
1. Creating a Windows ser... | [
"import urllib\nimport time\n\nwhile True:\n urllib.urlopen(url, post_data)\n time.sleep(60)\n\n",
"If you have cygwin, you probably have cron - run a python script from your crontab.\n",
"This is trivially easy with a scheduled task which is the native Windows way to schedule tasks! There's no need for cyg... | [
5,
2,
1
] | [] | [] | [
"http",
"python",
"scheduled_tasks",
"windows_services"
] | stackoverflow_0004935257_http_python_scheduled_tasks_windows_services.txt |
Q:
Non-numbered pages in ReportLab
Is it possible to generate a PDF file using ReportLab in such a way that the front page (and possibly table of contents) are excluded from the page numbering done by Platypus?
A:
Yes. The first example on chapter 5 of the user guide, SimpleDocTemplate has two hooks:
doc.build(Sto... | Non-numbered pages in ReportLab | Is it possible to generate a PDF file using ReportLab in such a way that the front page (and possibly table of contents) are excluded from the page numbering done by Platypus?
| [
"Yes. The first example on chapter 5 of the user guide, SimpleDocTemplate has two hooks: \ndoc.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)\n\nJust change myLaterPages definition to conditionally print the page number.\n"
] | [
3
] | [] | [] | [
"page_numbering",
"pdf",
"python",
"reportlab"
] | stackoverflow_0004956283_page_numbering_pdf_python_reportlab.txt |
Q:
update a gtk.VBox dynamically
I have been using this website pretty often in order to solve small issues that I have while programming in Python. This time, somehow I could not find a suitable solution for my situation. So, here is my problem:
I want to dynamically add entries to a gtk.VBox widget. The problem is ... | update a gtk.VBox dynamically | I have been using this website pretty often in order to solve small issues that I have while programming in Python. This time, somehow I could not find a suitable solution for my situation. So, here is my problem:
I want to dynamically add entries to a gtk.VBox widget. The problem is that it doesn't work the way I want... | [
"The new check button is there, but not visible until you call show() on it:\ndef AddCheckButton(self, button):\n button = gtk.CheckButton(\"CheckButton\")\n self.vBox.pack_start(button, True, True, 1)\n button.show()\n print \"adding checkbox...\"\n\n"
] | [
6
] | [] | [] | [
"containers",
"hbox",
"pygtk",
"python"
] | stackoverflow_0004956607_containers_hbox_pygtk_python.txt |
Q:
Matplotlib cannot find facefile, is using old Python interpreter location
I've a script that utilised the Matplotlib library, the script works fine at home and in the Uni labs, but I have an issue when I try and run it on my work machine.
Originally, I was running the interpreter from my USB stick - no problems th... | Matplotlib cannot find facefile, is using old Python interpreter location | I've a script that utilised the Matplotlib library, the script works fine at home and in the Uni labs, but I have an issue when I try and run it on my work machine.
Originally, I was running the interpreter from my USB stick - no problems there - but I've recently copied the interpreter to the hard drive to save messin... | [
"matplotlib keeps it's config file in the .matplotlib directory finding the location of the directory\nChange the MPLCONFIGDIR environment variable to change the directory location.\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004956863_matplotlib_python.txt |
Q:
Can any one please let me know that where exactly Python-Pickle used and give me one great example to understand
Possible Duplicate:
Pickle Python Serialization
Hi I am new to python. Please explain where exactly we will use pickle and give me one clear example to understand...it would be great if you could do t... | Can any one please let me know that where exactly Python-Pickle used and give me one great example to understand |
Possible Duplicate:
Pickle Python Serialization
Hi I am new to python. Please explain where exactly we will use pickle and give me one clear example to understand...it would be great if you could do this....
| [
"You will come to know when you really want to serialize the data, store it and reuse it.\nSuppose in a particular python script, you decide to create a graph, usually the graph can be best stored as a dictionary of lists. Now, you can store them some form of a database or a flat file, in which case you would have ... | [
1
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0004956817_pickle_python.txt |
Q:
More Pythonic (or perhaps functional) way of creating this list?
I'm returning a list of lists, but the following seems far more convoluted than it should be:
new_list = []
for key, value in group.items():
new_list.extend([['%s%s%s%s%s' % (
ncode, vendor, extra, value['suffix'], tariff),
value['latest... | More Pythonic (or perhaps functional) way of creating this list? | I'm returning a list of lists, but the following seems far more convoluted than it should be:
new_list = []
for key, value in group.items():
new_list.extend([['%s%s%s%s%s' % (
ncode, vendor, extra, value['suffix'], tariff),
value['latest_cost'], value['rrp'], value['rb']] for tariff in value['trf']])
retur... | [
"That's not particularly convoluted. You have two \"levels\", the items in the group which you are expanding into one level. For doing that it's not very convoluted.\nA more functional way would be to merge it all into one nested list expression, I think that could be possible. But it sure wouldn't be more readable... | [
8
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0004957030_functional_programming_python.txt |
Q:
Changing Date format in MySql
I have a large Csv file that I wanna bulk-load it to my table. A column of this csv file keeps the dates but in the DD-MM-YYYY format. When I am loading this file to my table, it does not accept it, since MySQL DATE format only accepts YYYY-MM-DD. Is there any way I could change this... | Changing Date format in MySql | I have a large Csv file that I wanna bulk-load it to my table. A column of this csv file keeps the dates but in the DD-MM-YYYY format. When I am loading this file to my table, it does not accept it, since MySQL DATE format only accepts YYYY-MM-DD. Is there any way I could change this in MySQL. I am using python to cre... | [
"Assuming your table has two columns named column1 and column2, the date is in column2 and that is the second column in the CSV file:\nLOAD DATA INFILE 'filename' (column1, @var1)\nSET column2 = STR_TO_DATE(@var1, '%d-%m-%Y')\n\nThe (column1, @var1) part says:\n\nThe first column of the CSV file goes directly into ... | [
4,
1
] | [] | [] | [
"database",
"mysql",
"python"
] | stackoverflow_0004957330_database_mysql_python.txt |
Q:
Python: Memory leak debugging
I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.
Following http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks I see this as the most common typ... | Python: Memory leak debugging | I have a small multithreaded script running in django and over time its starts using more and more memory. Leaving it for a full day eats about 6GB of RAM and I start to swap.
Following http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks I see this as the most common types (with only 800M of memory used):... | [
"See http://opensourcehacker.com/2008/03/07/debugging-django-memory-leak-with-trackrefs-and-guppy/ . Short answer: if you're running django but not in a web-request-based format, you need to manually run db.reset_queries() (and of course have DEBUG=False, as others have mentioned). Django automatically does reset_q... | [
32,
21,
6,
6,
1,
1,
0
] | [] | [] | [
"debugging",
"django",
"memory_leaks",
"python"
] | stackoverflow_0001339293_debugging_django_memory_leaks_python.txt |
Q:
From where to start Python
hi folks i am very new to python, i just intall it and configure it in netbeans but did't get from where to start and how to write my first program in python using netbean.
Any one recommend me some help, forume or any other resource.
Any kind of help will be greatly appreciated......... | From where to start Python | hi folks i am very new to python, i just intall it and configure it in netbeans but did't get from where to start and how to write my first program in python using netbean.
Any one recommend me some help, forume or any other resource.
Any kind of help will be greatly appreciated......
| [
"Try Zed Shaw's \"Learning Python The Hard Way\". Or S. Lott's \"Building Python Skills\".\nUPDATE: I should have thought of the official tutorial first.\nIf you'd be willing to consider books, I've gotten a great deal out of Wesley Chun's \"Core Python Programming\".\n",
"I would recommend avoiding use of an ID... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0004957713_python.txt |
Q:
Which version of Python should I use for web development?
I've finally decided to start working in Python but there seems to be so many versions out there. I'm mainly interested in web development in Python, so which version should I choose?
I don't know what versions the web frameworks usually support (Django, Py... | Which version of Python should I use for web development? |
I've finally decided to start working in Python but there seems to be so many versions out there. I'm mainly interested in web development in Python, so which version should I choose?
I don't know what versions the web frameworks usually support (Django, Pylons and so on) but maybe you guys know? Also, I'd like to kno... | [
"Basically, there are two versions - Python 2 and 3. Of course there's 2.6, 2.7, 3.1, etc. but generally n.x is compatible with n.(x+1), just improved in some ways - neat language additons, new stdlib modules, etc. And although e.g. 2.5 and 3.0 are still available, you should generally use the latest versions (toda... | [
6,
3,
3,
1,
0,
0
] | [] | [] | [
"python",
"version"
] | stackoverflow_0004957545_python_version.txt |
Q:
Check for pattern recursively
*Note i refer to thing as a matrix but it is not, it is just a collection of 1's and zeros
Suppose you have a matrix that is always square (n x n). Is it possible to determine if there exists a single column/row/diagonal such that each item is a 1.
Take the matrix below for instance (... | Check for pattern recursively | *Note i refer to thing as a matrix but it is not, it is just a collection of 1's and zeros
Suppose you have a matrix that is always square (n x n). Is it possible to determine if there exists a single column/row/diagonal such that each item is a 1.
Take the matrix below for instance (True):
1 0 0
1 1 0
0 0 1
Another ex... | [
"In search for an elegant solution I came up with this:\nclass LineOfOnesChecker(object):\n\n _DIAG_INDICES = (lambda i: i, lambda i: -i - 1)\n\n def __init__(self, matrix):\n self._matrix = matrix\n self._len_range = range(len(self._matrix))\n\n def has_any(self):\n return self.has_ro... | [
2,
0,
0
] | [] | [] | [
"algorithm",
"python",
"recursion"
] | stackoverflow_0004953864_algorithm_python_recursion.txt |
Q:
South django table already exists
I'm experiencing the same problem as with: django - "manage.py test" fails "table already exists"
The schemamigration / migration worked fine (although did have some problems that required me to --fake, but all subsequent migrations with south work). But when I run a unit test I g... | South django table already exists | I'm experiencing the same problem as with: django - "manage.py test" fails "table already exists"
The schemamigration / migration worked fine (although did have some problems that required me to --fake, but all subsequent migrations with south work). But when I run a unit test I get:
(1050, "Table '{tablename}' already... | [
"No, it doesn't mean that. Don't forget that Django already knows what your tables should look like if you create them from scratch now - it just uses the model definitions. South is useful because it allows you to easily transform your table structure when you change your models, but when you're running tests you ... | [
8
] | [] | [] | [
"data_migration",
"django_models",
"django_south",
"python"
] | stackoverflow_0004958136_data_migration_django_models_django_south_python.txt |
Q:
Why is my C module leaking memory?
I'm reading lists from a large file, which I eventually want to store as array.arrays. Because
map(int, line.split())
is very slow, I wrote a small C module which does strtok and a faster version of atoi:
inline long
minhashTables_myatoi(const char* s)
{
int r;
for (r = ... | Why is my C module leaking memory? | I'm reading lists from a large file, which I eventually want to store as array.arrays. Because
map(int, line.split())
is very slow, I wrote a small C module which does strtok and a faster version of atoi:
inline long
minhashTables_myatoi(const char* s)
{
int r;
for (r = 0; *s; r = r * 10 + *s++ - '0');
ret... | [
"I suggest you take a look at Valgrind - it is a very useful tool for getting to the bottom of memory leaks in C.\n",
"Do you really need to malloc off space for all those longs?\nI'm not familiar with the Python/C API, so this might be terrible advice, but can't you just iterate over the string and append each l... | [
2,
1
] | [
"Try this \ninline long\n minhashTables_myatoi(const char* s)\n {\n long result=0;\n while((*s)!='\\0'){\n result = result * 10 + (*s- '0');\n s++;\n }\n return result;\n }\n\n"
] | [
-1
] | [
"c",
"module",
"python",
"refcounting"
] | stackoverflow_0004955404_c_module_python_refcounting.txt |
Q:
Calling filter functions from within a block-by-block processing function
I have some memory intensive image filters that I want to call block by block on large images/arrays (because they compute the filter for an entire array, they run out of memory when trying to compute the whole array).
def block_process(Ic, ... | Calling filter functions from within a block-by-block processing function | I have some memory intensive image filters that I want to call block by block on large images/arrays (because they compute the filter for an entire array, they run out of memory when trying to compute the whole array).
def block_process(Ic, blocksize):
B = numpy.empty(Ic.shape)
colstart = 0
while colstart ... | [
"You can do it like this:\ndef block_process(a, blocksize, filt, args):\n b = numpy.empty(a.shape)\n for row in xrange(0, a.shape[0], blocksize):\n for col in xrange(0, a.shape[1], blocksize):\n b[row:row + blocksize, col:col + blocksize] = (\n filt(a[row:row + blocksize, col:... | [
2
] | [] | [] | [
"image_processing",
"numpy",
"python",
"workflow"
] | stackoverflow_0004958652_image_processing_numpy_python_workflow.txt |
Q:
python matplotlib mplot3d code for dancing landscape
I try to write the code for a animated dancing landscape. The landscape could look just like the matlab icon and the 'hills' should slowely rise and fall and new hills should appear. The lanscape is to illustrated the concept of complexity. Thanks. Arthur
A:
T... | python matplotlib mplot3d code for dancing landscape | I try to write the code for a animated dancing landscape. The landscape could look just like the matlab icon and the 'hills' should slowely rise and fall and new hills should appear. The lanscape is to illustrated the concept of complexity. Thanks. Arthur
| [
"This example should help, but for the filled surface (plot_surface) is very slow. Maybe a better solution would be Mayavi2.\n"
] | [
2
] | [] | [] | [
"3d",
"complexity_theory",
"matplotlib",
"python"
] | stackoverflow_0004957968_3d_complexity_theory_matplotlib_python.txt |
Q:
How do i hide the console window for my app?
Possible Duplicate:
How can I hide the console window in a PyQt app running on Windows?
I've made a simple app that opens a QWebView but in addition to the app window Windows console window is opened to.
What could be the reason for this?
import sys
import socket
fro... | How do i hide the console window for my app? |
Possible Duplicate:
How can I hide the console window in a PyQt app running on Windows?
I've made a simple app that opens a QWebView but in addition to the app window Windows console window is opened to.
What could be the reason for this?
import sys
import socket
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore im... | [
"Use pythonw.exe instead of python.exe\n",
"name your file .pyw instead of .py\n",
"On default Windows installations, .pyw files are opened without the console window (because they're loaded with pythonw), and .py files load in a console. So yeah, renaming to .pyw is probably easiest solution.\nAlso - if you'r... | [
6,
3,
2
] | [] | [] | [
"pyqt",
"python",
"qt",
"windows",
"windows_console"
] | stackoverflow_0004872523_pyqt_python_qt_windows_windows_console.txt |
Q:
Wave Simulation with Python
I want to simulate a propagating wave with absorption and reflection on some bodies in three dimensional space. I want to do it with python. Should I use numpy? Are there some special libraries I should use?
How can I simulate the wave? Can I use the wave equation? But what if I have a... | Wave Simulation with Python | I want to simulate a propagating wave with absorption and reflection on some bodies in three dimensional space. I want to do it with python. Should I use numpy? Are there some special libraries I should use?
How can I simulate the wave? Can I use the wave equation? But what if I have a reflection?
Is there a better me... | [
"If you do any computationally intensive numerical simulation in Python, you should definitely use NumPy.\nThe most general algorithm to simulate an electromagnetic wave in arbitrarily-shaped materials is the finite-difference time domain method (FDTD). It solves the wave equation, one time-step at a time, on a 3-D... | [
14,
3,
0
] | [
"Don't use Python. I've tried using it for computationally expensive things and it just wasn't made for that.\nIf you need to simulate a wave in a Python program, write the necessary code in C/C++ and export it to Python.\nHere's a link to the C API: http://docs.python.org/c-api/\nBe warned, it isn't the easiest AP... | [
-5
] | [
"numpy",
"physics",
"python",
"simulation",
"wave"
] | stackoverflow_0004956331_numpy_physics_python_simulation_wave.txt |
Q:
Weird HTTP data accumulation on App Engine with Python and CouchDB
I'm trying to make a relatively simple App Engine app to fetch some pages on a daily basis and post the data to a CouchDB server. I've got the following code in my App Engine app (with the couchdb-python library):
# post the result to CouchDB
... | Weird HTTP data accumulation on App Engine with Python and CouchDB | I'm trying to make a relatively simple App Engine app to fetch some pages on a daily basis and post the data to a CouchDB server. I've got the following code in my App Engine app (with the couchdb-python library):
# post the result to CouchDB
price_data = {
'source': 'blah',
'date': str(result.heade... | [
"During your investigation, try to use a raw HTTP library instead of a CouchDB library. I suggest the native App Engine library (urlfetch or perhaps urllib2). The CouchDB API is very simple, you will not have difficulty.\nIs there a difference in the result?\n"
] | [
1
] | [] | [] | [
"couchdb",
"google_app_engine",
"http",
"json",
"python"
] | stackoverflow_0004948987_couchdb_google_app_engine_http_json_python.txt |
Q:
How to write own logging methods for own logging levels
Hi
I would like to extend my logger (taken by logging.getLogger("rrcheck")) with my own methods like:
def warnpfx(...):
How to do it best?
My original wish is to have a root logger writing everything to a file and additionally named logger ("rrcheck") wri... | How to write own logging methods for own logging levels | Hi
I would like to extend my logger (taken by logging.getLogger("rrcheck")) with my own methods like:
def warnpfx(...):
How to do it best?
My original wish is to have a root logger writing everything to a file and additionally named logger ("rrcheck") writing to stdout, but the latter should also have some other me... | [
"If you check Python sources, you'll see that the culprit is the Logger.findCaller method that walks through the call stack and searches for a first line that is not in the logging.py file. Because of this, your custom call to self.log in CheloExtendedLogger.warnpfx registers a wrong line.\nUnfortunately, the code ... | [
5
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004957858_logging_python.txt |
Q:
Improving memory usage in an array-wide filter to avoid block-processing
I am implementing some satellite image filters, starting with one known as the Enhanced Lee filter. The images are easily up to 5000x5000 pixels and more. My current implementation is running out of memory trying to compute the filters on tho... | Improving memory usage in an array-wide filter to avoid block-processing | I am implementing some satellite image filters, starting with one known as the Enhanced Lee filter. The images are easily up to 5000x5000 pixels and more. My current implementation is running out of memory trying to compute the filters on those large arrays (note that the moving average and moving stddev filters can be... | [
"There are several (memory usage) optimizations you can make here... A few tricks to keep in mind are:\n\nMost numpy functions take an out parameter than can be used to specify the output array instead of returning a copy. E.g. np.sqrt(x, x) will take the square root of an array in-place.\nx += 1 uses half the memo... | [
5,
3,
2
] | [] | [] | [
"arrays",
"memory",
"numpy",
"python",
"scipy"
] | stackoverflow_0004959171_arrays_memory_numpy_python_scipy.txt |
Q:
How to scrape the height and width of a table using Beautifulsoup?
<table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0">
<tbody>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
</tbody>
</table>
A:
People tend to prefer lxml... | How to scrape the height and width of a table using Beautifulsoup? | <table id="t_id" cellspacing="0" border="0" align="center" height="700" width="600" cellpadding="0">
<tbody>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
<tr><td> ..test... </td></tr>
</tbody>
</table>
| [
"People tend to prefer lxml these days over BeautifulSoup. See how easy this is:\nfrom lxml import etree\ndata = \"\"\"<table id=\"t_id\" cellspacing=\"0\" border=\"0\" align=\"center\" height=\"700\" width=\"600\" cellpadding=\"0\">\n<tbody>\n<tr><td> ..test... </td></tr>\n<tr><td> ..test... </td></tr>\n<tr><td> .... | [
3,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004957520_beautifulsoup_python.txt |
Q:
Curl with authentication in Python using standard libraries
I'm trying to create the Python equivalent of
curl -u username:password http://policeapi2.rkh.co.uk/api/forces
as stated here http://www.police.uk/api/docs/authentication/
I've manually logged in through a browser and got the authentication to work
I fir... | Curl with authentication in Python using standard libraries | I'm trying to create the Python equivalent of
curl -u username:password http://policeapi2.rkh.co.uk/api/forces
as stated here http://www.police.uk/api/docs/authentication/
I've manually logged in through a browser and got the authentication to work
I first tried basic authentication from here:
voidspace.org.uk/python/... | [
"\nI've manually logged in through a browser and got the authentication to work\n\nHow did you do that?\nDid you use FireBug or some other tool to observe what actually happened?\nYou should probably study what worked before reading too many StackOverflow answers. \n"
] | [
0
] | [] | [] | [
"authentication",
"curl",
"python"
] | stackoverflow_0004958287_authentication_curl_python.txt |
Q:
Create Board Game-like Grid in Python
I am thinking of creating a board game in Python, one which will have a grid of spaces, each with different properties, and which may or may not have pieces resting on them. These pieces should be able to move between spaces, though subject to various rules. (Chess or checkers... | Create Board Game-like Grid in Python | I am thinking of creating a board game in Python, one which will have a grid of spaces, each with different properties, and which may or may not have pieces resting on them. These pieces should be able to move between spaces, though subject to various rules. (Chess or checkers would be good examples of what I'm thinkin... | [
"Drawing a chessboard is pretty trivial with Tkinter. Here's a really simple example:\nimport Tkinter as tk\nclass GameBoard(tk.Frame):\n def __init__(self, parent, rows=8, columns=8, size=32, color1=\"white\", color2=\"blue\"):\n '''size is the size of a square, in pixels'''\n\n self.rows = rows\n... | [
18,
3
] | [] | [] | [
"python"
] | stackoverflow_0004954395_python.txt |
Q:
How to find a specific tag in an XML file and then access its parent tag with Python and minidom
I'm trying to write some code that will search through an XML file of articles for a particular DOI contained within a tag. When it has found the correct DOI I'd like it to then access the <title> and <abstract> text f... | How to find a specific tag in an XML file and then access its parent tag with Python and minidom | I'm trying to write some code that will search through an XML file of articles for a particular DOI contained within a tag. When it has found the correct DOI I'd like it to then access the <title> and <abstract> text for the article associated with that DOI.
My XML file is in this format:
<root>
<article>
<number>
... | [
"Is minidom a requirement? It would be quite easy to parse it with lxml and XPath.\nfrom lxml import etree\ndatasource = open('/Users/philgw/Dropbox/PW-Honours-Project/Code/processed.xml').read()\ntree = etree.fromstring(datasource)\npath = tree.xpath(\"//article[DOI=\"10.1016/B978-0-12-381015-1.00004-6\") \n\nThis... | [
1,
0
] | [] | [] | [
"minidom",
"python",
"xml"
] | stackoverflow_0004958626_minidom_python_xml.txt |
Q:
How to Loop over a optparse.OptionGroup values in python
I'm trying to use optparse to make a command line tool in python
I have a group of options optparse.OptionGroup that I wan't to loop over to do whatever... but how do I do that ?
I have:
usage = ("polotools [options]")
parser = optparse.OptionParser(version=... | How to Loop over a optparse.OptionGroup values in python | I'm trying to use optparse to make a command line tool in python
I have a group of options optparse.OptionGroup that I wan't to loop over to do whatever... but how do I do that ?
I have:
usage = ("polotools [options]")
parser = optparse.OptionParser(version="polotools %s" % version, usage=usage)
parser.add_option('--am... | [
"You probably want something like this after you set options:\nfor groupAMR_arg in groupAMR.option_list:\n print getattr(options, groupAMR_arg.dest)\n\n"
] | [
1
] | [] | [] | [
"command_line",
"optparse",
"python"
] | stackoverflow_0004958610_command_line_optparse_python.txt |
Q:
Py_InitModule4 with Djapian/Xapian
I am trying to install Djapian on RedHat5 / Python2.6. I have already installed it successfully on my OSX 10.6 machine.
I have built and compiled Xapian and Djapian without issue for Py2.6. I then install the Python Bindings for Xapian and it works fine, however, if open the Pyt... | Py_InitModule4 with Djapian/Xapian | I am trying to install Djapian on RedHat5 / Python2.6. I have already installed it successfully on my OSX 10.6 machine.
I have built and compiled Xapian and Djapian without issue for Py2.6. I then install the Python Bindings for Xapian and it works fine, however, if open the Python interpreter and type 'import xapian,... | [
"In some configurations (i.e. when Py_DEBUG is defined) Py_InitModule4 does not have an implementation because of macro rewriting. It is meant to tell you that the ABI are not compatible. I had this issue when I tried to use the Py_Debug version with a release version of the executable. Make sure you are compiling ... | [
4
] | [] | [] | [
"python",
"redhat",
"xapian"
] | stackoverflow_0004959872_python_redhat_xapian.txt |
Q:
Unable to test persistent sessions in Django 1.1
As part of the registration process for my site I have several views that set session data. Later views depend on the session data being set. This all works fine in the browser, however when I try to test it the session data seems to be lost in between requests whic... | Unable to test persistent sessions in Django 1.1 | As part of the registration process for my site I have several views that set session data. Later views depend on the session data being set. This all works fine in the browser, however when I try to test it the session data seems to be lost in between requests which makes it impossible to test. Here's a simple example... | [
"Sessions are tested quite awkwardly in Django. You have to setup the session engine first.\nclass TestSession(TestCase):\n\"\"\"A class for working with sessions - working.\n\nhttp://groups.google.com/group/django-users/browse_thread/thread/5278e2f2b9e6da13?pli=1\n\nTo modify the session in the client do:\nsession... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004959831_django_python.txt |
Q:
How to use for loops to do multiple SQL statements in python
I have SQl statement List, when running the a single statement it work running the loop it gives:
pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.8]You have an error in your SQL syntax; check the manual that corresponds ... | How to use for loops to do multiple SQL statements in python | I have SQl statement List, when running the a single statement it work running the loop it gives:
pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.1 Driver][mysqld-5.5.8]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Sql... | [
"Your tuple should be\nSqls = (Sql,Sql_2,Sql_3)\n\ninstead of\nSqls = ('Sql','Sql_2','Sql_3')\n\n",
"You should additionally move connecting to the database as well as creating a cursor out of the for-loop, since it's unneeded overhead.\nSQl = \"\"\"Select something\"\"\"\nSQl_2 = \"\"\"Select something\"\"\"\nSQ... | [
6,
3
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0004960035_for_loop_python.txt |
Q:
javascript input validation
i am using javascript validation for my input box from javascript-coder but i have 2 problems here.
First: The validator in the script uses name to validate the object, is it possible to change to id in the gen_validatorv4.js and how?
Second: my page reloads itself despite of alert prod... | javascript input validation | i am using javascript validation for my input box from javascript-coder but i have 2 problems here.
First: The validator in the script uses name to validate the object, is it possible to change to id in the gen_validatorv4.js and how?
Second: my page reloads itself despite of alert produces by the textbox. it's suppose... | [
"To answer your second question: \nIf validation fails, you want to return false from the submit handler: \nfunction submitForm() {\n var result = validate(this);\n\n if ( result === false ) { return false; }\n}\n\nThat way the form submission process will be canceled. \n"
] | [
2
] | [] | [] | [
"javascript",
"python",
"validation"
] | stackoverflow_0004958773_javascript_python_validation.txt |
Q:
Python: Using a dictionary as switch not working
I'm a 'python neophyte' and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.
The problem was that for some reason the dictio... | Python: Using a dictionary as switch not working | I'm a 'python neophyte' and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.
The problem was that for some reason the dictionary kept evaluating ALL cases (two in this instance) ... | [
"You shouldn't call the functions. Just store the function objects itself in the dictionary, not their return values:\ndef keyboard(key):\n values = {\n 110: discoMode,\n 27: exit\n }\n values.get(key, default)()\n\nf() is a call to the function f and evaluates to the return value of this call. ... | [
15,
3,
0
] | [] | [] | [
"data_structures",
"python",
"switch_statement"
] | stackoverflow_0004960332_data_structures_python_switch_statement.txt |
Q:
Regular expression in loops
I have two lists with data that I want to compare dates for. I tried using regular expression within a loop to find the corresponding entry from L1 in L2. The entries in the lists consist of strings 'code, name, date', and I want to match the entry from L1 with the entry that begins w... | Regular expression in loops | I have two lists with data that I want to compare dates for. I tried using regular expression within a loop to find the corresponding entry from L1 in L2. The entries in the lists consist of strings 'code, name, date', and I want to match the entry from L1 with the entry that begins with the same code in L2. I wrote... | [
"You can use an anchor to achieve this:\nre.match('^' + code + r'(?=\\s*,)', line)\n\n^ anchors the match to the beginning of the line, and (?=\\s*,) means that the match must be followed by any amount of whitespace, followed by a comma.\nThis way you ensure that the code matches the code in its entirety, and also ... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004960327_python_regex.txt |
Q:
Moving Parallel Python code to the cloud
Upon hearing that the scientific computing project (happens to be the stochastic tractography method described here) I'm currently running for an investigator would take 4 months on our 50 node cluster, the investigator has asked me to examine other options. The project is... | Moving Parallel Python code to the cloud | Upon hearing that the scientific computing project (happens to be the stochastic tractography method described here) I'm currently running for an investigator would take 4 months on our 50 node cluster, the investigator has asked me to examine other options. The project is currently using parallel python to farm out c... | [
"You might be interested in PiCloud. I have never used it, but their offer apparently includes the Enthought Python Distribution, which covers the standard scientific libraries.\nIt's tough to say if this will work for your specific case, but the Parallel Python interface is pretty generic. So hopefully not too man... | [
6,
2
] | [] | [] | [
"amazon_ec2",
"mapreduce",
"parallel_processing",
"parallel_python",
"python"
] | stackoverflow_0004952720_amazon_ec2_mapreduce_parallel_processing_parallel_python_python.txt |
Q:
python array as list of parameters
I have an array that matches the parameters of a function:
TmpfieldNames = []
TmpfieldNames.append(Trademark.name)
TmpfieldNames.append(Trademark.id)
return func(Trademark.name, Trademark.id)
func(Trademark.name.Trademark.id) works, but func(Tmpfi... | python array as list of parameters | I have an array that matches the parameters of a function:
TmpfieldNames = []
TmpfieldNames.append(Trademark.name)
TmpfieldNames.append(Trademark.id)
return func(Trademark.name, Trademark.id)
func(Trademark.name.Trademark.id) works, but func(TmpfieldNames) doesn't. How can I call the fu... | [
"With * you can unpack arguments from a list or tuple and ** unpacks arguments from a dict.\n>>> range(3, 6) # normal call with separate arguments\n[3, 4, 5]\n>>> args = [3, 6]\n>>> range(*args) # call with arguments unpacked from a list\n[3, 4, 5]\n\nExample from the documentation.\n",
"I ... | [
39,
17,
2
] | [] | [] | [
"python"
] | stackoverflow_0004960689_python.txt |
Q:
Error in creating an SQLite database using the Python subprocess module
The following Python code tries to create an SQLite database and a table, using the command line in Linux:
#!/usr/bin/python2.6
import subprocess
args = ["sqlite3", "db.sqlite", "'CREATE TABLE my_table(my_column TEXT)'"]
print(" ".join(args))... | Error in creating an SQLite database using the Python subprocess module | The following Python code tries to create an SQLite database and a table, using the command line in Linux:
#!/usr/bin/python2.6
import subprocess
args = ["sqlite3", "db.sqlite", "'CREATE TABLE my_table(my_column TEXT)'"]
print(" ".join(args))
subprocess.call(args)
When I ran the code, it created a database with zero... | [
"Besides the extra quoting that @Dirk mentions before, you can also create the database without spawning a subprocess:\nimport sqlite3\n\ncnx = sqlite3.connect(\"e:/temp/db.sqlite\")\ncnx.execute(\"CREATE TABLE my_table(my_column TEXT)\")\ncnx.commit()\ncnx.close()\n\n",
"Drop the ' in the second argument to sqli... | [
3,
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004960777_python_sqlite.txt |
Q:
how to safely remove elements from a list in Python
I loop through a list and remove the elements that satisfy my condition. But why doesn't this work, as noted below? Thank you.
>>> a=[ i for i in range(4)]
>>> a
[0, 1, 2, 3]
>>> for e in a:
... if (e > 1) and (e < 4):
... a.remove(e)
...
>>> a
[0, 1... | how to safely remove elements from a list in Python | I loop through a list and remove the elements that satisfy my condition. But why doesn't this work, as noted below? Thank you.
>>> a=[ i for i in range(4)]
>>> a
[0, 1, 2, 3]
>>> for e in a:
... if (e > 1) and (e < 4):
... a.remove(e)
...
>>> a
[0, 1, 3]
>>> a=[ i for i in range(4)]
>>> for e in a:
... ... | [
"You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts).\nInstead, iterate over a copy (for e in a[:]: ...) or, instead of modifying an existing list, filter it to ge... | [
11,
6,
3,
3,
1
] | [] | [] | [
"iterator",
"list",
"python"
] | stackoverflow_0004960968_iterator_list_python.txt |
Q:
How to Implement in a ModelAdmin Form in Django a Inline inside a Inline?
Basic explanation:
I'm working on a catalog app that has Product as a model that has a 1-N relationship with Galleries. Each Gallerie has N Photos.
I need to customize the add/edit form of my model Product as follows:
In the same form can ... | How to Implement in a ModelAdmin Form in Django a Inline inside a Inline? | Basic explanation:
I'm working on a catalog app that has Product as a model that has a 1-N relationship with Galleries. Each Gallerie has N Photos.
I need to customize the add/edit form of my model Product as follows:
In the same form can add/edit Galleries (as Inlines, easy, implemented). [1]
But in each Gallerie In... | [
"in the inline you must put a list_display with related object :S\nOther way its create a view and with javascript get the images and append to inlines\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"django_models",
"python"
] | stackoverflow_0004961574_django_django_admin_django_forms_django_models_python.txt |
Q:
Creating a logical connection and calling procedures on a XML-RPC server which verifies CSRF tokens - python xmlrpclib
I am using xmlrpclib in python to connect to a xml-rpc server that verifies csrf tokens.
proxy = ServerProxy("http://127.0.0.1:9091/transmission/rpc/")
proxy.system.listMethods()
I am getting th... | Creating a logical connection and calling procedures on a XML-RPC server which verifies CSRF tokens - python xmlrpclib | I am using xmlrpclib in python to connect to a xml-rpc server that verifies csrf tokens.
proxy = ServerProxy("http://127.0.0.1:9091/transmission/rpc/")
proxy.system.listMethods()
I am getting the following exception
ProtocolError: <ProtocolError for 127.0.0.1:9091/transmission/rpc/: 409 Conflict>
When trying to acc... | [
"First of all, Transmission doesn't expose an XML-RPC service. It's a JSON-RPC service. Using xmlrpclib won't work at all.\nYou'll need to do exactly what the error message says... record the X-Transmission-Session-Id from the response header whenever you receive a 409 error, then re-send the request with X-Transmi... | [
1
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0004961328_python_xml_rpc.txt |
Q:
Does django have a user editable templating language that is secure like rails has liquid?
Does django have a user editable templating language that is secure like rails has liquid?
i.e. a end user can't hack template code to somehow output dangerous objects and hack the website.
A:
If you're using the template ... | Does django have a user editable templating language that is secure like rails has liquid? | Does django have a user editable templating language that is secure like rails has liquid?
i.e. a end user can't hack template code to somehow output dangerous objects and hack the website.
| [
"If you're using the template language the right way: yes.\nSee Django template tags and filters:\n\nhttp://docs.djangoproject.com/en/1.2/ref/templates/builtins/#escape\nhttp://docs.djangoproject.com/en/1.2/ref/templates/builtins/#autoescape\nhttp://docs.djangoproject.com/en/1.2/ref/templates/builtins/#escapejs\n\n... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004962069_django_python.txt |
Q:
App Engine gives error in number formatting when deployed
I have just deployed my app and as soon as I go on the homepage I get the '500 internal server error' page. Having looked through the logs I got the following error:
type 'exceptions.SyntaxError'>: Non-ASCII character '\xc2' in file /base/data/home/apps/sp... | App Engine gives error in number formatting when deployed | I have just deployed my app and as soon as I go on the homepage I get the '500 internal server error' page. Having looked through the logs I got the following error:
type 'exceptions.SyntaxError'>: Non-ASCII character '\xc2' in file /base/data/home/apps/spare-wheels/1.348259065130939449/sparewheels.py on line 465, but... | [
"Check the encoding of the python file, is it UTF-8? That error message suggests you may have saved the file as an ASCII format with international characters in the file (aka \"£\") causing Google's python runtime to barf up that 500 error.\nAlso try tossing this line on the first or second line of the python file:... | [
5,
1
] | [] | [] | [
"encoding",
"google_app_engine",
"python"
] | stackoverflow_0004961771_encoding_google_app_engine_python.txt |
Q:
Is this normal behaviour for an OO language?
I've defined this class:
class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
And overridden this method:
def total_form_count(self):
return self._total_form_count
It so happens... | Is this normal behaviour for an OO language? | I've defined this class:
class RequiredFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(RequiredFormSet, self).__init__(*args, **kwargs)
And overridden this method:
def total_form_count(self):
return self._total_form_count
It so happens that super(...).__init__ uses total_form_count() ... | [
"Yes, this is typical OOP behavior (polymorphism) to have subclass methods invoked by dynamic dispatch. This is part of the reason why C# requires the programmer to mark an overridable method as virtual. I'm sure you're familiar with this notion in general, and the surprise mainly comes from the fact that this is h... | [
4,
3,
3,
3,
1,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0004962397_oop_python.txt |
Q:
Python - Dijkstra's Algorithm
I need to implement Dijkstra's Algorithm in Python. However, I have to use a 2D array to hold three pieces of information - predecessor, length and unvisited/visited.
I know in C a Struct can be used, though I am stuck on how I can do a similar thing in Python, I am told it's possible... | Python - Dijkstra's Algorithm | I need to implement Dijkstra's Algorithm in Python. However, I have to use a 2D array to hold three pieces of information - predecessor, length and unvisited/visited.
I know in C a Struct can be used, though I am stuck on how I can do a similar thing in Python, I am told it's possible but I have no idea to be honest
| [
"Create a class for it.\nclass XXX(object):\n def __init__(self, predecessor, length, visited):\n self.predecessor = predecessor\n self.length = length\n self.visited = visited\n\nOr use collections.namedtuple, which is particular cool for holding struct-like compound types without own behav... | [
2,
1,
1,
1,
0
] | [] | [] | [
"dijkstra",
"python"
] | stackoverflow_0004962202_dijkstra_python.txt |
Q:
restructuredText, docstring and python interactive shell
I am using reStructuredText to document my code, so as to get nice offline HTML pages by means of epydoc.
Results are brilliant. The only drawback is that when I use the Python interactive shell, the help() function does not parse the reST metadata in the do... | restructuredText, docstring and python interactive shell | I am using reStructuredText to document my code, so as to get nice offline HTML pages by means of epydoc.
Results are brilliant. The only drawback is that when I use the Python interactive shell, the help() function does not parse the reST metadata in the documentation strings, and instead it displays the whole thing a... | [
"The help() function gets added to the builtin namespace by the site module, which you can customize by creating a sitecustomize.py module somewhere on your path (apparently it's usually kept in site-packages).\nThen in the sitecustomize.py file you add whatever customizations you want.\nYou could handle this a cou... | [
4
] | [] | [] | [
"epydoc",
"pydoc",
"python",
"restructuredtext"
] | stackoverflow_0004949935_epydoc_pydoc_python_restructuredtext.txt |
Q:
Qt4 + mplot3d of matplotlib
I am trying to embed a 3D plot in a Qt4 GUI (has other buttons), is this possible using matplotlib's mplot3d?
I am aware that 2d plots are possible using "matplotlib.backends.backend_qt4agg", and i have done this.
If yes, please quote an example.
If no, what is the favorite option? V... | Qt4 + mplot3d of matplotlib | I am trying to embed a 3D plot in a Qt4 GUI (has other buttons), is this possible using matplotlib's mplot3d?
I am aware that 2d plots are possible using "matplotlib.backends.backend_qt4agg", and i have done this.
If yes, please quote an example.
If no, what is the favorite option? VTK?
Thanks!
| [
"While not the cleanest thing you're going to see. I've noticed that is it not as fast as the tkinter backend. Then again it works.\nHave fun:\nimport os\nimport sys\n\nfrom PyQt4 import QtCore, QtGui\n\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.ba... | [
3
] | [] | [] | [
"matplotlib",
"pyqt4",
"python",
"qt4"
] | stackoverflow_0004899176_matplotlib_pyqt4_python_qt4.txt |
Q:
In python, is it easy to call a function multiple times using threads?
Say I have a simple function, it connects to a database (or a queue), gets a url that hasn't been visited, and then fetches the HTML at the given URL.
Now this process is serial, i.e. it will only fetch the html from a given url one at a time, ... | In python, is it easy to call a function multiple times using threads? | Say I have a simple function, it connects to a database (or a queue), gets a url that hasn't been visited, and then fetches the HTML at the given URL.
Now this process is serial, i.e. it will only fetch the html from a given url one at a time, how can I make this faster by doing this in a group of threads?
| [
"Yes. Many of the Python threading examples are just about this idea, since it's a good use for the threads.\nJust to pick the top four Goggle hits on \"python threads url\": 1, 2, 3, 4.\nBasically, things that are I/O limited are good candidates for threading speed-ups in Python; things the are processing limited... | [
2,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004962022_multithreading_python.txt |
Q:
In django, can you load a django app into the python interpreter like in rails?
In django, can you load a django app into the python interpreter like in rails?
i.e. does django have: irb
?
A:
you mean python manage.py shell ?
A:
If you want to have a more powerful Python shell to use with Django, you can look ... | In django, can you load a django app into the python interpreter like in rails? | In django, can you load a django app into the python interpreter like in rails?
i.e. does django have: irb
?
| [
"you mean python manage.py shell ?\n",
"If you want to have a more powerful Python shell to use with Django, you can look at IPython. Just install it and the python manage.py shell will use ipython instead of the default one.\nCheck the IPython website to see the interesting features it brings.\n",
"yes, it can... | [
25,
4,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004961951_django_python.txt |
Q:
Add image dynamically to wx.StaticBitmap?
It is possible to add dynamically images to wx.StaticBitmap?
Now I can only add one image and only change existing image.
I want to display next image after new line or something else.
My actual code:
self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition,
... | Add image dynamically to wx.StaticBitmap? | It is possible to add dynamically images to wx.StaticBitmap?
Now I can only add one image and only change existing image.
I want to display next image after new line or something else.
My actual code:
self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition,
size=(-1,100),
... | [
"I don't see how you could possibly include more than one image in a wx.StaticBitmap.\nHowever, you could: \n\ndynamically create the image that you are going to display in the StaticBitmap, using PIL or something to \"concatenate\" the images\njust display multiple wx.StaticBitmaps in a wx.Sizer of some kind\n\n"
... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003554672_python_wxpython.txt |
Q:
access decorator arguments inside the decorators wrapper function
im trying to access my decorators arguments inside the wrapper function with no luck.
what i have is:
def my_decorator(arg1=False, arg2=None):
def decorator(method):
@functools.wraps(method)
def wrapper(method, *args, **kwargs):... | access decorator arguments inside the decorators wrapper function | im trying to access my decorators arguments inside the wrapper function with no luck.
what i have is:
def my_decorator(arg1=False, arg2=None):
def decorator(method):
@functools.wraps(method)
def wrapper(method, *args, **kwargs):
# do something based on arg1 and arg2
# access... | [
"You can access arg1 and arg2, but you should not assign to these names, not even with \"augmented\" assign operators, because this would make them local variables in the inner function. The error message you get shows that you tried to do exactly this (though you did not show your code).\nIn Python 3, you can wor... | [
4,
0
] | [] | [] | [
"arguments",
"decorator",
"optional_arguments",
"python"
] | stackoverflow_0004962932_arguments_decorator_optional_arguments_python.txt |
Q:
Auto resize columns in TreeListCtrl
I create a tree control:
self.tree_cat = wx.gizmos.TreeListCtrl(self, -1, style=some-styles)
Then I add columns:
self.tree_cat.AddColumn("blah")
self.tree_cat.AddColumn("blah")
Now how do I make the columns auto-resize when I add elements?
A:
The way you should be able do th... | Auto resize columns in TreeListCtrl | I create a tree control:
self.tree_cat = wx.gizmos.TreeListCtrl(self, -1, style=some-styles)
Then I add columns:
self.tree_cat.AddColumn("blah")
self.tree_cat.AddColumn("blah")
Now how do I make the columns auto-resize when I add elements?
| [
"The way you should be able do this is to use the wx.lib.mixins.listctrl.ListCtrlAutoWidthMixin as a mixin class for the wx.TreeListCtrl.\nBut apparently there's a bug with it currently.\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004437046_python_wxpython.txt |
Q:
Django sessions: can you check for session data and set it in same view?
When using Django sessions, is it good practice to see if session data has been previously set, and if not to set the initial session data, in the same view?
Will this cause major issues, for me or users, if users have their cookies disabled?... | Django sessions: can you check for session data and set it in same view? | When using Django sessions, is it good practice to see if session data has been previously set, and if not to set the initial session data, in the same view?
Will this cause major issues, for me or users, if users have their cookies disabled?
(The presence of test cookies has confused me a little. However if you used t... | [
"This is exactly right. Session data isn't stored in cookies - the cookie just stores the unique ID of the user's data in the session database.\nOne minor nit: don't use has_key - it has been discouraged in Python for years. Use in: \nif game_name in game_votes:\n\n",
"It is perfectly fine to check for sessions i... | [
4,
1
] | [] | [] | [
"django",
"django_sessions",
"python"
] | stackoverflow_0004963186_django_django_sessions_python.txt |
Q:
Axes3D Data Labels and Plot Limits
Below is a small snippet the illustrates the problem I'm having related to the size of the cube used in an Axes3D instance from matplotlib and the cutting off of axis labels. While I can change the background color of the figure canvas pretty easily, this still causes the text l... | Axes3D Data Labels and Plot Limits | Below is a small snippet the illustrates the problem I'm having related to the size of the cube used in an Axes3D instance from matplotlib and the cutting off of axis labels. While I can change the background color of the figure canvas pretty easily, this still causes the text located on the labels to become distorted... | [
"change the distance - ax.dist - like this:\nax.dist = 15\n\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004962442_matplotlib_python.txt |
Q:
Follow datastore model structure on AppEngine - Order followers by date
In my app, users can follow other users, and get updates whenever the people they follow perform an activity.
I store the follow relationships in this manner:
class User(db.Model):
''' User details '''
username = db.StringProperty()
class... | Follow datastore model structure on AppEngine - Order followers by date | In my app, users can follow other users, and get updates whenever the people they follow perform an activity.
I store the follow relationships in this manner:
class User(db.Model):
''' User details '''
username = db.StringProperty()
class Contacts(db.Model):
'''Store users contacts
parent= User (followe... | [
"I would use a model to map from the user to their target rather then a list:\n\nInserting a new instance or deleting an existing one will probably be faster than modifying a huge list and resaving it. Also as the size of followed grows you can query a subset of the list rather that fetching it all (see below for ... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"social_networking"
] | stackoverflow_0004959215_google_app_engine_python_social_networking.txt |
Q:
Extract Words from a file
I open a file using python to find whether a predefined set of words are present in the opened file or not. I took the predefined set of words in a list and opened the file that has to be tested. Now is there any method to extract words in python rather than lines. Thats makes my work lot... | Extract Words from a file | I open a file using python to find whether a predefined set of words are present in the opened file or not. I took the predefined set of words in a list and opened the file that has to be tested. Now is there any method to extract words in python rather than lines. Thats makes my work lot easier.
| [
"import re\n\ndef get_words_from_string(s):\n return set(re.findall(re.compile('\\w+'), s.lower()))\n\ndef get_words_from_file(fname):\n with open(fname, 'rb') as inf:\n return get_words_from_string(inf.read())\n\ndef all_words(needle, haystack):\n return set(needle).issubset(set(haystack))\n\ndef a... | [
7,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004963499_python.txt |
Q:
Storing raw and processed data for efficient use in matplotlib
I have some large data sets (numeric and textual) and as I'm studying and making visualizations with python and numpy/matplotlib, I'm running into a problem: I load the raw data, apply calculations, then create graphs in matplotlib. This is all in one... | Storing raw and processed data for efficient use in matplotlib | I have some large data sets (numeric and textual) and as I'm studying and making visualizations with python and numpy/matplotlib, I'm running into a problem: I load the raw data, apply calculations, then create graphs in matplotlib. This is all in one program, so I'm redundantly and inefficiently calculating the same ... | [
"check out pytables, a wrapper for HDF5 libarary. It was designed for that sort of thing.\n",
"I would just pickle them. That's very simple, usually fast enough and (if you use the newer, binary protocols) also reasonably efficient in space. Make sure to use the highest available protocol:\nimport cPickle\nwith o... | [
3,
1
] | [] | [] | [
"python",
"storage"
] | stackoverflow_0004963183_python_storage.txt |
Q:
Logging output of file and process time out with python
I am going through a big list of files and running a command on all of them. I want to log the output and if the command takes more than 5 minutes for a file, I would like to stop the command and go to the next file.
I have two problems:
I want to record th... | Logging output of file and process time out with python | I am going through a big list of files and running a command on all of them. I want to log the output and if the command takes more than 5 minutes for a file, I would like to stop the command and go to the next file.
I have two problems:
I want to record the file name to the output file and also record the output mes... | [
"Here's what I use, roughly:\nfrom datetime import datetime\nfrom time import time\n\nimport subprocess\nimport sys\nimport threading\nimport os\n\nclass Execution(threading.Thread):\n comm = None\n proc = None\n returncode = None\n stdoutdata = None\n stderrdate = None\n\n def __init__(self, comm):\n thre... | [
1,
1
] | [] | [] | [
"flush",
"python",
"subprocess",
"timeout"
] | stackoverflow_0004963891_flush_python_subprocess_timeout.txt |
Q:
Max Value within a List of Lists of Tuple
I have a problem to get the highest Value in a dynamic List of Lists of Tuples.
The List can looks like this:
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
Now I loop through the List to get the highest Value (integer):
t... | Max Value within a List of Lists of Tuple | I have a problem to get the highest Value in a dynamic List of Lists of Tuples.
The List can looks like this:
adymlist = [[('name1',1)],[('name2',2),('name3',1), ...('name10', 20)], ...,[('name m',int),..]]
Now I loop through the List to get the highest Value (integer):
total = {}
y=0
while y < len(adymlist):
if ... | [
"To clarify, looks like you've got a list of lists of tuples. It doesn't look like we care about what list they are in, so we can simplify this to two steps\n\nFlatten the list of lists to a list of tuples\nFind the max value\n\nThe first part can be accomplished via itertools.chain (see e.g., Flattening a shallo... | [
16,
4
] | [] | [] | [
"list",
"max",
"python"
] | stackoverflow_0004963957_list_max_python.txt |
Q:
Quicksort sorts larger numbers faster?
I was messing around with Python trying to practice my sorting algorithms and found out something interesting.
I have three different pieces of data:
x = number of numbers to sort
y = range the numbers are in (all random generated ints)
z = total time taken to sort
... | Quicksort sorts larger numbers faster? | I was messing around with Python trying to practice my sorting algorithms and found out something interesting.
I have three different pieces of data:
x = number of numbers to sort
y = range the numbers are in (all random generated ints)
z = total time taken to sort
When:
x = 100000 and
y = (0,100000) then
z =... | [
"I think this has to do with the choice of a pivot. Depending on how your partition step works, if you have a lot of duplicate values, your algorithm can degenerate to quadratic behavior when confronted with many duplicates. For example, suppose that you're trying to quicksort this stream:\n [0 0 0 0 0 0 0 0 0 0 ... | [
34,
2,
1
] | [] | [] | [
"algorithm",
"performance",
"python",
"quicksort",
"sorting"
] | stackoverflow_0004964004_algorithm_performance_python_quicksort_sorting.txt |
Q:
How do I get the sum of all numbers in a range function in Python?
I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but ... | How do I get the sum of all numbers in a range function in Python? | I can't figure out how to take x (from code below) and add it to itself to get the sum and then divide it by the number of ratings. The example given in class was 4 ratings, with the numbers being 3,4,1,and 2. The average rating should be 2.5, but I can't seem to get it right!
number_of_ratings = eval(input("Enter the ... | [
"Your code doesn't add anything, it just overwrites x in each iteration. Adding something to a variable can be done with the += operator. Also, don't use eval:\nnumber_of_ratings = int(input(\"Enter the number of difficulty ratings as a positive integer: \"))\nx = 0\nfor i in range(number_of_ratings):\n x += int... | [
3,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004964286_python_python_3.x.txt |
Q:
Python "global name 'x' is not defined"
from dionaea.core import ihandler, incident, g_dionaea
from dionaea.util import md5file, sha512file
from dionaea import pyev
import logging
import json
import uuid
logger = logging.getLogger('submit_http')
logger.setLevel(logging.DEBUG)
class submmithttp_report:
def _... | Python "global name 'x' is not defined" | from dionaea.core import ihandler, incident, g_dionaea
from dionaea.util import md5file, sha512file
from dionaea import pyev
import logging
import json
import uuid
logger = logging.getLogger('submit_http')
logger.setLevel(logging.DEBUG)
class submmithttp_report:
def __init__(self, sha512h, md5, filepath):
... | [
"Class name is submmithttp_report but you are calling submithttp_report\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004964400_python.txt |
Q:
Max limit of bytes in method update of Hashlib Python module
I am trying to compute md5 hash of a file with the function hashlib.md5() from hashlib module.
So that I writed this piece of code:
Buffer = 128
f = open("c:\\file.tct", "rb")
m = hashlib.md5()
while True:
p = f.read(Buffer)
if len(p) != 0:
... | Max limit of bytes in method update of Hashlib Python module | I am trying to compute md5 hash of a file with the function hashlib.md5() from hashlib module.
So that I writed this piece of code:
Buffer = 128
f = open("c:\\file.tct", "rb")
m = hashlib.md5()
while True:
p = f.read(Buffer)
if len(p) != 0:
m.update(p)
else:
break
print m.hexdigest()
f.close()
I... | [
"Big (≈2**40) chunk sizes lead to MemoryError i.e., there is no limit other than available RAM. On the other hand bufsize is limited by 2**31-1 on my machine:\nimport hashlib\nfrom functools import partial\n\ndef md5(filename, chunksize=2**15, bufsize=-1):\n m = hashlib.md5()\n with open(filename, 'rb', bufsi... | [
3,
2,
0
] | [] | [] | [
"hashlib",
"python"
] | stackoverflow_0004949162_hashlib_python.txt |
Q:
Imported objects available within model but not within model's method
Within my models file, models can access imported items from within the model itself (as expected), but not from within the model's methods. For example:
from django.db import models
from datetime import datetime
foo1 = datetime.now() # this a... | Imported objects available within model but not within model's method | Within my models file, models can access imported items from within the model itself (as expected), but not from within the model's methods. For example:
from django.db import models
from datetime import datetime
foo1 = datetime.now() # this assigns successfully
class ServiceEventManager(models.Manager):
foo2 = ... | [
"Look for something in your code/model that is doing 'datetime = None' or 'datetime = something_that_returns_None()'\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004964292_django_django_models_python.txt |
Q:
How to sum columns in list with text fields
Say I've a Python list as below:
list = [ ['text',2,3,4], ['text2',4,5,6] ]
y= map(sum,zip(*list))
print y
Gives int /str error.
How would I pop all 'text' in all rows and sum the remaining columns.
Ans: Im looking for [6, 8, 10]
I noticed that field look like int b... | How to sum columns in list with text fields | Say I've a Python list as below:
list = [ ['text',2,3,4], ['text2',4,5,6] ]
y= map(sum,zip(*list))
print y
Gives int /str error.
How would I pop all 'text' in all rows and sum the remaining columns.
Ans: Im looking for [6, 8, 10]
I noticed that field look like int but are str. 4 vs '4'.
| [
"In [111]: lst = [ ['text',2,3,4], ['text2',4,5,6] ]\n\nIn [112]: import operator\n\nIn [113]: print(map(operator.add,*lst))\n['texttext2', 6, 8, 10]\n\n\nIf you don't know a priori which columns contain text, then you could use a try..except block to handle the text:\nlst = [ ['text',2,3,4], ['text2',4,5,6] ]\nr... | [
4,
3,
1,
0
] | [] | [] | [
"python",
"sum"
] | stackoverflow_0004964633_python_sum.txt |
Q:
libtool python module linking and installation
I work on a project written in C, using the autotools, that produces a static library. Am also providing a Python interface to the C API in the context of the same project. I did not have permission until recently to introduce libtool in the project, in order to be ab... | libtool python module linking and installation | I work on a project written in C, using the autotools, that produces a static library. Am also providing a Python interface to the C API in the context of the same project. I did not have permission until recently to introduce libtool in the project, in order to be able to provide both static and dynamic libraries in a... | [
"Have you read http://www.gnu.org/software/hello/manual/automake/Python.html ? I can't tell if you want to use pyexecdir as the location to install your modules. If so, add AM_PATH_PYTHON to configure.ac.\nAnyway, in automake, the name before the _PRIMARY specifies where something is to be installed: lib_LTLIBRARIE... | [
3
] | [] | [] | [
"autotools",
"distutils",
"libtool",
"python"
] | stackoverflow_0004959683_autotools_distutils_libtool_python.txt |
Q:
Python 3.2 UnicodeEncodeError
I am trying to write some data pulled from some source code (using httplib2 and lxml.html), but whenever I try to write the data I get this error:
UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in position 505: character maps to <undefined>
Throughout the whole pr... | Python 3.2 UnicodeEncodeError | I am trying to write some data pulled from some source code (using httplib2 and lxml.html), but whenever I try to write the data I get this error:
UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in position 505: character maps to <undefined>
Throughout the whole program I can print the text just fin... | [
"Specify an encoding that can handle the character:\nf = open(loc + fname + '.txt', 'w', encoding='utf-8')\n\n"
] | [
4
] | [] | [] | [
"python",
"python_3.x",
"unicode",
"utf_8"
] | stackoverflow_0004964721_python_python_3.x_unicode_utf_8.txt |
Q:
mutex decorator in python
I saw this: http://yukelzon.blogspot.com/2005/07/python-locks.html when looking for a solution to add some locking to existing code around writing to a file.
The simplified version for my needs looks like this:
def mlock(orig):
def inner(*args, **kwargs):
Coloring.lock.acquire... | mutex decorator in python | I saw this: http://yukelzon.blogspot.com/2005/07/python-locks.html when looking for a solution to add some locking to existing code around writing to a file.
The simplified version for my needs looks like this:
def mlock(orig):
def inner(*args, **kwargs):
Coloring.lock.acquire()
try:
ret = ori... | [
"If you're using Python 2.6+ (I think), mutex objects are context managers, so:\ndef mlock(f):\n def inner(*args, **kwargs):\n with Coloring.lock:\n return f(*args, **kwargs)\n return inner\n\n",
"I'm not a fan of free variables. I would probably make the lock an explicit variable of the ... | [
3,
0
] | [] | [] | [
"coding_style",
"decorator",
"locking",
"mutex",
"python"
] | stackoverflow_0004964736_coding_style_decorator_locking_mutex_python.txt |
Q:
Callback Functions across computers?
I'm writing a python server/client app. If I serialize a function on the client and pass it to the server, can the server use it as a callback? I'm assuming there must be something extra I'd have to do as the client and server are communicating via packets, I just don't know wh... | Callback Functions across computers? | I'm writing a python server/client app. If I serialize a function on the client and pass it to the server, can the server use it as a callback? I'm assuming there must be something extra I'd have to do as the client and server are communicating via packets, I just don't know what.
What I actually need is for the serve... | [
"Take a look at Twisted JSON RPC.\nA recent SO post: Python Twisted JSON RPC\n"
] | [
1
] | [] | [] | [
"callback",
"polling",
"python"
] | stackoverflow_0004964850_callback_polling_python.txt |
Q:
How does this strange python decorator work
I was looking through the source for the pyFacebook library and found the following code:
def require_login(next=None, internal=None, required_permissions=None):
def decorator(view):
def newview(request, *args, **kwargs):
next = newview.next
... | How does this strange python decorator work | I was looking through the source for the pyFacebook library and found the following code:
def require_login(next=None, internal=None, required_permissions=None):
def decorator(view):
def newview(request, *args, **kwargs):
next = newview.next
internal = newview.internal
t... | [
"In Python a variable defined inside a function is not the same as defined outside as a property of a function.\nThe following example will probably help:\ncass A:\n a = 1\n def `__init__`(self):\n self.a = 2\n\nprint A().a\nprint A.a\n\nUPD:\nThe object newview is in the scope inside the function is due to th... | [
1
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0004964984_decorator_python.txt |
Q:
Comparing `list`s in python
I have multiple lists. I need to find a way to generate list of unique items in each list as compared with all the lists. Is there any simple or straight forward way to do this. I know that these lists can basically be used as sets.
A:
import collections
def uniques(*args):
"... | Comparing `list`s in python | I have multiple lists. I need to find a way to generate list of unique items in each list as compared with all the lists. Is there any simple or straight forward way to do this. I know that these lists can basically be used as sets.
| [
"import collections\n\ndef uniques(*args):\n \"\"\"For an arbitrary number of sequences,\n return the items in each sequence which\n do not occur in any of the other sequences\n \"\"\"\n\n # ensure that each value only occurs once in each sequence\n args = [set(a) for a in args]\n\n... | [
5,
4,
1,
0,
0
] | [] | [] | [
"list",
"python",
"set",
"unique"
] | stackoverflow_0004965014_list_python_set_unique.txt |
Q:
Scraping sites with javascript screen delay
I'm attempting to scrape a site that has a split second javascript delay.
I'm currently using python for scraping. Whenever I 'get' the page, the javascript delay has not finished and is has not completely loaded the new dom yet.
How would I scrape such a pge?
A:
You c... | Scraping sites with javascript screen delay | I'm attempting to scrape a site that has a split second javascript delay.
I'm currently using python for scraping. Whenever I 'get' the page, the javascript delay has not finished and is has not completely loaded the new dom yet.
How would I scrape such a pge?
| [
"You can extend Mozilla to build a web scraper which can leverage the full power of the web browser. After all data have been loaded and the DOM has been built, you can extract needed data from the DOM using XSLT. If the DOM was dynamically changed after initial loading, you can take some approaches to wait for the... | [
1
] | [] | [] | [
"javascript",
"python",
"scraper",
"screen_scraping",
"web_scraping"
] | stackoverflow_0004883677_javascript_python_scraper_screen_scraping_web_scraping.txt |
Q:
GAE python - how to change the "one" that a "many" object points to?
I'm using the GAE database to store objects of type Supp, which are part of a SuppSet. A SuppSet can have many Supps in it. I'm using the ReferenceProperty model to create the one-to-many relationship between the SuppSet and Supps as follows:
cla... | GAE python - how to change the "one" that a "many" object points to? | I'm using the GAE database to store objects of type Supp, which are part of a SuppSet. A SuppSet can have many Supps in it. I'm using the ReferenceProperty model to create the one-to-many relationship between the SuppSet and Supps as follows:
class SuppSet(db.Model):
<stuff>
class Supp(db.Model):
<more stuff>
... | [
"from google.appengine.ext import db\n\nclass SuppSet(db.Model):\n name = db.StringProperty()\n\nclass Supp(db.Model):\n suppset = db.ReferenceProperty(SuppSet, collection_name='supp_list')\n\nsuppSet0, suppSet1 = SuppSet(name = '0'), SuppSet(name = '1')\nsuppSet0.put()\nsuppSet1.put()\n\nsupp = Supp(suppset=... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"referenceproperty"
] | stackoverflow_0004965033_google_app_engine_python_referenceproperty.txt |
Q:
GIL in Python 3.1
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
A:
GIL is still there in CPython 3.1; the Unladen Swallow projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2... | GIL in Python 3.1 | Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
| [
"GIL is still there in CPython 3.1; the Unladen Swallow projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by the time the 2.y version is considered ... | [
25,
17,
9,
4,
1,
1,
1
] | [] | [] | [
"gil",
"multithreading",
"python"
] | stackoverflow_0001222929_gil_multithreading_python.txt |
Q:
Import compressed SQL dump into Postgresql with python
I have to import a compressed sql dump into a PostgreSQL database.
The dump gets created by:
pg_dump -F c
So I get a compressed file, which I can't just parse line by line and then use psycopg2 to upload it into my database.
The compressed dumps I'm dealing w... | Import compressed SQL dump into Postgresql with python | I have to import a compressed sql dump into a PostgreSQL database.
The dump gets created by:
pg_dump -F c
So I get a compressed file, which I can't just parse line by line and then use psycopg2 to upload it into my database.
The compressed dumps I'm dealing with are quite big (up to 10GB). What would be an efficient w... | [
"You basically can't do that unless you reimplement pg_restore in your Python project. Consider instead calling pg_restore from your Python program.\n"
] | [
2
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0004963119_postgresql_python.txt |
Q:
My first Python program! Anyone care to review it an help me improve?
I just wrote my first Python program and it works! It is a program that will rename subtitle files to their matching video files so that media players will pick up the subtitles (e.g. it will rename "The_Office_3x01.str" to "The.Office.S03E01.st... | My first Python program! Anyone care to review it an help me improve? | I just wrote my first Python program and it works! It is a program that will rename subtitle files to their matching video files so that media players will pick up the subtitles (e.g. it will rename "The_Office_3x01.str" to "The.Office.S03E01.str" if a file named "The.Office.S03E01.avi" was present in the directory).
I... | [
"1) A hash-bang line only works if it is the first line in the file.\n2) Function and variable names are usually underscore_separated rather than camelCase.\n3) Docstrings usually use triple-quotes, even for single-line docstrings. \n4) Your coding style is very functional-flavored, with many lambdas, maps, reduce... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004965600_python.txt |
Q:
Pylons - url.current() incorrect, for '/test' shows '/test/test'?
I've got a pylons setup, using flup with nginx, and url.current() always returns totally wrong.
I have a route:
map.connect('testpage', '/test', controller='Main', action='test')
And in that controller, I do url.current() and I get /test/test' inst... | Pylons - url.current() incorrect, for '/test' shows '/test/test'? | I've got a pylons setup, using flup with nginx, and url.current() always returns totally wrong.
I have a route:
map.connect('testpage', '/test', controller='Main', action='test')
And in that controller, I do url.current() and I get /test/test' instead of '/test'. I've tried changingSCRIPT_NAME` as various posts about... | [
"Actually it looks like I solved this. Apparently you have to set SCRIPT_NAME to '' AND restart the Pylons application, which I apparently hadn't tried before.\nSo if anyone else has this problem - restart Pylons :)\n",
"in nginx i do\n#fastcgi_param SCRIPT_NAME $fastcgi_script_name;\n"
] | [
2,
0
] | [] | [] | [
"pylons",
"python",
"url_routing"
] | stackoverflow_0003842692_pylons_python_url_routing.txt |
Q:
get screen size in python
Possible Duplicate:
How do I get Monitor resolution in Python?
I was wondering if there was a way to get the screen size from a python script.
Similar Questions:
Getting monitor size in python
This question tells you how to get it through pygame. Is there a way to do it with just pytho... | get screen size in python |
Possible Duplicate:
How do I get Monitor resolution in Python?
I was wondering if there was a way to get the screen size from a python script.
Similar Questions:
Getting monitor size in python
This question tells you how to get it through pygame. Is there a way to do it with just python? I need the scripts to run o... | [
"I stole this from Finding the workspace size (screen size less the taskbar) using GTK\nimport gtk, pygtk\n\nwindow = gtk.Window()\nscreen = window.get_screen()\nprint \"width = \" + str(screen.get_width()) + \", height = \" + str(screen.get_height())\n\nJust to let you know, if you have multiple monitors the scree... | [
2
] | [] | [] | [
"monitor",
"python"
] | stackoverflow_0003375740_monitor_python.txt |
Q:
Refer to a Module within the Module in Python
I have a directory structure for a module like the following:
- foo
- __init__.py
- gui.py
I use the foo module from other places. Now I want to use something from the foo module in gui.py, but when I try to, I get this:
jsternberg@aquila:~$ python foo/gui.py
T... | Refer to a Module within the Module in Python | I have a directory structure for a module like the following:
- foo
- __init__.py
- gui.py
I use the foo module from other places. Now I want to use something from the foo module in gui.py, but when I try to, I get this:
jsternberg@aquila:~$ python foo/gui.py
Traceback (most recent call last):
File "foo/gui.p... | [
"The directory containing foo/ isn't in sys.path when you invoke it that way.\npython -m foo.gui\n\n"
] | [
2
] | [] | [] | [
"import",
"python"
] | stackoverflow_0004965722_import_python.txt |
Q:
need a python based solution for web based display of tabular data
I need to make a tabular data structure (tab delimited text file) available for viewing as a web based solution. I am a bioinformatics programmer with almost no experience in web based development. I know that django is very hot in the python commu... | need a python based solution for web based display of tabular data | I need to make a tabular data structure (tab delimited text file) available for viewing as a web based solution. I am a bioinformatics programmer with almost no experience in web based development. I know that django is very hot in the python community but I wanted to ask here before I went ahead and buy a book on djan... | [
"Django can do this fairly easily.\n",
"Django can do this, but I think the best way to go is to use a Javascript framework ontop of django, I am currently doing this. ExtJS has various types of grids in your situation I think a 'Live' grid would be perfect.\nIt loads x amount of rows, so that you dont have to lo... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"tabular"
] | stackoverflow_0004929054_python_tabular.txt |
Q:
Python: Write list to individual columns in each row
I'm writing data to a CSV but the current output is as follows:
(the top row is the headers)
A VC_s VC_i VT_s
1 (['Not Reported'],['reported'],['click'])
2 (['Not Reported'],['reported'],['click'])
The des... | Python: Write list to individual columns in each row | I'm writing data to a CSV but the current output is as follows:
(the top row is the headers)
A VC_s VC_i VT_s
1 (['Not Reported'],['reported'],['click'])
2 (['Not Reported'],['reported'],['click'])
The desired output is as follows:
A VC_s VC_i ... | [
"entry = [VC_s, VC_i, VT_s]\nrowAdd = tempfile.next()\nofile.writerow(rowAdd + entry)\n\n",
"You just want entry = [VC_s, VC_i, VT_s]\n"
] | [
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004965841_csv_python.txt |
Q:
django how to use AUTH_PROFILE_MODULE with multiple profiles?
Assuming I have different profiles for different user types - staff, teacher,students:
How do I specify AUTH_PROFILE_MODULE in order to get back the appropriate profile with get_profile?
A:
There no way to do that but you could use the generic key.
f... | django how to use AUTH_PROFILE_MODULE with multiple profiles? | Assuming I have different profiles for different user types - staff, teacher,students:
How do I specify AUTH_PROFILE_MODULE in order to get back the appropriate profile with get_profile?
| [
"There no way to do that but you could use the generic key.\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\n\nclass UserProfileOne(models.Model):\n pass\n\nclass UserProfileTwo(models.Model):\n pass\n\n\nclass UserProfile(models.Model):\n conten... | [
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004941125_django_django_models_python.txt |
Q:
File Upload and Processing using Python
I was approached by a friend a few days ago - who has very little programming experience, and he has a project that he asked for some help with.
Basically - this is what he is attempting to accomplish:
1.) Create a website that can accept text files as input.
2.) Read said f... | File Upload and Processing using Python | I was approached by a friend a few days ago - who has very little programming experience, and he has a project that he asked for some help with.
Basically - this is what he is attempting to accomplish:
1.) Create a website that can accept text files as input.
2.) Read said file and pass the parameters contained in the ... | [
"Flask is dead-simple, extremely powerful, and intuitive. I prefer it over Django for smaller projects, as Django uses way too many folders (just follow the introduction tutorial). Here's what I mean by simple and intuitive. I can't really explain it in words, so here's an example script:\nFile: script.py\napp = Fl... | [
6,
3,
0
] | [] | [] | [
"file_upload",
"python",
"web"
] | stackoverflow_0004916361_file_upload_python_web.txt |
Q:
Javascript image uploader/picker in a flask web app?
I'm trying to make a basic CMS with flask and I'm now thinking about images. I am going to use a javascript editor for the content area (like TinyMCE or CKedit), but I want to be able to upload images and have an image picker to insert them into the text editor ... | Javascript image uploader/picker in a flask web app? | I'm trying to make a basic CMS with flask and I'm now thinking about images. I am going to use a javascript editor for the content area (like TinyMCE or CKedit), but I want to be able to upload images and have an image picker to insert them into the text editor field.
I can find little scrips for this around the net, b... | [
"This page in the flask documentation recommends some rich UI solutions at the bottom as well as how to properly handle file uploads. There's also the extension Flask-Uploads which allows you to upload your assets in \"sets\".\n"
] | [
4
] | [] | [] | [
"flask",
"javascript",
"python"
] | stackoverflow_0004964964_flask_javascript_python.txt |
Q:
Transitive dependencies for static libraries and SCons
I've stumbled over a seemingly simple problem while building two libraries and test programs for both.
The Problem: I have two static libraries, libA and libB, and libB depends on libA. I don't want to explicitly link all programs that use libB to libA, I want... | Transitive dependencies for static libraries and SCons | I've stumbled over a seemingly simple problem while building two libraries and test programs for both.
The Problem: I have two static libraries, libA and libB, and libB depends on libA. I don't want to explicitly link all programs that use libB to libA, I want SCons to see that if a program links to library B it should... | [
"SCons does not have built in support for expressing transitive library dependencies as you describe, but its younger cousin Waf does. See the documentation for the \"use\" feature in the Waf book. The Boost build system also has this feature under a different name. You can also choose to implement this yourself in... | [
4,
0
] | [] | [] | [
"c",
"dependencies",
"python",
"scons"
] | stackoverflow_0004887728_c_dependencies_python_scons.txt |
Q:
Django newbie question
I have this code :
def encode_myway(obj):
if isinstance(obj, User):
data = dict()
data['username'] = obj.username
data['code'] = obj.code //a number = 30
return data
I'm serializing for json using simplejson.dumps(resp, default=encode_myway) the problem I h... | Django newbie question | I have this code :
def encode_myway(obj):
if isinstance(obj, User):
data = dict()
data['username'] = obj.username
data['code'] = obj.code //a number = 30
return data
I'm serializing for json using simplejson.dumps(resp, default=encode_myway) the problem I have is that code (an integer... | [
"You seem to be double-encoding. You don't show where resp comes from, but it seems to be JSON already.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004963834_django_python.txt |
Q:
Ordering a set of lines so that they follow one from the other
Line# Lat. Lon.
1a 1573313.042320 6180142.720910
..
..
1z 1569171.442602 6184932.867930
3a 1569171.764930 6184934.045650
..
..
3z 1570412.815667 6190358.086690
5a 1570605.667770 6190253.392920
..
..
5z ... | Ordering a set of lines so that they follow one from the other | Line# Lat. Lon.
1a 1573313.042320 6180142.720910
..
..
1z 1569171.442602 6184932.867930
3a 1569171.764930 6184934.045650
..
..
3z 1570412.815667 6190358.086690
5a 1570605.667770 6190253.392920
..
..
5z 1570373.562963 6190464.146120
4a 1573503.842910 6189595... | [
"Create a dictionary whose keys are (lat, long) tuples for either end point, and whose values are arrays of all of the lines that have such an end point. Search the dictionary for a tuple whose value has only one line. That is an end point. Use the dictionary to traverse the path.\nThis approach will run into is... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004966549_python.txt |
Q:
Why is pip unavailable when I install virtualenv?
The documentation says that if I already have virtualenv installed, then pip is available by default on my system. However, there exists /usr/bin/virtualenv but no /usr/bin/pip. What am I doing wrong ?
A:
It won't be /usr/bin/pip. pip is installed within your vir... | Why is pip unavailable when I install virtualenv? | The documentation says that if I already have virtualenv installed, then pip is available by default on my system. However, there exists /usr/bin/virtualenv but no /usr/bin/pip. What am I doing wrong ?
| [
"It won't be /usr/bin/pip. pip is installed within your virtualenv. It'll be in the bin directory within the virtualenv folder, which is added to the front of your path when you activate the environment.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004966258_python.txt |
Q:
Emacs subprocesses and filepaths in their arguments
I'm trying to create some short-cut keys to start and stop the "paster serve" command used in pyramid projects. Here's my elisp code:
(defun search-for-file (file dir)
"Recursively searches up the directory tree for a given filename"
(if (equal "/" dir)
... | Emacs subprocesses and filepaths in their arguments | I'm trying to create some short-cut keys to start and stop the "paster serve" command used in pyramid projects. Here's my elisp code:
(defun search-for-file (file dir)
"Recursively searches up the directory tree for a given filename"
(if (equal "/" dir)
nil
(if (member file (directory-files dir))
... | [
"I'm a bit wary of all those cd functions. Try this alternate definition of search-for-file, based on a similar function in project-local-variables.el:\n(defun search-for-file (file dir)\n \"Look up the file in and above `dir'.\"\n (let ((f (expand-file-name file dir))\n (parent (file-truename (expand-file-n... | [
2
] | [] | [] | [
"elisp",
"emacs",
"pyramid",
"python"
] | stackoverflow_0004966596_elisp_emacs_pyramid_python.txt |
Q:
creating Python classes with arbitrarily substituted attribute name
I apologize for not giving this question a better title; the reason that I am posting it is that I don't even have the correct terminology to know what I am looking for.
I have defined a class with an attribute 'spam':
def SpamClass(object):
... | creating Python classes with arbitrarily substituted attribute name | I apologize for not giving this question a better title; the reason that I am posting it is that I don't even have the correct terminology to know what I am looking for.
I have defined a class with an attribute 'spam':
def SpamClass(object):
def __init__(self, arg):
self.spam = arg
def __str__(self):
... | [
"Here is a way to get the effect I think you want.\nDefine a generic class with a generic attribute name. Then in each sub class follow the advice in http://docs.python.org/reference/datamodel.html#customizing-attribute-access to make the attribute look externally like it is called whatever you want it called.\nYo... | [
4,
1,
1,
0
] | [] | [] | [
"attributes",
"introspection",
"metaclass",
"python"
] | stackoverflow_0004966509_attributes_introspection_metaclass_python.txt |
Q:
Print Difference Between Time in Ms
I am reading a log file in my python script, and I have got a list of tuples of startTimes and endTimes -
('[19:49:40:680]', '[19:49:49:128]')
('[11:29:10:837]', '[11:29:15:698]')
('[11:30:18:291]', '[11:30:21:025]')
('[11:37:44:293]', '[11:38:02:008]')
('[11:39:14:897]', '[11:... | Print Difference Between Time in Ms | I am reading a log file in my python script, and I have got a list of tuples of startTimes and endTimes -
('[19:49:40:680]', '[19:49:49:128]')
('[11:29:10:837]', '[11:29:15:698]')
('[11:30:18:291]', '[11:30:21:025]')
('[11:37:44:293]', '[11:38:02:008]')
('[11:39:14:897]', '[11:39:21:572]')
('[11:42:19:968]', '[11:42:2... | [
">>> import datetime\n>>> a = ('[19:49:40:680]', '[19:49:49:128]')\n>>> start = datetime.datetime.strptime(a[0][:-1]+\"000\", \"[%H:%M:%S:%f\")\n>>> end = datetime.datetime.strptime(a[1][:-1]+\"000\", \"[%H:%M:%S:%f\")\n>>> delta = end-start\n>>> ms = delta.seconds*1000 + delta.microseconds/1000\n>>> ms\n8448.0\n\n... | [
7,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0004967512_python.txt |
Q:
Optimising Python dictionary access code
Question:
I've profiled my Python program to death, and there is one function that is slowing everything down. It uses Python dictionaries heavily, so I may not have used them in the best way. If I can't get it running faster, I will have to re-write it in C++, so is there ... | Optimising Python dictionary access code | Question:
I've profiled my Python program to death, and there is one function that is slowing everything down. It uses Python dictionaries heavily, so I may not have used them in the best way. If I can't get it running faster, I will have to re-write it in C++, so is there anyone who can help me optimise it in Python?
... | [
"node_after_b == node_a will try to call node_after_b.__eq__(node_a):\n>>> class B(object):\n... def __eq__(self, other):\n... print \"B.__eq__()\"\n... return False\n... \n>>> class A(object):\n... def __eq__(self, other):\n... print \"A.__eq__()\"\n... return False\n... \n>... | [
17,
6,
4,
4,
1
] | [] | [] | [
"dictionary",
"optimization",
"python",
"sparse_matrix"
] | stackoverflow_0004900747_dictionary_optimization_python_sparse_matrix.txt |
Q:
Implementing a function in Python vs C
Is there a difference (in terms of execution time) between implementing a function in Python and implementing it in C and then calling it from Python? If so, why?
A:
Python (at least the "standard" CPython implementation) never actually compiles to native machine code; it c... | Implementing a function in Python vs C | Is there a difference (in terms of execution time) between implementing a function in Python and implementing it in C and then calling it from Python? If so, why?
| [
"Python (at least the \"standard\" CPython implementation) never actually compiles to native machine code; it compiles to bytecode which is then interpreted. So a C function which is in fact compiled to machine code will run faster; the question is whether it will make a relevant difference. So what's the actual pr... | [
5,
1,
1,
0
] | [] | [] | [
"c",
"compilation",
"python"
] | stackoverflow_0004968235_c_compilation_python.txt |
Q:
Python. Class, Struct, Dictionary?
I am disassembling TCP/IP packet into string format. What is the best way to structure and store it? Should I store it as a ctypes struct, python class, dictionary, or some other way? What are the pros and cons of each method?
A:
You should use a class. It gives you the most f... | Python. Class, Struct, Dictionary? | I am disassembling TCP/IP packet into string format. What is the best way to structure and store it? Should I store it as a ctypes struct, python class, dictionary, or some other way? What are the pros and cons of each method?
| [
"You should use a class. It gives you the most flexibility to grow in the future.\nDictionaries have more verbose syntax to access their contents, and don't allow you to add methods if you need them.\nctypes is really for accessing structures packed for use in other APIs. If your data is going to stay in Python, ... | [
8,
1,
1
] | [] | [] | [
"ctypes",
"pcap",
"python",
"tcp"
] | stackoverflow_0004965262_ctypes_pcap_python_tcp.txt |
Q:
print result as hash in sqlalchemy
sql = select id,name from table
res = session.execute(sql)
for row in res:
print row
this code print result of execute sql( without names) as array. How to print result as hash ? (with id,name)
A:
Try this:
columns = ('id', 'name')
sql = 'select %s from table' % ','.join(... | print result as hash in sqlalchemy | sql = select id,name from table
res = session.execute(sql)
for row in res:
print row
this code print result of execute sql( without names) as array. How to print result as hash ? (with id,name)
| [
"Try this:\ncolumns = ('id', 'name')\n\nsql = 'select %s from table' % ','.join(columns)\nres = session.execute(sql)\nfor row in res:\n rowDict = dict(zip(columns, row))\n\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004968416_python_sqlalchemy.txt |
Q:
PEP 3118 warning when using ctypes array as numpy array
I'm getting the following warning message when I try to use a ctypes array as a numpy array:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> impor... | PEP 3118 warning when using ctypes array as numpy array | I'm getting the following warning message when I try to use a ctypes array as a numpy array:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes, numpy
>>> TenByteBuffer = ctypes.c_ubyte * 10
>>> a... | [
"It's a bug in Python. ctypes currently produces invalid PEP 3118 type codes, which Numpy notices: \nhttp://bugs.python.org/issue10746\nhttp://bugs.python.org/issue10744\nWhen such an inconsistency is present, Numpy skips using the PEP 3118 buffer interface, and falls back to the old (obsolete) buffer interface. Th... | [
14,
5
] | [] | [] | [
"ctypes",
"numpy",
"pep3118",
"python",
"warnings"
] | stackoverflow_0004964101_ctypes_numpy_pep3118_python_warnings.txt |
Q:
Exchanging data between 2 languages
I'm trying to pass data from C to python. I've hit a brick wall doing it with beanstalk. My last option is sockets.
Are they any fast queue daemons around which have client libraries for both C and python?
Edit:
Operating System: Ubuntu
Solved: Check comment by Yossarian
Edit2:
... | Exchanging data between 2 languages | I'm trying to pass data from C to python. I've hit a brick wall doing it with beanstalk. My last option is sockets.
Are they any fast queue daemons around which have client libraries for both C and python?
Edit:
Operating System: Ubuntu
Solved: Check comment by Yossarian
Edit2:
libbeanstalkclient, the C client for bean... | [
"You aren't linking against libsbeanstalkclient. try something like gcc -lbeanstalkclient when compiling (add the -l... parameter)\n(this isn't answer on the question, but solution of questioner's problem)\n"
] | [
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0004957320_c_python.txt |
Q:
string.split error? python
a = string.split("Test Test2 Test3"," ")
This returns an error:
Message File Name Line Position
Traceback
<module> C:\pyWiz.py 43
AttributeError: 'module' object has no attribute 'split'
Yes, I imported the string module.
Why is this... | string.split error? python | a = string.split("Test Test2 Test3"," ")
This returns an error:
Message File Name Line Position
Traceback
<module> C:\pyWiz.py 43
AttributeError: 'module' object has no attribute 'split'
Yes, I imported the string module.
Why is this happening?
| [
"Use:\na = 'Test Test2 Test3'.split(' ')\n\n(i.e. split method of str type). string.split is deprecated in 2.x and gone in 3.x.\n",
"string is a module while you were looking for the class/type object str. I would recommend doing this though:\na = \"Test Test2 Test3\".split()\n\n",
"why not just \"Test Test2 Te... | [
8,
3,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004964144_python_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.