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:
Referring to class names through strings?
I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Example of the text:
laptop
17" dell, weight: 12 lb
desktop
24" hp
I know in advance which entities ma... | Referring to class names through strings? | I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Example of the text:
laptop
17" dell, weight: 12 lb
desktop
24" hp
I know in advance which entities may exist in the text, and what attributes they a... | [
"If the classes are defined in computers.py, say, you can do\nimport computers\ngetattr( computers, \"Laptop\" )( <params> )\n\nto instantiate a computers.Laptop. If they are defined in the same file that you are running the code in (so that they are global variables), you can do\nglobals()[ \"Laptop\" ]\n\nbut thi... | [
11,
5,
4,
1,
0
] | [] | [] | [
"class",
"python",
"string"
] | stackoverflow_0003439082_class_python_string.txt |
Q:
incorporating a sys.argv into a mySQL query in python
I'm writing a program that first queries with mySQL and then sorts that data. I want to be able to have a user type "python program_name.py mySQL_query" and have the program insert "mySQL_query" into the query at the beginning of the program. The issue I'm runn... | incorporating a sys.argv into a mySQL query in python | I'm writing a program that first queries with mySQL and then sorts that data. I want to be able to have a user type "python program_name.py mySQL_query" and have the program insert "mySQL_query" into the query at the beginning of the program. The issue I'm running into is the sys.argv command converts the input into a ... | [
"Your code needs to like something like this:\nqb=\"SELECT DISTINCT q19_scan.array_orientation_equatorial, q19_scan.run_id, q19_scan.run_subid, q19_scan.patch_day_number, %s FROM q19_typeb NATURAL JOIN q19_scan NATURAL JOIN q19_timestream NATURAL JOIN q19_weather NATURAL JOIN q19_ces_usable WHERE \" % sys.argv[2]\n... | [
1
] | [] | [] | [
"command_line_arguments",
"mysql",
"python",
"string"
] | stackoverflow_0003419485_command_line_arguments_mysql_python_string.txt |
Q:
Why type coercion works differently on scripts / interactive prompt?
I'm using Python 3.1.2 (Mac OS X 10.6) and found this weird behavior (I'm a newbie, btw):
On the interactive prompt:
>>> fraction = 4 / 3
>>> print(fraction)
1.33333333333
>>> print(type(fraction))
<class 'float'>
However, if I do the same thing... | Why type coercion works differently on scripts / interactive prompt? | I'm using Python 3.1.2 (Mac OS X 10.6) and found this weird behavior (I'm a newbie, btw):
On the interactive prompt:
>>> fraction = 4 / 3
>>> print(fraction)
1.33333333333
>>> print(type(fraction))
<class 'float'>
However, if I do the same thing in a script, results are different:
## fraction.py
fraction = 4 / 3
prin... | [
"No it's not normal. Are you sure you are running Python 3 in that script? It's possible that Python 2.5 (the default install on Mac OS X) is chosen. Try to verify by\nimport sys\nprint (sys.version)\n\nIf you are running the script as ./fraction.py, you could force the shell to use Python 3.1 by putting\n#!/usr/bi... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003439442_python.txt |
Q:
matplotlib: add circle to plot
How do I add a small filled circle or point to a countour plot in matplotlib?
A:
Here is an example, using pylab.Circle:
import numpy as np
import matplotlib.pyplot as plt
e = np.e
X, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
F = X ** Y
G = Y ** X
fig = plt.... | matplotlib: add circle to plot | How do I add a small filled circle or point to a countour plot in matplotlib?
| [
"Here is an example, using pylab.Circle:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ne = np.e\nX, Y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))\nF = X ** Y\nG = Y ** X\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\ncirc = plt.Circle((e, e), radius=0.07, color='g')\nplt.contour(X... | [
38
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003439639_matplotlib_python.txt |
Q:
Modifying an open source python program
I have an open source project written in python , it has some Forms and I want to modify a few things in the code and in the forms but it is my first time with python and I don't know what IDE to use and how to start ..my basic question is can I deal with forms in python lik... | Modifying an open source python program | I have an open source project written in python , it has some Forms and I want to modify a few things in the code and in the forms but it is my first time with python and I don't know what IDE to use and how to start ..my basic question is can I deal with forms in python like c#, java ...etc ? and how should I start ? ... | [
"Because this project uses pyGTK, you can use glade which is a gtk forms designer, but it would probably add an extra layer of complexity that's really not necessary. Since you're already familiar with C#/Java, I'd recommend running through the official Python tutorial. Then I'd take a look at this excellent PyGTK ... | [
4
] | [] | [] | [
"open_source",
"python"
] | stackoverflow_0003439895_open_source_python.txt |
Q:
Python Equivalent to phpinfo()
Quite simply, is there a python equivalent to php's phpinfo();? If so, what is it and how do I use it (a link to a reference page would work great).
A:
Check this one out!
pyinfo() A good looking phpinfo-like python script
A:
Did you try this out: http://www.webhostingtalk.com/s... | Python Equivalent to phpinfo() | Quite simply, is there a python equivalent to php's phpinfo();? If so, what is it and how do I use it (a link to a reference page would work great).
| [
"Check this one out!\npyinfo() A good looking phpinfo-like python script\n",
"Did you try this out: http://www.webhostingtalk.com/showpost.php?s=f55e18d344e3783edd98aef5be809ac8&p=4632018&postcount=4\n",
"There is nothing directly comparable to phpinfo(), but you can get some bits of information ...\n>>> import... | [
4,
3,
2,
1,
0
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002572371_php_python.txt |
Q:
antlr to generate python code is feasible?
the requirement is to generate several classes which inherits the base ORM class,
and this class may have several static properties like columns and other things,
and little bit python expressions that can be eval at run time for small business logic,
my question is, it i... | antlr to generate python code is feasible? | the requirement is to generate several classes which inherits the base ORM class,
and this class may have several static properties like columns and other things,
and little bit python expressions that can be eval at run time for small business logic,
my question is, it is feasible to use antlr for such kind of things,... | [
"I think you have misunderstood the point of the ANTLR project. ANTLR is a parser generator, which means roughly:\n\nYou create a grammer for a language of your choosing. This could well be python, or a hybrid of it.\nYou run it through ANTLR which gives you code in a number of Languages capable of parsing your lan... | [
5
] | [] | [] | [
"antlr",
"code_generation",
"python"
] | stackoverflow_0003440224_antlr_code_generation_python.txt |
Q:
is there need for a more declarative way of expressing regular expressions ? :)
I am trying to create a Python function that can take an plain English description of a regular expression and return the regular expression to the caller.
Currently I am thinking of the description in YAML format.
So, we can store the... | is there need for a more declarative way of expressing regular expressions ? :) | I am trying to create a Python function that can take an plain English description of a regular expression and return the regular expression to the caller.
Currently I am thinking of the description in YAML format.
So, we can store the description as a raw string variable, which is passed on to this another function an... | [
"This is actually pretty similar (identical?) to how a lexer/parser works. If you had a defined grammar then you could probably write a parser with not too much trouble. For instance, you could write something like this:\n<expression> :: == <rule> | <rule> <expression> | <rule> \" followed by \" <expression>\n<rule... | [
6,
6,
3,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003439471_python_regex.txt |
Q:
Find text then add line after in Python
I need to read a plist file and search for a string, then add a new line of text on the next line. I can't imagine it will take much to do this. However the plist is in binary format so not exactly sure how to deal with that.
Thanks in advance,
Aaron
#Convert plist to XML
o... | Find text then add line after in Python | I need to read a plist file and search for a string, then add a new line of text on the next line. I can't imagine it will take much to do this. However the plist is in binary format so not exactly sure how to deal with that.
Thanks in advance,
Aaron
#Convert plist to XML
os.system('plutil -convert xml1 com.apple.iCha... | [
"You want to convert it into xml format first:\nplutil -convert xml file.plist\n\nThen the rest should be fairly easy.\nEDIT:\nnewFile = open('file.copy', 'w+')\nfor line in open('file'):\n if (line.find('string_to_find') >= 0):\n # do something with \"line\"\n newFile.write(line)\nnewFile.close()\n\nE... | [
2,
0
] | [] | [] | [
"plist",
"python"
] | stackoverflow_0003440750_plist_python.txt |
Q:
How to check type of variable? Python
I need to do one thing if args is integer and ather thing if args is string.
How can i chack type? Example:
def handle(self, *args, **options):
if not args:
do_something()
elif args is integer:
do_some_ather_thing:
elif args is st... | How to check type of variable? Python | I need to do one thing if args is integer and ather thing if args is string.
How can i chack type? Example:
def handle(self, *args, **options):
if not args:
do_something()
elif args is integer:
do_some_ather_thing:
elif args is string:
do_totally_different_thin... | [
"First of, *args is always a list. You want to check if its content are strings?\nimport types\ndef handle(self, *args, **options):\n if not args:\n do_something()\n # check if everything in args is a Int\n elif all( isinstance(s, types.IntType) for s in args):\n do_some_ather_thing()\n # as... | [
13,
1,
0,
0,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0003440969_python_variables.txt |
Q:
Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()?
I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..
Here is a snippet of the code:
g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)'... | Sqlite. How to get value of Auto Increment Primary Key after Insert, other than last_insert_rowid()? | I am using Sqlite3 with Flask microframework, but this question concerns only the Sqlite side of things..
Here is a snippet of the code:
g.db.execute('INSERT INTO downloads (name, owner, mimetype) VALUES (?, ?, ?)', [name, owner, mimetype])
file_entry = query_db('SELECT last_insert_rowid()')
g.db.commit()
The download... | [
"The way you're doing it is valid. There won't be a problem if the above snipped is executed concurrently by two scripts. last_insert_rowid() returns the rowid of the latest INSERT statement for the connection that calls it. You can also get the rowid by doing g.db.lastrowid.\n"
] | [
39
] | [] | [] | [
"flask",
"python",
"sqlite"
] | stackoverflow_0003442033_flask_python_sqlite.txt |
Q:
What is the proper way to do an INSERT query in Python MySQL?
I have a python script that connects to a local MySQL db. I know it is connecting correctly because I can do this and get the proper results:
cursor.execute("SELECT * FROM reel")
But when I try to do any insert statements it just does nothing. No error ... | What is the proper way to do an INSERT query in Python MySQL? | I have a python script that connects to a local MySQL db. I know it is connecting correctly because I can do this and get the proper results:
cursor.execute("SELECT * FROM reel")
But when I try to do any insert statements it just does nothing. No error messages, no exceptions. Nothing shows up in the database when I ch... | [
"You need to do a self.cursor.commit() after self.cursor.executemany(\"INSERT INTO reel (etime,etext) VALUES (%s,%s)\", tups)\nStarting with 1.2.0, MySQLdb disables autocommit by default, as required by the DB-API standard (PEP-249). If you are using InnoDB tables or some other type of transactional table type, you... | [
6
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003442307_mysql_python.txt |
Q:
What characters in key_name?
I wonder what you can use as a key_name?
I do a lot of queries on non-ascii unicode characters, I wonder if I can use these as key names to speed up the queries.
Thanks!
A:
Per the documentation, key_name is a unicode string, though plain str values get converted as ASCII -- so you'l... | What characters in key_name? | I wonder what you can use as a key_name?
I do a lot of queries on non-ascii unicode characters, I wonder if I can use these as key names to speed up the queries.
Thanks!
| [
"Per the documentation, key_name is a unicode string, though plain str values get converted as ASCII -- so you'll want to make sure you're actually providing a true unicode string (I strongly suggest reading the entire Python Unicode HOWTO).\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003442312_google_app_engine_python.txt |
Q:
How do I make Tkinter support PNG transparency?
I put in a partially transparent PNG image in Tkinter and all I get is this
How do I make the dark triangle on the right clear? (like it's supposed to be)
This is python 2.6 on Windows 7, btw.
A:
Here's an example (the PNG file example.png has lots of transparenc... | How do I make Tkinter support PNG transparency? | I put in a partially transparent PNG image in Tkinter and all I get is this
How do I make the dark triangle on the right clear? (like it's supposed to be)
This is python 2.6 on Windows 7, btw.
| [
"Here's an example (the PNG file example.png has lots of transparency in different places):\nfrom Tkinter import Tk, Frame, Canvas\nimport ImageTk\n\nt = Tk()\nt.title(\"Transparency\")\n\nframe = Frame(t)\nframe.pack()\n\ncanvas = Canvas(frame, bg=\"black\", width=500, height=500)\ncanvas.pack()\n\nphotoimage = Im... | [
25
] | [] | [] | [
"png",
"python",
"tkinter",
"transparency"
] | stackoverflow_0003270209_png_python_tkinter_transparency.txt |
Q:
django cleaned_data [help]
ok so I have the following problem i`ve looked around but I cant find a solution ...
lets say I have the following forms.py
from django import forms
class LoginForm(forms.Form):
_username = forms.CharField()
_password = forms.CharField()
and in views.py I have
def index(reques... | django cleaned_data [help] | ok so I have the following problem i`ve looked around but I cant find a solution ...
lets say I have the following forms.py
from django import forms
class LoginForm(forms.Form):
_username = forms.CharField()
_password = forms.CharField()
and in views.py I have
def index(request):
if request.method == 'PO... | [
"form.is_valid is a function. Use it as \nif form.is_valid():\n # actions\n\nOnly after is_valid() internally had called each field's own clean method, the form has dict named cleaned_data.\n"
] | [
7
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0003442376_django_forms_python.txt |
Q:
Can 2 objects have the same key name?
I wonder if 2 objects can have the same key name?
They wouldn't be the same class.
Thanks!
A:
Yes.
An entity is uniquely identified by its path, which is the kind & name or ID of the entity and all of its ancestors. If two entities have the same name, but different kinds and... | Can 2 objects have the same key name? | I wonder if 2 objects can have the same key name?
They wouldn't be the same class.
Thanks!
| [
"Yes.\nAn entity is uniquely identified by its path, which is the kind & name or ID of the entity and all of its ancestors. If two entities have the same name, but different kinds and/or ancestries, they will have distinct paths.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003442477_google_app_engine_python.txt |
Q:
Serving secure Django pages with HTTPS
What is the proper deployment configuration for a Django application that needs some pages served with HTTPS and others with HTTP?
I want to use HTTPS for the pages that involve registration and inputting passwords. I want to use HTTP for all other pages.
A:
There's no sin... | Serving secure Django pages with HTTPS | What is the proper deployment configuration for a Django application that needs some pages served with HTTPS and others with HTTP?
I want to use HTTPS for the pages that involve registration and inputting passwords. I want to use HTTP for all other pages.
| [
"There's no single approach as far as I know. You can use a decorator secure_required as developed in this post by Scott Barnham:\n\nSecuring Django with SSL\n\nor use middleware:\n\nSSLMidleware\n\nIf you're looking for deployment information with respect to Apache and mod_wsgi, then Graham Dumpleton provides a n... | [
6
] | [] | [] | [
"deployment",
"django",
"https",
"python"
] | stackoverflow_0003442448_deployment_django_https_python.txt |
Q:
WSGI content encoding
If I execute the following Python 3.1 program, I see only � instead of the correct characters in my browser. The file itself is UTF-8 encoded and the same encoding is sent with the response.
from wsgiref.simple_server import make_server
page = "<html><body>äöü€ßÄÖÜ</body></html>"
def applic... | WSGI content encoding | If I execute the following Python 3.1 program, I see only � instead of the correct characters in my browser. The file itself is UTF-8 encoded and the same encoding is sent with the response.
from wsgiref.simple_server import make_server
page = "<html><body>äöü€ßÄÖÜ</body></html>"
def application(environ, start_respon... | [
"WSGI on Python 3 doesn't exist yet. The Web-SIG have still not reached any conclusion about how strings (bytes/unicode) are to be handled in Python 3.x.\nwsgiref is largely an automated 2to3 conversion; it still has problems even apart from the factor of what WSGI on 3.x will actually mean. Don't rely on it as a r... | [
8,
0
] | [] | [] | [
"character_encoding",
"content_type",
"http",
"python",
"utf_8"
] | stackoverflow_0003442229_character_encoding_content_type_http_python_utf_8.txt |
Q:
wxPython: Highlight item in GidSizer upon mouse click
I have a Panel with a bunch of pictures placed on it in a GridSizer layout. How can I draw a highlighted color around the edge of an image or its border to show that it has been selected upon a mouse click event?
A:
Take a look at the Widget Inspection Tool's... | wxPython: Highlight item in GidSizer upon mouse click | I have a Panel with a bunch of pictures placed on it in a GridSizer layout. How can I draw a highlighted color around the edge of an image or its border to show that it has been selected upon a mouse click event?
| [
"Take a look at the Widget Inspection Tool's code. It can highlight any widget. On my machine, it's in the \"_InspectionHighlighter\" class in the inspection.py file, which is here: C:\\Python25\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\lib\nYou can read about the tool here: http://wiki.wxpython.org/Widget%20Ins... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003431154_python_wxpython.txt |
Q:
How to catch an OperationFailure from MongoDB and PyMongo in Python
I have been having a problem where after my mongodb connection to mongohq via pymongo goes idle for awhile (no queries), it will timeout. This is fine, but the connection the database is only created when the Django app is started up. It seems lik... | How to catch an OperationFailure from MongoDB and PyMongo in Python | I have been having a problem where after my mongodb connection to mongohq via pymongo goes idle for awhile (no queries), it will timeout. This is fine, but the connection the database is only created when the Django app is started up. It seems like it is reconnecting fine, but it needs to reauthenticate then. When the ... | [
"Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.\nI just tried this with an --auth database, and it worked:\ntry:\n connection.test.foo.find_one()\nexcept pymongo.errors.OperationFailure:\n print \"caught\"\n\n"
] | [
7
] | [] | [] | [
"django",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0003442267_django_mongodb_pymongo_python.txt |
Q:
How to package a python program
Im new to python programming.Im writing a simple command line based twitter app,and i have to use external libraries like simplejson,tweepy etc.
Is there a way i can package my python program to include these libraries as well,so that when i distribute this program, the user doesnt ... | How to package a python program | Im new to python programming.Im writing a simple command line based twitter app,and i have to use external libraries like simplejson,tweepy etc.
Is there a way i can package my python program to include these libraries as well,so that when i distribute this program, the user doesnt have to install the required librarie... | [
"Python will search for modules in the current directory, so you can just package the libraries along in a subdirectory. For example, if myprogram.py use the foo package:\nimport foo\n\nthis means that there's either\n\na foo.py on your Python path; put it into the same directory as myprogram.py, or\na directory fo... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003442886_python.txt |
Q:
When using soappy SOAPServer, how do I read the request's headers?
I've got a Python webservice using SOAPpy. The webservice server is structured as shown below:
class myClass:
def hello():
return 'world'
if __name__ == "__main__":
server = SOAPServer( ( 'localhost', 8888 ) )
myObject = myClass()
nam... | When using soappy SOAPServer, how do I read the request's headers? | I've got a Python webservice using SOAPpy. The webservice server is structured as shown below:
class myClass:
def hello():
return 'world'
if __name__ == "__main__":
server = SOAPServer( ( 'localhost', 8888 ) )
myObject = myClass()
namespace = 'whatever::namespace'
server.registerObject( myObject, namesp... | [
"Do you want to do the logging in your hello method? Here's a minimal example that shows how to pass the SOAPContext information (which can give you some of this info) into the function/method call:\nfrom SOAPpy import *\n\ndef hello(_SOAPContext = None):\n return \"Your IP address is %s\" % _SOAPContext.connec... | [
2,
1
] | [] | [] | [
"python",
"soap",
"soappy",
"web_services"
] | stackoverflow_0003442276_python_soap_soappy_web_services.txt |
Q:
Python - Reportlab: Error using custom font
Im using the reportlab framework for creating pdf's. I'm also using a custom font in my pdf's called '3of9'. Now, sometimes I'm getting the following error:
IOError: Cannot open resource "/usr/lib/python2.6/site-packages/reportlab/fonts/LeERC___.AFM", while looking for f... | Python - Reportlab: Error using custom font | Im using the reportlab framework for creating pdf's. I'm also using a custom font in my pdf's called '3of9'. Now, sometimes I'm getting the following error:
IOError: Cannot open resource "/usr/lib/python2.6/site-packages/reportlab/fonts/LeERC___.AFM", while looking for faceName='3of9'
This doesn't happens everytime, bu... | [
"either make sure you have LeERC___.AFM at the given path or try to upgrade to a more recent reportlab version. \nLeERC___.AFM is part of the reportlab distribution to version 2.1 (which can be downloaded at \nhttp://www.reportlab.com/ftp/ReportLab_2_1.zip)\n"
] | [
1
] | [] | [] | [
"pdf",
"python",
"reportlab"
] | stackoverflow_0003139617_pdf_python_reportlab.txt |
Q:
How do I step through/debug a python web application?
I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request.
is this just not possible? if no, why not?
A:
If you put
import pdb
pdb.set_trace()
in your code, the web app will drop ... | How do I step through/debug a python web application? | I can't seem to find any information on debugging a python web application, specifically stepping through the execution of a web request.
is this just not possible? if no, why not?
| [
"If you put\nimport pdb\npdb.set_trace()\n\nin your code, the web app will drop to a pdb debugger session upon executing set_trace. \nAlso useful, is \nimport code\ncode.interact(local=locals())\n\nwhich drops you to the python interpreter. Pressing Ctrl-d resumes execution.\nStill more useful, is \nimport IPython.... | [
11,
3,
0
] | [] | [] | [
"debugging",
"python",
"step_into"
] | stackoverflow_0003442920_debugging_python_step_into.txt |
Q:
Cross-platform subprocess with hidden window
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:
ValueError: startupinfo is only supported on Window... | Cross-platform subprocess with hidden window | I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux:
ValueError: startupinfo is only supported on Windows platforms
Is there a simpler way than creating ... | [
"You can reduce one line :)\nstartupinfo = None\nif os.name == 'nt':\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\nproc = subprocess.Popen(command, startupinfo=startupinfo)\n\n",
"Just a note: for Python 2.7 I have to use subprocess._subprocess.STARTF_US... | [
40,
12,
4,
1
] | [] | [] | [
"cross_platform",
"linux",
"python",
"subprocess",
"windows"
] | stackoverflow_0001016384_cross_platform_linux_python_subprocess_windows.txt |
Q:
Shifting thinking from CakePHP to Django - a monolithic views file?
I'm trying to get started with Django, and have previously worked with CakePHP, and so my MVC background comes out of that. I'm aware of Django's slightly different MTV architecture, and am fine with the monolithic model files - multiple classes ... | Shifting thinking from CakePHP to Django - a monolithic views file? | I'm trying to get started with Django, and have previously worked with CakePHP, and so my MVC background comes out of that. I'm aware of Django's slightly different MTV architecture, and am fine with the monolithic model files - multiple classes in one file I can handle just fine.
But I'm confused about how to do the ... | [
"Python view files are just Python modules. The views themselves are just functions that can live anywhere you like - the module doesn't even have to be called views.py. The urlconf (in urls.py) can refer to views anywhere at all.\nOne obvious way of separating things out is into separate applications, which is cov... | [
6
] | [] | [] | [
"django",
"django_views",
"model_view_controller",
"python"
] | stackoverflow_0003443157_django_django_views_model_view_controller_python.txt |
Q:
How can I do dynamic class generation in Python? (or would a series of if/elses be better)
So, I'm writing something and I've come into a roadblock on how to do it (and what is the proper way of doing things). SO, explaining the situation will help be better understand the problem, and hopefully someone will know ... | How can I do dynamic class generation in Python? (or would a series of if/elses be better) | So, I'm writing something and I've come into a roadblock on how to do it (and what is the proper way of doing things). SO, explaining the situation will help be better understand the problem, and hopefully someone will know the answer :) Here it goes:
Basically, I'm writing up some dynamic forms in Python (more specifi... | [
"Have you considered using a dictionary? They're excellent for this sort of conditional.\ndef get_option(field_type):\n options = {\n 'artifact': forms.BooleanField,\n 'environment': forms.Choice Field,\n }\n\nreturn options[field_type](label='blah')\n\n"
] | [
5
] | [] | [] | [
"django",
"forms",
"inheritance",
"oop",
"python"
] | stackoverflow_0003443078_django_forms_inheritance_oop_python.txt |
Q:
Django Piston Content Type Always Null
I had django-piston working a week ago but recently I'm unable to call any web services. Below is a simple example. I have a 'test' service that returns 'yes' if there is a content type and 'no' if content type is null. I've done this because I get HTTP 500 errors when I do a... | Django Piston Content Type Always Null | I had django-piston working a week ago but recently I'm unable to call any web services. Below is a simple example. I have a 'test' service that returns 'yes' if there is a content type and 'no' if content type is null. I've done this because I get HTTP 500 errors when I do a POST and try to parse my parameters via 'da... | [
"I don't think there is a data attribute in the HttpRequest object. You might be looking for raw_post_data.\n"
] | [
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0003443313_django_django_piston_python.txt |
Q:
Issue with passing paramters to a class method in Python
I have been playing with Python for the past week and I running into a problem with passing 4 parameters to a class method.
Here is the class method defined within it's class:
class Line:
locx0 = 0
locy0 = 0
locx1 = 0
locy1 = 0
def __in... | Issue with passing paramters to a class method in Python | I have been playing with Python for the past week and I running into a problem with passing 4 parameters to a class method.
Here is the class method defined within it's class:
class Line:
locx0 = 0
locy0 = 0
locx1 = 0
locy1 = 0
def __init__(self):
print'<<Line __init__()>>'
def setLi... | [
"You are missing self in your definition\nWhen a class method is called python includes the objects reference as the first function argument\ndef setLineCoordinates(self,x0,y0,x1,y1)\ndef getLineCoordinatesX0(self):\n...\n\n",
"You forgot to add self to the class methods' definitions. The first parameter (which b... | [
5,
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003443292_python.txt |
Q:
Finding the correlation matrix
I have a matrix which is fairly large (around 50K rows), and I want to print the correlation coefficient between each row in the matrix. I have written Python code like this:
for i in xrange(rows): # rows are the number of rows in the matrix.
for j in xrange(i, rows):
r ... | Finding the correlation matrix | I have a matrix which is fairly large (around 50K rows), and I want to print the correlation coefficient between each row in the matrix. I have written Python code like this:
for i in xrange(rows): # rows are the number of rows in the matrix.
for j in xrange(i, rows):
r = scipy.stats.pearsonr(data[i,:], da... | [
"New Solution\nAfter looking at Joe Kington's answer, I decided to look into the corrcoef() code and was inspired by it to do the following implementation.\nms = data.mean(axis=1)[(slice(None,None,None),None)]\ndatam = data - ms\ndatass = np.sqrt(scipy.stats.ss(datam,axis=1))\nfor i in xrange(rows):\n temp = np.... | [
10,
7,
0
] | [] | [] | [
"algorithm",
"python",
"scipy"
] | stackoverflow_0003437513_algorithm_python_scipy.txt |
Q:
Reading web pages with Python
I'm trying to read and handle a web-page in Python which has lines like the following in it:
<div class="or_q_tagcloud" id="tag1611"></div></td></tr><tr><td class="or_q_artist"><a title="[Artist916]" href="http://rateyourmusic.com/artist/ac_dc" class="artist">AC/DC</a></... | Reading web pages with Python | I'm trying to read and handle a web-page in Python which has lines like the following in it:
<div class="or_q_tagcloud" id="tag1611"></div></td></tr><tr><td class="or_q_artist"><a title="[Artist916]" href="http://rateyourmusic.com/artist/ac_dc" class="artist">AC/DC</a></td><td class="or_q_album"><a title=... | [
"Given the small snippit of HTML, I've no idea whether this would be effective on the full page, but here's how to extract 'AC/DC' and 'Live' using lxml.etree and xpath.\n>>> from lxml import etree\n>>> doc = etree.HTML(\"\"\"<html>\n... <head></head>\n... <body>\n... <tr>\n... <td class=\"or_q_artist\"><a title=\"... | [
2,
0
] | [] | [] | [
"libxml2",
"python"
] | stackoverflow_0003441447_libxml2_python.txt |
Q:
R, python or octave: empirical quantile (inverse cdf) with confidence intervals?
I'm looking for a built-in function that returns the sample quantile and an estimated confidence interval in something other than MATLAB (MATLAB's ecdf does this).
I'm guessing R has this built-in and I just haven't found it yet.
If y... | R, python or octave: empirical quantile (inverse cdf) with confidence intervals? | I'm looking for a built-in function that returns the sample quantile and an estimated confidence interval in something other than MATLAB (MATLAB's ecdf does this).
I'm guessing R has this built-in and I just haven't found it yet.
If you have any standalone code to do this, you could also point to it here, though I hope... | [
"The survfit function can be used to get the survival function with confidence intervals. Since it is just 1-ecdf, there is a direct relationship between the quantiles. To use this you have to create a variable that says that each of your observations is complete (not censored):\nlibrary(survival)\nx <- rexp(10)\ne... | [
4
] | [] | [] | [
"c#",
"octave",
"python",
"r",
"statistics"
] | stackoverflow_0003442810_c#_octave_python_r_statistics.txt |
Q:
Array broadcasting with numpy
How do I write the following loop using Python's implicit looping?
def kl(myA, myB, a, b):
lots of stuff that assumes all inputs are scalars
x, y = meshgrid(inclusive_arange(0.0, xsize, 0.10),\
inclusive_arange(0.0, ysize, 0.10))
for j in range(x.shape[0]):
f... | Array broadcasting with numpy | How do I write the following loop using Python's implicit looping?
def kl(myA, myB, a, b):
lots of stuff that assumes all inputs are scalars
x, y = meshgrid(inclusive_arange(0.0, xsize, 0.10),\
inclusive_arange(0.0, ysize, 0.10))
for j in range(x.shape[0]):
for i in range(x.shape[1]):
... | [
"The capability you're asking about only exists in Numpy, and it's called array broadcasting, not implicit looping. A function that broadcasts a scalar operation over an array is called a universal function, or ufunc. Many basic Numpy functions are of this type.\nYou can use numpy.frompyfunc to convert your existin... | [
5,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003443234_numpy_python.txt |
Q:
fullscreen matplotlib figures
I am visualising numpy arrays with imshow from pyplot, and would like to see just the array data in a fullscreen display with no toolbars or window borders.
Running with "ipython -pylab" and then calling imshow() and show() gives me a window but pressing "f" does not toggle fullscreen... | fullscreen matplotlib figures | I am visualising numpy arrays with imshow from pyplot, and would like to see just the array data in a fullscreen display with no toolbars or window borders.
Running with "ipython -pylab" and then calling imshow() and show() gives me a window but pressing "f" does not toggle fullscreen mode. Is there a function call to ... | [
"I think fullscreen is only implemented for the gtk matplotlib backend (I could be very wrong there...). At any rate, it's definitely not implemented for all platforms and backends that matplotlib supports.\nHowever, from the sounds of what you're doing (simple fullscreen display of a 2D numpy array), you might fi... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003443891_matplotlib_python.txt |
Q:
Function for class exemplar
I have something like that in my python code
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = myFN
b.doSome()
But this doesn't work. Where am I wrong?
python 2.6.5
upd: I want to redefine method ... | Function for class exemplar | I have something like that in my python code
class A:
__mess = "Yeap!"
def doSome(self):
self.FN()
def FN(self):
pass
def myFN(self):
print self.__mess
b = A()
b.FN = myFN
b.doSome()
But this doesn't work. Where am I wrong?
python 2.6.5
upd: I want to redefine method (FN) only for one exemplar (b).
u... | [
"myLoopFN is a function, not an instance method. Do\nimport new\nb.loopFN = new.instancemethod( myLoopFN, b, A )\n\nThe problem is that Python treats instance methods very slightly differently to regular functions: they get the instance upon which they are run as the default first argument. If you define a method i... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0003444075_python.txt |
Q:
What is twisted's equivalent of tornado's IOLoop.add_callback?
I'm trying to adapt some tornado code to work with twisted.
Tornado's IOLoop has a function (add_callback) that will essentially call the function back in the next iteration of the loop. As far as I can tell, twisted doesn't have a direct translation ... | What is twisted's equivalent of tornado's IOLoop.add_callback? | I'm trying to adapt some tornado code to work with twisted.
Tornado's IOLoop has a function (add_callback) that will essentially call the function back in the next iteration of the loop. As far as I can tell, twisted doesn't have a direct translation of this. Is there any way to simulate this in twisted?
| [
"reactor.callLater(0, x) or reactor.callFromThread(x)\n"
] | [
6
] | [] | [] | [
"python",
"tornado",
"twisted"
] | stackoverflow_0003444391_python_tornado_twisted.txt |
Q:
Can subprocess.Popen be used when called from py code running under mod_wsgi in Apache2
I'm using subprocess.Popen and getting IOErrors when running under mod_wsgi. The following code will work in a python term, or a django runserver, and under mod_python. If you put it under mod_wsgi (v2), it fails: (2, 'No su... | Can subprocess.Popen be used when called from py code running under mod_wsgi in Apache2 | I'm using subprocess.Popen and getting IOErrors when running under mod_wsgi. The following code will work in a python term, or a django runserver, and under mod_python. If you put it under mod_wsgi (v2), it fails: (2, 'No such file or directory') I have tried many variations involving using subprocess.PIPE. I have... | [
"That error message means that Popen can't find htmldoc. Check your $PATH environment variable through os.environ['PATH'] and make sure that htmldoc is installed in one of the paths there.\nAlternatively, you can call Popen using an absolute path. For example,\nsubprocess.Popen(['/usr/bin/htmldoc', ...\n\n"
] | [
0
] | [] | [] | [
"apache2",
"mod_wsgi",
"python",
"subprocess"
] | stackoverflow_0003444536_apache2_mod_wsgi_python_subprocess.txt |
Q:
How to use itertools.groupby when the key value is in the elements of the iterable?
To illustrate, I start with a list of 2-tuples:
import itertools
import operator
raw = [(1, "one"),
(2, "two"),
(1, "one"),
(3, "three"),
(2, "two")]
for key, grp in itertools.groupby(raw, key=lambda i... | How to use itertools.groupby when the key value is in the elements of the iterable? | To illustrate, I start with a list of 2-tuples:
import itertools
import operator
raw = [(1, "one"),
(2, "two"),
(1, "one"),
(3, "three"),
(2, "two")]
for key, grp in itertools.groupby(raw, key=lambda item: item[0]):
print key, list(grp).pop()[1]
yields:
1 one
2 two
1 one
3 three
2 two... | [
"groupby clusters consecutive elements of the iterable which have the same key.\nTo produce the output you desire, you must first sort raw.\nfor key, grp in itertools.groupby(sorted(raw), key=operator.itemgetter(0)):\n print key, map(operator.itemgetter(1), grp)\n\n# 1 ['one', 'one']\n# 2 ['two', 'two']\n# 3 ['t... | [
13,
7,
3
] | [] | [] | [
"group_by",
"python",
"python_itertools"
] | stackoverflow_0003440549_group_by_python_python_itertools.txt |
Q:
Printing a particular subset of keys in a dictionary
I have a dictionary in Python where the keys are pathnames. For example:
dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1
dict["/X"] = 10
dict["/X/Y"] = 11
I was wondering, what's a good way to print all "subpaths" given any key.
For example, given a function ... | Printing a particular subset of keys in a dictionary | I have a dictionary in Python where the keys are pathnames. For example:
dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1
dict["/X"] = 10
dict["/X/Y"] = 11
I was wondering, what's a good way to print all "subpaths" given any key.
For example, given a function called "print_dict_path" that does this, something like
pr... | [
"One possibility without using regex is to just use startswith\ntop_path = '/A/B'\nfor p in d.iterkeys():\n if p.startswith(top_path):\n print d[p]\n\n",
"You can use str.find:\ndef print_dict_path(prefix, d):\n for k in d:\n if k.find(prefix) == 0:\n print \"\\\"{0}\\\" = {1}\".for... | [
5,
1,
1,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003441255_dictionary_python.txt |
Q:
Making a key-command for a python program with no GUI
I want to make a key command so that the program will stop running when the Ctrl key then the 'e' key then the 'x' key then the 'i' and 't' keys are hit. So basically when the program is running if you type Ctrl + exit, the program will stop running. There is n... | Making a key-command for a python program with no GUI | I want to make a key command so that the program will stop running when the Ctrl key then the 'e' key then the 'x' key then the 'i' and 't' keys are hit. So basically when the program is running if you type Ctrl + exit, the program will stop running. There is no GUI and I don't want to do this via a python interpreter.... | [
"Use a simple FSM for the \"exiting logic\" while you're logging the received keys, e.g.:\nFINAL_STATE = 9999\ntransitions = {(None, 'e'): 1, (1, 'x'): 2, (2, 'i'): 3, (3, 't'): FINAL_STATE}\n\ndef keylogger_logic(filename, get_next_keystroke, fsm_state=None):\n with open(filename, 'w') as f:\n k = get_ne... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003444558_python.txt |
Q:
How to build a computationally intensive webservice?
I need to build a webservice that is very computationally intensive, and I'm trying to get my bearings on how best to proceed.
I expect users to connect to my service, at which point some computation is done for some amount of time, typically less than 60s. The ... | How to build a computationally intensive webservice? | I need to build a webservice that is very computationally intensive, and I'm trying to get my bearings on how best to proceed.
I expect users to connect to my service, at which point some computation is done for some amount of time, typically less than 60s. The user knows that they need to wait, so this is not really a... | [
"\nCan I use Node.js, web.py, CherryPy, etc.? \n\nYes. Pick one. Django is nice, also.\n\nDo I need a load balancer sitting in front of these pieces if used? \n\nAlmost never.\n\nI'll need a number of machines to host this number of users, \n\nDoubtful.\nRemember that each web transaction has several distinct (an... | [
6,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003444804_python.txt |
Q:
python unittest methods
Can I call a test method from within the test class in python? For example:
class Test(unittest.TestCase):
def setUp(self):
#do stuff
def test1(self):
self.test2()
def test2(self):
#do stuff
update: I forgot the other half of my question. Will setup o... | python unittest methods | Can I call a test method from within the test class in python? For example:
class Test(unittest.TestCase):
def setUp(self):
#do stuff
def test1(self):
self.test2()
def test2(self):
#do stuff
update: I forgot the other half of my question. Will setup or teardown be called only a... | [
"This is pretty much a Do Not Do That. If you want tests run in a specific order define a runTest method and do not name your methods test....\nclass Test_Some_Condition( unittest.TestCase ):\ndef setUp( self ):\n ...\ndef runTest( self ):\n step1()\n step2()\n step3()\ndef tearDown( self ):\n ...\n... | [
8,
6,
1,
0,
0
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0003444827_python_unit_testing.txt |
Q:
Twisted: degrade gracefully performance in case reactor is overloaded?
Is it somehow possible to "detect" that the reactor is overloaded and start dropping connections, or refuse new connections? How can we avoid the reactor being completely overloaded and not being able to catch up?
A:
If I understand Twisted ... | Twisted: degrade gracefully performance in case reactor is overloaded? | Is it somehow possible to "detect" that the reactor is overloaded and start dropping connections, or refuse new connections? How can we avoid the reactor being completely overloaded and not being able to catch up?
| [
"If I understand Twisted Reactors correctly, they don't parallelize everything. Whatever operations have been queued is scheduled and is done one by one.\nOne way out for you is to have a custom addCallback which checks for how many callbacks have been registered already and drop if necessary.\n",
"No easy way, b... | [
1,
1,
1
] | [] | [] | [
"performance",
"python",
"twisted"
] | stackoverflow_0003423845_performance_python_twisted.txt |
Q:
Distributing minimal python installation with application
My company is working on an application that is half Qt/C++ for the editor interface and half Django (via QtWebKit browser control) for the runtime. What we want to do is distribute a minimal python installation with our application.
For instance, our Mac ... | Distributing minimal python installation with application | My company is working on an application that is half Qt/C++ for the editor interface and half Django (via QtWebKit browser control) for the runtime. What we want to do is distribute a minimal python installation with our application.
For instance, our Mac app bundle would ideally be structured something like this:
The... | [
"You can find the set of modules you need with modulefinder -- indeed, I believe that's a key part of what the systems you mention, like py2exe and PyInstaller, do for you, so I'm not clear why you want to \"reinvent the wheel\" -- care to clarify? Have you looked at exactly what e.g. PyInstaller puts in the execu... | [
3
] | [] | [] | [
"distribution",
"django",
"macos",
"python",
"windows"
] | stackoverflow_0003444630_distribution_django_macos_python_windows.txt |
Q:
Designing a interface to a websites api
Ok I am programing a way to interface with Grooveshark (http://grooveshark.com). Right now I have a class Grooveshark and several methods, one gets a session with the server, another gets a token that is based on the session and another is used to construct api calls to the ... | Designing a interface to a websites api | Ok I am programing a way to interface with Grooveshark (http://grooveshark.com). Right now I have a class Grooveshark and several methods, one gets a session with the server, another gets a token that is based on the session and another is used to construct api calls to the server (and other methods use that). Right no... | [
"\nI find this unpythonic and ugly sense\n even after initializing the class you\n have to call two methods first or else\n the other methods won't work.\n\nIf so, then why not put the get_session part in your class's __init__? If it always must be performed before anything else, that would seem to make sense. ... | [
3,
0
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0003445006_python_twisted_twisted.web.txt |
Q:
issue with Python Gtk+
I can't nail exactly when/what update I did on my Lucid box but now I get:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: Gt... | issue with Python Gtk+ | I can't nail exactly when/what update I did on my Lucid box but now I get:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gtk
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open dis... | [
"I manage to get rid of the problem by completely reinstalling X:\nsudo apt-get remove --purge xserver-xorg\nsudo apt-get install xserver-xorg\nsudo dpkg-reconfigure xserver-xorg\nHope this helps someone!\n"
] | [
2
] | [] | [] | [
"gtk",
"linux",
"python"
] | stackoverflow_0003436781_gtk_linux_python.txt |
Q:
mod_wsgi and pylons: setting the working environment
I'm trying to setup Pylons (1.0) with Apache mod_wsgi. Everything works fine with mod_wsgi and I can run a simple python wsgi app just fine.
I've got the quickwiki example from the Pylons site working when running it with paster, but obviously I would never de... | mod_wsgi and pylons: setting the working environment | I'm trying to setup Pylons (1.0) with Apache mod_wsgi. Everything works fine with mod_wsgi and I can run a simple python wsgi app just fine.
I've got the quickwiki example from the Pylons site working when running it with paster, but obviously I would never deploy in such a manner - so I'm trying to get the Quickwiki... | [
"Read:\nhttp://code.google.com/p/modwsgi/wiki/VirtualEnvironments\n"
] | [
3
] | [] | [] | [
"mod_wsgi",
"pylons",
"python"
] | stackoverflow_0003445174_mod_wsgi_pylons_python.txt |
Q:
Is Python good for big software projects (not web based)?
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to th... | Is Python good for big software projects (not web based)? | Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).
Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it i... | [
"We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems, so I'd definitely say it's ready for production use of complex apps.\nThere are two ways in which this might not be a useful answer to you :-)\... | [
34,
23,
18,
13,
8,
5,
4,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0000035753_ide_python.txt |
Q:
How do I get this page programatically?
Here is the page THE LINK TO LYRICS SITE
If I use normal method, all I get is the "http://lyricsvip.com" and not the lyrics.
A:
it's because the lyrics are loaded by Javascript and the 'normal' method doesn't execute Javascript when you try to scrape the page.
Seems like y... | How do I get this page programatically? | Here is the page THE LINK TO LYRICS SITE
If I use normal method, all I get is the "http://lyricsvip.com" and not the lyrics.
| [
"it's because the lyrics are loaded by Javascript and the 'normal' method doesn't execute Javascript when you try to scrape the page.\nSeems like you're out of luck unfortunately, unless you manage to execute the Javascript-method found in the source:\n<body onload=\"javascript:getContent('aerosmith', 'crazy', '128... | [
4,
1,
0
] | [] | [] | [
"ajax",
"fetch",
"html",
"python",
"webpage"
] | stackoverflow_0003443769_ajax_fetch_html_python_webpage.txt |
Q:
Intentionally Buggy Code (Python)
This is a strange request but I'm looking for buggy Python code. I want to learn more about bugs and debuggers and I need some buggy code to work with. Unfortunately, all the code I've written is short and bug-free (so far).
Preferably it's not GUI stuff (b/c I'm just starting to... | Intentionally Buggy Code (Python) | This is a strange request but I'm looking for buggy Python code. I want to learn more about bugs and debuggers and I need some buggy code to work with. Unfortunately, all the code I've written is short and bug-free (so far).
Preferably it's not GUI stuff (b/c I'm just starting to learn it) but anything's good.
Thanks ... | [
"Not sure how to scout \"intentionally\" for source code with bugs but you can look into the bug trackers of the main Python projects (and the less widespread ones, too), look for the bugs the reports refer to and debug them. It's a win-win situation. You win the skill to debug and they (hopefully) win a patch for ... | [
6,
0,
0
] | [] | [] | [
"code_snippets",
"debugging",
"python"
] | stackoverflow_0003445429_code_snippets_debugging_python.txt |
Q:
Python/Django download Image from URL, modify, and save to ImageField
I've been looking for a way to download an image from a URL, preform some image manipulations (resize) actions on it, and then save it to a django ImageField. Using the two great posts (linked below), I have been able to download and save an im... | Python/Django download Image from URL, modify, and save to ImageField | I've been looking for a way to download an image from a URL, preform some image manipulations (resize) actions on it, and then save it to a django ImageField. Using the two great posts (linked below), I have been able to download and save an image to an ImageField. However, I've been having some trouble manipulating ... | [
"In an attempt to kill 2 birds with 1 stone. Why not use a (c)StringIO object instead of a NamedTemporaryFile? You won't have to store it on disk anymore and I know for a fact that something like this works (I use similar code myself).\nfrom cStringIO import StringIO\nimg_temp = StringIO()\ninImage.save(img_temp, '... | [
5
] | [] | [] | [
"django",
"file",
"python",
"python_imaging_library",
"urllib2"
] | stackoverflow_0003445568_django_file_python_python_imaging_library_urllib2.txt |
Q:
Are there Python statical analysis/validation tools?
I've never been a huge Python fan. I learned it for a course where the teacher was really into it, but his enthusiasm never quite made it to the rest of our class it seems: as soon as we had the chance, we all jumped off to C#/Java.
Anyways. This wasn't a conclu... | Are there Python statical analysis/validation tools? | I've never been a huge Python fan. I learned it for a course where the teacher was really into it, but his enthusiasm never quite made it to the rest of our class it seems: as soon as we had the chance, we all jumped off to C#/Java.
Anyways. This wasn't a concluding experience, and what annoyed me the most in the langu... | [
"\n\"but that Python won't bother to complain about until it's too late\"\n\nIt's not that the message comes too late. It's that you're waiting too long to use Python. Don't type a mountain of code and then complain that one small piece is bad.\n\nUse Unit Testing. Write less code before running a test.\nUse pyt... | [
7,
6,
1
] | [] | [] | [
"python",
"validation"
] | stackoverflow_0003445726_python_validation.txt |
Q:
Key commands in Tkinter
I made a GUI with Tkinter, now how do I make it so when a key command will execute a command even if the Tkinter window is not in focus? Basically I want it so everything is bound to that key command.
Example:
Say I was browsing the internet and the focus was on my browser, I then type Ct... | Key commands in Tkinter | I made a GUI with Tkinter, now how do I make it so when a key command will execute a command even if the Tkinter window is not in focus? Basically I want it so everything is bound to that key command.
Example:
Say I was browsing the internet and the focus was on my browser, I then type Ctrl + U. An event would then r... | [
"Tkinter, on its own, cannot grab keystrokes that (from the OS's/WM's viewpoint) were directed to other, unrelated windows -- you'll need to instruct your window manager, desktop manager, or \"operating system\", to direct certain keystrokes differently than it usually does. So, what platform do you need to suppor... | [
2
] | [] | [] | [
"binding",
"python",
"tkinter"
] | stackoverflow_0003445867_binding_python_tkinter.txt |
Q:
Calling a Python module from Perl
I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl.
What is the best way to make a plug in to this module? My thoughts are:
Provide... | Calling a Python module from Perl | I created a module in Python which provides about a dozen functionalities. While it will be mostly used from within Python, there is a good fraction of legacy users which will be calling it from Perl.
What is the best way to make a plug in to this module? My thoughts are:
Provide the functionalities as command line ut... | [
"One other choice is to inline Python directly in your Perl script, using Inline::Python.\nThis may be simpler than other solutions, and only requires one additional module.\n",
"In the short run the easiest solution is to use Inline::Python. Closely followed by calling a command-line script.\nIn the long run, u... | [
19,
9,
3
] | [] | [] | [
"interop",
"perl",
"python"
] | stackoverflow_0003441766_interop_perl_python.txt |
Q:
Edit ini file option values with ConfigParser (Python)
Anyone know how'd I'd go about editing ini file values preferably using ConfigParser? (Or even a place to start from would be great!) I've got lots of comments throughout my config file so I'd like to keep them by just editing the values, not taking the values... | Edit ini file option values with ConfigParser (Python) | Anyone know how'd I'd go about editing ini file values preferably using ConfigParser? (Or even a place to start from would be great!) I've got lots of comments throughout my config file so I'd like to keep them by just editing the values, not taking the values and playing around with multiple files.
Structure of my con... | [
"Here is an example\nimport sys\nimport os.path\nfrom ConfigParser import RawConfigParser as ConfParser\nfrom ConfigParser import Error\n\np = ConfParser()\n# this happend to me save as ASCII\no = open(\"config.ini\")\nif o.read().startswith(\"\\xef\\xbb\\xbf\"):\n print \"Fatal Error; Please save the file as AS... | [
2
] | [] | [] | [
"configparser",
"ini",
"python"
] | stackoverflow_0003446034_configparser_ini_python.txt |
Q:
Is it possible to write an IM server in python? (be able to handle the heavy connections)
i wanna write an IM server in python, but i'm not sure if python can handle the heavy connections?
Thanks in advance.
A:
Omegle is written in Python and as of writing is sustaining 7,057 concurrent online users.
It's not so... | Is it possible to write an IM server in python? (be able to handle the heavy connections) | i wanna write an IM server in python, but i'm not sure if python can handle the heavy connections?
Thanks in advance.
| [
"Omegle is written in Python and as of writing is sustaining 7,057 concurrent online users.\nIt's not so much about the choice of language, but the efficiency of your code and how well it is optimized.\nwhile true:\n # nothing\n\nisn't going to be any slower than\nwhile (1) ;\n\n",
"Yes, you could :)\nFor exam... | [
2,
2,
1
] | [] | [] | [
"instant_messaging",
"python"
] | stackoverflow_0002542718_instant_messaging_python.txt |
Q:
Python: Is it possible to have multiple exceptions statments for a try block?
try:
case_no = re.search("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
try:
try:
case_no = re.search("Citation Number:</span></td><td><span cla... | Python: Is it possible to have multiple exceptions statments for a try block? | try:
case_no = re.search("Case Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
try:
try:
case_no = re.search("Citation Number:</span></td><td><span class=\"Value\">([^<]*?)<",br.response().read()).group(1)
except:
... | [
"Probably you shouldn't be checking exception at all? \npatterns = [\n \"Case Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\",\n \"Citation Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\",\n \"Citation Number:</span></td><td><span class=\\\"Value\\\">([^<]*?)<\" # same as #2?\n]\ntext... | [
5,
3,
3,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003446878_python.txt |
Q:
GUI for the Linux and Windows platforms - Python CRUD app
i'm looking for a basic CRUD (create-read-update-delete) app
in Python, with some line-by-line display grid to browse through a file's
records and select individual records from there. It probably already
exists but i couldn't find anything yet.
Thanks
A:... | GUI for the Linux and Windows platforms - Python CRUD app | i'm looking for a basic CRUD (create-read-update-delete) app
in Python, with some line-by-line display grid to browse through a file's
records and select individual records from there. It probably already
exists but i couldn't find anything yet.
Thanks
| [
"Isn't Django all about web-based CRUD applications for Python?\n",
"Maybe Camelot is what you need. It is a RAD framework for creating desktop database apps using Python, SQLAlchemy and Qt.\n",
"hmm, probably more than what you need.\nhttp://dabodev.com/\nIf you are more interested in lower level stuff, wxPyt... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003443547_python.txt |
Q:
python: what is this funny notation? [0,1,3].__len__()
why would anyone use double underscores
why not just do len([1,2,3])?
my question is specifically What do the underscores mean?
A:
__len__() is the special Python method that is called when you use len().
It's pretty much like str() uses __str__(), repr use... | python: what is this funny notation? [0,1,3].__len__() |
why would anyone use double underscores
why not just do len([1,2,3])?
my question is specifically What do the underscores mean?
| [
"__len__() is the special Python method that is called when you use len().\nIt's pretty much like str() uses __str__(), repr uses __repr__(), etc. You can overload it in your classes to give len() a custom behaviour when used on an instance of your class.\nSee here: http://docs.python.org/release/2.5.2/ref/sequence... | [
4,
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003444611_python.txt |
Q:
Having several file pointers open simultaneaously alright?
I'm reading from certain offsets in several hundred and possibly thousands files. Because I need only certain data from certain offsets at that particular time, I must either keep the file handle open for later use OR I can write the parts I need into sepe... | Having several file pointers open simultaneaously alright? | I'm reading from certain offsets in several hundred and possibly thousands files. Because I need only certain data from certain offsets at that particular time, I must either keep the file handle open for later use OR I can write the parts I need into seperate files.
I figured keeping all these file handles open rather... | [
"Some systems may limit the number of file descriptors that a single process can have open simultaneously. 1024 is a common default, so if you need \"thousands\" open at once, you might want to err on the side of portability and design your application to use a smaller\npool of open file descriptors.\n",
"I recom... | [
4,
3
] | [] | [] | [
"file",
"handles",
"python"
] | stackoverflow_0003446457_file_handles_python.txt |
Q:
Which files are taking most of my process's I/O time?
I have a fairly large python program that is causing a lot of disk I/O (on top, %wa can get as high as 80, and iotop says that my process is the culprit).
There are several things that may cause this - I'm writing to more than one log file, and I'm saving cache... | Which files are taking most of my process's I/O time? | I have a fairly large python program that is causing a lot of disk I/O (on top, %wa can get as high as 80, and iotop says that my process is the culprit).
There are several things that may cause this - I'm writing to more than one log file, and I'm saving cached results to disk in several places, so it's not immediatel... | [
"You should have a look at SystemTap. It's very powerful tracing and profiling mechanism for Linux system calls:\nhttp://sourceware.org/systemtap/wiki\nI'm sure it is possible to trace exactly which file descriptor is responsible for IO load - but it will get complicated to start with systemtap.\n"
] | [
1
] | [] | [] | [
"linux",
"profiling",
"python"
] | stackoverflow_0003446396_linux_profiling_python.txt |
Q:
Sharing data between processes in Python
I have a complex data structure (user-defined type) on which a large number of independent calculations are performed. The data structure is basically immutable. I say basically, because though the interface looks immutable, internally some lazy-evaluation is going on. Some... | Sharing data between processes in Python | I have a complex data structure (user-defined type) on which a large number of independent calculations are performed. The data structure is basically immutable. I say basically, because though the interface looks immutable, internally some lazy-evaluation is going on. Some of the lazily calculated attributes are store... | [
"\nHow do I best share the data-structure between processes?\n\nPipelines.\norigin.py | process1.py | process2.py | process3.py\n\nBreak your program up so that each calculation is a separate process of the following form.\ndef transform1( piece ):\n Some transformation or calculation.\n\nFor testing, you can us... | [
8
] | [] | [] | [
"lazy_evaluation",
"multiprocessing",
"python",
"sharing"
] | stackoverflow_0003447846_lazy_evaluation_multiprocessing_python_sharing.txt |
Q:
CMYK overprinting (colour-separated PDF output) with Reportlab
is it possible to use CMYK overprinting without using the CMYKColorSep class, which always generates a new seperate color in the printer settings, i just want to use overprinting with the standard 4 CMYK inks (colour-separated PDF output, as stated in ... | CMYK overprinting (colour-separated PDF output) with Reportlab | is it possible to use CMYK overprinting without using the CMYKColorSep class, which always generates a new seperate color in the printer settings, i just want to use overprinting with the standard 4 CMYK inks (colour-separated PDF output, as stated in the 2.4 changelog)
here my example code (reportlab 2.4 needed):
from... | [
"You can only use overprint with CMYKColorSep. Its currently available in 2.4 but not stable (Robin is still messing with the code :) ). \nThere is a non public snippet on the reportlab website http://www.reportlab.com/snippets/10/ that demos it but hence the feature is still in development the snippet is not liste... | [
3,
0
] | [] | [] | [
"cmyk",
"pdf",
"pdf_generation",
"python",
"reportlab"
] | stackoverflow_0003140231_cmyk_pdf_pdf_generation_python_reportlab.txt |
Q:
Processing data by reference or by value in python
Consider the following session. How are the differences explained? I thought that a += b is a syntactical sugar of (and thus equivalent to) a = a + b. Obviously I'm wrong.
>>> import numpy as np
>>> a = np.arange(24.).reshape(4,6)
>>> print a
[[ 0. 1. 2. 3... | Processing data by reference or by value in python | Consider the following session. How are the differences explained? I thought that a += b is a syntactical sugar of (and thus equivalent to) a = a + b. Obviously I'm wrong.
>>> import numpy as np
>>> a = np.arange(24.).reshape(4,6)
>>> print a
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10. 11.]
[ 12. 13... | [
"Using the + operator results in a call to the special method __add__ which should create a new object and should not modify the original.\nOn the other hand, using the += operator results in a call to __iadd__ which should modify the object if possible rather than creating a new object.\n\n__add__\nThese methods a... | [
15,
7
] | [] | [] | [
"numpy",
"python",
"syntactic_sugar",
"syntax"
] | stackoverflow_0003447435_numpy_python_syntactic_sugar_syntax.txt |
Q:
Stopping a recursive generator & permutations
As an exercise, I've been trying out various ways of generating all permutations of a list in Python -- recursive, non-recursive... -- and comparing the performance with itertools.permutations(). But I'm having trouble with the generator version of the recursive method... | Stopping a recursive generator & permutations | As an exercise, I've been trying out various ways of generating all permutations of a list in Python -- recursive, non-recursive... -- and comparing the performance with itertools.permutations(). But I'm having trouble with the generator version of the recursive method, which doesn't finish cleanly with a StopIteration... | [
"You are missing an else:\nif (alist == []):\n yield []\nelse:\n for ...\n\nThis is because yield does not behave in the same way as return. Execution continues after the yield statement when you request the next value. \n"
] | [
6
] | [] | [] | [
"exception",
"generator",
"permutation",
"python",
"recursion"
] | stackoverflow_0003448231_exception_generator_permutation_python_recursion.txt |
Q:
How to change the boolean value of C to the boolean value of python on mac
I would like to code in c ,but use the value in python by compile the c source file to .so file.
A:
The ctypes library is probably the easiest way to do this.
| How to change the boolean value of C to the boolean value of python on mac | I would like to code in c ,but use the value in python by compile the c source file to .so file.
| [
"The ctypes library is probably the easiest way to do this.\n"
] | [
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003447769_c_python.txt |
Q:
How should I embed Python in a C++ Builder / Delphi 2010 application?
I'm interested in experimenting with embedding Python in my application, to let the user run Python scripts within the application environment, accessing internal (C++-implemented) objects, etc. I'm quite new to this so don't know exactly what ... | How should I embed Python in a C++ Builder / Delphi 2010 application? | I'm interested in experimenting with embedding Python in my application, to let the user run Python scripts within the application environment, accessing internal (C++-implemented) objects, etc. I'm quite new to this so don't know exactly what I'm doing.
I have read Embedding Python in Another Application, though this... | [
"You should not be afraid of the P4D project at google groups. It seems inactive because, in part, it is very stable and full-featured already. Those components are used in the much more active PyScripter application which is one of the best python development editors currently available. PyScripter is writte... | [
8,
1,
0
] | [] | [] | [
"c++builder",
"c++builder_2010",
"delphi",
"embed",
"python"
] | stackoverflow_0003446799_c++builder_c++builder_2010_delphi_embed_python.txt |
Q:
How to keep the width of the bars the same no matter the number of bars we compare in the figure?
I want to keep the width of the bars the same no matter the number of bars compared is high or low.
I am using Matplotlib stacked bar chart.
the width of the bars is relative to the number of the bars.
Here is my samp... | How to keep the width of the bars the same no matter the number of bars we compare in the figure? | I want to keep the width of the bars the same no matter the number of bars compared is high or low.
I am using Matplotlib stacked bar chart.
the width of the bars is relative to the number of the bars.
Here is my sample code.
How can I make the width the same no matter the number of bars I compare from 1 to 10
import n... | [
"The width of the bars doesn't change, the scale of your image changes. If you want the scale to stay the same you have to manually specify what range you want to show, whether your plot is 10x10, 100x100, or 1,000,000,000 x 10\nEdit:\nIf I understand correctly, what you want is something like this:\nGraph 1 - 2 ba... | [
2
] | [] | [] | [
"bar_chart",
"fixed_width",
"matplotlib",
"python"
] | stackoverflow_0003448350_bar_chart_fixed_width_matplotlib_python.txt |
Q:
Using datetime and manipulating date strings using python
I have a file of the following format
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z
I need ... | Using datetime and manipulating date strings using python | I have a file of the following format
Summary:meeting Description:None DateStart:20100629T110000 DateEnd:20100629T120000 Time:20100805T084547Z
Summary:meeting Description:None DateStart:20100630T090000 DateEnd:20100630T100000 Time:20100805T084547Z
I need to create a function that would retrieve "Summary" at a given "... | [
"Don't confuse the datetime module with the datetime Objects in the module.\nThe module has no strptime function, but the Object does have a strptime class method:\n>>> time = \"20100629T110000\"\n>>> import datetime\n>>> line_time = datetime.strptime(time, \"%Y%m%dT%H%M%S\")\nTraceback (most recent call last):\n ... | [
6,
6
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003447542_datetime_python.txt |
Q:
List all Tests Found by Nosetest
I use nosetests to run my unittests and it works well. I want to get a list of all the tests nostests finds without actually running them. Is there a way to do that?
A:
Version 0.11.1 is currently available. You can get a list of tests without running them as follows:
nosetests ... | List all Tests Found by Nosetest | I use nosetests to run my unittests and it works well. I want to get a list of all the tests nostests finds without actually running them. Is there a way to do that?
| [
"Version 0.11.1 is currently available. You can get a list of tests without running them as follows:\nnosetests -v --collect-only\n\n",
"I recommend using:\nnosetests -vv --collect-only\n\nWhile the -vv option is not described in man nosetests, \"An Extended Introduction to the nose Unit Testing Framework\" stat... | [
50,
18,
3
] | [] | [] | [
"nose",
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0000712020_nose_nosetests_python_unit_testing.txt |
Q:
Python - Is my code effecient? Or are people going to have fun killing my server...?
Aight, basically, I have a database that looks like this:
id | parentid | type | name
---------------------------------------------
1 | 0 | heading | this is my heading
---------------------------------------------
2 |... | Python - Is my code effecient? Or are people going to have fun killing my server...? | Aight, basically, I have a database that looks like this:
id | parentid | type | name
---------------------------------------------
1 | 0 | heading | this is my heading
---------------------------------------------
2 | 1 | child | this is one of many child elements
I'm using Mako to go through tha... | [
"First, there is no way to know if it's going to die under a heavy load without testing it. The only way to anwser you question honestly is to profile your code. Only you can do it.\nNow, nested relations are always slow, but you seem to use only 2 levels of nesting, therefor it's O(n^2), nothing that could kill re... | [
1
] | [] | [] | [
"performance",
"pylons",
"python",
"templates"
] | stackoverflow_0003445963_performance_pylons_python_templates.txt |
Q:
How can I sort the files on the basis of time stamp from the the below set of files?
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
for example:
If... | How can I sort the files on the basis of time stamp from the the below set of files? | File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
for example:
If I have the files shown below in a directory:
FILE NAME DATE CREATED/... | [
"How about this C# linq approach:\nvar query = Directory.GetFiles(\"D:\\\\\", \"*.txt\", SearchOption.AllDirectories)\n .Select(name => new FileInfo(name));\n\nvar orderedList = query.OrderBy(fileInfo => fileInfo.CreationTime).ToList();\n\n",
"In Python, if I understand you correctly:\nimport ... | [
1,
0,
0
] | [] | [] | [
"c#",
"python",
"ruby_on_rails"
] | stackoverflow_0003447537_c#_python_ruby_on_rails.txt |
Q:
Cannot read sections of config files containing []
Edited post
I'm not able to read the configuration file sections that contain []... for e.g if any section in ini file is something like [c:\\temp\\foo[1].txt] than my script fails to read that section..
config.read(dst_bkp)
for i in config.sections():
config.... | Cannot read sections of config files containing [] | Edited post
I'm not able to read the configuration file sections that contain []... for e.g if any section in ini file is something like [c:\\temp\\foo[1].txt] than my script fails to read that section..
config.read(dst_bkp)
for i in config.sections():
config.get(i,'FileName')
Thanks,
Vignesh
| [
"Assuming that you use a builtin subclass of ConfigParser.RawConfigParser module: This is not supported. Even in the newest revision, the regex for section headers is just\nSECTCRE = re.compile(\n r'\\[' # [\n r'(?P<header>[^]]+)' # very permissive!\n r'\\]'... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003448505_python.txt |
Q:
PyQt + QtWebkit behind a proxy
I'm writing a PyQt (Python bindings for the all-powerful Qt library) application and a small part of my application needs a web browser (hint, OAuth). So I started using QtWebkit, which is fantastic by the way. The only hitch is I would like to allow users behind a proxy to use my ap... | PyQt + QtWebkit behind a proxy | I'm writing a PyQt (Python bindings for the all-powerful Qt library) application and a small part of my application needs a web browser (hint, OAuth). So I started using QtWebkit, which is fantastic by the way. The only hitch is I would like to allow users behind a proxy to use my application.
I have read about the QNe... | [
"I was working on Windows XP (32-bit) with Python 2.6 and PyQt 4.7.4. The reason that...\nQtNetwork.QSslSocket.supportsSsl()\n\nwas returning false was because I had not installed OpenSSL binaries to my system.\nTo solve the problem I went here to download the binaries. Before they would properly install I had to a... | [
6
] | [] | [] | [
"https",
"pyqt",
"python",
"qtwebkit",
"ssl"
] | stackoverflow_0003444507_https_pyqt_python_qtwebkit_ssl.txt |
Q:
mail sending from website
I've developed a site with Python, hosted on Google Apps, and I want to send emails from that site.
Is that possible, and if so, where should I look to find out how?
A:
Use the Mail API.
A:
Here is a snippet for a quick start:
from google.appengine.api import mail
mail.send_mail(
... | mail sending from website | I've developed a site with Python, hosted on Google Apps, and I want to send emails from that site.
Is that possible, and if so, where should I look to find out how?
| [
"Use the Mail API.\n",
"Here is a snippet for a quick start:\nfrom google.appengine.api import mail\n\nmail.send_mail(\n sender='anything@your-app-id.appspotmail.com',\n to='john.doe@acme.com',\n subject=\"Hello, World!\",\n body=\"...\"]\n)\n\n"
] | [
9,
2
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0003440463_email_google_app_engine_python.txt |
Q:
Python subprocess.call weird behavior with multiple calls
I am trying to call remote (ssh) commands using the subprocess.call function like this.
import shlex
from subprocess import call
cmd1='ssh user@example.com mkdir temp'
cmd2='scp test.txt user@example.com:temp'
call(shlex.split(cmd1))
call(shlex.split(cmd2... | Python subprocess.call weird behavior with multiple calls | I am trying to call remote (ssh) commands using the subprocess.call function like this.
import shlex
from subprocess import call
cmd1='ssh user@example.com mkdir temp'
cmd2='scp test.txt user@example.com:temp'
call(shlex.split(cmd1))
call(shlex.split(cmd2))
When I call the above, the mkdir does not seem to execute -... | [
"It looks like you don't look for the result of call in the first method.\nif call(shlex.split(cmd1))!=0:\n call(shlex.split(cmd2))\n\n",
"Your problematic version always works for me. I would think this is a network problem especially since you indicate that it works in gigabit LANs.\n"
] | [
0,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003196286_python_subprocess.txt |
Q:
python + Semicolon written to file is written on the next line
I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))
And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_t... | python + Semicolon written to file is written on the next line | I have this simple python expression:
fscript.write (("update %s va set %s = %s where %s = %s;") % (argv[1],argv[2],vl[0],argv[3],vl[1]))
And I would expect to receive output like this
update some_table va set active_id = 1 where id = 5;
update some_table va set active_id = 1 where id = 3;
...more lines...
However, i... | [
"I would try adding a strip() to your latest parameter that could end with \\n.\nfscript.write ((\"update %s va set %s = %s where %s = %s;\") % (argv[1],argv[2],vl[0],argv[3],vl[1].strip()))\n\n",
"Some value of vl[1] is a string with a newline in it, not an integer. \n"
] | [
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003449358_python_python_3.x.txt |
Q:
how to make django custom template tag with variable length arg list
I'm writing a custom template tag 'firstnotnone', similar to the 'firstof' template tag of Django. How to use variable length arguments? The code below results in TemplateSyntaxError, firstnotnone takes 1 arguments.
Template:
{% load library %}
{... | how to make django custom template tag with variable length arg list | I'm writing a custom template tag 'firstnotnone', similar to the 'firstof' template tag of Django. How to use variable length arguments? The code below results in TemplateSyntaxError, firstnotnone takes 1 arguments.
Template:
{% load library %}
{% firstnotnone 'a' 'b' 'c' %}
Custom template tag library:
@register.simp... | [
"The firstof tag isn't implemented via the simple_tag decorator - it uses the long form of a template.Node subclass and a separate tag function. You can see the code in django.template.defaulttags - it should be fairly simple to change for your purposes.\n",
"Custom templatetags:\nfrom django.template import Libr... | [
4,
2
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003449265_django_django_templates_python.txt |
Q:
Decode values from django request
How to decode the values from request from django FW.
GET:<QueryDict: {}>,
POST:<QueryDict: {u'objarrid': [u'1035', u'1036', u'1037', u'1038', u'1039', u'1040', u'1041', u'1042']}>,
def get_data(request):
try:
if request.method == 'GET':
r_c = request.GET
elif req... | Decode values from django request | How to decode the values from request from django FW.
GET:<QueryDict: {}>,
POST:<QueryDict: {u'objarrid': [u'1035', u'1036', u'1037', u'1038', u'1039', u'1040', u'1041', u'1042']}>,
def get_data(request):
try:
if request.method == 'GET':
r_c = request.GET
elif request.method == 'POST':
r_c = requ... | [
"Use .getlist('objarrid').\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003449521_django_django_models_django_views_python.txt |
Q:
Is there anything similar to isfile() isdir() with ftp in Python?
Writing a script to retrieve logfiles from one server to NAS i need to determine if sth is a file or a directory.
Does anybody know a simple way to determine if an element of ftp.nlst() is a file or a directory??
Thanks in advance
A:
Consider the ... | Is there anything similar to isfile() isdir() with ftp in Python? | Writing a script to retrieve logfiles from one server to NAS i need to determine if sth is a file or a directory.
Does anybody know a simple way to determine if an element of ftp.nlst() is a file or a directory??
Thanks in advance
| [
"Consider the following code from here. It will append [F] to directories and leave the files as it is.\nfrom ftplib import FTP\nimport os\nftp = FTP(self.host)\nlistdir = self.ftp.nlst()\nfor i in listdir:\n if(self.ftp.sendcmd(os.path.isdir(bool(self.ftpdir + \"/\" + i)))):\n self.list_box_2.Append(\"... | [
1
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0003449843_ftp_python.txt |
Q:
Help me understand why my trivial use of Python's ctypes module is failing
I am trying to understand the Python "ctypes" module. I have put together a trivial example that -- ideally -- wraps the statvfs() function call. The code looks like this:
from ctypes import *
class struct_statvfs (Structure):
_field... | Help me understand why my trivial use of Python's ctypes module is failing | I am trying to understand the Python "ctypes" module. I have put together a trivial example that -- ideally -- wraps the statvfs() function call. The code looks like this:
from ctypes import *
class struct_statvfs (Structure):
_fields_ = [
('f_bsize', c_ulong),
('f_frsize', c_ulong),
... | [
"Execute this command to get the exact definition of struct statvfs on your system:\necho '#include <sys/statvfs.h>' | gcc -E - | less\n\nThen press /struct statvfs<enter> to skip to the definition and browse from there.\nAlso take a look at my patch to fusepy, and their definition.\n",
"The manpage for statvfs s... | [
4,
2,
2,
0
] | [] | [] | [
"ctypes",
"malloc",
"python"
] | stackoverflow_0003449442_ctypes_malloc_python.txt |
Q:
Using python to provide application services
My company's web architecture has essentially got an extra layer due to client security requirements, which complicates the process of developing applications a bit. I'd like to get some input and suggestions on the best way to do so.
First, an overview:
presentation l... | Using python to provide application services | My company's web architecture has essentially got an extra layer due to client security requirements, which complicates the process of developing applications a bit. I'd like to get some input and suggestions on the best way to do so.
First, an overview:
presentation layer - this is mostly PHP, with some flex applicat... | [
"django-piston is a mini-framework for Django for creating RESTful APIs, which I think should fulfill your requirements.\n",
"I've found that Pylons has been just the ticket for providing this capability; extension is really easy, testing is simple, and it gives loads of control to me as a developerl\n"
] | [
1,
0
] | [] | [] | [
"architecture",
"python",
"web_services"
] | stackoverflow_0003255933_architecture_python_web_services.txt |
Q:
python whois for windows
I try to get whois in python. I use this
http://code.google.com/p/pywhois/
but it run only in linux. Is it posible to run it on windows? currently i get errors (because internal linux command whois used)
A:
On Windows just like on Linux, pywhois gives an error if the whois program is not... | python whois for windows | I try to get whois in python. I use this
http://code.google.com/p/pywhois/
but it run only in linux. Is it posible to run it on windows? currently i get errors (because internal linux command whois used)
| [
"On Windows just like on Linux, pywhois gives an error if the whois program is not installed. You could try this whois, for example.\nThe reason, of course, is in pywhois/init.py, line 11:\nr = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)\n\nClearly this line needs to run some existing, installed wh... | [
6,
1
] | [] | [] | [
"python",
"whois",
"windows"
] | stackoverflow_0003450339_python_whois_windows.txt |
Q:
Call a method at a specific time for Django/Python?
In my Django web app, an event's status changes from 'upcoming' to 'completed' at a certain date/time. However, I want to update the database as soon as the event object's date/time has passed. Any ideas how I would code this?
My only idea so far is to have a thr... | Call a method at a specific time for Django/Python? | In my Django web app, an event's status changes from 'upcoming' to 'completed' at a certain date/time. However, I want to update the database as soon as the event object's date/time has passed. Any ideas how I would code this?
My only idea so far is to have a thread constantly running that that checks to see if the eve... | [
"The django-chronograph app is one way to schedule jobs -- it relies on a cron job to automate scheduled running of django commands.\n"
] | [
3
] | [] | [] | [
"call",
"datetime",
"django",
"methods",
"python"
] | stackoverflow_0003450249_call_datetime_django_methods_python.txt |
Q:
Google App Engine: Production versus Development Settings
How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?
For example, I would like to set up a settings file where I store the Absolute Root URL.
A:
It's not cle... | Google App Engine: Production versus Development Settings | How do you setup a settings file? One is for your local development server and another set of setting values for when you upload to Google App Engine?
For example, I would like to set up a settings file where I store the Absolute Root URL.
| [
"It's not clear from your question if you're asking about the Java or Python runtime. I'll assume Python for now.\nJust like any other Python webapp, the settings file can be wherever and whatever you want. I usually use a .py file called 'settings.py' or 'config.py' in the root directory of my app. For example, se... | [
16,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0000873949_google_app_engine_python.txt |
Q:
Is monkeypatching stdlib methods a good practice in Python?
Over time I found the need to override several stdlib methods from Python in order to overcome limitation or to add some missing functionality.
In all cases I added a wrapper function and replaced the original method from the module with my wrapper (the... | Is monkeypatching stdlib methods a good practice in Python? | Over time I found the need to override several stdlib methods from Python in order to overcome limitation or to add some missing functionality.
In all cases I added a wrapper function and replaced the original method from the module with my wrapper (the wrapper was calling the original method).
Why I did this? Just t... | [
"None of these things seem to require monkeypatching. All of them seem to have better, more robust and reliable solutions. \nAdding a logging handler is easy. No monkeypatch.\nFixing open is done this way.\nfrom io import open\n\nThat was easy. No patch.\nLogging to os.system()? I'd think that a simple \"wrapp... | [
7,
3
] | [] | [] | [
"monkeypatching",
"python",
"word_wrap"
] | stackoverflow_0003450332_monkeypatching_python_word_wrap.txt |
Q:
How to close file objects when downloading files over FTP using Twisted?
I've got the following code:
for f in fileListProtocol.files:
if f['filetype'] == '-':
filename = os.path.join(directory['filename'], f['filename'])
print 'Downloading %s...' % (filename)
newFile = open(filename, '... | How to close file objects when downloading files over FTP using Twisted? | I've got the following code:
for f in fileListProtocol.files:
if f['filetype'] == '-':
filename = os.path.join(directory['filename'], f['filename'])
print 'Downloading %s...' % (filename)
newFile = open(filename, 'w+')
d = ftpClient.retrieveFile(filename, FileConsumer(newFile))
... | [
"You're opening every file in fileListProtocol.files simultaneously, downloading contents to them, and then closing each when each download is complete. So, you have len(fileListProtocol.files) files open at the beginning of the process. If there are too many files in that list, then you'll try to open too many f... | [
1,
1
] | [] | [] | [
"ftp",
"ioerror",
"python",
"twisted"
] | stackoverflow_0003449901_ftp_ioerror_python_twisted.txt |
Q:
Sharepoint Filter for List Items(GetListItems)
I'm attempting to get a set of list items from sharepoint via the WebService. I want to query a small subset of items to be returned. My SOAP packet appears to be ordered properly, however, it still appears that the service is ignoring my set filter(query). Any ide... | Sharepoint Filter for List Items(GetListItems) | I'm attempting to get a set of list items from sharepoint via the WebService. I want to query a small subset of items to be returned. My SOAP packet appears to be ordered properly, however, it still appears that the service is ignoring my set filter(query). Any ideas why this would still be happening?
<SOAP-ENV:Enve... | [
"Try using the IncludeTimeValue attribute on your Value element:\n<Value Type=\"DateTime\" IncludeTimeValue=\"TRUE\">[Now+2Minute(s)]</Value>\n\nAccording to MSDN:\n\nIncludeTimeValue: Optional Boolean. Specifies to build DateTime queries based on time as well as date. If you do not set this attribute, the time po... | [
1
] | [] | [] | [
"python",
"sharepoint",
"soap"
] | stackoverflow_0003449039_python_sharepoint_soap.txt |
Q:
User store fails on dev_appserver when performing redirect to login page
I am using Python 2.7 as this seems to be only Python MSI downloadable at the moment from Python.org.
self.redirect(users.create_login_url(self.request.uri)) fails when running on dev_appserver
localhost:8081/_ah/login?continue=http%3A//local... | User store fails on dev_appserver when performing redirect to login page | I am using Python 2.7 as this seems to be only Python MSI downloadable at the moment from Python.org.
self.redirect(users.create_login_url(self.request.uri)) fails when running on dev_appserver
localhost:8081/_ah/login?continue=http%3A//localhost%3A8081/ returns a 500.
Although this does work: localhost:8081/_ah/admin/... | [
"I would recommend that you use 2.5.4, which is the exact version used in production. You can get an MSI from here:\nhttp://www.python.org/download/releases/2.5.4/\nI haven't tried 2.7, but I initially tried 2.6 and found that sending mail didn't work. It worked fine once I downgraded to 2.5.4 though.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003448670_google_app_engine_python.txt |
Q:
Python threading.Event() - Ensuring all waiting threads wake up on event.set()
I have a number of threads which wait on an event, perform some action, then wait on the event again. Another thread will trigger the event when it's appropriate.
I can't figure out a way to ensure that each waiting thread triggers exac... | Python threading.Event() - Ensuring all waiting threads wake up on event.set() | I have a number of threads which wait on an event, perform some action, then wait on the event again. Another thread will trigger the event when it's appropriate.
I can't figure out a way to ensure that each waiting thread triggers exactly once upon the event being set. I currently have the triggering thread set it, sl... | [
"You don't need an Event, and you don't need both a Lock and a Queue. All you need is a Queue.\nCall queue.put to drop a message in without waiting for it to be delivered or processed.\nCall queue.get in the worker thread to wait for a message to arrive.\nimport threading\nimport Queue\n\nactive_queues = []\n\nclas... | [
13,
3,
2,
1
] | [] | [] | [
"events",
"multithreading",
"python"
] | stackoverflow_0003409593_events_multithreading_python.txt |
Q:
Python: determining if an object is file-like?
I'm writing some unit tests (using the unittest module) for my application, and want to write something which can verify that a method I'm calling returns a "file-like" object. Since this isn't a simple isinstance call, I wonder what the best-practice would be for de... | Python: determining if an object is file-like? | I'm writing some unit tests (using the unittest module) for my application, and want to write something which can verify that a method I'm calling returns a "file-like" object. Since this isn't a simple isinstance call, I wonder what the best-practice would be for determining this?
So, in outline:
possible_file = self... | [
"There is no \"official definition\" of what objects are \"sufficiently file-like\", because the various uses of file-like objects have such different requirements -- e.g., some only require read or write methods, other require some subset of the various line-reading methods... all the ways to some requiring the fi... | [
7,
4,
2
] | [] | [] | [
"file",
"python",
"types"
] | stackoverflow_0003450857_file_python_types.txt |
Q:
How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines?
How can one change the following text
The quick brown fox jumps over the lazy dog.
to
The quick brown fox +
jumps over the +
lazy dog.
using regex?
UPDATE1
A solution for Ruby is still missing... A ... | How to wrap long lines in a text using Regular Expressions when you also need to indent the wrapped lines? | How can one change the following text
The quick brown fox jumps over the lazy dog.
to
The quick brown fox +
jumps over the +
lazy dog.
using regex?
UPDATE1
A solution for Ruby is still missing... A simple one I came to so far is
def textwrap text, width, indent="\n"
return text.split("\n").collect do |line|... | [
"Maybe use textwrap instead of regex:\nimport textwrap\n\ntext='The quick brown fox jumps over the lazy dog.'\n\nprint(' + \\n'.join(\n textwrap.wrap(text, initial_indent='', subsequent_indent=' '*4, width=20)))\n\nyields:\nThe quick brown fox + \n jumps over the + \n lazy dog.\n\n"
] | [
5
] | [] | [] | [
"python",
"regex",
"ruby",
"word_wrap"
] | stackoverflow_0003451308_python_regex_ruby_word_wrap.txt |
Q:
Django: how do you serve media / stylesheets and link to them within templates
Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongl... | Django: how do you serve media / stylesheets and link to them within templates | Variations of this question have been asked, but I'm still unable to get my stylesheets to load correctly when my templates are rendered.
I'm attempting to serve static media from the Django process during development - which is strongly discouraged in production, I'm aware. I'll post my configuration and my template, ... | [
"I just had to figure this out myself.\nsettings.py:\nMEDIA_ROOT = 'C:/Server/Projects/project_name/static/'\nMEDIA_URL = '/static/'\nADMIN_MEDIA_PREFIX = '/media/'\n\nurls.py:\nfrom django.conf import settings\n...\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^static/(?P<path>.*)$', 'django.vie... | [
51,
11,
6,
2,
1,
1,
0
] | [] | [] | [
"css",
"django",
"django_templates",
"media",
"python"
] | stackoverflow_0000446026_css_django_django_templates_media_python.txt |
Q:
Can a JSON data structure be directly saved as a CouchDB document?
I'm a Python programmer with experience using the json module. I've just meet CouchDB and seems very interesting.
I wonder know if JSON data structures can be directly saved as a CouchDB document.
Thanks,
A:
You only need to provide an unique ID ... | Can a JSON data structure be directly saved as a CouchDB document? | I'm a Python programmer with experience using the json module. I've just meet CouchDB and seems very interesting.
I wonder know if JSON data structures can be directly saved as a CouchDB document.
Thanks,
| [
"You only need to provide an unique ID that will be used as part of the resource name (URI) when PUTting it or you use POST and take an auto-generated ID. You can use any JSON, that does not contain _id and _rev, because these fields are reserved for CouchDB itself.\n",
"couchDB is inteded to work with JSON.\nhav... | [
3,
0,
0
] | [] | [] | [
"couchdb",
"json",
"python"
] | stackoverflow_0003441057_couchdb_json_python.txt |
Q:
How to use named parameters and global vars with same name in Python?
Example code from a module:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is ju... | How to use named parameters and global vars with same name in Python? | Example code from a module:
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value ... | [
"By far the best approach, as the other answers say, is to avoid this very, very bad design: just don't use the same names for two different things!\nIf you're locked into this terrible design, maybe because your company's Supreme Architect decreed it and it's just non-negotiable (e.g., there's tons of customer cod... | [
6,
1,
0,
0
] | [] | [] | [
"global_variables",
"python",
"python_module"
] | stackoverflow_0003451533_global_variables_python_python_module.txt |
Q:
Is there a wxpython event like program_start?
OK, I'm trying to explain what I want to achieve in another way. Here's an example:
Say if it's an anti virus program, and user can choose between two ways to run the program, choice one, automatically start to scan disks for virus when the program starts up, choice tw... | Is there a wxpython event like program_start? | OK, I'm trying to explain what I want to achieve in another way. Here's an example:
Say if it's an anti virus program, and user can choose between two ways to run the program, choice one, automatically start to scan disks for virus when the program starts up, choice two, hit the start button to make the program scan di... | [
"Why don't you run it just in module code? This way it will be run only once, because code in module is run only once per program instance.\n",
"In wxPython you can override the OnInit method of your Application class to run code when the program launches. For example:\n def OnInit(self):\n # Check for a run... | [
1,
1,
0
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003450525_event_handling_python_wxpython.txt |
Q:
Sending sqlite db over network
I have an sqlite database whose data I need to transfer over the network, the server needs to modify the data, and then I need to get the db back and either update my local version or overwrite it with the new db. How should I do this? My coworker at first wanted to scrap the db and ... | Sending sqlite db over network | I have an sqlite database whose data I need to transfer over the network, the server needs to modify the data, and then I need to get the db back and either update my local version or overwrite it with the new db. How should I do this? My coworker at first wanted to scrap the db and just use an .ini file, but this is g... | [
"Use the copy command in your OS. No reason to overthink this.\n"
] | [
3
] | [] | [] | [
"binary_data",
"embedded",
"python",
"sqlite"
] | stackoverflow_0003451708_binary_data_embedded_python_sqlite.txt |
Q:
Why should I use python 3.1 instead of python 2.6?
After reading some benchmarks, I noticed that python 3.1 is slower than python 2.6, especially with I/Os.
So I wonder what could be the good reasons to switch to Python 3.x ?
A:
Largely because of the new I/O library. This, however, has been completely rewritten... | Why should I use python 3.1 instead of python 2.6? | After reading some benchmarks, I noticed that python 3.1 is slower than python 2.6, especially with I/Os.
So I wonder what could be the good reasons to switch to Python 3.x ?
| [
"Largely because of the new I/O library. This, however, has been completely rewritten to C in Python 3.2 and 2.7. I think the performance numbers are pretty close right now if you compare it to 3.2.\nedit: I confused the version numbers. Nevermind.\n",
"Go to 3.1. Unless your code is run-once (which at almost nev... | [
0,
0,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0003451149_performance_python.txt |
Q:
Why is Python 3 (or later) better than Python 2?
I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would... | Why is Python 3 (or later) better than Python 2? | I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now?
T... | [
"As a key feature, a lot of people seem to be pretty exited about (supposedly) transparent unicode support. They changed it from str (8-bit char array/default string type) and unicode (unicode string), to str (default (unicode compatable) string) and bytes (binary data as 8-bit 'string'). \n(I think seperation of... | [
10,
3,
1,
0
] | [] | [] | [
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0003384361_python_python_2.x_python_3.x.txt |
Q:
Most memory-efficient way of holding base64 data in Python?
Suppose you have a MD5 hash encoded in base64. Then each
character needs only 6 bits to store each character in the
resultant 22-byte string (excluding the ending '=='). Thus, each
base64 md5 hash can shrink down to 6*22 = 132 bits, which
requires 25% l... | Most memory-efficient way of holding base64 data in Python? | Suppose you have a MD5 hash encoded in base64. Then each
character needs only 6 bits to store each character in the
resultant 22-byte string (excluding the ending '=='). Thus, each
base64 md5 hash can shrink down to 6*22 = 132 bits, which
requires 25% less memory space compared to the original 8*22=176
bits string.
I... | [
"The most efficient way to store base64 encoded data is to decode it and store it as binary. base64 is a transport encoding - there's no sense in storing data in it, especially in memory, unless you have a compelling reason otherwise.\nAlso, nitpick: The output of a hash function is not a hex string - that's just a... | [
8,
5,
4,
1
] | [] | [] | [
"algorithm",
"base64",
"data_structures",
"md5",
"python"
] | stackoverflow_0003430016_algorithm_base64_data_structures_md5_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.