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:
How to share a dictionary between multiple processes in python without locking
I need to share a huge dictionary (around 1 gb in size) between multiple processs, however since all processes will always read from it. I dont need locking.
Is there any way to share a dictionary without locking?
The multiprocessin... | How to share a dictionary between multiple processes in python without locking | I need to share a huge dictionary (around 1 gb in size) between multiple processs, however since all processes will always read from it. I dont need locking.
Is there any way to share a dictionary without locking?
The multiprocessing module in python provides an Array class which allows sharing without locking by s... | [
"Well, in fact the dict on a Manager has no locks at all! I guess this is true for the other shared object you can create through the manager too. How i know this? I tried:\nfrom multiprocessing import Process, Manager\n\ndef f(d):\n for i in range(10000):\n d['blah'] += 1\n\nif __name__ == '__main__':\n ... | [
5
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002936626_multithreading_python.txt |
Q:
Application closes on Nokia E71 when using urllib.urlopen
Im running the following code on my Nokia E71. But after the text input, the program closes abruptly. I have a GPRS connection on my phone,but i still seem to be having some problem with urllib.urlopen
The code is as follows :
import appuifw,urllib
amountI... | Application closes on Nokia E71 when using urllib.urlopen | Im running the following code on my Nokia E71. But after the text input, the program closes abruptly. I have a GPRS connection on my phone,but i still seem to be having some problem with urllib.urlopen
The code is as follows :
import appuifw,urllib
amountInDollars = appuifw.query(u"Enter amount in Dollars","text") dat... | [
"Rewriting to:\nimport appuifw,urllib\n\namountInDollars = appuifw.query(u\"Enter amount in Dollars\",\"text\") \nf=urllib.urlopen(\"http://www.google.com\")\ndata=f.read()\nf.close()\nappuifw.note(u\"Hey\",\"info\")\n\nit should work now.\n"
] | [
2
] | [] | [] | [
"pys60",
"python"
] | stackoverflow_0002878493_pys60_python.txt |
Q:
class browsing in django
I'd like to browse active classes in Django. I think I'd learn a lot that way. So what's a good way to do that?
I could use IDLE if I knew how to start Django from within IDLE. But as I'm new to Python/Django, I'm not particularly wedded to IDLE. Other alternatives?
A:
I imagine what you... | class browsing in django | I'd like to browse active classes in Django. I think I'd learn a lot that way. So what's a good way to do that?
I could use IDLE if I knew how to start Django from within IDLE. But as I'm new to Python/Django, I'm not particularly wedded to IDLE. Other alternatives?
| [
"I imagine what you mean by class browsing. If you are comfortable with the terminal you could try to inspect python/django objects via the shell and autocompletion. \n$ ./manage shell\nPython 2.6.4 (r264:75706, Feb 6 2010, 01:49:44) \nType \"copyright\", \"credits\" or \"license\" for more information.\n\nIPython... | [
1,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002936838_django_python.txt |
Q:
How to parse a directory tree in python?
I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra".
./notes
--> ./notes/maths
------> ./notes/maths/linear_algebra
--> ./notes/phys... | How to parse a directory tree in python? | I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra".
./notes
--> ./notes/maths
------> ./notes/maths/linear_algebra
--> ./notes/physics/
------> ./notes/physics/quantum_mechanics... | [
"You could utilize os.walk.\n#!/usr/bin/env python\n\nimport os\nfor root, dirs, files in os.walk('notes'):\n print(root, dirs, files)\n\n\nNaive two level traversing:\nimport os\nfrom os.path import isdir, join\n\ndef cats_and_subs(root='notes'):\n \"\"\"\n Collect categories and subcategories.\n \"\"\... | [
16,
1
] | [] | [] | [
"python"
] | stackoverflow_0002936909_python.txt |
Q:
Reading and writing to/from memory in Python
Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program.
Is this possible?
A:
Sort of.
python... | Reading and writing to/from memory in Python | Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program.
Is this possible?
| [
"Sort of.\npython p1.py | python p2.py\n\nIf p1 writes to stdout, the data goes to memory. If p2 reads from stdin, it reads from memory. \nThe issue is that there's no \"I will then start the second program\". You must start both programs so that they share the appropriate memory (in this case, the buffer betwee... | [
5,
3,
2,
1,
1,
1,
1,
1
] | [] | [] | [
"buffer",
"memory",
"python"
] | stackoverflow_0002499491_buffer_memory_python.txt |
Q:
A UnicodeDecodeError that occurs with json in python on Windows, but not Mac
On windows, I have the following problem:
>>> string = "Don´t Forget To Breathe"
>>> import json,os,codecs
>>> f = codecs.open("C:\\temp.txt","w","UTF-8")
>>> json.dump(string,f)
Traceback (most recent call last):
File "<stdin>", line 1... | A UnicodeDecodeError that occurs with json in python on Windows, but not Mac | On windows, I have the following problem:
>>> string = "Don´t Forget To Breathe"
>>> import json,os,codecs
>>> f = codecs.open("C:\\temp.txt","w","UTF-8")
>>> json.dump(string,f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\json\__init__.py", line 180, in dump
for... | [
"What does repr(string) show on each machine? On my Mac the apostrophe shows as \\xc2\\xb4 (utf8 coding, 2 bytes) so of course the utf8 codec can deal with it; on your Windows it clearly isn't doing that since it talks about three bytes being a problem - so on Windows you must have some other, non-utf8 encoding se... | [
2
] | [] | [] | [
"json",
"python",
"serialization",
"unicode"
] | stackoverflow_0002937095_json_python_serialization_unicode.txt |
Q:
django - variable declared in base project does not appear in app
I have a variable called STATIC_URL, declared in settings.py in my base project:
STATIC_URL = '/site_media/static/'
This is used, for example, in my site_base.html, which links to CSS files as follows:
<link rel="stylesheet" href="{{ STATIC_URL }}c... | django - variable declared in base project does not appear in app | I have a variable called STATIC_URL, declared in settings.py in my base project:
STATIC_URL = '/site_media/static/'
This is used, for example, in my site_base.html, which links to CSS files as follows:
<link rel="stylesheet" href="{{ STATIC_URL }}css/site_tabs.css" />
I have a bunch of templates related to different ... | [
"Variables in settings.py are not available to the templates. What is available to a template is determined by the view that renders it. When the template is rendered you pass in a dictionary which is the \"context\" for the template. The context is a dictionary of names of variables and their values.\nTo pass a v... | [
2,
0
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0002937041_django_pinax_python.txt |
Q:
python web script send job to printer
Is it possible for my python web app to provide an option the for user to automatically send jobs to the locally connected printer? Or will the user always have to use the browser to manually print out everything.
A:
If your Python webapp is running inside a browser on the c... | python web script send job to printer | Is it possible for my python web app to provide an option the for user to automatically send jobs to the locally connected printer? Or will the user always have to use the browser to manually print out everything.
| [
"If your Python webapp is running inside a browser on the client machine, I don't see any other way than manually for the user.\nSome workarounds you might want to investigate:\n\nif you web app is installed on the client machine, you will be able to connect directly to the printer, as you have access to the underl... | [
0,
0
] | [] | [] | [
"printing",
"python",
"web_applications"
] | stackoverflow_0002936384_printing_python_web_applications.txt |
Q:
Pass arguments from django-registration to django-profiles when user registers
I'm using both django-registrations and django-profiles. When the user registers I'd like to ask them to fill in the form fields from profiles as well as the usual username and password. How do I combine these two into one sign up page?... | Pass arguments from django-registration to django-profiles when user registers | I'm using both django-registrations and django-profiles. When the user registers I'd like to ask them to fill in the form fields from profiles as well as the usual username and password. How do I combine these two into one sign up page?
| [
"Recently, I answered a question (on SO) on adjusting the RegistrationForm class. In this RegistrationForm you could prompt the user for his profile information. You should process this data in the register method of the DefaultBackend. \n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002937245_django_python.txt |
Q:
Sqlite3 "chained" query
I need to create a configuration file from a data file that looks as follows:
MAN1_TIME '01-JAN-2010 00:00:00.0000 UTC'
MAN1_RX 123.45
MAN1_RY 123.45
MAN1_RZ 123.45
MAN1_NEXT 'MAN2'
MAN2_TIME '01-MAR-2010 00:00:00.0000 UTC'
MAN2_RX 123.45
[...]
MAN2_NEXT 'MANX'
[...]
MANX_TIME [...]
This f... | Sqlite3 "chained" query | I need to create a configuration file from a data file that looks as follows:
MAN1_TIME '01-JAN-2010 00:00:00.0000 UTC'
MAN1_RX 123.45
MAN1_RY 123.45
MAN1_RZ 123.45
MAN1_NEXT 'MAN2'
MAN2_TIME '01-MAR-2010 00:00:00.0000 UTC'
MAN2_RX 123.45
[...]
MAN2_NEXT 'MANX'
[...]
MANX_TIME [...]
This file describes different "legs... | [
"I found the answer to my own question in the SQLAlchemy website. From the documentation:\n\nThe adjacency list pattern is a common\n relational pattern whereby a table\n contains a foreign key reference to\n itself. This is the most common and\n simple way to represent hierarchical\n data in flat tables. The ... | [
1,
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0001892111_python_sql_sqlite.txt |
Q:
Python: Improving long cumulative sum
I have a program that operates on a large set of experimental data. The data is stored as a list of objects that are instances of a class with the following attributes:
time_point - the time of the sample
cluster - the name of the cluster of nodes from which the sample was... | Python: Improving long cumulative sum | I have a program that operates on a large set of experimental data. The data is stored as a list of objects that are instances of a class with the following attributes:
time_point - the time of the sample
cluster - the name of the cluster of nodes from which the sample was taken
node - the name of the node from whi... | [
"This seems like a classic opportunity to apply a little object-orientation. I would suggest making the derived data a class and abstracting the cumulative sum calculation to something which works on that class.\nSomething like:\nclass DerivedData(object):\n def __init__(self):\n self.qty1 = 0.0\n ... | [
3
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002937383_list_comprehension_python.txt |
Q:
how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python?
how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python?
import os,sys,libxml2
files=[]
sha1s=[]
doc = libxml2.parseFile('file... | how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python? | how to compare the checksums in a list corresponding to a file path with the file path in the operating system In Python?
import os,sys,libxml2
files=[]
sha1s=[]
doc = libxml2.parseFile('files.xml')
for path in doc.xpathEval('//File/Path'):
files.append(path.content)
for sha1 in doc.xpathEval('//File/Hash'):
sha1... | [
"import hashlib\nimport libxml2\n\ndoc = libxml2.parseFile('files.xml')\nfilePaths = [\"/\" + path.content for path in doc.xpathEval('//File/Path')]\nxmlDigests = [hash.content for hash in doc.xpathEval('//File/Hash')]\n\nfor filePath, xmlDigest in zip(filePaths, xmlDigests):\n with open(filePath) as inFile:\n ... | [
0
] | [] | [] | [
"checksum",
"compare",
"python",
"sha1"
] | stackoverflow_0002908118_checksum_compare_python_sha1.txt |
Q:
Using Python to get a CSV output for the following example
I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project.
Going with the idea of the Assignment Problem and Hungaria... | Using Python to get a CSV output for the following example | I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project.
Going with the idea of the Assignment Problem and Hungarian Algorithm I would like to express my data in the form of a .cs... | [
"Check out the csv module. Basically, you just need to get your data into some kind of sequence (list, tuple, etc.), and then you can just do csv.writerow()\nimport csv\ncot=csv.writer(open('file.csv','wb'))\n\ntmp=[['','Project 1','Project 2','Project 3'],\n ['Student1','','2','1'],\n ['Student2','1','2',... | [
5,
3
] | [] | [] | [
"csv",
"project",
"python"
] | stackoverflow_0002937586_csv_project_python.txt |
Q:
Update model instance with dynamic field names
What I want to do is pretty simple:
f=Foobar.objects.get(id=1)
foo='somefield'
bar='somevalue'
f.foo=bar
f.save()
This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this?
A:
You can use setattr:
f... | Update model instance with dynamic field names | What I want to do is pretty simple:
f=Foobar.objects.get(id=1)
foo='somefield'
bar='somevalue'
f.foo=bar
f.save()
This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this?
| [
"You can use setattr:\nf = Foobar.objects.get(id=1)\nfoo = 'somefield'\nbar = 'somevalue'\nsetattr(f, foo, bar) # f.foo=bar\nf.save()\n\n\n[setattr] is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The functi... | [
35
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002937661_django_python.txt |
Q:
What is a flexible, hybrid python collection object?
As a way to get used to python, I am trying to translate some of my code to python from Autohotkey_L.
I am immediately running into tons of choices for collection objects. Can you help me figure out a built in type or a 3rd party contributed type that has as m... | What is a flexible, hybrid python collection object? | As a way to get used to python, I am trying to translate some of my code to python from Autohotkey_L.
I am immediately running into tons of choices for collection objects. Can you help me figure out a built in type or a 3rd party contributed type that has as much as possible, the functionality of the AutoHotkey_L ob... | [
"Don't write Python as <another-language>. Write Python as Python.\nThe data structure should be chosen just to have the minimal ability you need to use.\n\nlist — an ordered sequence of elements, with 1 flexible end.\ncollections.deque — an ordered sequence of elements, with 2 flexible ends (e.g. a queue).\nset / ... | [
10,
1
] | [] | [] | [
"autohotkey",
"data_structures",
"python"
] | stackoverflow_0002937842_autohotkey_data_structures_python.txt |
Q:
linear combinations in python/numpy
greetings,
I'm not sure if this is a dumb question or not.
Lets say I have 3 numpy arrays, A1,A2,A3, and 3 floats, c1,c2,c3
and I'd like to evaluate B = A1*c1+ A2*c2+ A3*c3
will numpy compute this as for example,
E1 = A1*c1
E2 = A2*c2
E3 = A3*c3
D1 = E1+E2
B = D1+E3
or is ... | linear combinations in python/numpy | greetings,
I'm not sure if this is a dumb question or not.
Lets say I have 3 numpy arrays, A1,A2,A3, and 3 floats, c1,c2,c3
and I'd like to evaluate B = A1*c1+ A2*c2+ A3*c3
will numpy compute this as for example,
E1 = A1*c1
E2 = A2*c2
E3 = A3*c3
D1 = E1+E2
B = D1+E3
or is it more clever than that? In c++ I had a ... | [
"While numpy, in theory, could at any time always upgrade its internals to perform wondrous optimizations, at the present time it does not: B = A1*c1 + A2*c2 + A3*c3 will indeed produce and then discard intermediate temporary arrays (\"spending\" some auxiliary memory, of course -- nothing else). \nB = A1 * c1 fol... | [
7,
3
] | [] | [] | [
"arrays",
"linear_algebra",
"numpy",
"python"
] | stackoverflow_0002937669_arrays_linear_algebra_numpy_python.txt |
Q:
Sort and limit queryset by comment count and date using queryset.extra() (django)
I am trying to sort/narrow a queryset of objects based on the number of comments each object has as well as by the timeframe during which the comments were posted. Am using a queryset.extra() method (using django_comments which util... | Sort and limit queryset by comment count and date using queryset.extra() (django) | I am trying to sort/narrow a queryset of objects based on the number of comments each object has as well as by the timeframe during which the comments were posted. Am using a queryset.extra() method (using django_comments which utilizes generic foreign keys).
I got the idea for using queryset.extra() (and the code) ... | [
"Try this [updated to include time difference (cutoff_date) ]\n queryset = queryset.extra(select={\n 'comment_count' : \"\"\"\n SELECT COUNT(*)\n FROM django_comments\n WHERE\n django_comments.content_type_id=%s AND\n djan... | [
1
] | [] | [] | [
"django",
"mysql",
"python",
"sql"
] | stackoverflow_0002938519_django_mysql_python_sql.txt |
Q:
Caveats to be aware of when using threading in Python?
I'm quite new to threading in Python and have a couple of beginner questions.
When starting more than say fifty threads using the Python threading module I start getting MemoryError. The threads themselves are very slim and not very memory hungry, so it seems ... | Caveats to be aware of when using threading in Python? | I'm quite new to threading in Python and have a couple of beginner questions.
When starting more than say fifty threads using the Python threading module I start getting MemoryError. The threads themselves are very slim and not very memory hungry, so it seems like it is the overhead of the threading that causes the mem... | [
"Your question cannot be answered in a general way, as good usage of threading always depends on concrete problem to be solved. You also do not tell us, which Python version you are using, so I assume you use the \"default\" CPython and not IronPython or something like that. To give you some hints and ideas to furt... | [
5,
2,
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002938405_multithreading_python.txt |
Q:
Python making sure x is an int, and not a pesky float
For example:
import random
x = random.randint(1, 6)
y = 2
new = x / y
...
now, lets say x turns out to be 5.
How can I catch if it's an int or a float before doing other things in my program?
A:
By default, integer division works a little unexpected in pytho... | Python making sure x is an int, and not a pesky float | For example:
import random
x = random.randint(1, 6)
y = 2
new = x / y
...
now, lets say x turns out to be 5.
How can I catch if it's an int or a float before doing other things in my program?
| [
"By default, integer division works a little unexpected in python 2, if you don't \nfrom __future__ import division\n\nExample:\n>>> 5 / 3\n1\n>>> isinstance(5 / 3, int)\nTrue\n\nExplanation: Why doesn’t this division work in python?\nFinally, you can always convert numbers to int:\n>>> from __future__ import divis... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002939279_python.txt |
Q:
Python how to handle # in a dictionary
I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below.
{
"artist": "similar": {
"artist": {
"name": "Blah",
"image": [{
"#text": "URLHERE",
"size": "sma... | Python how to handle # in a dictionary | I've got some json from last.fm's api which I've serialised into a dictionary using simplejson. A quick example of the basic structure is below.
{
"artist": "similar": {
"artist": {
"name": "Blah",
"image": [{
"#text": "URLHERE",
"size": "small"
}, {
"#text": "URLHERE",
... | [
"Python does not have any problem with # in strings used as dict keys. \n>>> import json\n>>> j = '{\"#foo\": 6}'\n>>> print json.loads(j)\n{u'#foo': 6}\n>>> print json.loads(j)[u'#foo']\n6\n>>> print json.loads(j)['#foo']\n6\n\nThere are, however, problems with the JSON you post. For one, it isn't valid (perhaps y... | [
4,
3,
0
] | [] | [] | [
"api",
"json",
"python"
] | stackoverflow_0002938911_api_json_python.txt |
Q:
SSL and WSGI apps - Python
I have a WSGI app that I would like to place behind SSL. My WSGI server is gevent.
What would a good way to serve the app through SSL in this case be?
A:
The gevent.wsgi module does not have built-in SSL support. If you're using it, put it behind nginx which would receive request over ... | SSL and WSGI apps - Python | I have a WSGI app that I would like to place behind SSL. My WSGI server is gevent.
What would a good way to serve the app through SSL in this case be?
| [
"The gevent.wsgi module does not have built-in SSL support. If you're using it, put it behind nginx which would receive request over HTTPS but proxy them to your gevent app using non-encrypted HTTP.\nThe gevent.pywsgi module does have built-in SSL support and has a compatible interface. Set the keyfile and certfile... | [
9,
3,
2
] | [] | [] | [
"gevent",
"python",
"ssl",
"wsgi"
] | stackoverflow_0002857273_gevent_python_ssl_wsgi.txt |
Q:
Django how to handle # in variable name
I've got a dictionary in python which is assigned as a template variable. One of the keys is named "#text" but when i try to access it using {{ artist.image.3."#text"}} I get an error which is
File "/home/jack/Desktop/test/appengine/lib/django/django/template/__init__.py"... | Django how to handle # in variable name | I've got a dictionary in python which is assigned as a template variable. One of the keys is named "#text" but when i try to access it using {{ artist.image.3."#text"}} I get an error which is
File "/home/jack/Desktop/test/appengine/lib/django/django/template/__init__.py", line 558, in __init__
raise TemplateSyn... | [
"Django except such variables to be proper names, you have two options\n\nif possible just change #text to text or something like that\nelse write a template filter which excepts key name and returns value\n\ne.g.\n@register.filter\ndef get_key(d, key):\n return d[key]\n\nusage:\n {{ my_dict|get_key:'#text' }}\n... | [
0
] | [] | [] | [
"django_templates",
"python"
] | stackoverflow_0002939267_django_templates_python.txt |
Q:
How to split line at non-printing ascii character in Python
How can I split a line in Python at a non-printing ascii character (such as the long minus sign hex 0x97 , Octal 227)?
I won't need the character itself. The information after it will be saved as a variable.
A:
You can use re.split.
>>> import re
>>> re... | How to split line at non-printing ascii character in Python | How can I split a line in Python at a non-printing ascii character (such as the long minus sign hex 0x97 , Octal 227)?
I won't need the character itself. The information after it will be saved as a variable.
| [
"You can use re.split.\n>>> import re\n>>> re.split('\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']\n\nAdjust the pattern to only include the characters you want to keep.\nSee also: stripping-non-printable-characters-from-a-string-in-python\n\nExample (w/ the long minus):\n>>> # \\xe2\\x80\\x93 rep... | [
5,
2,
1
] | [] | [] | [
"ascii",
"extended_ascii",
"python",
"split"
] | stackoverflow_0002936174_ascii_extended_ascii_python_split.txt |
Q:
set / line intersection solution
I have two lists in python and I want to know if they intersect at the same index. Is there a mathematical way of solving this?
For example if I have [9,8,7,6,5] and [3,4,5,6,7] I'd like a simple and efficient formula/algorithm that finds that at index 3 they intersect. I know I ... | set / line intersection solution | I have two lists in python and I want to know if they intersect at the same index. Is there a mathematical way of solving this?
For example if I have [9,8,7,6,5] and [3,4,5,6,7] I'd like a simple and efficient formula/algorithm that finds that at index 3 they intersect. I know I could do a search just wondering if th... | [
"You could take the set-theoretic intersection of the coordinates in both lists:\nintersecting_points = set(enumerate(list1)).intersection(set(enumerate(list2)))\n\n...enumerate gives you an iterable of tuples of indexes and values - in other words, (0,9),(1,8),(2,7),etc. \nhttp://docs.python.org/library/stdtypes.h... | [
4,
1,
0,
0
] | [] | [] | [
"intersection",
"list",
"python",
"set"
] | stackoverflow_0002939513_intersection_list_python_set.txt |
Q:
Convert data retrieved from MySQL database into JSON object using Python/Django
I have a MySQL database called People which contains the following schema <id,name,foodchoice1,foodchoice2>. The database contains a list of people and the two choices of food they wish to have at a party (for example). I want to creat... | Convert data retrieved from MySQL database into JSON object using Python/Django | I have a MySQL database called People which contains the following schema <id,name,foodchoice1,foodchoice2>. The database contains a list of people and the two choices of food they wish to have at a party (for example). I want to create some kind of Python web-service that will output a JSON object.
An example of outp... | [
"If you ever need anything more fancy than just a dump of a specific queryset in JSON, consider using django-piston to help automate the creation of APIs.\n",
"You can serialize any django model: http://docs.djangoproject.com/en/1.2/topics/serialization/#topics-serialization\nThe serializers support both xml and ... | [
2,
0
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0002939973_django_json_python.txt |
Q:
Python/PyParsing: Difficulty with setResultsName
I think I'm making a mistake in how I call setResultsName():
from pyparsing import *
DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code")
COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number")
COURSE_NUMBER.setParseAction(lambda s, l, toks : int... | Python/PyParsing: Difficulty with setResultsName | I think I'm making a mistake in how I call setResultsName():
from pyparsing import *
DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code")
COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number")
COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0]))
course = DEPT_CODE + COURSE_NUMBER
course... | [
"If you change the definition of course to \ncourse = (DEPT_CODE + COURSE_NUMBER).setResultsName(\"Course\")\n\nyou get the following behavior:\nx=statement.parseString(\"CS 2110\")\nprint(repr(x))\n# (['CS', 2110], {'Course': [((['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}), 0)], 'Dept Co... | [
5
] | [] | [] | [
"nlp",
"pyparsing",
"python"
] | stackoverflow_0002940166_nlp_pyparsing_python.txt |
Q:
Why doesn't this list comprehension do what I expect it to do?
The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110.
Thus:
for project in projects.itervalues():
# The projects dicti... | Why doesn't this list comprehension do what I expect it to do? | The original list project_keys = sorted(projects.keys()) is [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] where the following projects were deemed invalid this year: 108, 109, 110.
Thus:
for project in projects.itervalues():
# The projects dictionary is mapped to the Project class
if project.invalid:
# W... | [
"Your list comprehension works using side-effects. Just executing it should update project_keys to give the result you want.\n[project_keys.remove(project.proj_id)\n for project in projects.itervalues()\n if project.invalid]\n\nThe return value from remove is None. Assigning the result of the list comprehension to ... | [
6,
4
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002940053_list_comprehension_python.txt |
Q:
Fixing color in scatter plots in matplotlib
I want to fix the color range on multiple scatter plots and add in a colorbar to each plot (which will be the same in each figure). Essentially, I'm fixing all aspects of the axes and colorspace etc. so that the plots are directly comparable by eye.
For the life of me, ... | Fixing color in scatter plots in matplotlib | I want to fix the color range on multiple scatter plots and add in a colorbar to each plot (which will be the same in each figure). Essentially, I'm fixing all aspects of the axes and colorspace etc. so that the plots are directly comparable by eye.
For the life of me, I can't seem to figure out all the various ways o... | [
"Setting vmin and vmax should do this.\nHere's an example:\nimport matplotlib.pyplot as plt\n\nxyc = range(20)\n\nplt.subplot(121)\nplt.scatter(xyc[:13], xyc[:13], c=xyc[:13], s=35, vmin=0, vmax=20)\nplt.colorbar()\nplt.xlim(0, 20)\nplt.ylim(0, 20)\n\nplt.subplot(122)\nplt.scatter(xyc[8:20], xyc[8:20], c=xyc[8:20],... | [
52,
0
] | [] | [] | [
"colors",
"matplotlib",
"python",
"scatter_plot"
] | stackoverflow_0002925806_colors_matplotlib_python_scatter_plot.txt |
Q:
Parsing an RDF file in python
Does anyone know how to pars RDF file in Python to get all the values within a specific tag?
thanks
A:
Are you using an RDF library? Otherwise, perhaps you should. For example, see the documentation of three RDF libraries for Python:
Redland RDF libraries
RDFLib
RDF/XML parser
| Parsing an RDF file in python | Does anyone know how to pars RDF file in Python to get all the values within a specific tag?
thanks
| [
"Are you using an RDF library? Otherwise, perhaps you should. For example, see the documentation of three RDF libraries for Python:\n\nRedland RDF libraries\nRDFLib\nRDF/XML parser\n\n"
] | [
11
] | [] | [] | [
"parsing",
"python",
"rdf",
"xml"
] | stackoverflow_0002940454_parsing_python_rdf_xml.txt |
Q:
Is it possible to create a python iterator over pre-defined mutable data?
I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible:
I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example:
items... | Is it possible to create a python iterator over pre-defined mutable data? | I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible:
I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example:
items = {"ball" : ItemInstance1, "sword" : ItemInstance2}
people = {"Jerry" : Person... | [
"If I understand you question correctly then adding the following method to your class should do it:\ndef __iter__(self):\n import itertools\n return itertools.chain(self.items.itervalues(), self.people.itervalues())\n\nThis chains together two iterators, and the ones chosen here are for the values of items a... | [
2,
1
] | [] | [] | [
"class",
"iterator",
"python"
] | stackoverflow_0002940519_class_iterator_python.txt |
Q:
Google App Engine appcfg.py data_upload Authentication fail
I am using appcfg.py to upload data to datastore from a csv file.
But every time I try, I am getting error:
[info ] Authentication failed
even if i am using Admin id and password.
In my app.yaml file I am having:
handlers:
- url: /remote_api
scr... | Google App Engine appcfg.py data_upload Authentication fail | I am using appcfg.py to upload data to datastore from a csv file.
But every time I try, I am getting error:
[info ] Authentication failed
even if i am using Admin id and password.
In my app.yaml file I am having:
handlers:
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
log... | [
"That app.yaml file looks good to me, but are you sure it's been deployed to the server? The docs explicitly note that you need to update your app on the server before using appcfg.py to bulk upload data will work, so you might try the suggested command:\nappcfg.py update <app-directory>\n\nYou might also look at d... | [
2,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002895397_google_app_engine_python.txt |
Q:
Using custom Qt subclasses in Python
First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work.
I'm attempting to formulate a modular architecture for ... | Using custom Qt subclasses in Python | First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work.
I'm attempting to formulate a modular architecture for some in-house software. The core component... | [
"PyQt exposes C++ code to Python via SIP; PySide does so via Shiboken. Both have roughly the same capabilities as SWIG (except that they only support \"extended C++ to Python\", while SWIG has back-ends for Ruby, Perl, Java, and so forth as well). Neither SWIG nor SIP and Shiboken are designed to interoperate wit... | [
9
] | [] | [] | [
"c++",
"python",
"qt",
"swig"
] | stackoverflow_0002940686_c++_python_qt_swig.txt |
Q:
PyParsing: What does Combine() do?
What is the difference between:
foo = TOKEN1 + TOKEN2
and
foo = Combine(TOKEN1 + TOKEN2)
Thanks.
UPDATE: Based on my experimentation, it seems like Combine() is for terminals, where you're trying to build an expression to match on, whereas plain + is for non-terminals. But I'm... | PyParsing: What does Combine() do? | What is the difference between:
foo = TOKEN1 + TOKEN2
and
foo = Combine(TOKEN1 + TOKEN2)
Thanks.
UPDATE: Based on my experimentation, it seems like Combine() is for terminals, where you're trying to build an expression to match on, whereas plain + is for non-terminals. But I'm not sure.
| [
"Combine has 2 effects:\n\nit concatenates all the tokens into a single string\nit requires the matching tokens to all be adjacent with no intervening whitespace\n\nIf you create an expression like \nrealnum = Word(nums) + \".\" + Word(nums)\n\nThen realnum.parseString(\"3.14\") will return a list of 3 tokens: the ... | [
19
] | [] | [] | [
"nlp",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0002940489_nlp_parsing_pyparsing_python.txt |
Q:
PyParsing: Not all tokens passed to setParseAction()
I'm parsing sentences like "CS 2110 or INFO 3300". I would like to output a format like:
[[("CS" 2110)], [("INFO", 3300)]]
To do this, I thought I could use setParseAction(). However, the print statements in statementParse() suggest that only the last tokens ar... | PyParsing: Not all tokens passed to setParseAction() | I'm parsing sentences like "CS 2110 or INFO 3300". I would like to output a format like:
[[("CS" 2110)], [("INFO", 3300)]]
To do this, I thought I could use setParseAction(). However, the print statements in statementParse() suggest that only the last tokens are actually passed:
>>> statement.parseString("CS 2110 or I... | [
"Works better if you set the parse action on both course and the Optional (you were setting only on the Optional!):\n>>> statement = (course + Optional(OR_CONJ + course)).setParseAction(statementParse).setDebug()\n>>> statement.parseString(\"CS 2110 or INFO 3300\") \n\ngives\nMatch {Re:('[A-Z]{2,}') Re:('[0-9]{4... | [
2,
2
] | [] | [] | [
"nlp",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0002940516_nlp_parsing_pyparsing_python.txt |
Q:
How do I split filenames from paths using python?
I have a list of files that look like this:
Input
/foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4
/foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4
/bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d... | How do I split filenames from paths using python? | I have a list of files that look like this:
Input
/foo/bar/baz/d4dc7c496100e8ce0166e84699b4e267fe652faeb070db18c76669d1c6f69f92.mp4
/foo/baz/bar/60d24a24f19a6b6c1c4734e0f288720c9ce429bc41c2620d32e01e934bfcd344.mp4
/bar/baz/foo/cd53fe086717a9f6fecb1d0567f6d76e93c48d7790c55e83e83dd1c43251e40e.mp4
And I would like to spl... | [
"os.path.split does exactly what you require, and I quote...:\nos.path.split(path)\n\n\nSplit the pathname path into a pair,\n (head, tail) where tail is the last\n pathname component and head is\n everything leading up to that. The\n tail part will never contain a slash;\n if path ends in a slash, tail will b... | [
17
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002940909_python_regex.txt |
Q:
How to send file from C# to apache with mod_wsgi (django) and python?
How to send file from C# to apache with mod_wsgi (django) and python? It will be nice to see code example in both c# (client) and python (server).
A:
In C#, you can just use WebClient.UploadFile. For Django, it obviously depends what you're d... | How to send file from C# to apache with mod_wsgi (django) and python? | How to send file from C# to apache with mod_wsgi (django) and python? It will be nice to see code example in both c# (client) and python (server).
| [
"In C#, you can just use WebClient.UploadFile. For Django, it obviously depends what you're doing, but the documentation has simple examples.\n"
] | [
2
] | [] | [] | [
"apache",
"c#",
"mod_wsgi",
"python"
] | stackoverflow_0002940948_apache_c#_mod_wsgi_python.txt |
Q:
how to show the right word in my code, my code is : os.urandom(64)
My code is:
print os.urandom(64)
which outputs:
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
\xd0\xc8=<\xdbD'
\xdf\xf0\xb3>\xfc\xf2\x99\x93
=S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84
... | how to show the right word in my code, my code is : os.urandom(64) | My code is:
print os.urandom(64)
which outputs:
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
\xd0\xc8=<\xdbD'
\xdf\xf0\xb3>\xfc\xf2\x99\x93
=S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84
which isn't readable, so I tried this:
print os.urandom(64).decode("utf... | [
"No shortage of choices. Here's a couple:\n>>> os.urandom(64).encode('hex')\n'0bf760072ea10140d57261d2cd16bf7af1747e964c2e117700bd84b7acee331ee39fae5cff6f3f3fc3ee3f9501c9fa38ecda4385d40f10faeb75eb3a8f557909'\n>>> os.urandom(64).encode('base64')\n'ZuYDN1BiB0ln73+9P8eoQ3qn3Q74QzCXSViu8lqueKAOUYchMXYgmz6WDmgJm1DyTX598... | [
8,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002941070_python.txt |
Q:
django file serving issues
I have in my url patterns,
urlpatterns += patterns('',
(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/tipu/Dropbox/dev/workspace/search/images'})
In my template when I do
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css" />
It ... | django file serving issues | I have in my url patterns,
urlpatterns += patterns('',
(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/home/tipu/Dropbox/dev/workspace/search/images'})
In my template when I do
<link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}style.css" />
It serves the css just fine. But th... | [
"Very strange. What error code is returned when you run curl -I http://localhost:8000/logo.png?\nJust off the top of my head, the possible problems could be:\n\nTypo (in the file name or in the template)\nPermissions\nBad data (is it really a PNG? Did it get emptied somehow?)\n\nAlso, the urlpatterns you've got the... | [
0,
0,
0
] | [] | [] | [
"django",
"python",
"serving"
] | stackoverflow_0002940034_django_python_serving.txt |
Q:
Django doesn't refresh my request object when reloading the current page
I have a Django web site which I want ot be viewable in different languages. Until this morning everything was working fine. Here is the deal. I go to my say About Us page and it is in English. Below it there is the change language button and... | Django doesn't refresh my request object when reloading the current page | I have a Django web site which I want ot be viewable in different languages. Until this morning everything was working fine. Here is the deal. I go to my say About Us page and it is in English. Below it there is the change language button and when I press it everything "magically" translates to Bulgarian just the way I... | [
"That's far too much code to read through. You really need to make an effort to trim it down.\nIf you're sure that the error is somewhere in displayClothes, then I would comment bits out until you no longer get the error. But there doesn't appear to be anything there which changes the cookies in that view, so I don... | [
1
] | [] | [] | [
"django",
"javascript",
"python",
"refresh",
"request"
] | stackoverflow_0002938045_django_javascript_python_refresh_request.txt |
Q:
nested for loop
Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file
Here is my code so far:
#!/usr/bin/python
#... | nested for loop | Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file
Here is my code so far:
#!/usr/bin/python
# this section puts em... | [
"I'm not quite sure what you're asking, but an obvious problem with the above is that readlines() returns a list of lines, each of which (except potentially the last) will have a \\n line terminator. So email will have a newline at the end of it, so won't be found in line unless it's right at the end.\nSo perhaps s... | [
1,
0
] | [] | [] | [
"loops",
"nested",
"python"
] | stackoverflow_0002932214_loops_nested_python.txt |
Q:
How to Not Force Login After Users Close Their Browser on gae
...Like Django's session or cookies
Does anyone have a simple way of allowing this?
A:
Under Application Settings in the App Engine dashboard, you can choose either 1 day, 1 week, or 2 week cookie expiration, assuming you're using the Users API.
I d... | How to Not Force Login After Users Close Their Browser on gae | ...Like Django's session or cookies
Does anyone have a simple way of allowing this?
| [
"Under Application Settings in the App Engine dashboard, you can choose either 1 day, 1 week, or 2 week cookie expiration, assuming you're using the Users API. \nI don't believe the cookie should ever be set to expire when the browser is closed, unless the user's browser setting is causing this behavior. I can ce... | [
2,
1
] | [] | [] | [
"authentication",
"google_app_engine",
"python",
"session"
] | stackoverflow_0002941021_authentication_google_app_engine_python_session.txt |
Q:
Trying to provide a global logging function
I typically write my scripts with a structure like s
#!/usr/bin/python
import stuff
def do_things():
print "FOO"
def main():
do_things()
if __name__ == "__main__":
main()
The problem I have is I'd like to have a logging function that is defined globally ... | Trying to provide a global logging function | I typically write my scripts with a structure like s
#!/usr/bin/python
import stuff
def do_things():
print "FOO"
def main():
do_things()
if __name__ == "__main__":
main()
The problem I have is I'd like to have a logging function that is defined globally and I"m not really sure how to do this. I tried a... | [
"import logging\n\nPython's logging library should satisfy your requirements.\n"
] | [
4
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0002941173_logging_python.txt |
Q:
How to remove commas etc from a matrix in python
say ive got a matrix that looks like:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
how can i make it on seperate lines:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
and then remove commas etc:
0 0 0 0 0
And also to make it blank instead of 0's, so t... | How to remove commas etc from a matrix in python | say ive got a matrix that looks like:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
how can i make it on seperate lines:
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
and then remove commas etc:
0 0 0 0 0
And also to make it blank instead of 0's, so that numbers can be put in later, so in the end it will... | [
"This allocates 4 spaces for each number in the matrix. You may have to adjust this depending on your data of course.\nThis also uses the string format method introduced in Python 2.6. Ask if you'd like to see how to do it the old way.\nmatrix=[[0, 1, 2, 0, 0], [0, 1, 0, 0, 0], [20, 0, 0, 0, 1]]\nfor row in matrix:... | [
4,
3,
1,
1,
0,
0
] | [] | [] | [
"matrix",
"python"
] | stackoverflow_0002937353_matrix_python.txt |
Q:
Django attribute error: 'module' object has no attribute 'is_usable'
I got the following error when calling the url in Django.
It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are.
Thanks before for the help,
Robert
Environment:
Request Method: GET Reques... | Django attribute error: 'module' object has no attribute 'is_usable' | I got the following error when calling the url in Django.
It's working before, I guess it's related with some accidental changes I made, but I have no idea what they are.
Thanks before for the help,
Robert
Environment:
Request Method: GET Request URL: http://localhost:8000/time/ Django Version: 1.2 Python Version: 2.6... | [
"It looks like Django is looking for a usable template loader, but is finding something in settings.TEMPLATE_LOADERS that isn't honoring the template loader function protocol (described briefly here.)\nIs it possible that one of your recent changes was to either settings.TEMPLATE_LOADERS or to a custom template loa... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002941108_django_python.txt |
Q:
small code redundancy within while-loops (doesn't feel clean)
So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often:
the_input = raw_input("what to print?\n")
while the_input != "quit":
print the_input
the_input = raw_input("what to print?\n"... | small code redundancy within while-loops (doesn't feel clean) | So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often:
the_input = raw_input("what to print?\n")
while the_input != "quit":
print the_input
the_input = raw_input("what to print?\n")
Maybe I'm being too picky, but I don't like how the line the_inp... | [
"Think iterators -- e.g., in this specific case:\nfor the_input in iter(lambda: raw_input('what to print?\\n'), 'quit'):\n print the_input\n\nMost loops in Python, except at the very lowest levels of abstractions, are best implemented as for loops with the help of some underling iterator which captures the \"loo... | [
30
] | [] | [] | [
"maintainability",
"organization",
"python",
"redundancy"
] | stackoverflow_0002941272_maintainability_organization_python_redundancy.txt |
Q:
Custom constructors for models in Google App Engine (python)
I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a ... | Custom constructors for models in Google App Engine (python) | I'm getting back to programming for Google App Engine and I've found, in old, unused code, instances in which I wrote constructors for models. It seems like a good idea, but there's no mention of it online and I can't test to see if it works. Here's a contrived example, with no error-checking, etc.:
class Dog(db.Mode... | [
"In your example, why not use the default syntax instead of a custom constructor:\nrufus = Dog( name='Rufus', breeds=['spaniel','terrier','labrador'] )\n\nYour version makes it less clear semantically IMHO.\nAs for overriding Model constructors, Google recommends against it (see for example: http://groups.google.co... | [
2,
1
] | [] | [] | [
"constructor",
"google_app_engine",
"python"
] | stackoverflow_0002937823_constructor_google_app_engine_python.txt |
Q:
indexing for faster search of lists in a file?
I have a file with around 100k lists and have a another file with again a list of around an average of 50.
I want to compare 2nd item of list in second file with the 2nd element of 1st file and repeat this for each of the 50 lists in 2nd file and get the result of all... | indexing for faster search of lists in a file? | I have a file with around 100k lists and have a another file with again a list of around an average of 50.
I want to compare 2nd item of list in second file with the 2nd element of 1st file and repeat this for each of the 50 lists in 2nd file and get the result of all the matching element.
I have written the code for a... | [
"You can afford to read all the \"lakh\" (hundred thousands) lines from the first file in memory once:\nimport collections\nd = collections.defaultdict(list)\n\nwith open('lakhlists.txt') as f:\n for line in f:\n aslist = line.split() # assuming whitespace separators\n d[aslist[1]].append(aslist)\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002941525_python.txt |
Q:
Errors Installing PIL on Mac OS Tiger
I'm trying to install the Python Imaging Library on Mac OS X 10.4, but I get errors. I'm not sure where the error starts, it's just a huge wall of text when executing sudo python setup.py install.
But the last few lines are:
...
collect2: ld returned 1 exit status
lipo: can't... | Errors Installing PIL on Mac OS Tiger | I'm trying to install the Python Imaging Library on Mac OS X 10.4, but I get errors. I'm not sure where the error starts, it's just a huge wall of text when executing sudo python setup.py install.
But the last few lines are:
...
collect2: ld returned 1 exit status
lipo: can't open input file: /var/tmp//ccNKvQpP.out (N... | [
"It is a good idea to install the Fink package manager, if you have not yet done so: you have a single point entry to many open-source packages; they have been configured to as to be precisely adapted to Mac OS X.\nOnce you have installed Fink, a simple\nfink install pil\n\nwill do.\nIf there is any package not in ... | [
0
] | [] | [] | [
"macos",
"osx_tiger",
"python"
] | stackoverflow_0002941209_macos_osx_tiger_python.txt |
Q:
Converting a single ordered list in python to a dictionary, pythonically
I can't seem to find an elegant way to start from t and result in s.
>>>t = ['a',2,'b',3,'c',4]
#magic
>>>print s
{'a': 2, 'c': 4, 'b': 3}
Solutions I've come up with that seems less than elegant :
s = dict()
for i in xrange(0, len(t),2): s[... | Converting a single ordered list in python to a dictionary, pythonically | I can't seem to find an elegant way to start from t and result in s.
>>>t = ['a',2,'b',3,'c',4]
#magic
>>>print s
{'a': 2, 'c': 4, 'b': 3}
Solutions I've come up with that seems less than elegant :
s = dict()
for i in xrange(0, len(t),2): s[t[i]]=t[i+1]
# or something fancy with slices that I haven't figured out yet
... | [
"I'd use itertools, but, if you think that's complicated (as you've hinted in a comment), then maybe:\ndef twobytwo(t):\n it = iter(t)\n for x in it:\n yield x, next(it)\n\nd = dict(twobytwo(t))\n\nor equivalently, and back to itertools again,\ndef twobytwo(t):\n a, b = itertools.tee(iter(t))\n next(b)\n re... | [
10,
9,
7,
6,
2,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"python_itertools"
] | stackoverflow_0001639772_dictionary_list_python_python_itertools.txt |
Q:
Coding the Python way
I've just spent the last half semester at Uni learning python. I've really enjoyed it, and was hoping for a few tips on how to write more 'pythonic' code.
This is the __init__ class from a recent assignment I did. At the time I wrote it, I was trying to work out how I could re-write this usi... | Coding the Python way | I've just spent the last half semester at Uni learning python. I've really enjoyed it, and was hoping for a few tips on how to write more 'pythonic' code.
This is the __init__ class from a recent assignment I did. At the time I wrote it, I was trying to work out how I could re-write this using lambdas, or in a neater,... | [
"Couple things that can clean up your code a bit:\nUse the dictionary's setdefault. If the key is missing, then it sets it to the default you provide it with, then returns it. Otherwise, it just ignores the 2nd parameter and returns what was in the dictionary. This avoids the clunky if-statements.\nEnrol.venues_dic... | [
5,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002941271_python.txt |
Q:
Dynamically loading modules in Python (+ multi processing question)
I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file.
I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new... | Dynamically loading modules in Python (+ multi processing question) | I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file.
I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new process, so that the code runs ASYNCHRONOUSLY in a separate process.
At ... | [
"Question 1: use __import__().\nQuestion 2: why not just do the cleanup at the end of the do_work() function?\nQuestion 3: IIRC daemon thread just means that the program won't automatically wait for this thread to end.\n",
"This was revised to make use of import() documentation here: import and refactored to util... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002942025_python.txt |
Q:
SQLAlchemy - relationship limited on more than just the foreign key
I have a wiki db layout with Page and Revisions. Each Revision has a page_id referencing the Page, a page relationship to the referenced page; each Page has a all_revisions relationship to all its revisions. So far so common.
But I want to impleme... | SQLAlchemy - relationship limited on more than just the foreign key | I have a wiki db layout with Page and Revisions. Each Revision has a page_id referencing the Page, a page relationship to the referenced page; each Page has a all_revisions relationship to all its revisions. So far so common.
But I want to implement different epochs for the pages: If a page was deleted and is recreated... | [
"Try installing relationship after both classes are created:\nPage.revisions = relationship(\n 'Revision',\n primaryjoin = (Page.id==Revision.page_id) & \\\n (Page.current_epoch==Revision.epoch),\n foreign_keys=[Page.id, Page.current_epoch],\n uselist=True,\n)\n\nBTW, your test is not... | [
4
] | [] | [] | [
"database",
"python",
"relationship",
"sqlalchemy"
] | stackoverflow_0002935605_database_python_relationship_sqlalchemy.txt |
Q:
Setting System.Drawing.Color through .NET COM Interop
I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like... | Setting System.Drawing.Color through .NET COM Interop | I am trying to use Aspose.Words library through COM Interop. There is one critical problem: I cannot set color. It is supposed to work by assigning to DocumentBuilder.Font.Color, but when I try to do it I get OLE error 0x80131509. My problem is pretty much like this one.
update:
Code Sample:
from win32com.client import... | [
"Please, check the answer provided here:\nhttp://www.aspose.com/community/forums/thread/240901/create-a-pivot-table-from-multiple-data-ranges.aspx\nI think, this approach should help you to resolve the problem.\n"
] | [
0
] | [] | [] | [
".net",
"aspose",
"com",
"interop",
"python"
] | stackoverflow_0002934640_.net_aspose_com_interop_python.txt |
Q:
Application in which I need Auto-update just like Gmail inbox,calendar Face-Book etc
I have made application in which I have kept calendar. Now I need that if admin changes his calendar and if it is affected to user and if that user is currently looking that calendar then whatever changes Admin has done that shoul... | Application in which I need Auto-update just like Gmail inbox,calendar Face-Book etc | I have made application in which I have kept calendar. Now I need that if admin changes his calendar and if it is affected to user and if that user is currently looking that calendar then whatever changes Admin has done that should reflect to user without refreshing the page,
just like when email comes to Gmail then wi... | [
"go to $.ajax()\n",
"Python Comet Server this thread contains info on a comet like server for python, this would give you the real time browser data push I think you are referring to. I believe gmail does it by using an iframe hack and a setinterval check using some javascript ajax call.\n"
] | [
2,
0
] | [] | [] | [
"google_apps",
"jquery",
"python"
] | stackoverflow_0002942691_google_apps_jquery_python.txt |
Q:
python dictionary with constant value-type
I bumped into a case where I need a big (=huge) python dictionary, which turned to be quite memory-consuming.
However, since all of the values are of a single type (long) - as well as the keys, I figured I can use python (or numpy, doesn't really matter) array for the va... | python dictionary with constant value-type | I bumped into a case where I need a big (=huge) python dictionary, which turned to be quite memory-consuming.
However, since all of the values are of a single type (long) - as well as the keys, I figured I can use python (or numpy, doesn't really matter) array for the values ; and wrap the needed interface (in: x ; ou... | [
"This kind of task is a typical database-type access (large volume of data in columns of a given type). You would create a simple table with indexed keys, for fast access. I don't have experience with it, but you might want to check out the standard sqlite3 module.\nIf your keys do not change over time, you could... | [
2,
0
] | [] | [] | [
"arrays",
"data_structures",
"dictionary",
"python"
] | stackoverflow_0002942375_arrays_data_structures_dictionary_python.txt |
Q:
Python doesn't work properly when I execute a script after using Right Click >> Command Prompt Here
This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it.
If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command P... | Python doesn't work properly when I execute a script after using Right Click >> Command Prompt Here | This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it.
If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command Prompt using Run>>cmd.exe and navigate manually it works fine. But if I use Windows 7's convenient Right C... | [
"First of all, I work on Windows7 (among others) and running python from the command line works for me using \"Command Prompt Here\". Make sure you have the directory containing python.exe in your PATH environment variable, by running \"Command Prompt Here\" and running set.\nNow for import errors. When importing, ... | [
2,
1,
0
] | [] | [] | [
"path",
"python",
"windows_7"
] | stackoverflow_0002943071_path_python_windows_7.txt |
Q:
midi input in python
I'm coding a demo in python and I need to read a MIDI file in python (no real-time stuff is needed).
In particular, I'm looking for a library which preserves channel information.
The most promising libraries I found are:
http://code.google.com/p/midiutil/
http://www.mxm.dk/products/public/pyt... | midi input in python | I'm coding a demo in python and I need to read a MIDI file in python (no real-time stuff is needed).
In particular, I'm looking for a library which preserves channel information.
The most promising libraries I found are:
http://code.google.com/p/midiutil/
http://www.mxm.dk/products/public/pythonmidi
Any experience wi... | [
"I've been using MXM's library in harpy for some time now, and am quite satisfied with it. Fast enough for my purposes, and easy to extend. I suppose it does what you need, seeing as how I use it to split MIDI files into single channel files.\n"
] | [
2
] | [] | [] | [
"file",
"midi",
"python"
] | stackoverflow_0002942381_file_midi_python.txt |
Q:
Django: Sum on an date attribute grouped by month/year
I'd like to put this query from SQL to Django:
"select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;"
The part that causes problem is to group by month when aggregating. I tried... | Django: Sum on an date attribute grouped by month/year | I'd like to put this query from SQL to Django:
"select date_format(date, '%Y-%m') as month, sum(quantity) as hours from hourentries group by date_format(date, '%Y-%m') order by date;"
The part that causes problem is to group by month when aggregating. I tried this (which seemed logical), but it didn't work :
HourEntri... | [
"aggregate can only generate one aggregate value.\nYou can get the aggregate sum of Hours of the current month by the following query.\nfrom datetime import datetime\nthis_month = datetime.now().month\nHourEntries.objects.filter(date__month=this_month).aggregate(Sum(\"quantity\"))\n\nSo, to obtain the aggregate val... | [
2,
0
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0002943314_django_django_orm_python.txt |
Q:
Python for Windows Extensions - what does it do?
Can someone explain what this library does? Apparently, one of the things it does is allow automatic detection of SDKs. No, they don't mention what it does on their website :-(.
A:
It provides Python bindings for the Win32 API and for COM.
A:
you can find many e... | Python for Windows Extensions - what does it do? | Can someone explain what this library does? Apparently, one of the things it does is allow automatic detection of SDKs. No, they don't mention what it does on their website :-(.
| [
"It provides Python bindings for the Win32 API and for COM.\n",
"you can find many examples of use of win32com and other win32 packages in here.\nIn addition, Tim Golden's win32 How do I? and Mike Driscoll blog are very rich sources for win32 examples. \nIf you install Activepython you get win32all/pywin bundled... | [
8,
5
] | [] | [] | [
"python"
] | stackoverflow_0002943739_python.txt |
Q:
Dynamic resize with MPlayer and PyGTK
I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui.
I assume I use GtkSocket and the slave mode of mplayer with the -wid option.
But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And w... | Dynamic resize with MPlayer and PyGTK | I've wrote a piece of code in python and pygtk for an embeded mplayer in a gui.
I assume I use GtkSocket and the slave mode of mplayer with the -wid option.
But I've got an issue, when the size of my GTK window is smaller than my stream, the stream appears to be cropped. And when the size of my window is bigger than my... | [
"You'll want to connect to the 'size-allocate' signal of whatever widget you embedded MPlayer in. Once you know the new size of the widget, say 200x300, send the commands\nset_property width 300\nset_property height 200\n\nto MPlayer in slave mode.\n(See http://www.mplayerhq.hu/DOCS/tech/slave.txt for a list of sla... | [
1,
1
] | [] | [] | [
"gtk",
"mplayer",
"pygtk",
"python"
] | stackoverflow_0002417705_gtk_mplayer_pygtk_python.txt |
Q:
How to add a '-' apex in Python
I have a problem: i can't find the '-' apex character...
i'm writing code on math function: and i want to insert representation like
², ³.
i found that
print '\xb2, \xb3' work good.
now, i have to insert negative numbers at the apex, like :¯².
so, i need the ¯ charachter.
How can... | How to add a '-' apex in Python | I have a problem: i can't find the '-' apex character...
i'm writing code on math function: and i want to insert representation like
², ³.
i found that
print '\xb2, \xb3' work good.
now, i have to insert negative numbers at the apex, like :¯².
so, i need the ¯ charachter.
How can i find that?
| [
">>> print('\\xaf') # or '\\u00af'\n¯ # macron\n>>> print('\\u2212')\n− # minus\n>>> print('\\u207b')\n⁻ # superscript minus\n\nYou'll need u'' notation in python-2.x\n"
] | [
3
] | [] | [] | [
"character",
"python",
"unicode"
] | stackoverflow_0002944460_character_python_unicode.txt |
Q:
Generate all permutations with sort constraint
I have a list consisting of other lists and some zeroes, for example:
x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0]
I would like to generate all the combinations of this list while keeping the order of the inner lists unchanged, so
[[1, 1, 2], 0, 0, [1, 1, 1, 2],... | Generate all permutations with sort constraint | I have a list consisting of other lists and some zeroes, for example:
x = [[1, 1, 2], [1, 1, 1, 2], [1, 1, 2], 0, 0, 0]
I would like to generate all the combinations of this list while keeping the order of the inner lists unchanged, so
[[1, 1, 2], 0, 0, [1, 1, 1, 2], [1, 1, 2], 0]
is fine, but
[[1, 1, 1, 2], [1, 1, 2... | [
"One hint: If there are z zeros and t lists then the number of combinations you describe is choose(z+t, z). (The stars and bars trick will help to see why that's true.)\nTo generate those combinations, you could generate all the length-z subsets of {1,...,z+t}.\nEach of those would give the positions of the zeros... | [
2,
2,
0
] | [] | [] | [
"combinatorics",
"list",
"python"
] | stackoverflow_0002944590_combinatorics_list_python.txt |
Q:
Whats wrong with this task queue setup?
I've setup this task queue implementation on a site I host for a customer, it has a cron job which runs each morning at 2am "/admin/tasks/queue", this queues up emails to be sent out, "/admin/tasks/email", and uses cursors so as to do the queuing in small chunks. For some re... | Whats wrong with this task queue setup? | I've setup this task queue implementation on a site I host for a customer, it has a cron job which runs each morning at 2am "/admin/tasks/queue", this queues up emails to be sent out, "/admin/tasks/email", and uses cursors so as to do the queuing in small chunks. For some reason last night /admin/tasks/queue kept getti... | [
"I can see a couple of potential problems. First, you store your cursor in memcache, which is not guaranteed to persist anything. If you get a cache miss halfway through your processing, you'll re-send every message again.\nSecondly, tasks will get re-tried if they fail for any reason; they're supposed to be desi... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002942165_google_app_engine_python.txt |
Q:
python intercepting communication
lets say you run third party program on your computer whitch create a process named example.exe
how do i determinate if this process is running and how many windows does he open? How do i intercept network communication between this windows and server?
my goal is to create an app ... | python intercepting communication | lets say you run third party program on your computer whitch create a process named example.exe
how do i determinate if this process is running and how many windows does he open? How do i intercept network communication between this windows and server?
my goal is to create an app whitch will be monitoring network trafi... | [
"For network sniffing, use pypcap to capture network traffic. pypcap is a Python interface to libpcap (WinPcap on Windows), which is used the popular network sniffer Wireshark (once known as Ethereal).\nRegarding process information, such as whether it is running and finding all of its open windows, I'm pretty sure... | [
2,
0
] | [] | [] | [
"communication",
"networking",
"python"
] | stackoverflow_0002945074_communication_networking_python.txt |
Q:
Generating a python file
I'm havin issues with python (Sorry for my personal feelings before.. :P).
I have a txt file, it contains a custom language and I have to translate it to a working python code.
The input:
import sys
n = int(sys.argv[1]) ;;print "Beginning of the program!"
LOOP i in range(1,n) {pri... | Generating a python file | I'm havin issues with python (Sorry for my personal feelings before.. :P).
I have a txt file, it contains a custom language and I have to translate it to a working python code.
The input:
import sys
n = int(sys.argv[1]) ;;print "Beginning of the program!"
LOOP i in range(1,n) {print "The number:";;print i}
BR... | [
"If you change the very end of your program:\n # print allWords[i][j],\n print a,\n\nthe output becomes:\nimport sys \n\nn = int(sys.argv[1]) \nprint \"Beginning of the program!\"\n\nfor i in range(1,n) :\n print \"The number:\"\n print i\n\nif n < 5 :\n print n \n print \"less than 5\" \n\nLooks pr... | [
3,
1
] | [] | [] | [
"compiler_construction",
"programming_languages",
"python"
] | stackoverflow_0002945044_compiler_construction_programming_languages_python.txt |
Q:
Optimizing python link matching regular expression
I have a regular expression, links = re.compile('<a(.+?)href=(?:"|\')?((?:https?://|/)[^\'"]+)(?:"|\')?(.*?)>(.+?)</a>',re.I).findall(data)
to find links in some html, it is taking a long time on certain html, any optimization advice?
One that it chokes on is http... | Optimizing python link matching regular expression | I have a regular expression, links = re.compile('<a(.+?)href=(?:"|\')?((?:https?://|/)[^\'"]+)(?:"|\')?(.*?)>(.+?)</a>',re.I).findall(data)
to find links in some html, it is taking a long time on certain html, any optimization advice?
One that it chokes on is http://freeyourmindonline.net/Blog/
| [
"Is there any reason you aren't using an html parser? Using something like BeautifulSoup, you can get all links without using an ugly regex like that.\n",
"I'd suggest using BeautifulSoup for this task.\n",
"How about more straight handling of href's?\nre_href = re.compile(r\"\"\"<\\s*a(?:[^>]+?)href=(\"[^\"]*(... | [
2,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002945364_python_regex.txt |
Q:
Calling/selecting variables (float valued) with user input in Python
I've been working on a computational physics project (plotting related rates of chemical reactants with respect to eachother to show oscillatory behavior) with a fair amount of success. However, one of my simulations involves more than two active... | Calling/selecting variables (float valued) with user input in Python | I've been working on a computational physics project (plotting related rates of chemical reactants with respect to eachother to show oscillatory behavior) with a fair amount of success. However, one of my simulations involves more than two active oscillating agents (five, in fact) which would obviously be unsuitable fo... | [
"Once you have calculated the different arrays, you could add them to a dict that maps names to arrays. This can then be used to look up the correct arrays for display_x and display_y:\nnamed_arrays = {\n \"X\": array_X,\n \"Y\": array_Y,\n \"E\": array_E,\n ...\n}\n\nreturn (named_arrays[display_x], named_arra... | [
1
] | [] | [] | [
"floating_point",
"input",
"python",
"raw_input",
"variables"
] | stackoverflow_0002945486_floating_point_input_python_raw_input_variables.txt |
Q:
Can the Django urls.py system be turned into Pylon's Routes?
Can the Django urls.py system be turned into Pylon's Routes?
A:
Could you be more specific?
If you want to adapt a django urlconf to routes at runtime it would be really tricky if not impossible and would require having a django settings.py present a... | Can the Django urls.py system be turned into Pylon's Routes? | Can the Django urls.py system be turned into Pylon's Routes?
| [
"Could you be more specific? \nIf you want to adapt a django urlconf to routes at runtime it would be really tricky if not impossible and would require having a django settings.py present and an env variable pointing to it.\nOtherwise translating a django urlconf to routes manually is doable. Routes is as flexible... | [
0
] | [] | [] | [
"django",
"pylons",
"python",
"routes"
] | stackoverflow_0002945615_django_pylons_python_routes.txt |
Q:
How do I fix this unicode/cPickle error in Python?
ids = cPickle.loads(gem.value)
loads() argument 1 must be string, not unicode
A:
cPickle.loads wants a byte string (which is exactly what cPickle.dumps outputs) and you're feeding it a unicode string instead. You'll need to "encode" that Unicode string to get ... | How do I fix this unicode/cPickle error in Python? | ids = cPickle.loads(gem.value)
loads() argument 1 must be string, not unicode
| [
"cPickle.loads wants a byte string (which is exactly what cPickle.dumps outputs) and you're feeding it a unicode string instead. You'll need to \"encode\" that Unicode string to get back the byte string that dumps had originally given you, but it's hard to guess what encoding you accidentally imposed on it -- mayb... | [
8,
1
] | [
"You can fix it by making gem.value a string, not unicode.\nUse str(gem.value)\n"
] | [
-1
] | [
"pickle",
"python",
"unicode"
] | stackoverflow_0002946068_pickle_python_unicode.txt |
Q:
django 1.2.1: Override model name in admin interface?
I have a model called "Activity" in my django app. in the admin interface, it appears on the screen as "Activitys". how can I override the label on the admin page to make it "Activities" instead?
I see in the archives how to do this for a field, but not for a m... | django 1.2.1: Override model name in admin interface? | I have a model called "Activity" in my django app. in the admin interface, it appears on the screen as "Activitys". how can I override the label on the admin page to make it "Activities" instead?
I see in the archives how to do this for a field, but not for a model itself. thanks!
| [
"class MyModel(models.Model):\n\n # your fields....\n\n class Meta:\n verbose_name = 'Activity'\n verbose_name_plural = 'Activities'\n\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002946466_django_python.txt |
Q:
WN server filter won't work
WN servers have an alternative to cgi programs called filters. I have been trying to get one to work, but I have had no luck. I am writing in python. It looks like the server is not receiving any output from the program but is parsing nothing and wrapping this nothing in my standard ... | WN server filter won't work | WN servers have an alternative to cgi programs called filters. I have been trying to get one to work, but I have had no luck. I am writing in python. It looks like the server is not receiving any output from the program but is parsing nothing and wrapping this nothing in my standard header and footer. I have chmod ... | [
"I have no real-world WN experience, but I've read its docs and it seems to me there's something wrong with your code -- quoting,\n\nno headers should be supplied by the\n program as WN will automatically\n provide them. For example, while a\n CGI/1.1 program typically starts with\n printing \"Content-type: tex... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002946299_python.txt |
Q:
Recursion function not working properly
I'm having quite a hard time figuring out what's going wrong here:
class iterate():
def __init__(self):
self.length=1
def iterated(self, n):
if n==1:
return self.length
elif n%2==0:
self.length+=1
self.itera... | Recursion function not working properly | I'm having quite a hard time figuring out what's going wrong here:
class iterate():
def __init__(self):
self.length=1
def iterated(self, n):
if n==1:
return self.length
elif n%2==0:
self.length+=1
self.iterated(n/2)
elif n!=1:
self.... | [
"In the two elif blocks, you don't return a value after making the recursive call. You need a return before the recursive calls to iterated (e.g. return self.iterated(n/2)). If you don't explicitly return, the function will return None.\nThat will fix this issue, but there is a way to make your code simpler: You do... | [
5,
3,
2,
2
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0002946631_python_recursion.txt |
Q:
CSS file pathing problem
When designing a HTML template in my favorite editor (TextPad at the moment) I can view my code in a browser by pressing F11 or the appropriate toolbar button. I have my common css rules in a separate file so my HTML contains the code:
<link rel="stylesheet" href="commoncss.css" type="te... | CSS file pathing problem | When designing a HTML template in my favorite editor (TextPad at the moment) I can view my code in a browser by pressing F11 or the appropriate toolbar button. I have my common css rules in a separate file so my HTML contains the code:
<link rel="stylesheet" href="commoncss.css" type="text/css">
This works when the ... | [
"If you put your CSS files in a top-level \"/css\" directory, then your HTML files can just refer to that.\n<link rel='stylesheet' href='/css/style_file1.css'>\n\nI don't know much about your framework; sometimes there's an additional layer under the server root to identify an \"application\" or something. If that'... | [
3,
2
] | [] | [] | [
"css",
"jinja2",
"path",
"python",
"templates"
] | stackoverflow_0002946404_css_jinja2_path_python_templates.txt |
Q:
python simpleJSONDecoder and complex JSON issue
In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an object that isn't there, but should be.
I went through the sub-objects and found tha... | python simpleJSONDecoder and complex JSON issue | In a unit test case that I am running, I get a KeyError exception on the 4th json object in the json text below because the piece of code responsible for decoding is looking for an object that isn't there, but should be.
I went through the sub-objects and found that it was the "cpuid" object that causes the problem. ... | [
"Copying and pasting what you're passing to self.json_encode, and using it as an argument of json.dumps (after an import json in Python 2.6), works just fine. So it seems the bug may be in the json_encode method you're not showing us: what else does it do, besides just calling json.dumps...? (or simplejson.dumps ... | [
1,
0
] | [] | [] | [
"json",
"python",
"simplejson"
] | stackoverflow_0002946768_json_python_simplejson.txt |
Q:
Index of nth biggest item in Python list
I can't edit or sort the list. How can I get that index?
A:
The heapq module provides a nlargest function that efficiently finds the n largest elements of a list:
>>> from heapq import nlargest
>>> items = [100, 300, 200, 400]
>>> indexes = [0, 1, 2, 3]
>>> nlargest(2, in... | Index of nth biggest item in Python list | I can't edit or sort the list. How can I get that index?
| [
"The heapq module provides a nlargest function that efficiently finds the n largest elements of a list:\n>>> from heapq import nlargest\n>>> items = [100, 300, 200, 400]\n>>> indexes = [0, 1, 2, 3]\n>>> nlargest(2, indexes, key=lambda i: items[i])\n[3, 1]\n\n",
"What you've got is already O(n) in complexity (max ... | [
6,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002946861_list_python.txt |
Q:
Transitioning from php to python/pylons/SQLAlchemy -- Are ORMs the standard now?
Should I invest a lot of time trying to figure out an ORM style implementation, or is it still common to just stick with standard SQL queries in python/pylons/sqlalchemy?
A:
ORMs are very popular, for several reasons -- e.g.: some p... | Transitioning from php to python/pylons/SQLAlchemy -- Are ORMs the standard now? | Should I invest a lot of time trying to figure out an ORM style implementation, or is it still common to just stick with standard SQL queries in python/pylons/sqlalchemy?
| [
"ORMs are very popular, for several reasons -- e.g.: some people would rather not learn SQL, ORMs can ease porting among different SQL dialects, they may fit in more smoothly with the mostly-OOP style of applications, indeed might even ease some porting to non-SQL implementations (e.g, moving a Django app to Google... | [
8,
1
] | [] | [] | [
"orm",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002947172_orm_python_sql_sqlalchemy.txt |
Q:
Python vs all the major professional languages
I've been reading up a lot lately on comparisons between Python and a bunch of the more traditional professional languages - C, C++, Java, etc, mainly trying to find out if its as good as those would be for my own purposes. I can't get this thought out of my head that... | Python vs all the major professional languages | I've been reading up a lot lately on comparisons between Python and a bunch of the more traditional professional languages - C, C++, Java, etc, mainly trying to find out if its as good as those would be for my own purposes. I can't get this thought out of my head that it isn't good for 'real' programming tasks beyond a... | [
"An open source project I work on for VCS integration (RabbitVCS) is written entirely in Python/PyGTK and includes:\n\nTwo file browser extensions\nA text editor extension\nA backend VCS status cache running asynchronously, using DBUS for the interface\nA fairly comprehensive set of dialogs, including VCS log brows... | [
5
] | [] | [] | [
"c",
"comparison",
"python"
] | stackoverflow_0002947341_c_comparison_python.txt |
Q:
Efficient job progress update in web application
Creating a web application (Django in my case, but I think the question is more general) that is administrating a cluster of workers doing queued jobs, there is a need to track each jobs progress.
When I've done it using database UPDATE (PostgreSQL in this case), it... | Efficient job progress update in web application | Creating a web application (Django in my case, but I think the question is more general) that is administrating a cluster of workers doing queued jobs, there is a need to track each jobs progress.
When I've done it using database UPDATE (PostgreSQL in this case), it severely hits the database performance, because each ... | [
"There is a package called memcached which sets up a fast server for key-value retrieval. It's used by big clustered sites like wikipedia.\nIt lets you share frequent-changed data around your cluster without DB overhead.\n",
"If you are doing the inserts/updates/retreives based on keys (for example you are access... | [
1,
1
] | [] | [] | [
"database",
"django",
"postgresql",
"python",
"web_applications"
] | stackoverflow_0002855277_database_django_postgresql_python_web_applications.txt |
Q:
optparse: No option string
I am trying to use optparse but I am having a problem.
My script usage would be: script <filename>
I don't intend to add any option string, such as: script -f <filename> or script --file <filename>
Is there any way I can choose not to pass an argument string? Or is there any way I can al... | optparse: No option string | I am trying to use optparse but I am having a problem.
My script usage would be: script <filename>
I don't intend to add any option string, such as: script -f <filename> or script --file <filename>
Is there any way I can choose not to pass an argument string? Or is there any way I can allow the user to do this:
script ... | [
"import optparse\n\nparser = optparse.OptionParser()\nparser.add_option(\"-f\", \"--filename\", metavar=\"FILE\", dest=\"input_file\", action=\"append\")\noptions, args = parser.parse_args()\nif options.input_file:\n args.extend(options.input_file)\n\nfor arg in args:\n process_file(arg)\n\nThis will simply u... | [
1
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0002947993_optparse_python.txt |
Q:
Problems parsing a xml file
I am editing a xml file that is originally like that:
<SequencerLoopCommand id="1073"
IterationCount="2"
CommandList="1241 1242"
Name="Loop Stream IDU64ToIDU63">
<IterateLoadSizeCommand id="1241"
LoadType="STEP"
LoadUnits="KILOBITS_PER_SECOND"
... | Problems parsing a xml file | I am editing a xml file that is originally like that:
<SequencerLoopCommand id="1073"
IterationCount="2"
CommandList="1241 1242"
Name="Loop Stream IDU64ToIDU63">
<IterateLoadSizeCommand id="1241"
LoadType="STEP"
LoadUnits="KILOBITS_PER_SECOND"
LoadStart="100"
LoadE... | [
"I guess it's not easy by default as both XMLs are identical (from parser POV).\nHowever, You can write custom SAX serializer that will break & ident attributes. See http://docs.python.org/library/xml.sax.handler.html#module-xml.sax.handler , but I'd say it's not worth the effort. \n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002948386_python.txt |
Q:
Why can't my function access a variable in an enclosing function?
I know about the LEGB rule. But a simple test of whether a function has read access to variables defined in an enclosing function doesn't seem to actually work. Ie:
#!/usr/bin/env python2.4
'''Simple test of Python scoping rules'''
def myfunction()... | Why can't my function access a variable in an enclosing function? | I know about the LEGB rule. But a simple test of whether a function has read access to variables defined in an enclosing function doesn't seem to actually work. Ie:
#!/usr/bin/env python2.4
'''Simple test of Python scoping rules'''
def myfunction():
print 'Hope this works: '+myvariable
def enclosing():
myvari... | [
"you can...\nif you did it like this:\n#!/usr/bin/env python2.4\n'''Simple test of Python scoping rules'''\n\ndef enclosing():\n myvariable = 'ooh this worked'\n\n def myfunction():\n print 'Hope this works: ' + myvariable\n\n myfunction()\n\nif __name__ == '__main__':\n enclosing()\n\n...otherw... | [
2
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0002948526_python_scope.txt |
Q:
How do I create a Django ModelForm, so that it's fields are sometimes required, sometimes not?
Ok, here is the question.
Imagine I have a ModelForm which have only two fields. like this one:
class ColorForm(forms.Form):
color_by_name = forms.CharField()
color = forms.IntegerField(widget = forms.Select(ch... | How do I create a Django ModelForm, so that it's fields are sometimes required, sometimes not? | Ok, here is the question.
Imagine I have a ModelForm which have only two fields. like this one:
class ColorForm(forms.Form):
color_by_name = forms.CharField()
color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES))
So a user can either input a color name, a choose it from a list. Color is re... | [
"Make them both required=False, but write a clean() method which checks for one or the other. See the validation documentation for an example.\n"
] | [
7
] | [] | [] | [
"django",
"modelform",
"python"
] | stackoverflow_0002948626_django_modelform_python.txt |
Q:
Equivalent of alarm(3600) in Python
Starting a Perl script with alarm(3600) will make the script abort if it is still running after one hour (3600 seconds).
Assume I want to set an upper bound on the running time of a Python script, what is the easiest way to achieve that?
A:
on Unix you could use signal.alarm.
... | Equivalent of alarm(3600) in Python | Starting a Perl script with alarm(3600) will make the script abort if it is still running after one hour (3600 seconds).
Assume I want to set an upper bound on the running time of a Python script, what is the easiest way to achieve that?
| [
"on Unix you could use signal.alarm.\n",
"Just for your information: this is much self-descriptive to use multiplication when you set up timers, for example alarm(24 * 60 * 60) for 24 hours, instead of alarm(86400) for the same period. Hope this will help keep your code clean and easy-maintainable :)\n"
] | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0002948455_python.txt |
Q:
What would the jvm have to sacrifice in order to implement tail call optimisation?
People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation.
http://lambda-the-ultimate.org/node/2547
It has been sa... | What would the jvm have to sacrifice in order to implement tail call optimisation? | People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation.
http://lambda-the-ultimate.org/node/2547
It has been said that to implement TCO into Python would sacrifice
stack-trace dumps, and
debugging... | [
"Whilst different (in that the il instructions existed already) it's worth noting the additional effort the .Net 64 bit JIT team had to go through to respect all tail calls.\nI call out in particular the comment:\n\nThe down side of course is that if you have to debug or profile optimized code, be prepared to deal ... | [
6,
2,
0
] | [] | [] | [
"clojure",
"jvm",
"python",
"stack_trace",
"tail_call_optimization"
] | stackoverflow_0001006596_clojure_jvm_python_stack_trace_tail_call_optimization.txt |
Q:
python win32gui finding child windows
for example at first you have to find hwnd of skype
hwnd = win32gui.FindWindow(None, 'skype')
and than all his child windows and their titles
child = ???
any idea?
A:
This code shows hwnd of EditPlus child windows that has WindowsText of some length:
EDIT
You will have to ... | python win32gui finding child windows | for example at first you have to find hwnd of skype
hwnd = win32gui.FindWindow(None, 'skype')
and than all his child windows and their titles
child = ???
any idea?
| [
"This code shows hwnd of EditPlus child windows that has WindowsText of some length:\nEDIT\nYou will have to find hwnd of your application, and then use this handle with EnumChildWindows. I extended example code with it. Once you get application hwnd you can enumerate only its windows. When you give 0 as hwnd to En... | [
8
] | [] | [] | [
"python",
"win32gui"
] | stackoverflow_0002948964_python_win32gui.txt |
Q:
UDP packages appear in wireshark, but are not received by program
I am trying to read UDP packages sent by an FPGA with my computer. They are sent
to port 21844 and to the IP 192.168.1.2 (which is my computer's IP). I can see the package in wireshark, they have no errors. When I run however this little python scri... | UDP packages appear in wireshark, but are not received by program | I am trying to read UDP packages sent by an FPGA with my computer. They are sent
to port 21844 and to the IP 192.168.1.2 (which is my computer's IP). I can see the package in wireshark, they have no errors. When I run however this little python script, then only a very very small fraction of all packages are received b... | [
"The TCP/IP stack of your OS doesn't hold those packets for you for eternity. Your script looks like something that very much depends on when it is run. Try to recvfrom in a loop, and run the script in the background. Then, start sending packets from your FPGA. \nFor extra convenience, explore the SocketServer modu... | [
3,
3
] | [] | [] | [
"python",
"udp",
"wireshark"
] | stackoverflow_0002928507_python_udp_wireshark.txt |
Q:
Error in unzipping a file from a python script running as daemon
I am getting an error whenever i try to run following unzip command from a python script which is running as a daemon
Command :
unzip abcd.zip > /dev/null
Error
End-of-central-directory signature not found$ a zip file, or it
constitutes one disk... | Error in unzipping a file from a python script running as daemon | I am getting an error whenever i try to run following unzip command from a python script which is running as a daemon
Command :
unzip abcd.zip > /dev/null
Error
End-of-central-directory signature not found$ a zip file, or it
constitutes one disk of a multi-part archive. In the latter case
the central directory and... | [
"Usually that would mean exactly what it says: that the file abcd.zip is not a valid ZIP file. Are you able to unzip abcd.zip as a normal user? If not, it would seem to have become corrupted. How did you get hold of it? Check for newline-mangling operations like ASCII-mode FTP.\nCan you read the file with the built... | [
1,
0
] | [] | [] | [
"linux",
"python",
"unzip"
] | stackoverflow_0002949429_linux_python_unzip.txt |
Q:
Unable to write to a text file
I am running some tests and need to write to a file. When I run the test's the open = (file, 'r+') does not write to the file. The test script is below:
class GetDetailsIP(TestGet):
def runTest(self):
self.category = ['PTZ']
try:
# This run's and re... | Unable to write to a text file | I am running some tests and need to write to a file. When I run the test's the open = (file, 'r+') does not write to the file. The test script is below:
class GetDetailsIP(TestGet):
def runTest(self):
self.category = ['PTZ']
try:
# This run's and return's a value
result = ... | [
"After writing, your cursor is at the end of the file. If you want to read the text you have to move to the beginning:\n>>> mylogfile = open(\"test10.txt\", \"w+\")\n>>> print >> mylogfile, 'hola'\n>>> mylogfile.flush() #just in case\n>>> print mylogfile.read()\n #nothing because ... | [
5
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002949581_file_io_python.txt |
Q:
Python: Networked IDLE/Redo IDLE front-end while using the same back-end?
Is there any existing web app that lets multiple users work with an interactive IDLE type session at once?
Something like:
IDLE 2.6.4
Morgan: >>> letters = list("abcdefg")
Morgan: >>> # now, how would you iterate over letters?
Jack: >>> for ... | Python: Networked IDLE/Redo IDLE front-end while using the same back-end? | Is there any existing web app that lets multiple users work with an interactive IDLE type session at once?
Something like:
IDLE 2.6.4
Morgan: >>> letters = list("abcdefg")
Morgan: >>> # now, how would you iterate over letters?
Jack: >>> for char in letters:
print "char %s" % char
char a
char b
char c
char d
char ... | [
"I could implement something like this pretty quickly in Nevow. Obviously, access would need to be pretty restricted since doing something like this involves allowing access to a Python console to someone via HTTP.\nWhat I'd do is create an Athena widget for the console, that used an instance of a custom subclass ... | [
1,
1,
0
] | [
"this is likely possible with the upcoming implimentation of IPython using a 0MQ backend.\n",
"I would use ipython and screen. With this method, you would have to create a shared login, but you could both connect to the shared screen session. One downside would be that you would both appear as the same user.\n"
] | [
-1,
-1
] | [
"python",
"python_idle",
"user_interface"
] | stackoverflow_0002893401_python_python_idle_user_interface.txt |
Q:
Where to store a datastore cursor, in memcache or in the datastore?
In the google documentation it shows storing cursors in memcache, however as pointed out in an answer to this question memcache retention isn't guaranteed.
So I was wondering how other people store cursors and what strategies you use for handling ... | Where to store a datastore cursor, in memcache or in the datastore? | In the google documentation it shows storing cursors in memcache, however as pointed out in an answer to this question memcache retention isn't guaranteed.
So I was wondering how other people store cursors and what strategies you use for handling missing cursors?
| [
"In the case of task queue chaining, as in the linked question, it may be best to just send the cursor in the payload for the next task (which is also mentioned in the documentation.) Memcache is fine if occasionally losing your place and starting over is acceptable. In theory if you're storing a small bit of dat... | [
3,
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002948728_google_app_engine_python.txt |
Q:
how to get selected item in pyqt Qmenu
is there any way to get the selected item in a qmenu ?
i want to bind all items in that list to one function and get the item once user click it .
i've been looking for a way to get the item's label or index for 3 days , but couldn't find it .
any ideas ?
thanks in advance
... | how to get selected item in pyqt Qmenu | is there any way to get the selected item in a qmenu ?
i want to bind all items in that list to one function and get the item once user click it .
i've been looking for a way to get the item's label or index for 3 days , but couldn't find it .
any ideas ?
thanks in advance
| [
"You can achieve this with signals.\nConnect all triggered slots of your menu items to your function. Then, in this function, use the static function QObject::sender to retrieve the menu item which has sent the signal.\n"
] | [
3
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0002948411_pyqt_pyqt4_python_qt_qt4.txt |
Q:
How to exit a program: sys.stderr.write() or print
I am writing a small app and I need to quit the program multiple number of times.
Should I use:
sys.stderr.write('Ok quitting')sys.exit(1)
Or should I just do a:
print 'Error!'sys.exit(1)
Which is better and why? Note that I need to do this a lot. The program shou... | How to exit a program: sys.stderr.write() or print | I am writing a small app and I need to quit the program multiple number of times.
Should I use:
sys.stderr.write('Ok quitting')sys.exit(1)
Or should I just do a:
print 'Error!'sys.exit(1)
Which is better and why? Note that I need to do this a lot. The program should completely quit.
| [
"sys.exit('Error!')\n\nNote from the docs:\n\nIf another type of object is passed,\n None is equivalent to passing zero,\n and any other object is printed to\n sys.stderr and results in an exit code\n of 1. In particular, sys.exit(\"some\n error message\") is a quick way to exit\n a program when an error occu... | [
124,
17,
10
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0002949974_error_handling_python.txt |
Q:
Update a gallery webpage via Dropbox?
I'd like to know if the following situation and scripts are at all possible:
I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?).
That is, when someone adds a picture to the Dropbox fo... | Update a gallery webpage via Dropbox? | I'd like to know if the following situation and scripts are at all possible:
I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?).
That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that... | [
"If you can install the DropBox client on the webserver then it would be simple to let it sync your folder and then iterate over the contents of the folder with a programming language (PHP, Python, .NET etc) and produce the gallery page. This could be done every time the page is requested or as a scheduled job whi... | [
2,
1,
0
] | [] | [] | [
"dropbox",
"html",
"php",
"python"
] | stackoverflow_0001522951_dropbox_html_php_python.txt |
Q:
strange(?) module import syntax
I've come across the following code in a Python script
from pprint import pprint
why not simply import pprint?
Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)
A:
It does contain a functi... | strange(?) module import syntax | I've come across the following code in a Python script
from pprint import pprint
why not simply import pprint?
Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)
| [
"It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you?\n",
"Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name.\n",... | [
3,
1,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0002950275_import_python.txt |
Q:
Django - Expression based model constraints
Is it possible to set an expression based constraint on a django model object, e.g. If I want to impose a constraint where an owner can have only one widget of a given type that is not in an expired state, but can have as many others as long as they are expired. Obviousl... | Django - Expression based model constraints | Is it possible to set an expression based constraint on a django model object, e.g. If I want to impose a constraint where an owner can have only one widget of a given type that is not in an expired state, but can have as many others as long as they are expired. Obviously I can do this by overriding the save method, bu... | [
"This sounds like a job for the new model validation support in Django 1.2. \n",
"No, I don't think this will fly. The model's expecting a tuple of tuples and then the modelform base that checks it seems to grab and compare values, not run expressions.\nStill, you can do it in save(), as you say - or using model ... | [
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002948813_django_python.txt |
Q:
App Engine Transaction Entity group problem
I have an issue with creating a transaction. I get an error back that the objects are not in the same entity group.
I have a type called Relationship and I need to create a two way relationship between two parties.
def _transaction():
relationship1 = Relationship(fir... | App Engine Transaction Entity group problem | I have an issue with creating a transaction. I get an error back that the objects are not in the same entity group.
I have a type called Relationship and I need to create a two way relationship between two parties.
def _transaction():
relationship1 = Relationship(firstParty = party1, secondParty = party2)
relat... | [
"You need to understand entity groups before you can effectively work with transactions in app engine. Start here. In short, only entities (what you call records) in the same entity group can be involved in a transaction. By default, entities are created in their own group, so you will not be able to perform a ... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"transactions"
] | stackoverflow_0002950360_google_app_engine_python_transactions.txt |
Q:
Several modules in a package importing one common module
I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a separate process.
Because of the base commonality between the plugins (e... | Several modules in a package importing one common module | I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a separate process.
Because of the base commonality between the plugins (e.g. all extend a base class 'Worker'), The plugin module gener... | [
"No worry: only the first import of a module in the course of a program's execution causes it to be loaded. Every further import after that first one just fetches the module object from a \"cache\" dictionary (sys.modules, indexed by module name strings) and therefore it's both very fast and bereft of side effects... | [
26
] | [] | [] | [
"python"
] | stackoverflow_0002950557_python.txt |
Q:
Realtime processing and callbacks with Python and C++
I need to write code to do some realtime processing that is fairly computationally complex. I would like to create some Python classes to manage all my scripting, and leave the intensive parts of the algorithm coded in C++ so that they can run as fast as possib... | Realtime processing and callbacks with Python and C++ | I need to write code to do some realtime processing that is fairly computationally complex. I would like to create some Python classes to manage all my scripting, and leave the intensive parts of the algorithm coded in C++ so that they can run as fast as possible. I would like to instantiate the objects in Python, and... | [
"Have a look at Boost.Python. Its tutorial starts here.\n",
"I suggest using Boost.Python as suggested by ChristopheD. A gotcha would be if the C++ extension is running in it's own thread context (not created by Python). If that's the case, make sure to use the PyGILState_Ensure() and PyGILState_Release() funct... | [
4,
3,
0,
0
] | [] | [] | [
"c++",
"callback",
"python",
"real_time"
] | stackoverflow_0002946226_c++_callback_python_real_time.txt |
Q:
Debugging (displaying) SQL command sent to the db by SQLAlchemy
I have an ORM class called Person, which wraps around a person table:
After setting up the connection to the db etc, I run the statement:
people = session.query(Person).all()
The person table does not contain any data (as yet), so when I print the va... | Debugging (displaying) SQL command sent to the db by SQLAlchemy | I have an ORM class called Person, which wraps around a person table:
After setting up the connection to the db etc, I run the statement:
people = session.query(Person).all()
The person table does not contain any data (as yet), so when I print the variable people, I get an empty list.
I renamed the table referred to i... | [
"In addition to echo parameter of create_engine() there is a more flexible way: configuring logging to echo engine statements:\nimport logging\nlogging.basicConfig()\nlogging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)\n\nSee Configuring Logging section of documentation for more information.\n",
"You ca... | [
272,
119
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002950385_python_sqlalchemy.txt |
Q:
python,running command line servers - they're not listening properly
Im attempting to start a server app (in erlang, opens ports and listens for http requests) via the command line using pexpect (or even directly using subprocess.Popen()).
the app starts fine, logs (via pexpect) to the screen fine, I can interac... | python,running command line servers - they're not listening properly | Im attempting to start a server app (in erlang, opens ports and listens for http requests) via the command line using pexpect (or even directly using subprocess.Popen()).
the app starts fine, logs (via pexpect) to the screen fine, I can interact with it as well via command line...
the issue is that the servers wont l... | [
"It could be to do with the way that command line arguments are passed to the subprocess.\nWithout more specific code, I can't say for sure, but I had this problem working on sshsplit ( https://launchpad.net/sshsplit )\nTo pass arguments correctly (in this example \"ssh -ND 3000\"), you should use something like th... | [
0
] | [] | [] | [
"command_line",
"pexpect",
"python"
] | stackoverflow_0002947724_command_line_pexpect_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.