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:
Using DictWriter to write a subset of a dictionary's keys
I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:
data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)
However, I sometimes want to write out to a file only a subset of each dict... | Using DictWriter to write a subset of a dictionary's keys | I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:
data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)
However, I sometimes want to write out to a file only a subset of each dictionary's keys. If I pass as fieldnames a subset of the keys tha... | [
"Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:\n\nIf the dictionary passed to the\n writerow() method contains a key not\n found in fieldnames, the optional\n extrasaction parameter indicates what\n action to take. If it is s... | [
52,
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0003208874_csv_dictionary_python.txt |
Q:
How do I do a Rails style before_filter with Google App Engine?
The app is setup as a basic WSGI application. I'm just trying to call a function before the requestHandler is run.
I would like something very much like the way before_filter works in Rails.
Thanks.
A:
I would use decorators, it's not exactly the sa... | How do I do a Rails style before_filter with Google App Engine? | The app is setup as a basic WSGI application. I'm just trying to call a function before the requestHandler is run.
I would like something very much like the way before_filter works in Rails.
Thanks.
| [
"I would use decorators, it's not exactly the same as before_filter in rails, but maybe good enough for you:\ndef before_filter(fn):\n def inner_function(self):\n # do stuff before\n return fn(self)\n return inner_function\n\nclass MainPage(webapp.RequestHandler):\n\n @before_filter\n def ... | [
1,
1
] | [] | [] | [
"django_middleware",
"google_app_engine",
"python",
"wsgi"
] | stackoverflow_0003208869_django_middleware_google_app_engine_python_wsgi.txt |
Q:
binding generic c++ libraries to python with boost.python
I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
A:
You can only bind a generated class. H... | binding generic c++ libraries to python with boost.python | I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
| [
"You can only bind a generated class. However, it is possible to write a template function to export your class, and call this function for each concrete types you want to export. For example:\ntemplate<class T>\nstruct foo {};\n\ntemplate<class T>\nvoid export_foo(std::string name) { \n boost::python::class_<fo... | [
3
] | [] | [] | [
"boost",
"c++",
"generics",
"python",
"templates"
] | stackoverflow_0003205561_boost_c++_generics_python_templates.txt |
Q:
Odd Behavior when Connecting to my Program
I'm using Twisted to implement a server, of sorts. When I test it, the first line it receives is always strange:
Starting Server...
New connection from 192.168.1.140
192.168.1.140: ÿûÿû ÿûÿû'ÿýÿûÿý\NAME Blurr
192.168.1.140: \NAME Blurr
(for both inputs I sent \NAME Blu... | Odd Behavior when Connecting to my Program | I'm using Twisted to implement a server, of sorts. When I test it, the first line it receives is always strange:
Starting Server...
New connection from 192.168.1.140
192.168.1.140: ÿûÿû ÿûÿû'ÿýÿûÿý\NAME Blurr
192.168.1.140: \NAME Blurr
(for both inputs I sent \NAME Blurr.)
This is the code that prints the input:
def... | [
"You can find an explanation of the \"ÿûÿû mystery\" here. Short form: telnet is not a simple protocol, and what you're seeing is a trace of a telnet negotiation (trying to) occur with a server that doesn't speak \"telnettese\";-). Good guess about \"is this a telnet protocol I'm missing\";-)\nThe RFCs involved i... | [
5,
1
] | [] | [] | [
"networking",
"putty",
"python",
"telnet",
"twisted"
] | stackoverflow_0003208993_networking_putty_python_telnet_twisted.txt |
Q:
Detect Caps Lock in Python curses
For such a basic question, I'm surprised I couldn't find anything by searching...
Anyways, I made a curses app in Python that assists in solving puzzles of a certain DSiWare game. With it, you can take a puzzle and inspect the components of it individually. The keys qweasdzx are... | Detect Caps Lock in Python curses | For such a basic question, I'm surprised I couldn't find anything by searching...
Anyways, I made a curses app in Python that assists in solving puzzles of a certain DSiWare game. With it, you can take a puzzle and inspect the components of it individually. The keys qweasdzx are used to paint tiles (the keys are arra... | [
"I found a solution on my own:\nSince curses is completely unaware of the Caps Lock setting according to ΤΖΩΤΖΙΟΥ, I tried an alternative solution. Specifically, I looked up how to check Caps Lock in a BASH script. What I found was this:\nLinux only. Requires X Window System.\n$ xset q | grep LED\n> auto repeat:... | [
7,
3
] | [] | [] | [
"capslock",
"curses",
"python"
] | stackoverflow_0003207032_capslock_curses_python.txt |
Q:
Is it possible to use readline instead of libedit in Python's raw_input under OS X?
From the readline module documentation, it mentions:
On MacOS X the readline module can be implemented using the libedit library instead of GNU readline. The configuration file for libedit is different from that of GNU readline.
... | Is it possible to use readline instead of libedit in Python's raw_input under OS X? | From the readline module documentation, it mentions:
On MacOS X the readline module can be implemented using the libedit library instead of GNU readline. The configuration file for libedit is different from that of GNU readline.
Is it possible to use the readline library in /usr/lib/libreadline.dylib for example, or ... | [
"$ sudo easy_install readline\n\n",
"It is possible to use GNU readline from MacPorts or elsewhere when building Python by specifying the additional library and include files when invoking the configure script. See the python installer build script in the Python source tree (Mac/BuildScript/build-installer.py) fo... | [
3,
2
] | [] | [] | [
"macos",
"python",
"readline"
] | stackoverflow_0003138574_macos_python_readline.txt |
Q:
Restrictons of Python compared to Ruby: lambda's
I was going over some pages from WikiVS, that I quote from:
because lambdas in Python are restricted to expressions and cannot
contain statements
I would like to know what would be a good example (or more) where this restriction would be, preferably compared to ... | Restrictons of Python compared to Ruby: lambda's | I was going over some pages from WikiVS, that I quote from:
because lambdas in Python are restricted to expressions and cannot
contain statements
I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language.
Thank you for your answers, commen... | [
"I don't think you're really asking about lambdas, but inline functions.\nThis is genuinely one of Python's seriously annoying limitations: you can't define a function (a real function, not just an expression) inline; you have to give it a name. This is very frustrating, since every other modern scripting language... | [
14,
9,
4,
2,
1
] | [] | [] | [
"lambda",
"python",
"restriction",
"ruby"
] | stackoverflow_0002654425_lambda_python_restriction_ruby.txt |
Q:
How to replace an instance in __init__() with a different object?
I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to __init__() ('self' in the example below) within __init__() but it ... | How to replace an instance in __init__() with a different object? | I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to __init__() ('self' in the example below) within __init__() but it doesn't seem to do what I want.
in main:
import ClassA
my_obj = ClassA... | [
"You need __new__() for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing object.)\nclass ClassA(object):\n def __new__(cls,theirnumber):\n if theirnumber > 10:\n # all big numbers should be ClassB objects:\n return ClassB.ClassB(th... | [
47,
18,
16
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003209233_oop_python.txt |
Q:
How can I refactor this django query to not select each individual object?
Here's my view:
def rsvp_list(request, id, template="rsvp/rsvp_list.html"):
rsvp = RSVP.objects.get(id=id)
return render_to_response(template, {
'attendees': rsvp.attendee_set.all().order_by('email__first_name'),
}, co... | How can I refactor this django query to not select each individual object? | Here's my view:
def rsvp_list(request, id, template="rsvp/rsvp_list.html"):
rsvp = RSVP.objects.get(id=id)
return render_to_response(template, {
'attendees': rsvp.attendee_set.all().order_by('email__first_name'),
}, context_instance=RequestContext(request))
and here's my template:
{% for attende... | [
"I should have read a bit further in the documentation.\nIn order to reduce the queries that are going to happen on related object later, just use select_related. So my query becomes:\nattendees = rsvp.attendee_set.select_related().all().order_by('email__first_name')\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003209228_django_python_sql.txt |
Q:
python - appending different columns from a file to different lists?
I have a tab-delimited file as below:
A 3 A 6
B 6 B 9
C 0 C 2
I wish to read the file in as below:
LIST = [['A', '3'], ['B', '6'], ['C', '0'], ['A', '6'], ['B', '9'], ['C', '2']]
The order is not important. I am only ... | python - appending different columns from a file to different lists? | I have a tab-delimited file as below:
A 3 A 6
B 6 B 9
C 0 C 2
I wish to read the file in as below:
LIST = [['A', '3'], ['B', '6'], ['C', '0'], ['A', '6'], ['B', '9'], ['C', '2']]
The order is not important. I am only concerned that each row is read in increments of two and assigned to a sub... | [
"The most straightforward way would be:\n>>> n = []\n>>> for line in open(fname):\n els = line.split('\\t')\n n.append(els[:2])\n n.append(els[2:])\n\n\n>>> n\n[['A', '3'], ['A', '6'], ['B', '6'], ['B', '9'], ['C', '0'], ['C', '2']]\n\nmaybe slightly more efficient would be:\n>>> g = (line.split('\\t') for... | [
3,
0
] | [] | [] | [
"file",
"list",
"python"
] | stackoverflow_0003204114_file_list_python.txt |
Q:
Initialized string variable in Python?
Create a string variable that is initialized to your entire name??
Im a little lost
Thanks Kim:)
A:
You want to create a string variable with my name? Sure, here it is:
my_name = 'Samuel Robert Dolan'
If that's not what you want, please be more descriptive in your quest... | Initialized string variable in Python? | Create a string variable that is initialized to your entire name??
Im a little lost
Thanks Kim:)
| [
"You want to create a string variable with my name? Sure, here it is:\n my_name = 'Samuel Robert Dolan'\n\nIf that's not what you want, please be more descriptive in your question. :)\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003209326_python.txt |
Q:
How to remove values from item list
I am new to python. I have a item list looks like this:
rank_item = [
(9, 0.99999999745996648),
(8, 0.99999996796861101),
(1, 0.99999996796861101),
(10, 0.0) ]
The question is how do i remove the item list with value 0.0 and return
[(9, 0.99999999745996648)... | How to remove values from item list | I am new to python. I have a item list looks like this:
rank_item = [
(9, 0.99999999745996648),
(8, 0.99999996796861101),
(1, 0.99999996796861101),
(10, 0.0) ]
The question is how do i remove the item list with value 0.0 and return
[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.9999999... | [
"Use list.remove - which will modify your rank_item list in-place:\n rank_item.remove( (10, 0.0) )\n\nrank_item will contain:\n[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]\n\nOr, if you want to remove all tuples from your list, which have a the value 0.0 at position 1, you can try ... | [
5,
5,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003205956_python.txt |
Q:
Reference ID in GAE
I have a feeling the answer is simple and documented, but I'm absolutely missing it:
Is there a way, using Python and webapp through Google App Engine, to pass the id field of a record to the template? I'm fairly new to the app engine, and yes, I have searched all around the Google Documentatio... | Reference ID in GAE | I have a feeling the answer is simple and documented, but I'm absolutely missing it:
Is there a way, using Python and webapp through Google App Engine, to pass the id field of a record to the template? I'm fairly new to the app engine, and yes, I have searched all around the Google Documentation to find this.
| [
"I can reference it through record.key().id(). I just found this RIGHT AFTER I posted this question (as luck would have it). Sorry for wasting anybody's time.\n",
"Assuming you're using the built-in Django 0.96 templates, you can access the ID (assuming the entity has one; it might have a key name instead if you ... | [
3,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003207671_google_app_engine_google_cloud_datastore_python.txt |
Q:
data.dat python
say i have the following data in a .dat file:
*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5
how can i print the these data like this?:
A : 1 2 3 4
B : 8 2 4
C : 4 2 5 1 5
randomly print any one number for each letter.
A, B and C can be any word.
and the amount of the numbers can be different.
i know that it has s... | data.dat python | say i have the following data in a .dat file:
*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5
how can i print the these data like this?:
A : 1 2 3 4
B : 8 2 4
C : 4 2 5 1 5
randomly print any one number for each letter.
A, B and C can be any word.
and the amount of the numbers can be different.
i know that it has some thing to do with ... | [
"Read in the file, then split() the characters:\ncontents = open(\"file.dat\").read()\nfor line in contents.split(\"*\"):\n if not line: continue # Remove initial empty string.\n line = line.strip() # Remove whitespace from beginning/end of lines.\n items = line.split(\"-\")\n print items[0], \":\", \" \".jo... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003209529_python.txt |
Q:
Information about computer in python
How would i go about gathering information about a system in python? Seems most of the commands are made for Unix... Are there any options in windows?
Thanks,
Jake.
A:
Getting system information under Windows (Python), from ActiveState code recipes.
A:
What about the platfo... | Information about computer in python | How would i go about gathering information about a system in python? Seems most of the commands are made for Unix... Are there any options in windows?
Thanks,
Jake.
| [
"Getting system information under Windows (Python), from ActiveState code recipes.\n",
"What about the platform module\n",
"This page highlights the list of infos you can get from the OS and for each tells you the OS availability.\nhttp://docs.python.org/library/os.html\nAlso check out this page\nhttp://code.ac... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"system",
"windows"
] | stackoverflow_0003208827_python_system_windows.txt |
Q:
How do I change out the underlying object inside a method call?
I thought all function and method arguments in Python were passed by reference, leading me to believe that the following code would work:
class Insect:
def status(self):
print "i am a %s" % self
class Caterpillar(Insect):
def grow... | How do I change out the underlying object inside a method call? | I thought all function and method arguments in Python were passed by reference, leading me to believe that the following code would work:
class Insect:
def status(self):
print "i am a %s" % self
class Caterpillar(Insect):
def grow_up(self):
self = Butterfly() # replace myself with a... | [
"When you say self = Butterfly() all you're doing is changing what the variable self points to; you're not changing what self is, any more than:\nx = 1\nx = 2\n\n... changes the number 1 to 2.\nIn general, when people need this, rather than change the type of the object (which many languages flat out forbid) people... | [
3,
2,
1,
1,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003209419_oop_python.txt |
Q:
"self" inside plain function?
I've got a bunch of functions (outside of any class) where I've set attributes on them, like funcname.fields = 'xxx'. I was hoping I could then access these variables from inside the function with self.fields, but of course it tells me:
global name 'self' is not defined
So... what c... | "self" inside plain function? | I've got a bunch of functions (outside of any class) where I've set attributes on them, like funcname.fields = 'xxx'. I was hoping I could then access these variables from inside the function with self.fields, but of course it tells me:
global name 'self' is not defined
So... what can I do? Is there some magic variab... | [
"self isn't a keyword in python, its just a normal variable name. When creating instance methods, you can name the first parameter whatever you want, self is just a convention.\nYou should almost always prefer passing arguments to functions over setting properties for input, but if you must, you can do so using the... | [
12,
3,
2,
2,
1,
1,
1,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003207572_python.txt |
Q:
What is the easiest method to compare large amounts of similar text?
somewhat open ended question here as I am mostly looking for opinions. I am grabbing some data from craigslist for apt ads in my area since I am looking to move. My goal is to be able to compare items to see when something is a duplicate so tha... | What is the easiest method to compare large amounts of similar text? | somewhat open ended question here as I am mostly looking for opinions. I am grabbing some data from craigslist for apt ads in my area since I am looking to move. My goal is to be able to compare items to see when something is a duplicate so that I don't spend all day looking at the same 3 ads. The problem is that th... | [
"You could calculate the Levenshtein difference between both strings - after some sane normalizing like minimizing duplicate whitespace and what not. After you run through enough \"duplicates\" you should get an idea of what your threshold is - then you can run Levenshtein on all new incoming data and if its less-t... | [
2,
1,
1,
1,
0
] | [] | [] | [
"perl",
"php",
"python",
"regex",
"sql"
] | stackoverflow_0003095057_perl_php_python_regex_sql.txt |
Q:
Determining number of sites on a website in python
I have the following link:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0001&language=EN
the reference part of the url has the following information:
A7 == The parliament (current is the seventh parliament, the former is A6 ... | Determining number of sites on a website in python | I have the following link:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0001&language=EN
the reference part of the url has the following information:
A7 == The parliament (current is the seventh parliament, the former is A6 and so forth)
2010 == year
0001 == document number
For e... | [
"First, make sure that scraping their site is legal.\nSecond, notice that when a document is not present, the HTML file contains:\n<title>Application Error</title>\n\nThird, use urllib to iterate over all the things you want to:\nfor p in range(1,7):\n for y in range(2000, 2011):\n doc = 1\n while True:\n # us... | [
3,
1,
1
] | [] | [] | [
"python",
"url",
"web_scraping"
] | stackoverflow_0003210012_python_url_web_scraping.txt |
Q:
Unable to upload file using django
I'm unable to upload a file using django. When I hit submit button I get "This webpage is not available. The webpage at http://127.0.0.1:8000/results might be temporarily down or it may have moved permanently to a new web address." error in chrome.
For the file upload HTTP query ... | Unable to upload file using django | I'm unable to upload a file using django. When I hit submit button I get "This webpage is not available. The webpage at http://127.0.0.1:8000/results might be temporarily down or it may have moved permanently to a new web address." error in chrome.
For the file upload HTTP query the corresponding webserver's log entry ... | [
"I guess its because of csrf http://docs.djangoproject.com/en/dev/ref/contrib/csrf/\ntry changing your from\n<form name=\"myform\" action=\"results\" method=\"POST\" ENCTYPE=\"multipart/form-data\">{% csrf_token %}\n\nan the view generating it\nfrom django.core.context_processors import csrf\nfrom django.shortcuts ... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003165526_django_python.txt |
Q:
How to call C functions from python?
I have a scenario where GUI (Developed in VB) is sending commands to the target system application developed in C language (Xilinx).
User on a PC sends the commands to target using GUI.
But now I need to remove the GUI and want to send commands (call C functions in target syste... | How to call C functions from python? | I have a scenario where GUI (Developed in VB) is sending commands to the target system application developed in C language (Xilinx).
User on a PC sends the commands to target using GUI.
But now I need to remove the GUI and want to send commands (call C functions in target system application) using Python.
I found some ... | [
"Invoke a SWIG wrapper to make C functions look like Python functions. Take a look at this example. \n"
] | [
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003210435_ctypes_python.txt |
Q:
How to get pynotify to display line breaks and HTML?
How can I make pynotify display line breaks and HTML in the notifications?
Here is what I got:
>>> import pynotify
>>> n = pynotify.Notification ("This is a test.\n\nAnd this too!",
"","notification-message-im")
>>> n.show()
Contr... | How to get pynotify to display line breaks and HTML? | How can I make pynotify display line breaks and HTML in the notifications?
Here is what I got:
>>> import pynotify
>>> n = pynotify.Notification ("This is a test.\n\nAnd this too!",
"","notification-message-im")
>>> n.show()
Contrary to what is expected, there is no line-break between th... | [
"You can use '\\n' in message body but not in summary. \n>>> n = pynotify.Notification(\"summary\", \"body\\n next line\", \"dialog-warning\")\n>>> n.show()\n\n"
] | [
2
] | [] | [] | [
"pynotify",
"python",
"ubuntu"
] | stackoverflow_0003209981_pynotify_python_ubuntu.txt |
Q:
centos libjpeg error _imaging
I am trying to get my libjpeg working with python with little or no luck.
I have followed this tutorial to get it up and running http://blaolao.com/setting-up-django-mysql-mysql-python-pil-etc on my 10.6, worked like a charm
now that I am looking at getting this onto my server I am ge... | centos libjpeg error _imaging | I am trying to get my libjpeg working with python with little or no luck.
I have followed this tutorial to get it up and running http://blaolao.com/setting-up-django-mysql-mysql-python-pil-etc on my 10.6, worked like a charm
now that I am looking at getting this onto my server I am getting stuck
I believe it already ha... | [
"I managed to CentOS working with a lot of the defaults.\nI now have a running django app, with mod_wsgi, git, django-south, django-imagekit, rackspace CDN, apache, mysql etc.\nI've found that there were so many people having issues with this, however all the answers only took me half-way, I have tracked what I hav... | [
2
] | [] | [] | [
"libjpeg",
"python",
"python_imaging_library"
] | stackoverflow_0003037381_libjpeg_python_python_imaging_library.txt |
Q:
Python No Longers Sees MySQLdb
Whilst writing working my way through a list of scripts I need to write I started using the MySQLdb package. This all worked fine in my Terminal by doing a simple python at the command line then import MySQLdb. However after about 30 minutes I figured I better move this to Eclipse in... | Python No Longers Sees MySQLdb | Whilst writing working my way through a list of scripts I need to write I started using the MySQLdb package. This all worked fine in my Terminal by doing a simple python at the command line then import MySQLdb. However after about 30 minutes I figured I better move this to Eclipse incase I start making some stupid mist... | [
"Could this be the answer; your current path does no longer exist: http://bugs.python.org/issue6612 thus os.getcwd () doesn't work.\n"
] | [
2
] | [] | [] | [
"import",
"mysql",
"python"
] | stackoverflow_0003203698_import_mysql_python.txt |
Q:
python file read
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output!
A:
While yo... | python file read | def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output!
| [
"While your own answer prints the bytes read, it doesn't return them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:\n\nfile_open isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.\nYou should make s... | [
7,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003211031_file_python.txt |
Q:
No module named django.core
I'm following the step by step guide here and I hit an error at the "Create Django Project" step when I try the command;
django-admin.py startproject myproject
The error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py",
line 2, in
from django.core ... | No module named django.core | I'm following the step by step guide here and I hit an error at the "Create Django Project" step when I try the command;
django-admin.py startproject myproject
The error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py",
line 2, in
from django.core import management ImportError: No... | [
"Thanks to Daniel Roseman's comment, I investigated and found my symlink was broken. Just had to recreate that and it worked nicely.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003211110_django_python.txt |
Q:
How to deploy a python webapp with dependencies using virtualenv?
I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the... | How to deploy a python webapp with dependencies using virtualenv? | I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the server ?
In development, I have a virtualenv in which I install extern... | [
"With pip you can create a requirements file:\n$ pip freeze > requirements.txt\n\nThen in the server to install all of these you do:\n$ pip install -r requirements.txt\n\nAnd with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.\n"
] | [
9
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0003211080_python_virtualenv.txt |
Q:
How should I share and store data in a small multithreaded python application?
I'm writing a small multithreaded client-side python application that contains a small webserver (only serves page to the localhost) and a daemon. The webserver loads and puts data into a persistent "datastore", and the daemon processes... | How should I share and store data in a small multithreaded python application? | I'm writing a small multithreaded client-side python application that contains a small webserver (only serves page to the localhost) and a daemon. The webserver loads and puts data into a persistent "datastore", and the daemon processes this data, modifies it and adds some more. It should also takes care of the synchro... | [
"What you're seeking isn't too Python specific, because AFAIU you want to communicate between two different processes, which are only incidentally written in Python. If this indeed is your problem, you should look for a general solution, not a Python-specific one.\nI think that a simple No-SQL key-value datastore s... | [
0
] | [] | [] | [
"concurrency",
"datastore",
"multithreading",
"python"
] | stackoverflow_0003211379_concurrency_datastore_multithreading_python.txt |
Q:
SQLAlchemy and Elixir?
I have been using django ORM, it's nice and very easy, but this time I'm doing a desktop app and I found SQLAlchemy, but I'm not sure to use it with Elixir. What do you think? is it really useful?
A:
I'm not sure you need Elixir any more. With the Declarative mapper, you can create classes... | SQLAlchemy and Elixir? | I have been using django ORM, it's nice and very easy, but this time I'm doing a desktop app and I found SQLAlchemy, but I'm not sure to use it with Elixir. What do you think? is it really useful?
| [
"I'm not sure you need Elixir any more. With the Declarative mapper, you can create classes that map to your tables similar to the way it's done by Elixir. Is there a specific elixir feature that you're looking for? \n",
"Use SQLAlchemy with Elixir if you need Django-style (or Rails-style) simple object-relationa... | [
11,
5
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0003112014_python_python_elixir_sqlalchemy.txt |
Q:
Google application engine Datastore - any alternatives to aggregate functions and group by?
As is mentioned in the doc for google app engine, it does not support group by and other aggregation functions. Is there any alternatives to implement the same functionality?
I am working on a project where I need it on urg... | Google application engine Datastore - any alternatives to aggregate functions and group by? | As is mentioned in the doc for google app engine, it does not support group by and other aggregation functions. Is there any alternatives to implement the same functionality?
I am working on a project where I need it on urgent basis, being a large database its not efficient to iterate the result set and then perform th... | [
"The best way is to populate the summaries (aggregates) at the time of write. This way your reads will be faster, since they just read - at the cost of writes which will have to update the summaries if its likely to be effected by the write. \nHopefully you will be reading more often than writing/updating summaries... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003210577_google_app_engine_python.txt |
Q:
Can iterator be restored and can its value/status be assigned?
I have below snippet which use the generator to give the new ID
...
def __init__(self, id_generator = None):
if id_generator is None: id_generator = 0
if isinstance(id_generator, int):
import itertools
sel... | Can iterator be restored and can its value/status be assigned? | I have below snippet which use the generator to give the new ID
...
def __init__(self, id_generator = None):
if id_generator is None: id_generator = 0
if isinstance(id_generator, int):
import itertools
self._generator = itertools.count(id_generator)
else:
... | [
"No, generators just generate items, you cannot set or save their state once they have been created. So self._generator = itertools.count(99) is really the best way to go.\nWhat you can do is duplicate a generator with itertools.tee, which memorizes the output sequence from the first iterable and passes it to the n... | [
1
] | [] | [] | [
"duplicates",
"generator",
"iterator",
"python",
"restore"
] | stackoverflow_0003211478_duplicates_generator_iterator_python_restore.txt |
Q:
PyGTK Window not hiding when told to
In my PyGTK application, I am asking a user to find a file so that operations can be performed on it. The application asks the user for the file, and relays that filename to the necessary methods. Unfortunately, when calling the gtk.dispose() method on that dialog, it just ha... | PyGTK Window not hiding when told to | In my PyGTK application, I am asking a user to find a file so that operations can be performed on it. The application asks the user for the file, and relays that filename to the necessary methods. Unfortunately, when calling the gtk.dispose() method on that dialog, it just hangs there until the method being called up... | [
"There's probably no need to perform the file operations in a separate thread, since you're not really doing anything in this thread while the file operations are running -- just busy-waiting. And that brings me to why the code doesn't work: GUI updates are processed within the GTK main loop. But the whole time whi... | [
2,
1
] | [] | [] | [
"gtk",
"linux",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0003203783_gtk_linux_multithreading_pygtk_python.txt |
Q:
append a particular column from a csv file to another using python
I'll explain my whole problem:
I have 2 csv files:
project-table.csv (has about 50 columns)
interaction-matrix.csv (has about 45 columns)
I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-mat... | append a particular column from a csv file to another using python | I'll explain my whole problem:
I have 2 csv files:
project-table.csv (has about 50 columns)
interaction-matrix.csv (has about 45 columns)
I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-matrix.csv with a dot(.) in between both the strings
next,
interaction-mat... | [
"Edit your question to show what error message are you getting. Update: NameError probably means you are using an (older) version of Python (which one?) without all() or (you have used all as a variable name AND are not showing the exact code that you ran)\nNote: open both files in binary mode (\"rb\" and \"wb\") r... | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003211570_csv_python.txt |
Q:
How to guarantee two related models get saved?
How do I guarantee data only gets saved when the related objects are both filled with data?
class A(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class B(A):
author = models.CharField(max_length=255)
url = models.U... | How to guarantee two related models get saved? | How do I guarantee data only gets saved when the related objects are both filled with data?
class A(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class B(A):
author = models.CharField(max_length=255)
url = models.URLField()
I insert data by accessing model B:
b = B... | [
"Depending on your environment, transactions are probably the answer\n",
"Database transactions?\n",
"Override B's save method (as described in the docs), have it call A's full_clean method. if it raises an exception, just don't save the model.\n"
] | [
3,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003211976_django_django_models_python.txt |
Q:
sparse file usage in python
I'm creating sparse files in python as follows:
>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()
when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):
igor47@piglet:~/test$ ls -lh testfile
-rw-r--r-- 1 igor47 igor... | sparse file usage in python | I'm creating sparse files in python as follows:
>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()
when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):
igor47@piglet:~/test$ ls -lh testfile
-rw-r--r-- 1 igor47 igor47 1000K 2010-07-09 04:02 testfil... | [
">>> os.stat('testfile').st_blocks*512\n0\n\nTadaa :)\nst_blocks is the number of 512-byte blocks actually allocated to the file. Note that st_blocks is not guaranteed to be present in all operating systems, but those that support sparse files generally do.\n"
] | [
18
] | [] | [] | [
"file",
"filesize",
"macos",
"python",
"sparse_file"
] | stackoverflow_0003211999_file_filesize_macos_python_sparse_file.txt |
Q:
Windows Server cannot execute a py2exe-generated app
A simple python script needs to run on a windows server with no python installed.
I used py2exe, which generated a healthy dist subdirectory, with script.exe that runs fine on the local machine.
However, when I run it on the server (Windows Server 2003 R2), it p... | Windows Server cannot execute a py2exe-generated app | A simple python script needs to run on a windows server with no python installed.
I used py2exe, which generated a healthy dist subdirectory, with script.exe that runs fine on the local machine.
However, when I run it on the server (Windows Server 2003 R2), it produces this:
The system cannot execute the specified prog... | [
"For py2exe to work, you have to include the correct version of the Microsoft C runtime DLL with your application.\nFor Python2.6, this is MSVCR90.dll version 9.0.21022.8, which can be obtained from the Microsoft Visual C++ 2008 Redistributable Package:\nhttp://www.microsoft.com/downloads/details.aspx?FamilyID=9b2d... | [
6,
2,
1,
1
] | [] | [] | [
"py2exe",
"python",
"windows"
] | stackoverflow_0001959811_py2exe_python_windows.txt |
Q:
how to find target path of link if the file is a link file
how to find if the file is a link file, and find the path of the target file (actual file pointed by the link file)
A:
os.path.islink (is it a link?) and os.path.realpath (get ultimate pointed to path, regardless of whether it's a link).
If os.path.islin... | how to find target path of link if the file is a link file | how to find if the file is a link file, and find the path of the target file (actual file pointed by the link file)
| [
"os.path.islink (is it a link?) and os.path.realpath (get ultimate pointed to path, regardless of whether it's a link).\nIf os.path.islink is True, and you only want to follow the first link, use os.readlink.\n",
"Use os.lstat(), then inspect the st_mode field.\n"
] | [
33,
0
] | [] | [] | [
"file",
"hyperlink",
"python"
] | stackoverflow_0003212712_file_hyperlink_python.txt |
Q:
generating equation representations in python/on the web
Is it possible to take something like x^2+5 and have it generate this: http://imgur.com/Muq2X.gif
I'll be using Python so anything based in Python would work, but I'm open to other solutions such as latex output.
A:
Sympy can output LaTeX code and MathML, ... | generating equation representations in python/on the web | Is it possible to take something like x^2+5 and have it generate this: http://imgur.com/Muq2X.gif
I'll be using Python so anything based in Python would work, but I'm open to other solutions such as latex output.
| [
"Sympy can output LaTeX code and MathML, from there you can create images or other forms of display, depending on what exactly you need. You'll find some methods for that in this old StackOverflow question.\nIn theory, MathML would be ideal to display equations in a browser, but not all browsers support MathML.\n",... | [
3,
2,
1
] | [] | [] | [
"equations",
"latex",
"math",
"python"
] | stackoverflow_0003212367_equations_latex_math_python.txt |
Q:
wx.CreateStatusBar() without the resize handle
I am creating a wx.Frame that cannot be resized.
How do I disable the size grip at the right side of a status bar?
Quoting http://docs.wxwidgets.org/2.6/wx_wxstatusbar.html#wxstatusbar :
Window styles
wxST_SIZEGRIP -- On Windows 95, displays a gripper at right-hand... | wx.CreateStatusBar() without the resize handle | I am creating a wx.Frame that cannot be resized.
How do I disable the size grip at the right side of a status bar?
Quoting http://docs.wxwidgets.org/2.6/wx_wxstatusbar.html#wxstatusbar :
Window styles
wxST_SIZEGRIP -- On Windows 95, displays a gripper at right-hand side of the status bar.
Translating to wxPython, i... | [
"Instead of setting style later, set it at creation time e.g.\nstatusBar = self.CreateStatusBar(style=0)\n\nYou may try other styles for statusbar if they exist.\n"
] | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003211615_python_wxpython.txt |
Q:
python.exe is getting crashed at time of frame close
I am making an application using wxpython in which i have imported some modules and added the some widgets but when i am closing the application window ie Frame(wxFrame) python.exe getting crashed and showing the following message "python.exe get encountered a ... | python.exe is getting crashed at time of frame close | I am making an application using wxpython in which i have imported some modules and added the some widgets but when i am closing the application window ie Frame(wxFrame) python.exe getting crashed and showing the following message "python.exe get encountered a problem and need to be close... Tell microsoft donttell sm... | [
"Start debugging it, and see where it crashes. If you are not familiar with pdb or such debugger try print statements to pinpoint the location where it crashes, once you are sure what code crashes may be we can help then.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003211613_python.txt |
Q:
conditionally including queries in an advanced query in zope
I'm building a quite thorough searching mechanism for a zope site. There are lots of different ways of searching, and because it might want to search for multiple values on the same index (and match all of them) I need to do it using AdvanceQuery. I've b... | conditionally including queries in an advanced query in zope | I'm building a quite thorough searching mechanism for a zope site. There are lots of different ways of searching, and because it might want to search for multiple values on the same index (and match all of them) I need to do it using AdvanceQuery. I've built my queries like this:
if self.text():
text_query = And()
... | [
"As I said in the comment, using the &= within the if statement seems to do the trick\n"
] | [
0
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0003212303_python_zope.txt |
Q:
Numpy transpose multiplication problem
I tried to find the eigenvalues of a matrix multiplied by its transpose but I couldn't do it using numpy.
testmatrix = numpy.array([[1,2],[3,4],[5,6],[7,8]])
prod = testmatrix * testmatrix.T
print eig(prod)
I expected to get the following result for the product:
5 11 1... | Numpy transpose multiplication problem | I tried to find the eigenvalues of a matrix multiplied by its transpose but I couldn't do it using numpy.
testmatrix = numpy.array([[1,2],[3,4],[5,6],[7,8]])
prod = testmatrix * testmatrix.T
print eig(prod)
I expected to get the following result for the product:
5 11 17 23
11 25 39 53
17 39 61 ... | [
"You might find this tutorial useful since you know MATLAB.\nAlso, try multiplying testmatrix with the dot() function, i.e. numpy.dot(testmatrix,testmatrix.T)\nApparently numpy.dot is used between arrays for matrix multiplication! The * operator is for element-wise multiplication (.* in MATLAB).\n",
"You're using... | [
27,
8
] | [] | [] | [
"eigenvalue",
"numpy",
"python",
"scipy"
] | stackoverflow_0003213105_eigenvalue_numpy_python_scipy.txt |
Q:
Django: ImportError: No module named ?z?
Hi I am trying to deploy a django app with uwsgi. I keep getting Import Errors that look like this:
ImportError: No module named ?z?
-or-
ImportError: No module named ?j?
-or-
ImportError: No module named `?6
So basically the output of the module seems like gibberish and I ... | Django: ImportError: No module named ?z? | Hi I am trying to deploy a django app with uwsgi. I keep getting Import Errors that look like this:
ImportError: No module named ?z?
-or-
ImportError: No module named ?j?
-or-
ImportError: No module named `?6
So basically the output of the module seems like gibberish and I am unable to figure out the problem. Does anyb... | [
"Seems like you have missed a comma in the settings.INSTALLED_APPS, after the app name. Go, check!\n"
] | [
1
] | [] | [] | [
"django",
"importerror",
"python",
"uwsgi"
] | stackoverflow_0003212396_django_importerror_python_uwsgi.txt |
Q:
Case-insensitive query that supports multiple search words
I'm trying to perform a case-insensitive query. I would generally use __icontains, but since it doesn't support the .split() method, I'm stuck to using __in instead:
def search(request):
query = request.GET.get('q', '')
query = query.lower()
p... | Case-insensitive query that supports multiple search words | I'm trying to perform a case-insensitive query. I would generally use __icontains, but since it doesn't support the .split() method, I'm stuck to using __in instead:
def search(request):
query = request.GET.get('q', '')
query = query.lower()
product_results = []
category_results = []
if query:
... | [
"I have solved this problem by using exec to generate code from a string using icontains instead of in. I admit, it's sloppy and not elegant, and should be audited for security but it worked.\nsee the untested/pseudocode:\nquery = \"product_results = Product.objects.filter(\"\nfor word in words:\n query += \"Q... | [
1,
1
] | [] | [] | [
"case_sensitive",
"django",
"python"
] | stackoverflow_0003213284_case_sensitive_django_python.txt |
Q:
Many-to-many relationships in Google AppEngine - efficient?
I'm using Google Appengine to store a list of favorites, linking a Facebook UserID to one or more IDs from Bing. I need function calls returning the number of users who have favorited an item, and the number of times an item has been favorited (and by who... | Many-to-many relationships in Google AppEngine - efficient? | I'm using Google Appengine to store a list of favorites, linking a Facebook UserID to one or more IDs from Bing. I need function calls returning the number of users who have favorited an item, and the number of times an item has been favorited (and by whom).
My question is, should I resolve this relationship into two t... | [
"I don't think there's a hard and fast answer to questions like this. \"Is this optimization worth it\" always depends on many variables such as, is the lack of optimization actually a problem to start with? How much of a problem is it? What's the cost in terms of extra time and effort and risk of bugs of a more co... | [
0
] | [] | [] | [
"google_app_engine",
"many_to_many",
"performance",
"python"
] | stackoverflow_0003210994_google_app_engine_many_to_many_performance_python.txt |
Q:
form.cleaned_data as a dictionary
Why when I call a function like this :
function(request, **form.cleaned_data)
I can send form's data as a dictionary, but when I try doing like this :
data = **form.cleaned_data
I'm getting error ?
A:
The ** trick only works when a dictionary is expanded in a function call; yo... | form.cleaned_data as a dictionary | Why when I call a function like this :
function(request, **form.cleaned_data)
I can send form's data as a dictionary, but when I try doing like this :
data = **form.cleaned_data
I'm getting error ?
| [
"The ** trick only works when a dictionary is expanded in a function call; you can't use it outside of a function call.\n"
] | [
2
] | [] | [] | [
"dictionary",
"django",
"django_forms",
"keyword_argument",
"python"
] | stackoverflow_0003213881_dictionary_django_django_forms_keyword_argument_python.txt |
Q:
Unknown Python Syntax
I've found the following syntax in a python file:
units = (
(100, 1 << 30, _('%.0f GB')),
(10, 1 << 30, _('%.1f GB')),
(1, 1 << 30, _('%.2f GB')),
(100, 1 << 20, _('%.0f MB')),
(10, 1 << 20, _('%.1f MB')),
(1, 1 << 20, _('%.2f MB')),
(1... | Unknown Python Syntax | I've found the following syntax in a python file:
units = (
(100, 1 << 30, _('%.0f GB')),
(10, 1 << 30, _('%.1f GB')),
(1, 1 << 30, _('%.2f GB')),
(100, 1 << 20, _('%.0f MB')),
(10, 1 << 20, _('%.1f MB')),
(1, 1 << 20, _('%.2f MB')),
(100, 1 << 10, _('%.0f KB')),... | [
"Underscore is a valid variable name, so you have to look at the context of your example code. Obviously the underscore is a method which has been defined somewhere else. Usually it's used for translation stuff or similar things.\n",
"As said in other answers, _ is a valid name for a Python function. It's probabl... | [
4,
3,
3,
2,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003212819_python_syntax.txt |
Q:
How to retrieve a time stamp with the right formatting from a sql database using python
I want to retrieve a time stamp from a sql database with proper formatting. This is the partial code I am using:
import MySQLdb
def connectDB(self):
global cursor
DATABASE = MySQLdb.connect(
host = self.HOST... | How to retrieve a time stamp with the right formatting from a sql database using python | I want to retrieve a time stamp from a sql database with proper formatting. This is the partial code I am using:
import MySQLdb
def connectDB(self):
global cursor
DATABASE = MySQLdb.connect(
host = self.HOST,
user = self.USER,
passwd = self.PASS,
db = self.DB,
... | [
"You could use the DATE_FORMAT mysql function, though this is no easier than doing it on the Python side. In fact, it is much more limited, because fetchone returns a Python string instead of a datetime object.\nsql = \"SELECT DATE_FORMAT(timestamp,\"%Y-%m-%d %k:%i\") FROM dataset Limit 0,1;\"\n\ncompared to\nadat... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003214345_mysql_python.txt |
Q:
Creating square subplots (of equal height and width) in matplotlib
When I run this code
from pylab import *
figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
I get two subplots which are "squished" in the X-dimension. How do I get... | Creating square subplots (of equal height and width) in matplotlib | When I run this code
from pylab import *
figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
I get two subplots which are "squished" in the X-dimension. How do I get these subplots such that the height of the Y-axis equals the width of t... | [
"Your problem in setting the aspect of the plots is coming in when you're using sharex and sharey. \nOne workaround is to just not used shared axes. For example, you could do this:\nfrom pylab import *\n\nfigure()\nsubplot(121, aspect='equal')\nplot([1, 2, 3], [1, 2, 3])\nsubplot(122, aspect='equal')\nplot([1, 2,... | [
25,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003207850_matplotlib_python.txt |
Q:
Python: Print in rows
Say I have a list
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
How would I print the list in rows containing 4 columns, so it would look like:
apple pear tomato bean
carrot grape
A:
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
for i in xrange(... | Python: Print in rows | Say I have a list
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
How would I print the list in rows containing 4 columns, so it would look like:
apple pear tomato bean
carrot grape
| [
"food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']\nfor i in xrange(0, len(food_list), 4):\n print '\\t'.join(food_list[i:i+4])\n\n",
"Try with this\nfood_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']\nsize = 4\ng = (food_list[i:i+size] for i in xrange(0, len(food_list), size))... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003214926_python.txt |
Q:
Matplotlib autoscale
I need to get a plot that fits the data automatically using matplotlib. This is the code I was given:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
....
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collec... | Matplotlib autoscale | I need to get a plot that fits the data automatically using matplotlib. This is the code I was given:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
....
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collection(lines)
plt.axes().set... | [
"Not sure if this what you wanted, but I can change it if this was not what you were looking for.\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\n\nimport pylab as p\n\nfig = plt.figure()\npts1 = []\npts2 = []\nfor i in range(100):\n pts1.append([i,i])\n pts2.append([-i-3,... | [
13,
1
] | [] | [] | [
"matplotlib",
"plot",
"python",
"visualization"
] | stackoverflow_0003214576_matplotlib_plot_python_visualization.txt |
Q:
lists and sublists
say i have an output of this, i think its a list
['', 'AB-a-b-c-d', 'BC-f-c-a-r', 'CD-i-s-r']
i want to make the following:
['',[AB,a,b,c,d],[BC,f,c,a,r],[CD,i,s,r]]
or
['',[AB,BC,CD],[a,b,c,d],[f,c,a,r],[i,s,r]]
A:
newlist = [item.split("-") for item in oldlist]
or (this works better beca... | lists and sublists | say i have an output of this, i think its a list
['', 'AB-a-b-c-d', 'BC-f-c-a-r', 'CD-i-s-r']
i want to make the following:
['',[AB,a,b,c,d],[BC,f,c,a,r],[CD,i,s,r]]
or
['',[AB,BC,CD],[a,b,c,d],[f,c,a,r],[i,s,r]]
| [
"newlist = [item.split(\"-\") for item in oldlist]\n\nor (this works better because the empty string is kept as is)\nnewlist = []\nfor item in oldlist:\n if not item:\n newlist.append(item)\n else:\n newlist.append(item.split(\"-\"))\n\n",
"I'll try to point you in the right direction rather t... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003215045_python.txt |
Q:
How do I debug code that segfaults unless run through gdb?
That's a single threaded code.
In particular: ahocorasick Python extension module (easy_install ahocorasick).
I isolated the problem to a trivial example:
import ahocorasick
t = ahocorasick.KeywordTree()
t.add("a")
When I run it in gdb, all is fine, same ... | How do I debug code that segfaults unless run through gdb? | That's a single threaded code.
In particular: ahocorasick Python extension module (easy_install ahocorasick).
I isolated the problem to a trivial example:
import ahocorasick
t = ahocorasick.KeywordTree()
t.add("a")
When I run it in gdb, all is fine, same happens when I enter these instructions into Python CLI. However... | [
"There are other tools you can use that will find faults that does not necessarily crash the program. \nvalgrind, electric fence, purify, coverity, and lint-like tools may be able to help you.\nYou might need to build your own python in some cases for this to be usable. Also, for memory corruption things, there is ... | [
2,
0
] | [] | [] | [
"gdb",
"python",
"segmentation_fault"
] | stackoverflow_0003211667_gdb_python_segmentation_fault.txt |
Q:
Admin site registering models
I have those models
class A(models.Model):
name = CharField(max_length=255)
class B(models.Model):
name = CharField(max_length=255)
relation = ForeignKey(A)
And I can register like this:
admin.site.register(A)
admin.site.register(B)
In /admin/ page, I can see A and B re... | Admin site registering models | I have those models
class A(models.Model):
name = CharField(max_length=255)
class B(models.Model):
name = CharField(max_length=255)
relation = ForeignKey(A)
And I can register like this:
admin.site.register(A)
admin.site.register(B)
In /admin/ page, I can see A and B registered.
and "Add B" admin page, w... | [
"relation = ForeignKey(A, null=True, blank=True) will let you save a B without needing to link it to an A. Does that help?\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003214429_django_django_models_python.txt |
Q:
Python AttributeError in using a member variable
I am having an issue with Python throwing an AttributeError on accessing a variable.
The code is below, redacted for clarity.
class mycollection(object):
"""
Collection of stuff.
"""
#"compile-time" define class variables.
__slots__ = ["stuff_li... | Python AttributeError in using a member variable | I am having an issue with Python throwing an AttributeError on accessing a variable.
The code is below, redacted for clarity.
class mycollection(object):
"""
Collection of stuff.
"""
#"compile-time" define class variables.
__slots__ = ["stuff_list"]
def __init__(self):
self.stuff_list ... | [
"__ini__ should be __init__\n",
"Wouldn't this be \"more Pythonic\"?\ncollection.stuff_list.append(test_stuff)\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003215189_python.txt |
Q:
Elegant parsing of this? "a,b,c",d,"e,f"
I'm looking to parse these kinds of strings into lists in Python:
"a,b,c",d,"e,f" => ['a','b','c'] , ['d'] , ['e','f']
"a,b,c",d,e => ['a','b','c'] , ['d'] , ['e']
a,b,"c,d,e,f" => ['a'],['b'],['c','d','e','f']
a,"b,c,d",{x(a,b,c-d)} => ['a'],... | Elegant parsing of this? "a,b,c",d,"e,f" | I'm looking to parse these kinds of strings into lists in Python:
"a,b,c",d,"e,f" => ['a','b','c'] , ['d'] , ['e','f']
"a,b,c",d,e => ['a','b','c'] , ['d'] , ['e']
a,b,"c,d,e,f" => ['a'],['b'],['c','d','e','f']
a,"b,c,d",{x(a,b,c-d)} => ['a'],['b','c','d'],[('x',['a'],['b'],['c-d'])]
It ... | [
"So, here you are, your \"honest python parser\". Coding for you rather than answering the question, but I will be fine if you put it to use :-) \nQUOTE = '\"'\nSEP = ',(){}\"'\nS_BRACKET = '{'\nE_BRACKET = '}'\nS_PAREN = '('\n\ndef parse_plain(string):\n counter = 0\n token = \"\"\n while counter<len(str... | [
2,
0
] | [
"do you have quotes in strings? \nIf no - just replace control characters to make is compatible with JSON and use JSON parser\n",
"For the first three cases, you can just recursively apply the CSV reader:\nimport csv\n\ndef expand( st ):\n if \",\" not in st:\n return st\n return [ expand( col ) for ... | [
-1,
-1
] | [
"parsing",
"python",
"string"
] | stackoverflow_0003214256_parsing_python_string.txt |
Q:
Python and HTML table
I'm using the code below to print out rows containing 4 columns. How would I append each value in the list to a HTML table that also contains rows with four columns?
random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
pr... | Python and HTML table | I'm using the code below to print out rows containing 4 columns. How would I append each value in the list to a HTML table that also contains rows with four columns?
random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
print '\t'.join(food_list[i:i... | [
"With some minor modification...\nfood_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']\nfor i in xrange(0, len(food_list), 4):\n print '<tr><td>' + '</td><td>'.join(food_list[i:i+4]) + '</td></tr>'\n\nThis basically changes the delimiter to not be tab, but the table elements. Also, puts the open ... | [
3,
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003215260_html_python.txt |
Q:
subscripting a specific line from python's csv reader?
i'd like to be able to access specific lines of a csv file through the csv reader. For example, the fourth line. Is there a way to do this with python's csv reader module?
A:
You just have to parse all the CSV file, and then use normal sequencing indexing.... | subscripting a specific line from python's csv reader? | i'd like to be able to access specific lines of a csv file through the csv reader. For example, the fourth line. Is there a way to do this with python's csv reader module?
| [
"You just have to parse all the CSV file, and then use normal sequencing indexing.\nOtherwise, you can do something like this\ndef my_filter(csv_file, lines):\n for line_number, line in enumerate(csv_file):\n if line_number in lines:\n yield line\n\nmy_file = open(\"file.csv\")\nmy_reader = csv.rea... | [
4
] | [] | [] | [
"csv",
"file_io",
"python"
] | stackoverflow_0003215347_csv_file_io_python.txt |
Q:
CGI download image after generating
I have a small python cgi script that accepts an image upload from the user, converts in into a different format, and saves the new file in a temp location. I would like it to then automatically prompt the user to download the converted file. I have tried:
# image conversion s... | CGI download image after generating | I have a small python cgi script that accepts an image upload from the user, converts in into a different format, and saves the new file in a temp location. I would like it to then automatically prompt the user to download the converted file. I have tried:
# image conversion stuff....
print "Content-Type: image/eps\n... | [
"I'm not sure, but have you tried separating actual data from headers by newline? EDIT: writing print \"\\n\" outputs two newlines, so I think it should be written like that:\nprint \"Content-Type: image/eps\"\nprint \"Content-Disposition: attachment; filename=%s\" % new_filename\nprint\nprint open(converted_file_f... | [
0,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0003215623_cgi_python.txt |
Q:
Paramiko SSH exec_command (shell script) returns before completion
I launch a shell script from a remote Linux machine using Paramiko. The shell script is launched and execute a command make -j8. However the exec_command returns before the completion of the make.
If I launch the script on the local machine it exe... | Paramiko SSH exec_command (shell script) returns before completion | I launch a shell script from a remote Linux machine using Paramiko. The shell script is launched and execute a command make -j8. However the exec_command returns before the completion of the make.
If I launch the script on the local machine it executes correctly.
Could someone explain me this behaviour?
| [
"You need to wait for application to finish, exec_command isn't a blocking call.\nprint now(), \"before call\"\nstdin, stdout, sterr = ssh.exec_command(\"sleep(10)\")\nprint now(), \"after call\"\nchannel = stdout.channel\nprint now(), \"before status\"\nstatus = channel.recv_exit_status()\nprint now(), \"after sta... | [
28
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0003215727_paramiko_python_ssh.txt |
Q:
Problem with deepcopy?
Source
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
pass
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, deepcopy(attrs.pop(name))) for name, obj in attrs.... | Problem with deepcopy? | Source
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
pass
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, deepcopy(attrs.pop(name))) for name, obj in attrs.items() if isinstance(obj, F... | [
"By setting the dict fields in the metaclass, you are creating a class attribute.\nThe __new__ method you defined is only run once -- on class creation. \nUpdate\nYou should manipulate attrs in __new__ like you are, but name it something like _fields. Then create an __init__ method that performs a deepcopy into an ... | [
2,
0
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0003215363_deep_copy_python.txt |
Q:
Arguments disappear from a dictionary when passed to a function
In my function I read user's data from session and store them in a dictionary. Next I'm sending it to 'register' function from registration.backend but the function somehow get's it empty and a KeyError is thrown. Where are my data gone ? The code fro... | Arguments disappear from a dictionary when passed to a function | In my function I read user's data from session and store them in a dictionary. Next I'm sending it to 'register' function from registration.backend but the function somehow get's it empty and a KeyError is thrown. Where are my data gone ? The code from function calling 'register' function :
data = request.session['temp... | [
"Judging by the method's signature:\n\nyou need to unpack your dictionary\nyou need to pass relevant request variable\n\nSomething like this:\nbackend.register(request, **userdata)\n\nAssuming register is a method on backend instance.\n",
"No need to mess with ** in register method. What you want to do is simply ... | [
3,
3,
0
] | [] | [] | [
"dictionary",
"django",
"python",
"session"
] | stackoverflow_0003215135_dictionary_django_python_session.txt |
Q:
ImportError: [libraryname].so: undefined symbol: [function name]
I'm extending my Python program with a C module that uses the GstPhotography interface for GStreamer. My C module compiles fine, but when I try running it from Python, I get this error:
$python Program.py
Traceback (most recent call last):
File "P... | ImportError: [libraryname].so: undefined symbol: [function name] | I'm extending my Python program with a C module that uses the GstPhotography interface for GStreamer. My C module compiles fine, but when I try running it from Python, I get this error:
$python Program.py
Traceback (most recent call last):
File "Program.py", line 10, in <module>
import MyPythonClass
File "/p... | [
"It means that you didn't link against enough libraries, either because it wasn't indicated in the pkgconfig file, or you didn't refer to the pkgconfig file in the first place.\n"
] | [
0
] | [] | [] | [
"extending",
"gstreamer",
"importerror",
"python"
] | stackoverflow_0003215818_extending_gstreamer_importerror_python.txt |
Q:
(Django) object is unsubscriptable
When I'm trying to create an extended user profile I'm getting UserProfile object is unsubscriptable. I've googled for solution, but 'your object is not a sequence' does not help here much. Here's the function I'm using, 'temp_data' is the data from my registration form :
def cre... | (Django) object is unsubscriptable | When I'm trying to create an extended user profile I'm getting UserProfile object is unsubscriptable. I've googled for solution, but 'your object is not a sequence' does not help here much. Here's the function I'm using, 'temp_data' is the data from my registration form :
def create_user(request):
data = reques... | [
"data = UserProfile(user=user) rebinds data. It cannot be both the model and the session data at the same time.\n"
] | [
3
] | [] | [] | [
"django",
"object",
"python"
] | stackoverflow_0003215891_django_object_python.txt |
Q:
Python and HTML: Not all arguments converted to a string
I writing HTML to a text file which is then read by the browser, but I get an error stating "not all arguments converted during string formatting"
But i can't see hwere im going wrong.
z.write('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>' %... | Python and HTML: Not all arguments converted to a string | I writing HTML to a text file which is then read by the browser, but I get an error stating "not all arguments converted during string formatting"
But i can't see hwere im going wrong.
z.write('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>' % k)
| [
"You're missing parentheses:\nz.write(('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k)\n\nBut it would be better not to mix concatenation and formatting. So consider:\n'<td><a href=/Plone/query/species_strain?species=%(k)s>%(k)s</td>' % {'k': k}\n\nYou might want to generate HTML using a dedi... | [
4,
4,
0,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003216150_html_python.txt |
Q:
I'm running nginx with fastcgi, is that all I need to serve python apps also?
I'm running ubuntu with nginx with fastcgi, is that all I need to serve python apps also?
A:
You'll probably also need flup to bridge wsgi and fcgi. You obviously need Python, and whatever libraries your app depends upon. Likely need... | I'm running nginx with fastcgi, is that all I need to serve python apps also? | I'm running ubuntu with nginx with fastcgi, is that all I need to serve python apps also?
| [
"You'll probably also need flup to bridge wsgi and fcgi. You obviously need Python, and whatever libraries your app depends upon. Likely need a database and the appropriate connectors as well, but that should all be in the documentation of whatever project you're trying to host (or framework you're using to write... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003216222_python.txt |
Q:
MySQLdb Handle Row Lock
I'm using MySQLdb and when I perform an UPDATE to a table row I sometimes get an infinite process hang.
At first I thought, maybe its COMMIT since the table is Innodb, but even with autocommit(True) and db.commit() after each update I still get the hang.
Is it possible there is a row lock a... | MySQLdb Handle Row Lock | I'm using MySQLdb and when I perform an UPDATE to a table row I sometimes get an infinite process hang.
At first I thought, maybe its COMMIT since the table is Innodb, but even with autocommit(True) and db.commit() after each update I still get the hang.
Is it possible there is a row lock and the query just fails to ca... | [
"Depending on your user privileges, you can execute SHOW PROCESSLIST or SELECT from information_schema.processlist while the UPDATE hangs to see if there is a contention issue with another query. Also do an EXPLAIN on a SELECT of the WHERE clause used in the UPDATE to see if you need to change the statement. \nIf... | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003216027_mysql_python.txt |
Q:
Entering precise degrees into python
What is the standard way to enter degrees into python? My total station gives degrees in degree-minute-second format. I could write a function to convert this to a decimal degree but I would like to know if there is a common way to do this that I am unaware of.
-Chris
A:
Chri... | Entering precise degrees into python | What is the standard way to enter degrees into python? My total station gives degrees in degree-minute-second format. I could write a function to convert this to a decimal degree but I would like to know if there is a common way to do this that I am unaware of.
-Chris
| [
"Chris: not likely.\nSince you need radians, anyway, this should od the trick:\nimport math\ndef radians_from_triple(deg, min=0, sec=0):\n return math.radians(deg + min * 60 ** -1 + sec * 60 ** -2)\n\n",
"Python uses radians, as a float.\nThere is no specific \"angle\" type, although you can write one yourself... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003216654_python.txt |
Q:
lists and sublists
i use this code to split a data to make a list with three sublists.
to split when there is * or -. but it also reads the the \n\n *.. dont know why?
i dont want to read those? can some one tell me what im doing wrong?
this is the data
*Quote of the Day
-Education is the ability to listen to almo... | lists and sublists | i use this code to split a data to make a list with three sublists.
to split when there is * or -. but it also reads the the \n\n *.. dont know why?
i dont want to read those? can some one tell me what im doing wrong?
this is the data
*Quote of the Day
-Education is the ability to listen to almost anything without losi... | [
"The \"\\n\\n\" is part of the input data, so it's preserved in python. Just add a strip() to remove it:\nfinallist = [item.strip() for item in newlist]\n\nSee the strip() docs: http://docs.python.org/library/stdtypes.html#str.strip\nUPDATED FROM COMMENT:\nfinallist = [item.replace(\"\\\\n\", \"\\n\").strip() for i... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003216238_python.txt |
Q:
Django: How do I get every table and all of that table's columns in a project?
I'm creating a set of SQL full database copy scripts using MySQL's INTO OUTFILE and LOAD DATA LOCAL INFILE.
Specifically:
SELECT {columns} FROM {table} INTO OUTFILE '{table}.csv'
LOAD DATA LOCAL INFILE '{table}.csv' REPLACE INTO {table... | Django: How do I get every table and all of that table's columns in a project? | I'm creating a set of SQL full database copy scripts using MySQL's INTO OUTFILE and LOAD DATA LOCAL INFILE.
Specifically:
SELECT {columns} FROM {table} INTO OUTFILE '{table}.csv'
LOAD DATA LOCAL INFILE '{table}.csv' REPLACE INTO {table} {columns}
Because of this, I don't need just the tables, I also need the columns ... | [
"Have you taken a look at manage.py ?\nYou can get boatloads of SQL information, for example to get all the create table syntax for an app within your project you can do:\npython manage.py sqlall <appname>\n\nIf you type:\npython manage.py help\n\nYou can see a ton of other features.\n",
"I dug in to the source t... | [
5,
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003207859_django_python.txt |
Q:
(How) Can I use string substitution for working w/ Django’s i18n {% trans %} tag?
I'm looking for something like this:
{% trans "There are %{flowers}n flowers in the vase" < flowers:3 %}
Now obviously syntax is fake, but it should be sufficient to demonstrate what I'm looking for.
Should I cook something of my o... | (How) Can I use string substitution for working w/ Django’s i18n {% trans %} tag? | I'm looking for something like this:
{% trans "There are %{flowers}n flowers in the vase" < flowers:3 %}
Now obviously syntax is fake, but it should be sufficient to demonstrate what I'm looking for.
Should I cook something of my own? It looks like a common usecase, so I was quite surprised that quick web search didn... | [
"I'm not absolutely sure what you're trying to do (what's < flowers:3 supposed to do?), but have you looked at blocktrans?\n{% blocktrans count flowers|length as counter %}\n There is one flower in the vase.\n{% plural %}\n There are {{ counter }} flowers in the vase.\n{% endblocktrans %}\n\n",
"Use {% bloc... | [
3,
1,
0
] | [] | [] | [
"django",
"formatting",
"internationalization",
"python",
"templates"
] | stackoverflow_0002337077_django_formatting_internationalization_python_templates.txt |
Q:
Vim's omnicompletion fails with "from" imports in Python
Omnicompletion for Python seems to fail when there is a "from" import instead of a normal one.
For example, if I have these two files:
Test.py:
class Test:
def method(self):
pass
main.py:
from Test import Test
class Test2:
def __init__(self... | Vim's omnicompletion fails with "from" imports in Python | Omnicompletion for Python seems to fail when there is a "from" import instead of a normal one.
For example, if I have these two files:
Test.py:
class Test:
def method(self):
pass
main.py:
from Test import Test
class Test2:
def __init__(self):
self.x = Test()
If I try to activate omnicompletion... | [
"update: ooh, so I checked your example, and I get completion for\nx = Test()\nx.<C-x><C-o>\n\nbut not\no = object()\no.x = Test()\no.x.<C-x><C-o>\n\n...I'm gonna do some digging\nupdate 2: revenge of Dr. Strangelove\nand...this is where it get's weird.\nfrom StringIO import StringIO\nclass M:\n pass\ns = M()\ns... | [
2
] | [] | [] | [
"import",
"omnicomplete",
"python",
"vim"
] | stackoverflow_0003213129_import_omnicomplete_python_vim.txt |
Q:
Python: No csv.close()?
I'm using the CSV module to read a tab delimited file. Code below:
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
z.close()
So how do i c... | Python: No csv.close()? | I'm using the CSV module to read a tab delimited file. Code below:
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
z.close()
So how do i close "Z"?
| [
"The reader is really just a parser. When you ask it for a line of data, it delegates the reading action to the underlying file object and just converts the result into a set of fields. The reader itself doesn't manage any resources that would need to be cleaned up when you're done using it, so there's no need to c... | [
65,
39,
8
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003216954_csv_python.txt |
Q:
Why am I getting this error when I try writing a client for soaplib?
Traceback (most recent call last):
File "", line 1, in
NameError: name 'HelloWorldService' is not defined
I am following the example at http://github.com/jkp/soaplib by writing the following code:
from soaplib.client import make_service_clien... | Why am I getting this error when I try writing a client for soaplib? | Traceback (most recent call last):
File "", line 1, in
NameError: name 'HelloWorldService' is not defined
I am following the example at http://github.com/jkp/soaplib by writing the following code:
from soaplib.client import make_service_client
client = make_service_client('http://localhost:7789/',HelloWorldService(... | [
"You're neglecting the paragraph after that code snippet:\n\nAs in this case, the stub can be the instance of the remote functionality, however the requirements are that it just have the same method signatures and definitions as the server implementation.\n\nYou need to add a stub to your project that simulates the... | [
1
] | [] | [] | [
"python",
"web_services"
] | stackoverflow_0003217098_python_web_services.txt |
Q:
How can I improve this number2words script
import sys
words = {
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten',
11 : 'eleven',
12 : 'twelve',
13 : 'thirteen',
14 : 'fourteen',
15 : '... | How can I improve this number2words script | import sys
words = {
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten',
11 : 'eleven',
12 : 'twelve',
13 : 'thirteen',
14 : 'fourteen',
15 : 'fifteen',
16 : 'sixteen',
17 : 'seventee... | [
"Two improvements come to mind:\n\n40 is spelled \"forty\", not \"fourty\"\nyour program needs unit tests\n\nHave a look at the Python doctest and unittest modules.\n",
"You can't group digits into \"segments\" going from left-to-right. The range(0,len(),3) is not going to work out well. You'll have to write t... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000289735_python.txt |
Q:
Python "draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)"
This is a class I made using Python with pyglet to display a window.
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
pyglet.text.Label("Prototype"... | Python "draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)" | This is a class I made using Python with pyglet to display a window.
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
pyglet.text.Label("Prototype")
windowText = text.Label.draw(Window, "Hello World",
font_name = "Times New Ro... | [
"If I had to guess, I'd say that you should bind the instance you create 2 lines above and use that instead.\n mylabel = pyglet.text.Label(\"Prototype\")\n\n windowText = mylabel.draw(...\n\n",
"you give a class \"Window\" instead of an instance as argument, try \"self\"\n"
] | [
2,
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0003030348_pyglet_python.txt |
Q:
How to get root premissions for my app?
My app needs to do some privileged work. I've been looking everywhere, but I can't find anything useful. I know I want to use Policykit1 and dbus because all the other alternatives I've found aren't used anymore.
This is the code I got so far:
import dbus
import os
bus = db... | How to get root premissions for my app? | My app needs to do some privileged work. I've been looking everywhere, but I can't find anything useful. I know I want to use Policykit1 and dbus because all the other alternatives I've found aren't used anymore.
This is the code I got so far:
import dbus
import os
bus = dbus.SystemBus()
proxy = bus.get_object('org.fr... | [
"Filesystem security is stopping you because your user doesn't have write permissions to /usr/local/share/somefolder. You could use sudo to temporarily escalate permissions for that directory creation. But it doesn't stop there if you need to perform more operations as superuser. \nIf you need to write to somethin... | [
1
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0003217420_dbus_linux_python.txt |
Q:
Is it possible to use soaplib server with Apache?
Almost every documentation I am seeing shows Soaplib servers to be deployed using Cherry Py or some other server. Instead of that can be be deployed using apache?
Thanks
A:
soaplib makes its servers be WSGI applications, so they can be deployed in any WSGI enviro... | Is it possible to use soaplib server with Apache? | Almost every documentation I am seeing shows Soaplib servers to be deployed using Cherry Py or some other server. Instead of that can be be deployed using apache?
Thanks
| [
"soaplib makes its servers be WSGI applications, so they can be deployed in any WSGI environment. Best way to use WSGI on Apache is mod_wsgi.\n"
] | [
3
] | [] | [] | [
"python",
"soaplib",
"web_services"
] | stackoverflow_0003216924_python_soaplib_web_services.txt |
Q:
Using Suds for SOAP in python, are suds.client.Client objects thread safe?
I'm using Suds to access a SOAP web service from python. If I have multiple threading.Thread threads of execution, can each of them safely access the same suds.client.Client instance concurrently, or must I create separate Client objects f... | Using Suds for SOAP in python, are suds.client.Client objects thread safe? | I'm using Suds to access a SOAP web service from python. If I have multiple threading.Thread threads of execution, can each of them safely access the same suds.client.Client instance concurrently, or must I create separate Client objects for each thread?
| [
"As far as I know they are NOT thread safe. You could safely use the same client object so long as you are using a queue or thread pool. That way when one thread is done with the client, the next one can use it.\nFor network-based events however, you should probably ask yourself which is better. Threading or asyn... | [
2
] | [] | [] | [
"multithreading",
"python",
"soap",
"suds"
] | stackoverflow_0002991864_multithreading_python_soap_suds.txt |
Q:
Writing a 'print' function in Python
I want to create a function that works like the build-in print function in Python:
print 'test', i, 'started'
So a call like this should work:
log('test', i, 'started)
The log function should call the logging.info() function (from the Python logging module). How can I create ... | Writing a 'print' function in Python | I want to create a function that works like the build-in print function in Python:
print 'test', i, 'started'
So a call like this should work:
log('test', i, 'started)
The log function should call the logging.info() function (from the Python logging module). How can I create such a function?
This is my first try:
im... | [
"This works:\ndef log(*args):\n logging.info(' '.join(map(str, args)))\n\n",
"You can do this kind of thing:\ndef log(*args):\n logging.info(' '.join(args))\n\n",
"Define a function that takes a variable number of arguments, you can operate on the parameter list args to print it how you'd like:\n>>> def log... | [
7,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0003212938_arguments_python.txt |
Q:
Python signals hosted on WSGI
I'm using the python signals library to kill a function if it runs longer than a set period of time.
It works well in my tests but when hosted on the server I get the following error
"signal only works in main thread"
I have set the WSGI signals restriction to be off in my httpd.conf
... | Python signals hosted on WSGI | I'm using the python signals library to kill a function if it runs longer than a set period of time.
It works well in my tests but when hosted on the server I get the following error
"signal only works in main thread"
I have set the WSGI signals restriction to be off in my httpd.conf
WSGIRestrictSignal Off
as described... | [
"The only time any code under Apache/mod_wsgi runs as main thread is when a WSGI script file is being imported via WSGIImportScript or equivalent methods. Although one could use that method to register the signal handler from the main thread, it will be of no use as all subsequent requests are serviced via secondar... | [
1
] | [] | [] | [
"mod_wsgi",
"python",
"signals"
] | stackoverflow_0003208577_mod_wsgi_python_signals.txt |
Q:
Matplotlib: move graph to the right
I have two graphs with in one image, each with 5 points. Their value on the X axis is not important, all that I require is that they're all equally distributed on it.
import matplotlib.pyplot as plt
data = [43,51,44,73,60]
data2 = [34,25,42,53,61]
fig = plt.figure(1)
ax = fig.... | Matplotlib: move graph to the right | I have two graphs with in one image, each with 5 points. Their value on the X axis is not important, all that I require is that they're all equally distributed on it.
import matplotlib.pyplot as plt
data = [43,51,44,73,60]
data2 = [34,25,42,53,61]
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(data, '-o', co... | [
"Make a list of the X values,\nx = [5,6,7,8,9]\n\nand use\nax.plot(x, data2, ...)\n\nNote that you could also use range(5,10) or numpy's arange(5,10) or linspace(5,9,5) to generate the X values.\n"
] | [
1
] | [] | [] | [
"graph",
"matplotlib",
"python"
] | stackoverflow_0003217715_graph_matplotlib_python.txt |
Q:
sql server function native parameter bind error
I'm using the following software stack on Ubuntu 10.04 Lucid LTS to
connect to a database:
python 2.6.5 (ubuntu package)
pyodbc git trunk commit eb545758079a743b2e809e2e219c8848bc6256b2
unixodbc 2.2.11 (ubuntu package)
freetds 0.82 (ubuntu package)
Windows with Mic... | sql server function native parameter bind error | I'm using the following software stack on Ubuntu 10.04 Lucid LTS to
connect to a database:
python 2.6.5 (ubuntu package)
pyodbc git trunk commit eb545758079a743b2e809e2e219c8848bc6256b2
unixodbc 2.2.11 (ubuntu package)
freetds 0.82 (ubuntu package)
Windows with Microsoft SQL Server 2000 (8.0)
I get this error when t... | [
"Ultimately, this probably isn't the answer you're looking for, but when I had to connect to MSSQL from Perl two or three years ago, ODBC + FreeTDS was initially involved, and I didn't get anywhere with it (though I don't recall the specific errors, I was trying to do binding, though, and it seemed the source of so... | [
0
] | [] | [] | [
"freetds",
"pyodbc",
"python",
"sql_server",
"unixodbc"
] | stackoverflow_0003143704_freetds_pyodbc_python_sql_server_unixodbc.txt |
Q:
Scapy SYN send on our own IP address
I tried to send SYN packets on my local network and monitoring them with Wireshark and everything works just fine, except when i try to send a packet to my own ip address it "seems" to work because it says Sent 1 packet, but it is not really sent, i can't see the packet in Wire... | Scapy SYN send on our own IP address | I tried to send SYN packets on my local network and monitoring them with Wireshark and everything works just fine, except when i try to send a packet to my own ip address it "seems" to work because it says Sent 1 packet, but it is not really sent, i can't see the packet in Wireshark nor any answers to the packet. My se... | [
"What network device(s) is your Wireshark installation listening on? I suspect it's listening on the actual network card (ethernet, wifi, or otherwise, as per the Wireshark FAQ) -- and when sending from a computer to itself the OS can of course bypass the device (why bother with it?) and just do the \"sending\" by... | [
2
] | [] | [] | [
"generator",
"packet",
"python",
"scapy",
"send"
] | stackoverflow_0003217486_generator_packet_python_scapy_send.txt |
Q:
How to add __iter__ to dynamic type?
Source
def flags(*opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
attrs = dict(zip(keys,nums))
choices = iter(zip(nums,words))
return type('Flags', (), dict(attrs))
Abilities = flags(
('FLY', '... | How to add __iter__ to dynamic type? | Source
def flags(*opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
attrs = dict(zip(keys,nums))
choices = iter(zip(nums,words))
return type('Flags', (), dict(attrs))
Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fir... | [
"There's no need to use a dynamic type here; I'd restructure this as a simple class, for example:\nclass flags(object):\n def __init__(self, *opts):\n keys = [t[0] for t in opts]\n words = [t[1] for t in opts]\n nums = [2**i for i in range(len(opts))]\n self.attrs = dict(zip(keys,nums... | [
4,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003217768_python.txt |
Q:
Still wondering about directed graphs drawn from AppEngine
With reference to another case of pretty much the same question I have, Brightside asked:
Library to render Directed Graphs (similar to graphviz) on Google App Engine
The accepted answer was "canvis", which looks very cool from a rendering perspective, but... | Still wondering about directed graphs drawn from AppEngine | With reference to another case of pretty much the same question I have, Brightside asked:
Library to render Directed Graphs (similar to graphviz) on Google App Engine
The accepted answer was "canvis", which looks very cool from a rendering perspective, but canvis just does the drawing. It still needs to call graphvis b... | [
"Canvis doesn't call graphviz itself - it renders xdot directly in the browser. Of course you still have to have some way to generate xdot files, but canvis doesn't care where they come from.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"graphviz",
"python"
] | stackoverflow_0003217536_google_app_engine_graphviz_python.txt |
Q:
Socket in python will only send data it receives
I must be missing something in the code. I've rewritten an 'echo server' example to do a bit more when it receives something.
This is how it currently looks:
#!/usr/bin/env python
import select
import socket
import sys
import threading
import time
import Queue
gl... | Socket in python will only send data it receives | I must be missing something in the code. I've rewritten an 'echo server' example to do a bit more when it receives something.
This is how it currently looks:
#!/usr/bin/env python
import select
import socket
import sys
import threading
import time
import Queue
globuser = {}
queue = Queue.Queue()
class Server:
d... | [
"Here's a cleaned-up, functional version of your code! I tested it myself, though I didn't write unit tests.\nThere were some syntax errors and other miscellaneous problems with the \noriginal code, so I took some liberties. I'm assuming that the protocol is \nframed by using ; as a delimiter, since a ; is sent at ... | [
2
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003216577_python_sockets.txt |
Q:
Python list initialization (by ref problem)
I have some simple code that represents a graph using a square boolean matrix where rows/columns are nodes and true represents an undirected link between two nodes. I am initializing this matrix with False values and then setting the value to True where a link exists.
I... | Python list initialization (by ref problem) | I have some simple code that represents a graph using a square boolean matrix where rows/columns are nodes and true represents an undirected link between two nodes. I am initializing this matrix with False values and then setting the value to True where a link exists.
I believe the way I am initializing the list is ca... | [
"Actually, you've slightly misunderstood the problem. You believe that the boolean references are shared (this is true, but not important-- booleans are immutable, so sharing references to the same object doesn't mean much). What's happened is that the list references are shared, and that's caused your troubles. Le... | [
5,
1
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0003218136_arrays_list_python.txt |
Q:
Import large chunk of data into Google App Engine Data Store at one go
I have a large CSV file, approx 10 MB in size, which contains all the data which need to be imported in the Google App Engine DataStore.
I tried following approaches to perform import but all the times it failed in half way.
Import using map... | Import large chunk of data into Google App Engine Data Store at one go | I have a large CSV file, approx 10 MB in size, which contains all the data which need to be imported in the Google App Engine DataStore.
I tried following approaches to perform import but all the times it failed in half way.
Import using mapping a command to url and then executing url, failed because of request time... | [
"you can post row by row. using built in bulk loader.\nhttp://code.google.com/appengine/docs/python/tools/uploadingdata.html\nthis is good article. \nand here is my contactloader.py that i used 2 years ago for reference. it is more sophisticated since last i used but still.....\nimport datetime\nfrom google.appengi... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003218220_google_app_engine_google_cloud_datastore_python.txt |
Q:
Using other languages with ruby
Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff ... | Using other languages with ruby | Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff and probably get the data from DB, ca... | [
"If you are offloading work to an exterior process, you may want to make this a webservice (ajax, perhaps) of some sort so that you have some sort of consistent interface.\nOtherwise, you could always execute the python script in a subshell through ruby, using stdin/stdout/argv, but this can get ugly quick.\n",
"... | [
4,
2,
1,
1
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003215455_python_ruby_ruby_on_rails.txt |
Q:
How do I execute Python/bash code in the current directory as part of a code?
Lets say I am designing a tool foobuzzle (foobuzzle's exact job is to set up SRPM files for cross-compiling a variety of codes into their own compartmentalized prefix directories, but this is not important). I would like foobuzzle to ta... | How do I execute Python/bash code in the current directory as part of a code? | Lets say I am designing a tool foobuzzle (foobuzzle's exact job is to set up SRPM files for cross-compiling a variety of codes into their own compartmentalized prefix directories, but this is not important). I would like foobuzzle to take in an input file (buzzle_input) specified by an (intelligent, code-savvy) client... | [
"My interpretation of your context, is that you have a Python script that performs various make- or autoconf-like operations, and you want to allow clients to write their own Makefiles for Foobuzzle.\nThe problem with directories I don't understand. import will always search the local directory? And you can os.chdi... | [
1
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0003218599_bash_python.txt |
Q:
How to use SQLAlchemy to dump an SQL file from query expressions to bulk-insert into a DBMS?
Please bear with me as I explain the problem, how I tried to solve it,
and my question on how to improve it is at the end.
I have a 100,000 line csv file from an offline batch job and I needed to
insert it into the databas... | How to use SQLAlchemy to dump an SQL file from query expressions to bulk-insert into a DBMS? | Please bear with me as I explain the problem, how I tried to solve it,
and my question on how to improve it is at the end.
I have a 100,000 line csv file from an offline batch job and I needed to
insert it into the database as its proper models. Ordinarily, if this is a fairly straight-forward load, this can be trivial... | [
"Ordinarily, no, there's no way to get the query with the values included.\nWhat database are you using though? Cause a lot of databases do have some bulk load feature for CSV available.\n\nPostgres: http://www.postgresql.org/docs/8.4/static/sql-copy.html\nMySQL: http://dev.mysql.com/doc/refman/5.1/en/load-data.htm... | [
3,
2,
0
] | [] | [] | [
"bulkinsert",
"orm",
"performance",
"python",
"sqlalchemy"
] | stackoverflow_0002880517_bulkinsert_orm_performance_python_sqlalchemy.txt |
Q:
Python function implementations
I've seen various answers to the ball collision detection question explaining why sqrt operations are slow, why absolute value operations are fast on floating ponts etc. How can I find out which operations are expensive and which are not?
Basically, I'm looking for a resource where ... | Python function implementations | I've seen various answers to the ball collision detection question explaining why sqrt operations are slow, why absolute value operations are fast on floating ponts etc. How can I find out which operations are expensive and which are not?
Basically, I'm looking for a resource where I can learn about the implementation ... | [
"Python is, like any language, translated to machine code and then run. So yes, they could be talking about low-level implementation details.\nAnyway, the best way to learn about speed implementation of the various Python functions is taking a look in the source code.\nHave fun! \nEDIT: This tip actually applies to... | [
2,
1,
1,
0
] | [] | [] | [
"implementation",
"performance",
"python"
] | stackoverflow_0003216504_implementation_performance_python.txt |
Q:
Binding a list of strings to an IN clause
Possible Duplicate:
python list in sql query as parameter
Consider this (using apsw here):
s = ["A", "B", "C"]
c.execute("SELECT foo.y FROM foo WHERE foo.x in (?)", (s, ))
This doesn't work, because a binding parameter cannot be a list. I want to bind a list of strings ... | Binding a list of strings to an IN clause |
Possible Duplicate:
python list in sql query as parameter
Consider this (using apsw here):
s = ["A", "B", "C"]
c.execute("SELECT foo.y FROM foo WHERE foo.x in (?)", (s, ))
This doesn't work, because a binding parameter cannot be a list. I want to bind a list of strings to ?. I know how to build the appropriate quer... | [
"Going with the multiple question marks idea by Fabian, how about\nc.execute(\"SELECT foo.y FROM foo WHERE foo.x in (%s)\" % ', '.join('?' * len(s)), s)\n\n",
"I had this problem around 4 years ago, and then I found out it was impossible to bind lists to sql (i was using mssql server and ODBC provider, but also c... | [
1,
0
] | [] | [] | [
"binding",
"list",
"python",
"sqlite"
] | stackoverflow_0003212559_binding_list_python_sqlite.txt |
Q:
why does my pygtk application crash when copying text on a clipboard?
I'm writing a python application using pygtk. I have a main thread who occasionally calls another thread that is supposed to build a string and then copy it on the clipboard before dying. My "slave" thread looks pretty much like this:
class Slav... | why does my pygtk application crash when copying text on a clipboard? | I'm writing a python application using pygtk. I have a main thread who occasionally calls another thread that is supposed to build a string and then copy it on the clipboard before dying. My "slave" thread looks pretty much like this:
class Slave(threading.Thread):
def run(self):
s = build_string()
... | [
"You can't interact with Gtk from threads without taking some necessary precautions. Check this PyGTK FAQ entry.\n"
] | [
0
] | [] | [] | [
"clipboard",
"gtk",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0003212010_clipboard_gtk_multithreading_pygtk_python.txt |
Q:
Python file.read() grabs more data than necessary, under the hood
cat file_ro.py
import sys
def file_open(filename):
fo=open(filename,'r')
fo.seek(7)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
But strace says
readlink("file_ro.py", 0x7fff31fc7ea0... | Python file.read() grabs more data than necessary, under the hood | cat file_ro.py
import sys
def file_open(filename):
fo=open(filename,'r')
fo.seek(7)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
But strace says
readlink("file_ro.py", 0x7fff31fc7ea0, 4096) = -1 EINVAL (Invalid argument)
getcwd("/home/laks/python", 4096... | [
"Since you're reading in another py file things become confused, but it seems the built-in function ignores the value you pass to read(), and buffers the rest of the value. Maybe trying using os.read() instead?\nfile_ro.py:\nimport sys\ndef file_open(filename):\n fo=open(filename,'r')\n fo.seek(7)\n ... | [
6,
6
] | [] | [] | [
"file",
"python",
"strace"
] | stackoverflow_0003211569_file_python_strace.txt |
Q:
making more rows in a row of treeview!
I wanna make sth like this in transmission: [link text]here1
(also in pidgin too, Status under IDs)
can anyone show me a sample code here?
A:
You need a TreeView with a custom CellRenderer. Here's some documentation and an example of the latter.
| making more rows in a row of treeview! | I wanna make sth like this in transmission: [link text]here1
(also in pidgin too, Status under IDs)
can anyone show me a sample code here?
| [
"You need a TreeView with a custom CellRenderer. Here's some documentation and an example of the latter.\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003211049_pygtk_python.txt |
Q:
What's the VT100 escape code for the "esc" keyboard key itself
I'm writing a script to navigate a text-based menu system, using python's telnetlib to access a serial connection.
I can happily press the F-keys, using the escape codes. e.g. F9 = "\033OX", where "\033" is the escape sequence.
How do I encode the "es... | What's the VT100 escape code for the "esc" keyboard key itself | I'm writing a script to navigate a text-based menu system, using python's telnetlib to access a serial connection.
I can happily press the F-keys, using the escape codes. e.g. F9 = "\033OX", where "\033" is the escape sequence.
How do I encode the "esc" keyboard key? I would have expected just "\033", but that doesn'... | [
"There is no such thing as an \"escape sequence\" for the ESC key on a VT-100 (or other terminals that used escape sequences).\nThe escape character, ASCII 27, was used to indicate that the following sequences of characters had special meaning. This usually put the terminal into a simple state machine. In general... | [
8,
6
] | [] | [] | [
"escaping",
"python",
"serial_port"
] | stackoverflow_0002420671_escaping_python_serial_port.txt |
Q:
Writing a Python mail server with authentication
I'm trying to write a simple mail server using Python.
I found smtpd that can be used as a simple smtp server, but I don't think it supports any form of authentication.
For pop or imap, I haven't found anything at all yet.
I do know Twisted has some support for both... | Writing a Python mail server with authentication | I'm trying to write a simple mail server using Python.
I found smtpd that can be used as a simple smtp server, but I don't think it supports any form of authentication.
For pop or imap, I haven't found anything at all yet.
I do know Twisted has some support for both smtp and pop or imap, but I can't find any examples o... | [
"Here is an example from Twisted. \nAnd the main page. Follow the link for documentation to find the example and a tutorial.\nEdit:\nCheck the attachment for this ticket for an example IMAP server. Definitely read the thread as it talks about the shortcomings of the example.\n",
"A bit late probably but for ex... | [
2,
1
] | [] | [] | [
"clojure",
"imap",
"pop3",
"python",
"smtp"
] | stackoverflow_0003085248_clojure_imap_pop3_python_smtp.txt |
Q:
keep alive thread in PyQt4
I have a PyQt4 application, which at some point packs a big file using the tarfile module. Since the tarfile module does not implement any callback strategy, it blocks and the Qt GUI gets unresponsive.
I want the GUI to keep updating during that time. The only possibility is a separate t... | keep alive thread in PyQt4 | I have a PyQt4 application, which at some point packs a big file using the tarfile module. Since the tarfile module does not implement any callback strategy, it blocks and the Qt GUI gets unresponsive.
I want the GUI to keep updating during that time. The only possibility is a separate thread.
So, I start a QThread. Wh... | [
"QThread's are pretty much identical to normal Python threads so you can just use normal communication methods. However, QThreads also have a few signals available, so if you simply connect to those, than you're done.\nIn your GUI code do something like this and you're pretty much done:\nthread = Thread()\nthread.f... | [
1
] | [] | [] | [
"multithreading",
"pyqt4",
"python",
"qthread"
] | stackoverflow_0003213891_multithreading_pyqt4_python_qthread.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.