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:
Testing for external resource consistency / skipping django tests
I'm writing tests for a Django application that uses an external data source. Obviously, I'm using fake data to test all the inner workings of my class but I'd like to have a couple of tests for the actual fetcher as well. One of these will need to ... | Testing for external resource consistency / skipping django tests | I'm writing tests for a Django application that uses an external data source. Obviously, I'm using fake data to test all the inner workings of my class but I'd like to have a couple of tests for the actual fetcher as well. One of these will need to verify that the external source is still sending the data in the format... | [
"I created a separate answer since your edit invalidated my last answer.\nI assume you're running on Python version 2.6 - I believe the changes that you're looking for in unittest are available in Python version 2.7. Since unittest is in the standard library, updating to Python 2.7 should make those changes availa... | [
1,
1,
0
] | [] | [] | [
"django",
"python",
"skip",
"unit_testing"
] | stackoverflow_0003240049_django_python_skip_unit_testing.txt |
Q:
Sorting list that has tuple as an element with Python
I have a list as follows.
[(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
How can I sort the list to get
[1,2,3,4,5,6,7,8]
or
[8,7,6,5,4,3,2,1]
?
A:
Convert the list of tuples into a list of integers, then sort it:
thelist = [(5,), (2,), (4,), (1,), (3,... | Sorting list that has tuple as an element with Python | I have a list as follows.
[(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]
How can I sort the list to get
[1,2,3,4,5,6,7,8]
or
[8,7,6,5,4,3,2,1]
?
| [
"Convert the list of tuples into a list of integers, then sort it:\nthelist = [(5,), (2,), (4,), (1,), (3,), (6,), (7,), (8,)]\n\nsortedlist = sorted([x[0] for x in thelist])\n\nprint sortedlist\n\nSee it on codepad\n",
"I'll give you an even more generalized answer:\nfrom itertools import chain\nsorted( chain.fr... | [
4,
1,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003689830_python_sorting.txt |
Q:
Use of ctypes module
I need to program VIX API of VMware. It´s a dll wrote with C functions...
I want program in python calling this functions using ctypes and I don´t understand the documentation of ctypes in python web page...
Can someone give some samples with how to do this????
Thanks,
A:
I've been meaning t... | Use of ctypes module | I need to program VIX API of VMware. It´s a dll wrote with C functions...
I want program in python calling this functions using ctypes and I don´t understand the documentation of ctypes in python web page...
Can someone give some samples with how to do this????
Thanks,
| [
"I've been meaning to do something like this for a while. I downloaded the VIX API kit, and extracted the vix.h file, containing all of the VIX API function prototypes. I then wrote a short pyparsing parser to extract the typedefs and function declarations, and convert them to ctypes definitions. With these defi... | [
3,
2,
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003687762_ctypes_python.txt |
Q:
Writing white-space delimited text to be human readable in Python
I have a list of lists that looks something like this:
data = [['seq1', 'ACTAGACCCTAG'],
['sequence287653', 'ACTAGNACTGGG'],
['s9', 'ACTAGAAACTAG']]
I write the information to a file like this:
for i in data:
for j in i:
... | Writing white-space delimited text to be human readable in Python | I have a list of lists that looks something like this:
data = [['seq1', 'ACTAGACCCTAG'],
['sequence287653', 'ACTAGNACTGGG'],
['s9', 'ACTAGAAACTAG']]
I write the information to a file like this:
for i in data:
for j in i:
file.write('\t')
file.write(j)
file.write('\n')
The o... | [
"You need a format string:\nfor i,j in data:\n file.write('%-15s %s\\n' % (i,j))\n\n%-15s means left justify a 15-space field for a string. Here's the output:\nseq1 ACTAGACCCTAG\nsequence287653 ACTAGNACTGGG\ns9 ACTAGAAACTAG\n\n",
"data = [['seq1', 'ACTAGACCCTAG'],\n ['sequence2... | [
10,
1,
0
] | [] | [] | [
"human_readable",
"python",
"whitespace"
] | stackoverflow_0003689936_human_readable_python_whitespace.txt |
Q:
Django DB design to glob words quickly
I need to quickly look up words for a web application that I am writing in Django. I was thinking of putting each character of the word in an integerfield of its own, indexed by position.
class Word(models.Model):
word = models.CharField(max_length=5)
length = models... | Django DB design to glob words quickly | I need to quickly look up words for a web application that I am writing in Django. I was thinking of putting each character of the word in an integerfield of its own, indexed by position.
class Word(models.Model):
word = models.CharField(max_length=5)
length = models.IntegerField()
c0 = models.IntegerFiel... | [
"\nWould mapping[2] work?\n\nNo, it wouldn't.\n\nWould I be able to pass in a dictionary to the filter command so that I can have a variable number of keyword arguments?\n\nCertainly. For instance:\nconditions = dict(word__startswith = 'A', length = 5)\nWord.objects.filter(**conditions)\n\nwould find all Word insta... | [
0
] | [] | [] | [
"database_design",
"django",
"glob",
"python"
] | stackoverflow_0003689971_database_design_django_glob_python.txt |
Q:
Best way to suppress exceptions raised when third-party service is unavailable?
I've written a Django application which interacts with a third-party API (Disqus, although this detail is unimportant) via a Python wrapper. When the service is unavailable, the Python wrapper raises an exception.
The best way for the ... | Best way to suppress exceptions raised when third-party service is unavailable? | I've written a Django application which interacts with a third-party API (Disqus, although this detail is unimportant) via a Python wrapper. When the service is unavailable, the Python wrapper raises an exception.
The best way for the application to handle such exceptions is to suppress them so that the rest of the pag... | [
"Making API calls from views is not so good idea. You should probably create another module, that does the job.\nie. when I make Facebook apps I create publish.py file to store all \"publish to live stream\" calls. Functions in that module are named based on when they should be called. Ie.:\n# publish.py\ndef autho... | [
2,
1
] | [] | [] | [
"django",
"exception_handling",
"python"
] | stackoverflow_0003690077_django_exception_handling_python.txt |
Q:
Parse JavaScript variable with Python
How can I convert a JavaScript variable (not JSON format) into a python variable?
Example JavaScript variable:
{
title: "TITLE",
name: "NAME",
active: false,
info: {
key1: "value1",
dict1: {
sub_key1: "sub_value1",
sub_ke... | Parse JavaScript variable with Python | How can I convert a JavaScript variable (not JSON format) into a python variable?
Example JavaScript variable:
{
title: "TITLE",
name: "NAME",
active: false,
info: {
key1: "value1",
dict1: {
sub_key1: "sub_value1",
sub_key2: "sub_value2",
},
dict2:... | [
"This format looks just like the input in this question. Try adapting the pyparsing parser I posted there.\n",
"Convert it to JSON and read it in python.\nI really do not understand what is the problem?\ne.g. JSON.stringify gives\n{\"title\":\"TITLE\",\"name\":\"NAME\",\"active\":false,\"info\":{\"key1\":\"value... | [
3,
1
] | [] | [] | [
"javascript",
"python",
"variables"
] | stackoverflow_0003690116_javascript_python_variables.txt |
Q:
Many-To-One Relation Query in Django
Can someone tell me, how I can access all contacts relating to a specific group? I'm new to Django and did this (according to the docs):
def view_group(request, group_id):
groups = Group.objects.all()
group = Group.objects.get(pk=group_id)
contacts = group.contacts... | Many-To-One Relation Query in Django | Can someone tell me, how I can access all contacts relating to a specific group? I'm new to Django and did this (according to the docs):
def view_group(request, group_id):
groups = Group.objects.all()
group = Group.objects.get(pk=group_id)
contacts = group.contacts.all()
return render_to_response('mana... | [
"One way:\ngroup = Group.objects.get(pk=group_id)\ncontacts_in_group = Contact.objects.filter(group=group)\n\nAnother, more idomatic, way:\ngroup = Group.objects.get(pk=group_id)\ncontacts_in_group = group.contact_set.all() \n\ncontact_set is the default related_name for the relation as shown in the related objects... | [
6,
3
] | [] | [] | [
"django",
"exception",
"foreign_key_relationship",
"orm",
"python"
] | stackoverflow_0003690825_django_exception_foreign_key_relationship_orm_python.txt |
Q:
This piece of python code should print out some information, but doesn't
The code I'm tring to get should look something like this:
send: 'GET /xml/atom.xml HTTP/1.0\r\nHost: diveintomark.org\r\nUser-Agent: Python-urllib/1.17\r\n\r\n'
reply: 'HTTP/1.1 410 Gone\r\n'
header: Date: Sat, 11 Sep 2010 11:47:19 GMT
... | This piece of python code should print out some information, but doesn't | The code I'm tring to get should look something like this:
send: 'GET /xml/atom.xml HTTP/1.0\r\nHost: diveintomark.org\r\nUser-Agent: Python-urllib/1.17\r\n\r\n'
reply: 'HTTP/1.1 410 Gone\r\n'
header: Date: Sat, 11 Sep 2010 11:47:19 GMT
header: Server: Apache
header: Content-Length: 307
header: Connection: c... | [
"I believe the example is simply wrong, try this instead:\nimport urllib2\n\nrequest = urllib2.Request('http://www.google.co.uk/')\nhttp_handler = urllib2.HTTPHandler(debuglevel=1)\nopener = urllib2.build_opener(http_handler)\nfeeddata = opener.open(request).read()\n\n",
"I got something out of this:\nhttplib.HTT... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0003690923_python.txt |
Q:
I can't delete a folder that I just extracted from a zip file in python
So here's my problem. I have a python script that takes a zipfile and extracts its contents. Then based on some constraint, I will try to delete the folder whose contents were just extracted. For some reason I get an error, WindowsError: [Erro... | I can't delete a folder that I just extracted from a zip file in python | So here's my problem. I have a python script that takes a zipfile and extracts its contents. Then based on some constraint, I will try to delete the folder whose contents were just extracted. For some reason I get an error, WindowsError: [Error 5] Access is denied: 'Foldername' when i try to delete that folder. The sim... | [
"Many reasons possible. \n\nYou need to use os.rmdir to remove directories\nYou need to empty the folder\nfirst - remember, the Windows command\nrmdir needs a /S option to\nremove the contents, and Python probably uses that.\nIs the unzip\nalso using the archive's attributes?\nRead-only attributes may be applied.\n... | [
4,
1
] | [] | [] | [
"operating_system",
"python",
"windows",
"windows_vista",
"zip"
] | stackoverflow_0003688456_operating_system_python_windows_windows_vista_zip.txt |
Q:
Python: quickly loading 7 GB of text files into unicode strings
I have a large directory of text files--approximately 7 GB. I need to load them quickly into Python unicode strings in iPython. I have 15 GB of memory total. (I'm using EC2, so I can buy more memory if absolutely necessary.)
Simply reading the file... | Python: quickly loading 7 GB of text files into unicode strings | I have a large directory of text files--approximately 7 GB. I need to load them quickly into Python unicode strings in iPython. I have 15 GB of memory total. (I'm using EC2, so I can buy more memory if absolutely necessary.)
Simply reading the files will be too slow for my purposes. I have tried copying the files t... | [
"There is much that is confusing here, which makes it more difficult to answer this question:\n\nThe ipython requirement. Why do you need to process such large data files from within ipython instead of a stand-alone script?\nThe tmpfs RAM disk. I read your question as implying that you read all of your input data... | [
3,
2
] | [] | [] | [
"ctypes",
"ipython",
"memory",
"python",
"shared_memory"
] | stackoverflow_0003647937_ctypes_ipython_memory_python_shared_memory.txt |
Q:
python html form library that supports forms within form (form as a field )?
The question says it all,
For example,
In a contact book if someone has multiple addresses with each address having multiple fields I want to display an "add another address" button. This button would add another address form. (I want o... | python html form library that supports forms within form (form as a field )? | The question says it all,
For example,
In a contact book if someone has multiple addresses with each address having multiple fields I want to display an "add another address" button. This button would add another address form. (I want one round trip to the server, I do not want javascript or webforms2.)
It would be n... | [
"Try django-formsets, and if you want dynamic behavior use this http://code.google.com/p/django-dynamic-formset/\n"
] | [
1
] | [] | [] | [
"form_processing",
"forms",
"python"
] | stackoverflow_0003691140_form_processing_forms_python.txt |
Q:
Counting content only in HTML page
Is there anyway I can parse a website by just viewing the content as displayed to the user in his browser? That is, instead of downloading "page.htm"l and starting to parse the whole page with all the HTML/javascript tags, I will be able to retrieve the version as displayed to us... | Counting content only in HTML page | Is there anyway I can parse a website by just viewing the content as displayed to the user in his browser? That is, instead of downloading "page.htm"l and starting to parse the whole page with all the HTML/javascript tags, I will be able to retrieve the version as displayed to users in their browsers. I would like to "... | [
"You could get the source and strip the tags out, leaving only non-tag text, which works for almost all pages, except those where JavaScript-generated content is essential.\n",
"A browser also downloads the page.html and then renders it. You should work the same way. Use a html parser like lxml.html or BeautifulS... | [
0,
0,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003690560_html_python.txt |
Q:
To IDE or Not? A beginner developer's dilemma
Basically, me and a friend of mine are just planning to work on a Python project which would have GUI interface, and enable file transfer over and remote file listing. We have most of the tools which we are going to use, Glade, Python etcetera.
I just want to know if I... | To IDE or Not? A beginner developer's dilemma | Basically, me and a friend of mine are just planning to work on a Python project which would have GUI interface, and enable file transfer over and remote file listing. We have most of the tools which we are going to use, Glade, Python etcetera.
I just want to know if I should use an IDE or not.
I've heard only good thi... | [
"The ability to debug using an IDE makes your life so much easier.\n",
"Python is a particularly strange language in that having a full-fledged IDE doesn't really add much (and some would argue that an IDE tends to severely limit your thinking-flow in Python). I've been using regular Vim and Gedit to develop in P... | [
8,
4,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"anjuta",
"ide",
"python"
] | stackoverflow_0003690915_anjuta_ide_python.txt |
Q:
How is pip install using git different than just cloning a repository?
I'm a beginner with Django and I'm having trouble installing django-basic-apps using pip.
If I do this...
$ cat requirements.txt
git+git://github.com/nathanborror/django-basic-apps.git
$ pip install -r requirements.txt
I end up with lib/py... | How is pip install using git different than just cloning a repository? | I'm a beginner with Django and I'm having trouble installing django-basic-apps using pip.
If I do this...
$ cat requirements.txt
git+git://github.com/nathanborror/django-basic-apps.git
$ pip install -r requirements.txt
I end up with lib/python2.6/site-packages/basic/blog that does NOT have a templates directory.
I... | [
"When you use \"pip\" to install something, the package's setup.py is used to determine what packages to install. And this project's setup.py, if I'm reading it correctly, says \"just install these Python packages inside the basic directory\" — the setup.py makes absolutely no mention of any non-Python files it wa... | [
28
] | [] | [] | [
"django",
"pip",
"python"
] | stackoverflow_0003689685_django_pip_python.txt |
Q:
How to detect when Firefox has finished loading a page using Python?
Is it possible to use Python to detect when a web page has finished loading in the Firefox browser? I'm trying to automate some browser tasks using Python and this is the major stumbling block for me. Note that this is for small-scale personal u... | How to detect when Firefox has finished loading a page using Python? | Is it possible to use Python to detect when a web page has finished loading in the Firefox browser? I'm trying to automate some browser tasks using Python and this is the major stumbling block for me. Note that this is for small-scale personal use, not a server farm or anything like that. The Firefox browser is in an ... | [
"\nselenium which can execute your scripts.\n\nPythonExt python extension for mozilla.\nEither of these should work.\n\n\n"
] | [
1
] | [] | [] | [
"automation",
"firefox",
"python"
] | stackoverflow_0003691647_automation_firefox_python.txt |
Q:
Iterating over N dimensions in Python
I have a map, let's call it M, which contains data mapped through N dimensions.
# If it was a 2d map, I could iterate it thusly:
start, size = (10, 10), (3, 3)
for x in range(start[0], start[0]+size[0]):
for y in range(start[1], start[1]+size[1]):
M.get((x, y))
# A... | Iterating over N dimensions in Python | I have a map, let's call it M, which contains data mapped through N dimensions.
# If it was a 2d map, I could iterate it thusly:
start, size = (10, 10), (3, 3)
for x in range(start[0], start[0]+size[0]):
for y in range(start[1], start[1]+size[1]):
M.get((x, y))
# A 3d map would add a for z in ... and access... | [
"In Python 2.6+:\nitertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])\n\n",
"With do it your self generator expreessions:\nstart, size = (10, 10), (3, 3)\nvalues2=((x+xd,y+yd)\n for x,y in (start,)\n for xr,yr in (size,)\n for xd in range(xr)\n for yd in range(yr))\n\nfor ... | [
8,
0
] | [] | [] | [
"iteration",
"python",
"recursion"
] | stackoverflow_0003691468_iteration_python_recursion.txt |
Q:
Make Python bool print 'On' or 'Off' rather than 'True' or 'False'
What is the best way to make a variable that works exactly like a bool but prints On or Off rather than True or False? Currently the program is printing: Color: True, whereas Color: On would make more sense.
For the record, I initially tried to mak... | Make Python bool print 'On' or 'Off' rather than 'True' or 'False' | What is the best way to make a variable that works exactly like a bool but prints On or Off rather than True or False? Currently the program is printing: Color: True, whereas Color: On would make more sense.
For the record, I initially tried to make an OnOff class that inherits from bool:
class OnOff(bool):
def __s... | [
"print (\"Off\", \"On\")[value] works too (because (False, True) == (0,1))\n",
"def Color(object):\n\n def __init__(self, color_value=False):\n self.color_value = color_value\n\n def __str__(self):\n if self.color_value:\n return 'On'\n else:\n return 'Off'\n\n def __... | [
19,
10,
6,
4,
3,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"boolean",
"printing",
"python"
] | stackoverflow_0003687109_boolean_printing_python.txt |
Q:
A container for accessing contents by 2d/3d coordinates
There are a lot of games that can generally be viewed as a bunch of objects spread out through space, and a very common operation is to pick all objects in a sub-area. The typical example would be a game with tons of units across a large map, and an explosion... | A container for accessing contents by 2d/3d coordinates | There are a lot of games that can generally be viewed as a bunch of objects spread out through space, and a very common operation is to pick all objects in a sub-area. The typical example would be a game with tons of units across a large map, and an explosion that affects units in a certain radius. This requires pickin... | [
"The first step to writing a practical program is accepting that choices for some constants come from real-world considerations and not transcendent mathematical truths. This especially applies to game design/world simulation type coding, where you'd never get anywhere if you persisted in trying to optimally model ... | [
1,
0,
0
] | [] | [] | [
"c",
"containers",
"python"
] | stackoverflow_0003691278_c_containers_python.txt |
Q:
How to know the path the script the python run?
sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path.
How can I do that with python?
A:
os.path.abspath(sys.argv[0])
A:
import sys
print(sys.path[0])
... | How to know the path the script the python run? | sys.arg[0] gives me the python script. For example 'python hello.py' returns hello.py for sys.arg[0]. But I need to know where the hello.py is located in full path.
How can I do that with python?
| [
"os.path.abspath(sys.argv[0])\n\n",
"import sys\nprint(sys.path[0])\n\nFrom the docs:\n\nAs initialized upon program startup,\n the first item of this list, sys.path[0],\n is the directory containing the script\n that was used to invoke the Python\n interpreter.\n\n",
"You can use __file__, a variable that ... | [
6,
4,
3
] | [] | [] | [
"path",
"python"
] | stackoverflow_0003691921_path_python.txt |
Q:
How to display user error in Python
What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)?
The method should print the error in the standard error and exit the program.
A:
In small programs, I use something like this:
import sys
def ... | How to display user error in Python | What is the best way (standard) to display an error to the user in Python (for example: bad syntax, invalid arguments, logic errors)?
The method should print the error in the standard error and exit the program.
| [
"In small programs, I use something like this:\nimport sys\n\ndef error(message):\n sys.stderr.write(\"error: %s\\n\" % message)\n sys.exit(1)\n\nFor bigger tools, I use the logging package.\ndef error(message):\n logging.error('error: ', message)\n sys.exit(1)\n\n",
"In Python 2, for example:\nimport... | [
4,
4
] | [] | [] | [
"python",
"standards"
] | stackoverflow_0003691798_python_standards.txt |
Q:
"%s" % format vs "{0}".format() vs "?" format
In this post about SQLite, aaronasterling told me that
cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong
cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct
cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing
But, I've thought th... | "%s" % format vs "{0}".format() vs "?" format | In this post about SQLite, aaronasterling told me that
cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong
cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct
cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing
But, I've thought the first and second are the same. What are the diffe... | [
"\"attach \\\"%s\\\" as toMerge\" % \"b.db\"\n\nYou should use ' instead of \", so you don't have to escape.\nYou used the old formatting strings that are deprecated.\n'attach \"{0}\" as toMerge'.format(\"b.db\")\n\nThis uses the new format string feature from newer Python versions that should be used instead of th... | [
20,
6,
3
] | [] | [] | [
"pysqlite",
"python",
"string_formatting"
] | stackoverflow_0003691975_pysqlite_python_string_formatting.txt |
Q:
How to guess out the grammars of a list of sentences generated by some way?
I have a lost of sentences generated from http://www.ywing.net/graphicspaper.php, a random computer graphics paper title generator, some of example sentences sorted are as following:
Abstract Ambient Occlusion using Texture Mapping
Abstra... | How to guess out the grammars of a list of sentences generated by some way? | I have a lost of sentences generated from http://www.ywing.net/graphicspaper.php, a random computer graphics paper title generator, some of example sentences sorted are as following:
Abstract Ambient Occlusion using Texture Mapping
Abstract Ambient Texture Mapping
Abstract Anisotropic Soft Shadows
Abstract Approximat... | [
"You may be interested in Alignment-Based Learning by Menno van Zaanen. It has been years since I read his papers, but the basic idea is to \n\nfind a common substring\nassign it a grammar rule\nrewrite the text to use this rule\ncheck whether rewritten-text+grammar is shorter than original-text.\n\nRun this for al... | [
1,
0,
0
] | [] | [] | [
"lisp",
"nlp",
"python"
] | stackoverflow_0003689855_lisp_nlp_python.txt |
Q:
How do I access outer functions variables inside a closure(python 2.6)?
From wikipedia
I need to access outer functions variables in a similar manner as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword)
A:
I always use helper o... | How do I access outer functions variables inside a closure(python 2.6)? | From wikipedia
I need to access outer functions variables in a similar manner as using the 'nonlocal' keyword from python 3.x. Is there some way to do that in python 2.6? (Not necessarily using the nonlocal keyword)
| [
"I always use helper objects in that case:\ndef outerFunction():\n class Helper:\n val = None\n helper = Helper()\n\n def innerFunction():\n helper.val = \"some value\"\n\nThis also comes in handy when you start a new thread that should write a value to the outer function scope. In that case,... | [
5
] | [] | [] | [
"python",
"python_2.6",
"python_nonlocal"
] | stackoverflow_0003692357_python_python_2.6_python_nonlocal.txt |
Q:
Rename dictionary keys/values in python
What I'm trying to do is this. I have a dictionary laid out as such:
legJointConnectors = {'L_hip_jnt': ['L_knee_jnt'], 'L_knee_jnt': ['L_ankle_jnt'], 'L_ankle_jnt': ['L_ball_jnt'], 'L_ball_jnt': ['L_toe_jnt']}
What I want to be able to do is iterate through this, but chang... | Rename dictionary keys/values in python | What I'm trying to do is this. I have a dictionary laid out as such:
legJointConnectors = {'L_hip_jnt': ['L_knee_jnt'], 'L_knee_jnt': ['L_ankle_jnt'], 'L_ankle_jnt': ['L_ball_jnt'], 'L_ball_jnt': ['L_toe_jnt']}
What I want to be able to do is iterate through this, but change the L_ to R_. Here's how I tried to do it, ... | [
"Do the substitution on every element of the list then.\nfor key, value in legJointConnectors.iteritems():\n if side != 'L':\n key = 'R_' + key[2:]\n value = ['R_' + v[2:] for v in value]\n cmds.connectJoint(value, key, pm=True)\n\n(BTW, it is better to use v.replace('L_', 'R_'), or just 'R_' + ... | [
3
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003692430_dictionary_python.txt |
Q:
Security considerations - office website/portal on GAE
If one needs to create an office website (that serves as a platform for clients/customers/employees) to login and access shared data, what are the security considerations.
to give you some more detail,
The office portal has been developed in django/python and... | Security considerations - office website/portal on GAE | If one needs to create an office website (that serves as a platform for clients/customers/employees) to login and access shared data, what are the security considerations.
to give you some more detail,
The office portal has been developed in django/python and hosted through GAE. Essentially, the end point comes with a... | [
"There is always the choice between usabiity and secutity. The more security features you implent, the more difficult it gets to use it.\n\ncan we host the apps on GAE (appspot.com) with https?\n\nYes, but not on your own domain, only on appspot.com. If you are serving your app off of an own domain, you must direct... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python",
"security"
] | stackoverflow_0003692526_django_google_app_engine_python_security.txt |
Q:
creating a masked array from text fields
The numpy documentation shows an example of masking existing values with ma.masked a posteriori (after array creation), or creating a masked array from an list of what seem to be valid data types (integer if dtype=int). I am trying to read in data from a file (and requires ... | creating a masked array from text fields | The numpy documentation shows an example of masking existing values with ma.masked a posteriori (after array creation), or creating a masked array from an list of what seem to be valid data types (integer if dtype=int). I am trying to read in data from a file (and requires some text manipulation) but at some point I wi... | [
"The way you're doing it is fine. (though you could definitely make it a bit more readable by avoiding building the temporary \"triple\" dict, just to expand it a step later, i.m.o.)\nThe built-in way is to use numpy.genfromtxt. Depending on the amount of pre-processing you need to do to your text file, it may or ... | [
1
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0003692401_numpy_python_scipy.txt |
Q:
Storing passwords with python
I have a program I'm writing in python, and I have the need to store some passwords. These passwords will be the passwords to ftp servers, so it's important that they're not just plainly visible to everybody. This also means that I can't store a non-reversible hash of the password lik... | Storing passwords with python | I have a program I'm writing in python, and I have the need to store some passwords. These passwords will be the passwords to ftp servers, so it's important that they're not just plainly visible to everybody. This also means that I can't store a non-reversible hash of the password like you would on a webserver, because... | [
"You could use the system's key ring, e.g. GNOME key ring or KDE wallet.\nThere's a Python module called keyring that supports multiple key ring providers. I have only tried it on Windows, where it doesn't yet work correctly. Seems like development isn't very active, but you should give it a try. You can also try t... | [
6,
2,
2,
0
] | [
"I would recommend hashing the password a hash is a one way function so can't be worked back to find a plain text version of the password (unlike an encryption).\nMD5 is a algorithm that I like and is already implemented in Python. You could always add a salt to the hash like abdPasswordABDA where Password is the p... | [
-4
] | [
"passwords",
"python",
"storage"
] | stackoverflow_0003691587_passwords_python_storage.txt |
Q:
How to properly store object reference in treemodel?
I'm trying to store an object reference in the rows of a treemodel so that I can access and modify the data in the underlying data structure. What would be the proper way to do this? The only way I've found so far to accomplish this is to inherit my data structu... | How to properly store object reference in treemodel? | I'm trying to store an object reference in the rows of a treemodel so that I can access and modify the data in the underlying data structure. What would be the proper way to do this? The only way I've found so far to accomplish this is to inherit my data structure nodes from gobject, and then store a gobject column in ... | [
"Model column type of:\ngobject.TYPE_PYOBJECT\n\nCan be anything!\n"
] | [
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003653639_pygtk_python.txt |
Q:
Adding shared python packages to multiple virtualenvs
Current Python Workflow
I have pip, distribute, virtualenv, and virtualenvwrapper installed into my Python 2.7 site-packages (a framework Python install on Mac OS X). In my ~/.bash_profile I have the line
export PIP_DOWNLOAD_CACHE=$HOME/.pip_download_cache
Th... | Adding shared python packages to multiple virtualenvs | Current Python Workflow
I have pip, distribute, virtualenv, and virtualenvwrapper installed into my Python 2.7 site-packages (a framework Python install on Mac OS X). In my ~/.bash_profile I have the line
export PIP_DOWNLOAD_CACHE=$HOME/.pip_download_cache
This gives a workflow as follows:
$ mkvirtualenv pip-test
$ p... | [
"Unless you are doing development on an embedded system, I find that chasing disk space in this way is always counter-productive. It took me a long time to reach this realization, because I grew up when a very large hard drive was a few megabytes in size, and RAM was measured in K. But today, unless you are under v... | [
11
] | [] | [] | [
"pip",
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0003692632_pip_python_virtualenv_virtualenvwrapper.txt |
Q:
from list to select menu in django
I thought I had it figured out but now I'm missing something.
First I have a QuerySet, records
records = Record.objects.all()
Now I want to make this into a list of one of the columns of the table, columnA
alist = records.values_list('columnA')
And then I want to pass this list... | from list to select menu in django | I thought I had it figured out but now I'm missing something.
First I have a QuerySet, records
records = Record.objects.all()
Now I want to make this into a list of one of the columns of the table, columnA
alist = records.values_list('columnA')
And then I want to pass this list in as a parameter to a custom form.
Fil... | [
"The problem is the word list in this line:\nnumbers = forms.ChoiceField(list)\n\nYou need to provide a specific list to ChoiceField.\n",
"Here's an error:\nclass FilterForm(forms.Form,list):\n numbers = forms.ChoiceField(list)\n\nYou make FilterForm a subclass of forms.Form and list; then you expect list to b... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003692922_django_python.txt |
Q:
python qt, display text/label above another widget(phonon)
I'm making a video player using PySide which is a python bind to the Qt framework. I'm using phonon(a module) to display the video and I want to display text above the video as a subtitle. How can I put another widget above my phonon widget. Is opengl an o... | python qt, display text/label above another widget(phonon) | I'm making a video player using PySide which is a python bind to the Qt framework. I'm using phonon(a module) to display the video and I want to display text above the video as a subtitle. How can I put another widget above my phonon widget. Is opengl an option?
| [
"If you just create your label and set the phonon widget as the parent, the label should appear over it.\nQLabel *label = new QLabel(phononWidget);\nlabel->setText(\"Text over video!\");\n\n(I realize this is C++ and you are working in Python but it should be similar)\nUpdate:\nThe above will not work for hardware ... | [
5
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt",
"widget"
] | stackoverflow_0003692712_pyqt_pyside_python_qt_widget.txt |
Q:
How to dynamically define functions?
I have functions like this:
def activate_field_1():
print 1
def activate_field_2():
print 2
def activate_field_3():
print 3
How do I define activate_field_[x] for x=1:10, without typing out each one of them? I'd much rather pass a parameter, of course, but for my pu... | How to dynamically define functions? | I have functions like this:
def activate_field_1():
print 1
def activate_field_2():
print 2
def activate_field_3():
print 3
How do I define activate_field_[x] for x=1:10, without typing out each one of them? I'd much rather pass a parameter, of course, but for my purposes this is not possible.
| [
"Do you want to define these individually in your source file, statically? Then your best option would be to write a script to generate them.\nIf on the other hand you want these functions at runtime you can use a higher order function. For e.g. \n>>> def make_func(value_to_print):\n... def _function():\n... ... | [
22,
11,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0003687682_python.txt |
Q:
Python GTK/threading/sockets error
I'm trying to build a Python application using pyGTK, treads, and sockets. I'm having this weird error, but given all the modules involved, I'm not entirely sure where the error is. I did a little debugging with some print statements to narrow things down a bit and I think the er... | Python GTK/threading/sockets error | I'm trying to build a Python application using pyGTK, treads, and sockets. I'm having this weird error, but given all the modules involved, I'm not entirely sure where the error is. I did a little debugging with some print statements to narrow things down a bit and I think the error is somewhere in this snippet of code... | [
"timeout_add is scheduling the action to happen on the main thread -- so the recv just blocks the main thread (when it's just waiting for data) and therefore the GUI, so, no exception unless you put a timeout or set the socket to non-blocking.\nYou need to delegate the receiving to the thread from the scheduled act... | [
1,
0
] | [] | [] | [
"gtk",
"multithreading",
"python",
"sockets"
] | stackoverflow_0003693083_gtk_multithreading_python_sockets.txt |
Q:
how to define a structure like in C
I am going to define a structure and pass it into a function:
In C:
struct stru {
int a;
int b;
};
s = new stru()
s->a = 10;
func_a(s);
How this can be done in Python?
A:
Unless there's something special about your situation that you're not telling us, just use something li... | how to define a structure like in C | I am going to define a structure and pass it into a function:
In C:
struct stru {
int a;
int b;
};
s = new stru()
s->a = 10;
func_a(s);
How this can be done in Python?
| [
"Unless there's something special about your situation that you're not telling us, just use something like this:\nclass stru:\n def __init__(self):\n self.a = 0\n self.b = 0\n\ns = stru()\ns.a = 10\n\nfunc_a(s)\n\n",
"use named tuples if you are ok with an immutable type.\nimport collections\n\ns... | [
34,
12,
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0003648442_python.txt |
Q:
Django/python is converting my post data from JavaScript
When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending:
info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' }
Yet when I access it in the django request... | Django/python is converting my post data from JavaScript | When I post a JSON string to Django by Ajax, it converts it into an invalid JSON format. Specifically, if I look in the post data in Firebug I am sending:
info {'mid':1,'sid':27,'name':'aa','desc':'Enter info' }
Yet when I access it in the django request I am seeing:
u'{\'mid\':1,\'sid\':27,\'name\':\'aa\',\'desc\'... | [
"How are you encoding your JSON string? The single quotes need to be double quotes, per the spec:\nIn [40]: s1 = \"{'mid':1,'sid':27,'name':'aa','desc':'Enter info' }\"\n\nIn [41]: simplejson.loads(s1)\nJSONDecodeError: Expecting property name: line 1 column 1 (char 1)\n\nIn [42]: s2 = '{\"mid\":1,\"sid\":27,\"nam... | [
7
] | [] | [] | [
"django",
"javascript",
"json",
"python",
"unicode"
] | stackoverflow_0003693621_django_javascript_json_python_unicode.txt |
Q:
How to detect if a file path is wrapped in " .. " with Python?
I read the ini file to open a file in python.
The thing is that the file info is sometimes inside the "..", but sometimes it's not.
For example,
fileA = "/a/b/c.txt"
fileB = /a/b/d.txt
Is there easy way to detect if a string is wrapped in "..", and re... | How to detect if a file path is wrapped in " .. " with Python? | I read the ini file to open a file in python.
The thing is that the file info is sometimes inside the "..", but sometimes it's not.
For example,
fileA = "/a/b/c.txt"
fileB = /a/b/d.txt
Is there easy way to detect if a string is wrapped in "..", and return the string inside the quotation?
| [
"The simple detection would involve checking s[:1] == s[-1:] == '\"' (carefully phrasing it with slicing rather than indexing to avoid exceptions if s is an empty string), and the conditional removal of exactly one quote from each end if one is present at both ends is\nif s[:1] == s[-1:] == '\"':\n s = s[1:-1]\n... | [
3,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003693744_python_string.txt |
Q:
How to check if user likes a given page on facebook, from an external site?
I'm building an app using facebook likes, under GAE with python.
I'd like do different actions if user likes the page or not:
page_url=url
if user likes page_url:
#do something
else:
#do something else
I'm interested in checking if... | How to check if user likes a given page on facebook, from an external site? | I'm building an app using facebook likes, under GAE with python.
I'd like do different actions if user likes the page or not:
page_url=url
if user likes page_url:
#do something
else:
#do something else
I'm interested in checking if the user already likes the page, not in the action of clicking the like button.
... | [
"Use GraphApi \"me/likes\" with the authenticated user, then search through the results and search for you your app / page id.\n"
] | [
2
] | [] | [] | [
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0003690799_facebook_google_app_engine_python.txt |
Q:
Is this statically bound?
Say that I have a C program and it has this line:
int a = 12;
Is the value of 12 bound to 'a' during compile time? Or is the value placed into memory during run time when the scope of the program hits 'a'?
What about programming languages like Python and Ruby?
Are there languages/instanc... | Is this statically bound? | Say that I have a C program and it has this line:
int a = 12;
Is the value of 12 bound to 'a' during compile time? Or is the value placed into memory during run time when the scope of the program hits 'a'?
What about programming languages like Python and Ruby?
Are there languages/instances where a value is statically ... | [
"Compilers and virtual machines effectively \"implement\" programming languages. They only have to do what is specified by the language semantics and observable for a given program in order to be correct.\nWhen you write the definition statement int a = 12; in a C program, you are informing the compiler that there ... | [
10,
2,
1,
0
] | [] | [] | [
"binding",
"c",
"compiler_construction",
"python",
"ruby"
] | stackoverflow_0003687600_binding_c_compiler_construction_python_ruby.txt |
Q:
Python: 'Nontype' object has no attribute keys
def index_dir(self, base_path):
num_files_indexed = 0
allfiles = os.listdir(base_path)
#print allfiles
num_files_indexed = len(allfiles)
#print num_files_indexed
docnumber = 0
self._inverted_index = {} #dict... | Python: 'Nontype' object has no attribute keys | def index_dir(self, base_path):
num_files_indexed = 0
allfiles = os.listdir(base_path)
#print allfiles
num_files_indexed = len(allfiles)
#print num_files_indexed
docnumber = 0
self._inverted_index = {} #dictionary
for file in allfiles:
... | [
"When self._inverted_index is a dictionary, self._inverted_index.update will update it in-place and return None (like most mutators do). So, the disastrous bug in your code is the line:\n self._inverted_index = self._inverted_index.update({term: docnumber})\n\nwhich sets self._inverted_index to None. Just change ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003693940_python.txt |
Q:
python auto restarting script
I need script which starts itself at the end of process.
I use this code but it wait for execfile. How to run it async? To do the effect of script restarting.
import time
print "start"
time.sleep(5)
print "go exec"
execfile('res.py')
print "stop exec"
A:
One of the many os.exec... f... | python auto restarting script | I need script which starts itself at the end of process.
I use this code but it wait for execfile. How to run it async? To do the effect of script restarting.
import time
print "start"
time.sleep(5)
print "go exec"
execfile('res.py')
print "stop exec"
| [
"One of the many os.exec... functions (on Unix-y systems, including e.g. Linux and Mac, and also on Windows) may be what you want. You'll need to execute the sys.executable (that's the .exe -- or equivalent executable file on non-Windows OSs -- with the Python version currently in use) with (roughly) the same argu... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003693935_python.txt |
Q:
storing passwords in class variables in python
I'm working on a python script that stores ssh passwords only during the current session. What I'm doing is declaring a class variable credentials = {}. When the script needs access to a specific server, it checks in credentials to see if credentials['server'] exists.... | storing passwords in class variables in python | I'm working on a python script that stores ssh passwords only during the current session. What I'm doing is declaring a class variable credentials = {}. When the script needs access to a specific server, it checks in credentials to see if credentials['server'] exists. If it does, it uses the password there, if it doesn... | [
"A bit of a digression, but when I've built scripts do this in the past, the security minded recommended using an ssh-agent approach. The agent is a background processes, independent of the python but running under the same user, that will store the credentials. Then the script doesn't need to worry about prompting... | [
1
] | [] | [] | [
"class_variables",
"passwords",
"python",
"security"
] | stackoverflow_0003693965_class_variables_passwords_python_security.txt |
Q:
how to use python to read .cbr files?
How can i use python to read .cbr/.cbt files?
cbr/cbt files are a RAR archive format used for comic book files.
A:
.cbr is a RAR archive. .cbt is a TAR archive. You can use standard tarfile module for latter but you need to use rar/unrar for former. You can look for the code... | how to use python to read .cbr files? | How can i use python to read .cbr/.cbt files?
cbr/cbt files are a RAR archive format used for comic book files.
| [
".cbr is a RAR archive. .cbt is a TAR archive. You can use standard tarfile module for latter but you need to use rar/unrar for former. You can look for the code you need in comix (more precisely, archive.py).\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0003694194_python.txt |
Q:
WTForms extension for Django templates not working
I feel like I am missing something really obvious. I'm trying to use the WTForms template extensions with Django. I have a project on my development server which is working great (IE the extensions are working properly) but when I put it out on a test server, su... | WTForms extension for Django templates not working | I feel like I am missing something really obvious. I'm trying to use the WTForms template extensions with Django. I have a project on my development server which is working great (IE the extensions are working properly) but when I put it out on a test server, suddenly they are broken. Both servers have the same vers... | [
"I'm not sure what the cause of this is, but I can assure you it's not WTForms. We don't do anything funky with the classes, so if Django isn't invoking action properly, it's something in Django. Have you tried renaming the function, to see if it's a weird issue with the name \"action\"?\nAlternately, you could try... | [
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003685313_django_django_templates_python.txt |
Q:
How to return an apache error page from a wsgi app?
I have a simple working wsgi app. I can successfully return whatever HTTP status code, headers, and HTML I want. What I would like to do, is that when I'm returning a status code other than '200 OK', for WSGI to let apache fall back to its error handling and disp... | How to return an apache error page from a wsgi app? | I have a simple working wsgi app. I can successfully return whatever HTTP status code, headers, and HTML I want. What I would like to do, is that when I'm returning a status code other than '200 OK', for WSGI to let apache fall back to its error handling and display whatever page apache is configured to display accordi... | [
"Presuming you actually mean with mod_wsgi under Apache, ensure you are using mod_wsgi daemon mode and set:\nWSGIErrorOverride On\n\nThere is a brief mention of this in mod_wsgi version 3.0 release notes.\nhttp://code.google.com/p/modwsgi/wiki/ChangesInVersion0300\nIf you are using Apache as proxy in front of disti... | [
5
] | [] | [] | [
"apache",
"python",
"wsgi"
] | stackoverflow_0003691204_apache_python_wsgi.txt |
Q:
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign a... | Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form | The green plus sign button for adding new instances in the admin form disappears for my MultiSelect field (photos) when I define it in my form. Ie, removing the line with the definition (photos = ...) makes the plus sign appear. However, in order to use a custom Field/Widget I need to figure this out.
class GalleryForm... | [
"With the help from lazerscience and this post I ended up with the following.\nThe ModelAdmin:\nclass GalleryAdmin(admin.ModelAdmin):\n\n form = GalleryForm\n \n def __init__(self, model, admin_site):\n self.form.admin_site = admin_site \n super(GalleryAdmin, self).__init__(model, admin_site)... | [
12,
8
] | [] | [] | [
"django",
"django_admin",
"many_to_many",
"python"
] | stackoverflow_0003692822_django_django_admin_many_to_many_python.txt |
Q:
Global static variables in Python
def Input():
c = raw_input ('Enter data1,data2: ')
data = c.split(',')
return data
I need to use list data in other functions, but I don't want to enter raw_input everytime. How I can make data like a global static in c++ and put it everywhere where it needed?
A:
Ad... | Global static variables in Python | def Input():
c = raw_input ('Enter data1,data2: ')
data = c.split(',')
return data
I need to use list data in other functions, but I don't want to enter raw_input everytime. How I can make data like a global static in c++ and put it everywhere where it needed?
| [
"Add the global keyword to your function:\ndef Input():\n global data\n c = raw_input ('Enter data1,data2: ')\n data = c.split(',')\n return data\n\nThe global data statement is a declaration that makes data a global variable. After calling Input() you will be able to refer to data in other functions.\n... | [
18,
4
] | [] | [] | [
"global",
"python",
"static",
"variables"
] | stackoverflow_0003694580_global_python_static_variables.txt |
Q:
Python 2.6.5: Divide timedelta with timedelta
I'm trying to divide one timedelta object with another to calculate a server uptime:
>>> import datetime
>>> installation_date=datetime.datetime(2010,8,01)
>>> down_time=datetime.timedelta(seconds=1400)
>>> server_life_period=datetime.datetime.now()-installation_date
>... | Python 2.6.5: Divide timedelta with timedelta | I'm trying to divide one timedelta object with another to calculate a server uptime:
>>> import datetime
>>> installation_date=datetime.datetime(2010,8,01)
>>> down_time=datetime.timedelta(seconds=1400)
>>> server_life_period=datetime.datetime.now()-installation_date
>>> down_time_percentage=down_time/server_life_perio... | [
"In Python ≥2.7, there is a .total_seconds() method to compute the total seconds contained in the timedelta:\n>>> down_time.total_seconds() / server_life_period.total_seconds()\n0.0003779903727652387\n\nOtherwise, there is no way but to compute the total microseconds (for versions < 2.7)\n>>> def get_total_seconds(... | [
33
] | [] | [] | [
"division",
"python",
"timedelta"
] | stackoverflow_0003694835_division_python_timedelta.txt |
Q:
Python: Should I put my data in lists or object attributes?
I am looking for an appropriate data structure in Python for processing variably structured forms. By variably structured forms I mean that the number of form fields and the types of the form's contents are not known in advance. They are defined by the us... | Python: Should I put my data in lists or object attributes? | I am looking for an appropriate data structure in Python for processing variably structured forms. By variably structured forms I mean that the number of form fields and the types of the form's contents are not known in advance. They are defined by the user who populates the forms with his input.
What are the pros and ... | [
"In Python, as in all object-oriented languages, the purpose of classes is to associate data and closely-related methods that act on that data. If there's no real encapsulation going on (i.e. the methods help define the ways you can interact with the data), the best choice is a conglomeration of builtin types like ... | [
5,
4,
0,
0,
0
] | [] | [] | [
"attributes",
"data_structures",
"list",
"object",
"python"
] | stackoverflow_0003694284_attributes_data_structures_list_object_python.txt |
Q:
Fetch a random entity from the datastore
Pretty simple, in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random?
A:
Maybe one solution but i don't know if it's the best :)
import random
from google.appengine.ext import db
from google.appengine.api impor... | Fetch a random entity from the datastore | Pretty simple, in my AppEngine application, I have over 1 million entities of one kind, what is the best way to pick one at random?
| [
"Maybe one solution but i don't know if it's the best :)\nimport random\nfrom google.appengine.ext import db\nfrom google.appengine.api import memcache\n\nDATA_KEY = \"models/keys/random\"\n\ndef get_data():\n data = memcache.get (DATA_KEY)\n if data is None:\n offset = random.randint (1, 1000000)\n ... | [
0,
-1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"random"
] | stackoverflow_0003694177_google_app_engine_google_cloud_datastore_python_random.txt |
Q:
python check url type
I wrote a crawler in python, fetched urls has different types: it can be url with html and url with image or big archives or other files. So i need fast determine this case to prevent of reading of big files such as big archives and continue crawling. How is the best way to determine url type... | python check url type | I wrote a crawler in python, fetched urls has different types: it can be url with html and url with image or big archives or other files. So i need fast determine this case to prevent of reading of big files such as big archives and continue crawling. How is the best way to determine url type at start of page loading?
... | [
"If you use a HTTP HEAD request on the resource, you will get relevant metadata on the resource without the resource data itself. Specifically, the content-length and content-type headers will be of interest.\nE.g.\nHEAD /stackoverflow/img/favicon.ico HTTP/1.1\nhost: sstatic.net\n\nHTTP/1.1 200 OK\nCache-Control: m... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0003695018_python.txt |
Q:
help me use proxy with twill
I read help here http://twill.idyll.org/browsing.html, then i open python and write
export http_proxy="http://www.someproxy.com:3128"
but i just receive an error. How can i use proxy with twill to browser web ?
A:
the export command is something you need to type on your shell (assum... | help me use proxy with twill | I read help here http://twill.idyll.org/browsing.html, then i open python and write
export http_proxy="http://www.someproxy.com:3128"
but i just receive an error. How can i use proxy with twill to browser web ?
| [
"the export command is something you need to type on your shell (assuming unix/linux). It's not a python statement!\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003695055_python.txt |
Q:
Confused about behaviour of base class
This follows a question I asked a few hours ago.
I have this code:
class A(object):
def __init__(self, a):
print 'A called.'
self.a = a
class B(A):
def __init__(self, b, a):
print 'B called.'
x = B(1, 2)
print x.a
This gives the error: Attr... | Confused about behaviour of base class | This follows a question I asked a few hours ago.
I have this code:
class A(object):
def __init__(self, a):
print 'A called.'
self.a = a
class B(A):
def __init__(self, b, a):
print 'B called.'
x = B(1, 2)
print x.a
This gives the error: AttributeError: 'B' object has no attribute 'a',... | [
"The way you defined it B does not have any attributes. When you do print a the a refers to the local variable a in the __init__ method, not to any attribute.\nIf you replace print a with print self.a you will get the same error message as before.\n",
"In your second code, calling print a works because you are pr... | [
4,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003695218_python.txt |
Q:
Pylons - How to get the current controller and action (current route)?
I'm in a Mako template, and I want to know what the current controller and action is (of the current page). How can I do this? I tried c.controller and c.action, but it didn't work. I also listed the keys of the context object but didn't find i... | Pylons - How to get the current controller and action (current route)? | I'm in a Mako template, and I want to know what the current controller and action is (of the current page). How can I do this? I tried c.controller and c.action, but it didn't work. I also listed the keys of the context object but didn't find it.
As a workaround, I've been setting c.controller and c.action from within ... | [
"In a template:\nCurrent url: \n${url.current()}\n\nController and action: \n${url.environ['pylons.routes_dict']['controller']}\n${url.environ['pylons.routes_dict']['action']}\n\n"
] | [
6
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003695107_pylons_python.txt |
Q:
Python (or maybe JavaScript / Ruby): open source projects that will give me a (bit) of hand-holding
Ive been roaming around the interwebs looking for my first open-source project to contribute to - and most cool ones seem to be one-man bands on github, which I could fork - but wouldnt quite provide the code review... | Python (or maybe JavaScript / Ruby): open source projects that will give me a (bit) of hand-holding | Ive been roaming around the interwebs looking for my first open-source project to contribute to - and most cool ones seem to be one-man bands on github, which I could fork - but wouldnt quite provide the code review etc. i think i want, so i can improve my python abilities.
Web.py, flask, celery, twisted etc look inter... | [
"You could have a look and see if you find RCTK interesting to contribute to. I'm trying to be as pythonic as possible, it actually supports python 3 if you find that interesting, and even writing demo applications is considered very useful.\nI (the head developer) currently already have two contributes whose code ... | [
2,
1
] | [] | [] | [
"javascript",
"open_source",
"python",
"ruby"
] | stackoverflow_0003694265_javascript_open_source_python_ruby.txt |
Q:
Boost.Python function pointers as class constructor argument
I have a C++ class that requires a function pointer in it's constructor (float(*myfunction)(vector<float>*))
I've already exposed some function pointers to Python.
The ideal way to use this class is something like this:
import mymodule
mymodule.some_cl... | Boost.Python function pointers as class constructor argument | I have a C++ class that requires a function pointer in it's constructor (float(*myfunction)(vector<float>*))
I've already exposed some function pointers to Python.
The ideal way to use this class is something like this:
import mymodule
mymodule.some_class(mymodule.some_function)
So I tell Boost about this class like... | [
"OK, so this is a fairly difficult question to answer in general. The root cause of your problem is that there really is no python type which is exactly equivalent to a C function pointer. Python functions are sort-of close, but their interface doesn't match for a few reasons.\nFirstly, I want to mention the techni... | [
2
] | [] | [] | [
"boost_python",
"compiler_errors",
"function_pointers",
"performance",
"python"
] | stackoverflow_0003641334_boost_python_compiler_errors_function_pointers_performance_python.txt |
Q:
How do I include an image in a window with pygtk?
I'm trying to make a program in python which creates a fullscreen window and includes an image, but I don't really know how to do that. I've tried to read documentations on pygtk and I've searched in both goodle and stackoverflow, without any success.
Here's my cur... | How do I include an image in a window with pygtk? | I'm trying to make a program in python which creates a fullscreen window and includes an image, but I don't really know how to do that. I've tried to read documentations on pygtk and I've searched in both goodle and stackoverflow, without any success.
Here's my current code.
def __init__(self):
pixbuf = gtk.gdk.pix... | [
"Please provide a little more context (e.g. class definition, imports).\nDo not forget to add the image object to your window (before showing image and window):\nself.window.add(image)\n\nThe tutorial example adds the image to a button, but you can try adding it directly to the main window:\n# an image widget to co... | [
4
] | [] | [] | [
"gtk",
"image",
"pygtk",
"python"
] | stackoverflow_0003695371_gtk_image_pygtk_python.txt |
Q:
how could we obtain magnitude of frequency from a set of complex numbers obtained after performing FFT in python?
i don't know what to do after obtaining a set of complex numbers from FFT on a wav file.How could i obtain the corresponding frequencies.This is output i got after performing FFT which is shown below
[... | how could we obtain magnitude of frequency from a set of complex numbers obtained after performing FFT in python? | i don't know what to do after obtaining a set of complex numbers from FFT on a wav file.How could i obtain the corresponding frequencies.This is output i got after performing FFT which is shown below
[ 12535945.00000000 +0.j -30797.74496367 +6531.22295858j
-26330.14948055-11865.08322966j ..., 3426... | [
"Actually the abs(x) operation only converts a real/imaginary pair from your result list into a magnitude. Do that unless you want to keep the imaginary portion for future use. So after conversion, each number in the result list represents a magnitude of signal at a certain frequency in your frequency spectrum. ... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003695202_python.txt |
Q:
I can't upload a file with CGIHTTPServer
I'm using the CGIHTTPServer to implement a simple cgi server. I'm trying to upload a file by a form with the post method and the multipart/form-data enctype but I have problems when I recover the value of the fields in the cgi script.
When the script catch the form fields,... | I can't upload a file with CGIHTTPServer | I'm using the CGIHTTPServer to implement a simple cgi server. I'm trying to upload a file by a form with the post method and the multipart/form-data enctype but I have problems when I recover the value of the fields in the cgi script.
When the script catch the form fields, the value of the file is a MiniFieldStorage w... | [
"Please provide some code example.\nGuessing from the text, you should look into the cgi module.\nFollow the examples, specially the cgi.test() function.\n\ncgi — Common Gateway Interface support\nSupport module for Common Gateway Interface (CGI) scripts.\nThis module defines a number of utilities for use by CGI sc... | [
1
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0003695441_cgi_python.txt |
Q:
UnicodeEncodeError when fetching URLs
I am using urlfetch to fetch a URL. When I try to send it to html2text function (strips off all HTML tags), I get the following message:
UnicodeEncodeError: 'charmap' codec can't encode characters in position ... character maps to <undefined>
I've been trying to process enco... | UnicodeEncodeError when fetching URLs | I am using urlfetch to fetch a URL. When I try to send it to html2text function (strips off all HTML tags), I get the following message:
UnicodeEncodeError: 'charmap' codec can't encode characters in position ... character maps to <undefined>
I've been trying to process encode('UTF-8','ignore') on the string but I ke... | [
"You need to decode the data you fetched first! With which codec? Depends on the website you fetch.\nWhen you have unicode and try to encode it with some_unicode.encode('utf-8', 'ignore') i can't image how it could throw an error.\nOk what you need to do:\nresult = fetch('http://google.com') \ncontent_type = result... | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003695567_google_app_engine_python.txt |
Q:
Simplest way to implement user login / authentication in Python
I'm developing a fairly simple Python web app and I want to allow users to log in. I know the solution will probably involve installing some sort of framework rather than doing it in straight Python and I'm OK with that, I'm just wondering, what would... | Simplest way to implement user login / authentication in Python | I'm developing a fairly simple Python web app and I want to allow users to log in. I know the solution will probably involve installing some sort of framework rather than doing it in straight Python and I'm OK with that, I'm just wondering, what would be the easiest, most hassle-free way to add authentication? The app ... | [
"Store the user's login, the salted hash of their password, and the salt in a database. (If you're going for cryptographic overkill, you can use a very expensive-to-compute hashing algorithm like bcrypt.)\nYou can use SQLite as that's bundled with Python, but it would probably make more sense to install a database ... | [
2
] | [] | [] | [
"authentication",
"frameworks",
"python"
] | stackoverflow_0003695702_authentication_frameworks_python.txt |
Q:
django, distinct() not behaving
For some reason duplicate values aren't eliminated.
records = Records.objects.all()
records2 = records.values_list('columna','columna').distinct()
print records2
I must be doing something stupid
A:
My solution was to cast the values_list to a set (to remove duplicates) then back ... | django, distinct() not behaving | For some reason duplicate values aren't eliminated.
records = Records.objects.all()
records2 = records.values_list('columna','columna').distinct()
print records2
I must be doing something stupid
| [
"My solution was to cast the values_list to a set (to remove duplicates) then back to a list\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003693405_django_python.txt |
Q:
python remove last character and id
I have list of
34.00B
65.89B
346M
I need
34.
65.89
.344
So, how do i remove last character, is if B or M, divide M's by 1000.
A:
I think you just want something like this:
divisors = {'B': 1, 'M': 1000}
def fn(number):
if number[-1] in divisors:
return str(flo... | python remove last character and id | I have list of
34.00B
65.89B
346M
I need
34.
65.89
.344
So, how do i remove last character, is if B or M, divide M's by 1000.
| [
"I think you just want something like this:\ndivisors = {'B': 1, 'M': 1000}\ndef fn(number):\n if number[-1] in divisors:\n return str(float(number[:-1]) / divisors[number[-1]])\n return number\n\nmap(fn, ['34.00B', '65.89B', '346M'])\n\nI converted the return value back to a string since your question... | [
6,
2
] | [] | [] | [
"python"
] | stackoverflow_0003695756_python.txt |
Q:
django custom form validation
In Django/Python, when you make a custom form, does it need to have a clean() method, or will calling .is_valid() perform a default validation?
if request.method == 'POST':
filter = FilterForm(request.POST)
if filter.is_valid():
print 'Month is ' + filter... | django custom form validation | In Django/Python, when you make a custom form, does it need to have a clean() method, or will calling .is_valid() perform a default validation?
if request.method == 'POST':
filter = FilterForm(request.POST)
if filter.is_valid():
print 'Month is ' + filter.cleaned_data['month']
... | [
"\ndoes it need to have a clean() method\n\nNo. Completely optional.\nThere's a big list of things that Django does in a specific order when it validates forms. You can learn about the process here:\nhttp://docs.djangoproject.com/en/dev/ref/forms/validation/\nAs for finding your problem, if you stick a {{form.error... | [
3,
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003695794_django_django_forms_python.txt |
Q:
how do I create an indented block in Python?
for example, how to I enter this in Python so that it is indented correctly?
if 1 + 2 == 2:
print "true"
print "this is my second line of the block"
print "this is the third line of the block"
A:
This is correctly indented.
if 1 + 2 == 2:
print "true"
... | how do I create an indented block in Python? | for example, how to I enter this in Python so that it is indented correctly?
if 1 + 2 == 2:
print "true"
print "this is my second line of the block"
print "this is the third line of the block"
| [
"This is correctly indented.\nif 1 + 2 == 2:\n print \"true\"\n print \"this is my second line of the block\"\n print \"this is the third line of the block\"\n\nIf you're using python's REPL... simply enter no spaces before the first line, and an arbitrary but consistent number of spaces for indented lines... | [
4,
2
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0003695837_if_statement_python.txt |
Q:
SVG Glyphs in Pyqt
How do I render glyphs in pyqt using the svggraphicsItem?
A:
Recently I found that svg files generated by Cairo do not plot properly in pyqt. The error comes from the use of glyphs which seem not to be shown in pyqt (this might be wrong but I couldn't find any way of getting glyphs to render)... | SVG Glyphs in Pyqt | How do I render glyphs in pyqt using the svggraphicsItem?
| [
"Recently I found that svg files generated by Cairo do not plot properly in pyqt. The error comes from the use of glyphs which seem not to be shown in pyqt (this might be wrong but I couldn't find any way of getting glyphs to render). \nI ended up writing a set of functions that will convert the glyphs to svg path... | [
4
] | [] | [] | [
"graphics",
"pyqt",
"python",
"rendering",
"svg"
] | stackoverflow_0003682127_graphics_pyqt_python_rendering_svg.txt |
Q:
How to know the directory where the python script is called?
Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py.
In a.py, how to detect /X/Y/? I mean, how to know in which dir... | How to know the directory where the python script is called? | Let's say that I have a python script a.py in /A/B/a.py, and it's in the PATH environment variable. The current working directory is /X/Y/, and it's the directory where I call the /A/B/a.py.
In a.py, how to detect /X/Y/? I mean, how to know in which directory the python call is made?
| [
"You can get the current working directory with:\nos.getcwd()\n\n",
">> os.getcwd()\n/X/Y\n>> os.path.dirname(os.path.realpath(__file__)) # cannot be called interactively\n/A/B\n>> sys.path[0]\n/A/B\n>> os.path.abspath(sys.argv[0])\n/A/B/a.py\n\n"
] | [
33,
8
] | [] | [] | [
"path",
"python"
] | stackoverflow_0003696223_path_python.txt |
Q:
python doctest: stop example execution and use the resulting context in some shell
i think there was some directive i could enter in the test that would allow me to run some commands interactively at the point of the directive and then continue the example, but i dont remember what it was...
A:
Do you mean you p... | python doctest: stop example execution and use the resulting context in some shell | i think there was some directive i could enter in the test that would allow me to run some commands interactively at the point of the directive and then continue the example, but i dont remember what it was...
| [
"Do you mean you place a breakpoint in your test to enter the debugger?\nimport pdb; pdb.set_trace()\n\n"
] | [
2
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0003696225_doctest_python.txt |
Q:
windows python script to traverse directory to remove folders, restart PC and continue the next line of the script?
I want to remove a incorrectly installed program and reinstall it. I can remove the program with subprocess.Popen calling the msiexe on it and install new program the same way BUT ONLY with two indep... | windows python script to traverse directory to remove folders, restart PC and continue the next line of the script? | I want to remove a incorrectly installed program and reinstall it. I can remove the program with subprocess.Popen calling the msiexe on it and install new program the same way BUT ONLY with two independent scripts. But i also need to remove some folders in C:\Programs files and also in C:\Doc& Settings. How can i trave... | [
"In a nutshell, here's what you'll need to do.\nYou can delete the files and folders by using the remove() and rmdir() or removedirs() methods in the os module (assuming your user/program has administrative rights).\nTo restart your script you will first need to add some command line argument handling to it that al... | [
1
] | [] | [] | [
"directory",
"python",
"traversal",
"windows"
] | stackoverflow_0003694051_directory_python_traversal_windows.txt |
Q:
Submitting Google with PyQT QWebElement
The following code does not reach searchResults. I have printed out documentElement.findFirst('input[name="btnG"]') and found it to be <input name="btnG" type="submit" value="Google Search" class="lsb"> so we are good up to that point. Note that my goal is not to scrape Goog... | Submitting Google with PyQT QWebElement | The following code does not reach searchResults. I have printed out documentElement.findFirst('input[name="btnG"]') and found it to be <input name="btnG" type="submit" value="Google Search" class="lsb"> so we are good up to that point. Note that my goal is not to scrape Google but it's simpler to learn via the well kno... | [
"I have finally figured it out! and submitted to http://drupal4hu.com/node/266\n"
] | [
0
] | [] | [] | [
"pyqt",
"python",
"qwebelement",
"qwebview"
] | stackoverflow_0003695781_pyqt_python_qwebelement_qwebview.txt |
Q:
Django POST/GET exercise
I'm trying to practice some django basics by implementing my own sortable table in Django and I've run into a couple of snags.
Here's the code that I'm working with in my view:
def __table_view_helper__(request):
if not request.session.__contains__('filters'):
filters = {'filte... | Django POST/GET exercise | I'm trying to practice some django basics by implementing my own sortable table in Django and I've run into a couple of snags.
Here's the code that I'm working with in my view:
def __table_view_helper__(request):
if not request.session.__contains__('filters'):
filters = {'filterA':'',
'fi... | [
"To set the initial values from the view you have to do:\nfilter.fields['fieldA'].initial = filters['filterA']\n\nTo keep user related data persistent through different requests you shouldn't use globals, but sessions!\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003696502_django_django_forms_python.txt |
Q:
Python trim last and sort list
I have list MC below:
MC = [('GGP', '4.653B'), ('JPM', '157.7B'), ('AIG', '24.316B'), ('RX', 'N/A'), ('PFE', '136.6B'), ('GGP', '4.653B'), ('MNKD', '672.3M'), ('ECLP', 'N/A'), ('WYE', 'N/A')]
def fn(number):
divisors = {'B': 1, 'M': 1000}
if number[-1] in divisors:
r... | Python trim last and sort list | I have list MC below:
MC = [('GGP', '4.653B'), ('JPM', '157.7B'), ('AIG', '24.316B'), ('RX', 'N/A'), ('PFE', '136.6B'), ('GGP', '4.653B'), ('MNKD', '672.3M'), ('ECLP', 'N/A'), ('WYE', 'N/A')]
def fn(number):
divisors = {'B': 1, 'M': 1000}
if number[-1] in divisors:
return ((float(number[:-1]) / diviso... | [
" def fn(tup):\n number = tup[1]\n divisors = {'B': 1, 'M': 1000}\n if number[-1] in divisors:\n return (tup[0], float(number[:-1]) / divisors[number[-1]])\n else:\n return tup\n\nThe problem is that that function was meant to run on a string representation of a nu... | [
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003696648_python_sorting.txt |
Q:
python: does `for i in obj.func()` re-run `func` every iteration?
let's say I have the following code:
for a in object.a_really_huge_function():
print a
In order to prevent a_really_huge_function from running multiple times, I am used to doing this in other languages:
a_list = object.a_really_huge_function()
... | python: does `for i in obj.func()` re-run `func` every iteration? | let's say I have the following code:
for a in object.a_really_huge_function():
print a
In order to prevent a_really_huge_function from running multiple times, I am used to doing this in other languages:
a_list = object.a_really_huge_function()
for a in a_list:
print a
Is that necessary in Python? Will the par... | [
"The python interpreter is your friend. \n>>> def some_func():\n... print 'in some_func'\n... return [1, 2, 3, 10]\n... \n>>> for a in some_func():\n... print a\n... \nin some_func\n1\n2\n3\n10\n\nIn short, no, it gets called once.\n",
"You can also use generators to avoid returning huge results by r... | [
8,
4,
1
] | [] | [] | [
"for_loop",
"loops",
"optimization",
"python"
] | stackoverflow_0003696992_for_loop_loops_optimization_python.txt |
Q:
which one of those python implementations is better
which one of the following is considered better a design and why ?.
i have 2 classes , one for the gui components and the other is for it's events.
please put in mind that the eventClass will be implemented so many times, (sometimes to get data from an oracle da... | which one of those python implementations is better |
which one of the following is considered better a design and why ?.
i have 2 classes , one for the gui components and the other is for it's events.
please put in mind that the eventClass will be implemented so many times, (sometimes to get data from an oracle databases and sometimes mysql databases )
class MainWind... | [
"The first choice is better \"decoupled\": the event class needs and has no knowledge whatsoever about the window object or its menu attribute -- an excellent approach that makes the event class especially easy to unit-test in isolation without any overhead. This is especially nice if many implementations of the s... | [
5
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003697066_oop_python.txt |
Q:
Possible to sandbox Python configuration file?
I'm thinking of implementing a configuration file written in Python syntax, not unlike what Django does.
While I've seen one or two SO questions about the merits of using executable code in configuration files, I'm curious whether there is a way to execute the config ... | Possible to sandbox Python configuration file? | I'm thinking of implementing a configuration file written in Python syntax, not unlike what Django does.
While I've seen one or two SO questions about the merits of using executable code in configuration files, I'm curious whether there is a way to execute the config file code in a "sandbox" to prevent mistakes in the ... | [
"We do this for some of our internal tools\nWhat we do protects us from exception issues and discourages any attempts by the users to get overly creative in the config scripts. However it doesn't protect us from infinite loops or actively malicious third parties.\nThe core of the approach here is to run the script ... | [
3,
2
] | [] | [] | [
"configuration",
"python",
"sandbox"
] | stackoverflow_0001757381_configuration_python_sandbox.txt |
Q:
Help writing the output to another file:
Hi here is the program I have:
with open('C://avy.txt', "rtU") as f:
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
# Skip empty lines
if not line.strip():
continue
values ... | Help writing the output to another file: | Hi here is the program I have:
with open('C://avy.txt', "rtU") as f:
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
# Skip empty lines
if not line.strip():
continue
values = line.split(" ")
for i in xrange(len(... | [
"Change the snippet which now reads:\n for index, summedRowValue in enumerate(sums):\n print columns[index], 1.0 * summedRowValue / numRows\n\nto make it, instead:\n with open('Finished', 'w') as ouf:\n for index, summedRowValue in enumerate(sums):\n print>>ouf, columns[index], 1.0 * summedRowVal... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003697163_python.txt |
Q:
How can I get the base URI in AppEngine?
How can I get the base URI in a Google AppEngine app written in Python? I'm using the webapp framework.
e.g.
http://example.appspot.com/
A:
The proper way to parse self.request.url is not with a regular expression, but with Python standard library's urlparse module:
impor... | How can I get the base URI in AppEngine? | How can I get the base URI in a Google AppEngine app written in Python? I'm using the webapp framework.
e.g.
http://example.appspot.com/
| [
"The proper way to parse self.request.url is not with a regular expression, but with Python standard library's urlparse module:\nimport urlparse\n\n...\n\no = urlparse.urlparse(self.request.url)\n\nObject o will be an instance of the ParseResult class with string-valued fields such as o.scheme (probably http;-) and... | [
5,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003697033_google_app_engine_python.txt |
Q:
Why isn't my route working?
The index route works when I go to /home/index
But it doesn't work why I type /home/test
What is wrong here, very confused!
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from helloworld.lib.base i... | Why isn't my route working? | The index route works when I go to /home/index
But it doesn't work why I type /home/test
What is wrong here, very confused!
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from helloworld.lib.base import BaseController, render
log ... | [
"Double check your indentation. If def test(self) is on the same indentation level as the class, you won't get an indentation error.\nThis throws an indentation error:\nclass HelloController(BaseController):\n def index(self):\n return \"hello from index()\"\n\n def test(self):\n return \"blah\"\n... | [
2
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003695670_pylons_python.txt |
Q:
SQLAlchemy Select statement - SQL Syntax Error
I have created a table (MySQL 5.1)
from sqlalchemy import *
def get():
db = create_engine('mysql://user:password@localhost/database')
db.echo = True
metadata = MetaData(db)
feeds = Table('feeds', metadata,
Column('id', Integer, primary_k... | SQLAlchemy Select statement - SQL Syntax Error | I have created a table (MySQL 5.1)
from sqlalchemy import *
def get():
db = create_engine('mysql://user:password@localhost/database')
db.echo = True
metadata = MetaData(db)
feeds = Table('feeds', metadata,
Column('id', Integer, primary_key=True),
Column('title', String(100)),
... | [
"I suspect Table.select() is only for selecting specific columns. For SELECT *, the expression language tutorial uses this syntax instead:\nfrom sqlalchemy.sql import select\ns = select([feeds])\nresult = db.execute(s)\n\n",
"there's something missing probably from your feeds.select() call, I'd have another look ... | [
1,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003697350_python_sql_sqlalchemy.txt |
Q:
In textmate, how do I reverse indent a block of selected code?
I have a block of code selected, I want to un-indent this selected code.
On a pc, I would do a shift-tab and it would un-indent.
A:
Option+Shift+Tab (or Cmd+]).
Omitting shift (or changing ] to [) will indent instead of reverse-indent.
A:
The follo... | In textmate, how do I reverse indent a block of selected code? | I have a block of code selected, I want to un-indent this selected code.
On a pc, I would do a shift-tab and it would un-indent.
| [
"Option+Shift+Tab (or Cmd+]).\nOmitting shift (or changing ] to [) will indent instead of reverse-indent.\n",
"The following is from TextMate Power Editing for the Mac by James Edward Gray II.\n\n⌘+[ or ⌥+⇧+⇥ \nDecrease selection indent (works on current line when nothing is selected)\n\n⌘+] or ⌥+⇥\nIncrease sele... | [
7,
4
] | [] | [] | [
"python",
"textmate"
] | stackoverflow_0003697628_python_textmate.txt |
Q:
Replacing some part of string with Python
I have a SQL string, for example
SELECT * FROM benchmark WHERE xversion = 1.0
And actually, xversion is aliased variable, and self.alias has all the alias info something like
{'CompilationParameters_Family': 'chip_name',
'xversion': 'CompilationParameters_XilinxVersio... | Replacing some part of string with Python | I have a SQL string, for example
SELECT * FROM benchmark WHERE xversion = 1.0
And actually, xversion is aliased variable, and self.alias has all the alias info something like
{'CompilationParameters_Family': 'chip_name',
'xversion': 'CompilationParameters_XilinxVersion', 'opt_param':
....
'chip_name': 'Compil... | [
"This should do it:\ndef processAliasString(self, sqlString):\n return ' '.join(self.alias.get(comp, comp) for comp in sqlString.split(' '))\n\n",
"If you could change your input string's format to make the replacements more clearly visible, e.g.\ns = 'SELECT * FROM benchmark WHERE %(xversion)s = 1.0'\n\nthen ... | [
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003697589_python_string.txt |
Q:
How to test the login func in flask?
I write this according to flaskr sample, I can login with browser,but test fails. Thanks for your help!
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
passw... | How to test the login func in flask? | I write this according to flaskr sample, I can login with browser,but test fails. Thanks for your help!
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if ... | [
"I needed to change this part in tests.py:\nreturn self.app.post('/Login', data=dict(\n\nto this one:\nreturn self.app.post('/login', data=dict(\n\nCapitalisation matters!\n"
] | [
7
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0003697648_flask_python.txt |
Q:
Python: intersection of lists/sets
def boolean_search_and(self, text):
results = []
and_tokens = self.tokenize(text)
tokencount = len(and_tokens)
term1 = and_tokens[0]
print ' term 1:', term1
term2 = and_tokens[1]
print ' term 2:', term2
#for term in and_tokens:
if term1 in s... | Python: intersection of lists/sets |
def boolean_search_and(self, text):
results = []
and_tokens = self.tokenize(text)
tokencount = len(and_tokens)
term1 = and_tokens[0]
print ' term 1:', term1
term2 = and_tokens[1]
print ' term 2:', term2
#for term in and_tokens:
if term1 in self._inverted_index.keys():
res... | [
"\nI want to generalize it for multiple\n tokens\n\ndef boolean_search_and_multi(self, text):\n and_tokens = self.tokenize(text)\n results = set(self._inverted_index[and_tokens[0]])\n for tok in and_tokens[1:]:\n results.intersection_update(self._inverted_index[tok])\n return list(results)\n\n",... | [
1,
0
] | [] | [] | [
"information_retrieval",
"python"
] | stackoverflow_0003697772_information_retrieval_python.txt |
Q:
How can I get better error information with try/except in Python
Consider this try/except block I use for checking error message stored in e.
Try/Catch to get the e
queryString = "SELECT * FROM benchmark WHERE NOC = 2"
try:
res = db.query(queryString)
except SQLiteError, e:
# `e` has the error info
p... | How can I get better error information with try/except in Python | Consider this try/except block I use for checking error message stored in e.
Try/Catch to get the e
queryString = "SELECT * FROM benchmark WHERE NOC = 2"
try:
res = db.query(queryString)
except SQLiteError, e:
# `e` has the error info
print `e`
The e object here contains nothing more than the above strin... | [
"This will show the trace to the error.\nimport traceback\n\ntry:\n res = db.query(queryString) \nexcept SQLiteError, e:\n # `e` has the error info \n print `e`\n for tb in traceback.format_tb(sys.exc_info()[2]):\n print tb\n\n",
"Like the first 2 answers, use traceback. Here is a more complete... | [
10,
3,
2
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0003697452_error_handling_python.txt |
Q:
Why is the Python script unreliable when run from rc.local on first boot?
The script below works great when logged in as root and run from the
command line, but when run at first boot using /etc/rc.local in Ubuntu
10.04, it fails about 25% of the time- the system root, mysql root and
some mysql user passwords a... | Why is the Python script unreliable when run from rc.local on first boot? | The script below works great when logged in as root and run from the
command line, but when run at first boot using /etc/rc.local in Ubuntu
10.04, it fails about 25% of the time- the system root, mysql root and
some mysql user passwords are set correctly, but one will fail with
console log reporting standard mysql ... | [
"Doesn't Popen execute asynchronously?\nIt seems that during boot, the load is high and you are getting a race condition between setting the root password and using it to set the next password (next command).\nTry\np = Popen(['mysql', '-uroot', \"--password=\" + mrootpass, \"-e\", \"UPDATE user SET Password = PASSW... | [
2
] | [] | [] | [
"boot",
"python"
] | stackoverflow_0003698010_boot_python.txt |
Q:
Using webpy's web.template.render() with a relative path when deployed on Apache
Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache?
The following code works using the development server but not w... | Using webpy's web.template.render() with a relative path when deployed on Apache | Using webpy, what's the proper way to reference the templates directory for web.template.render() so that it works on both the webpy development web server and on Apache?
The following code works using the development server but not when running on my Apache server.
import web
urls = (
'/', 'index',
)
class index... | [
"If you're using mod_wsgi, the easiest solution is to set the home= option appropriately,\nAlternatively, you can get the module's path and combine that with the template, i.e.\nos.path.join(os.path.dirname(__file__), 'templates/')\n\nPut it in a function if you need it often. Be aware that if you put it in a separ... | [
6
] | [] | [] | [
"python",
"web.py"
] | stackoverflow_0003697704_python_web.py.txt |
Q:
problems using observer pattern in django
I'm working on a website where I sell products (one class Sale, one class Product). Whenever I sell a product, I want to save that action in a History table and I have decided to use the observer pattern to do this.
That is: my class Sales is the subject and the History cl... | problems using observer pattern in django | I'm working on a website where I sell products (one class Sale, one class Product). Whenever I sell a product, I want to save that action in a History table and I have decided to use the observer pattern to do this.
That is: my class Sales is the subject and the History class is the observer, whenever I call the save_s... | [
"This may not be an acceptable answer since it's more architecture related, but have you considered using signals to notify the system of the change? It seems that you are trying to do exactly what signals were designed to do. Django signals have the same end-result functionality as Observer patterns.\nhttp://doc... | [
9,
4,
1,
1
] | [] | [] | [
"design_patterns",
"django",
"observer_pattern",
"python"
] | stackoverflow_0003676517_design_patterns_django_observer_pattern_python.txt |
Q:
Python multiprocessing handling sessions
I have a script receiveing data from a socket, each data contains a sessionid that a have to keep track of, foreach incomming message, i'm opening a new process with the multiprocessing module, i having trouble to figure out a way to keep track of the new incoming messages ... | Python multiprocessing handling sessions | I have a script receiveing data from a socket, each data contains a sessionid that a have to keep track of, foreach incomming message, i'm opening a new process with the multiprocessing module, i having trouble to figure out a way to keep track of the new incoming messages having the same sessionid. For example:
100100... | [
"To communicate with processes created suing multiprocessing you can use the classes Queue and Pipe (also from the multiprocessing module). Here is a short example of using a Queue to send a message to a process:\nfrom multiprocessing import Process, Queue\n\ndef f(q):\n print 'f(), waiting...'\n print q.get(... | [
1,
0,
0
] | [] | [] | [
"multiprocessing",
"python",
"queue",
"session"
] | stackoverflow_0003698051_multiprocessing_python_queue_session.txt |
Q:
prefer windows or unix line ending for code?
I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is which to prefer for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF on... | prefer windows or unix line ending for code? | I writing code that should compiled and run on both Windows and unix like Linux. I know about difference between line endings, but question is which to prefer for my code? Does it matter? I want it to be consistent - say all my code uses LF only, or is it better CRLF only? Are there critaria for comparing?
If it matter... | [
"Use a version control system that's smart enough to ignore line-endings on check-in, and use the correct value for the platform on check-out.\n",
"For the code itself, it does not matter. All reasonably modern editors and compilers handle both just as well (I presume you are not using notepad :-) ). Just use the... | [
9,
2,
2
] | [] | [] | [
"c++",
"line_endings",
"multiplatform",
"python"
] | stackoverflow_0003698084_c++_line_endings_multiplatform_python.txt |
Q:
Python, Django, how to use getattr (or other method) to call object that has multiple attributes?
After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use ... | Python, Django, how to use getattr (or other method) to call object that has multiple attributes? | After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner:
the way I do it that works (non-ge... | [
"You forgot to call the result.\ndbobject = mymodel.objects.all()\n\nAccesses the method mymodel.objects.all and then calls it.\nret = getattr(mymodel,'objects')\nself.dbobject = getattr(ret,'all')\n\naccesses the method mymodel.objects.all but does not call it.\nAll you need is to change the last line to:\nself.db... | [
14,
2
] | [] | [] | [
"code_reuse",
"django",
"getattr",
"object",
"python"
] | stackoverflow_0003698845_code_reuse_django_getattr_object_python.txt |
Q:
Handling unicode data in XMLRPC
I have to migrate data to OpenERP through XMLRPC by using TerminatOOOR.
I send a name with value "Rotule right Aurélia".
In Python the name with be encoded with value : 'Rotule right Aur\xc3\xa9lia '
But in TerminatOOOR (xmlrpc client) the data is encoded with value 'Rotule middle A... | Handling unicode data in XMLRPC | I have to migrate data to OpenERP through XMLRPC by using TerminatOOOR.
I send a name with value "Rotule right Aurélia".
In Python the name with be encoded with value : 'Rotule right Aur\xc3\xa9lia '
But in TerminatOOOR (xmlrpc client) the data is encoded with value 'Rotule middle Aur\357\277\275lia'
So in the server s... | [
"This issue comes from Kettle.\nMy program is using Kettle to get an Excel file, get the active sheet and transfer the data in that sheet to TerminateOOOR for further handling.\nAt the phase of reading data from Excel file, Kettle can not recognize the encoding then it gives bad data to TerminateOOOR. \nMy work ar... | [
1,
0
] | [] | [] | [
"python",
"ruby",
"unicode",
"xml_rpc"
] | stackoverflow_0003651031_python_ruby_unicode_xml_rpc.txt |
Q:
google code + temp server?
We are starting a new project to develop a website using django. We have created a project on google code. We would like to be able to occasionally show the progress of the site to some people, without having to purchase a real server.
We are all modifying the project through eclipse an... | google code + temp server? | We are starting a new project to develop a website using django. We have created a project on google code. We would like to be able to occasionally show the progress of the site to some people, without having to purchase a real server.
We are all modifying the project through eclipse and SVN. What's the best way to cr... | [
"One way is to run Django development server to bind on multiple interfaces:\npython manage.py runserver 0.0.0.0:8000 \n\nOr specify a IP of the interface to bind to, for example this would only listen on the interface who's IP is 192.168.1.100:\npython manage.py runserver 192.168.1.100:8000 \n\nBut Django developm... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003698964_django_python.txt |
Q:
Retrieving netmask for interfaces with multiple IP addresses using Python?
I need to list the available network interfaces and their IP addresses and corresponding netmasks using Python in a Linux environment. I can get the interfaces and the IP addresses of each interface using ioctl and SIOCGIFCONF as outlined ... | Retrieving netmask for interfaces with multiple IP addresses using Python? | I need to list the available network interfaces and their IP addresses and corresponding netmasks using Python in a Linux environment. I can get the interfaces and the IP addresses of each interface using ioctl and SIOCGIFCONF as outlined here, but I'm at loss when it comes to determining the netmask when there are mu... | [
"Technically what \"ip addr sh\" does is use the netlink library to interrogate (and optionally monitor) the kernel network interfaces / routing tables.\nYou might be able to do this in python, but I strongly recommend parsing the output of \"/sbin/ip addr sh\"\nThis is because\n\nUsing the rtnetlink library is com... | [
2
] | [] | [] | [
"linux",
"networking",
"python"
] | stackoverflow_0003698901_linux_networking_python.txt |
Q:
Django Celery implementation - OSError : [Errno 38] Function not implemented
I installed django-celery and I tried to start up the worker server but I get an OSError that a function isn't implemented. I'm running CentOS release 5.4 (Final) on a VPS:
. broker -> amqp://guest@localhost:5672/
. queues ->
... | Django Celery implementation - OSError : [Errno 38] Function not implemented | I installed django-celery and I tried to start up the worker server but I get an OSError that a function isn't implemented. I'm running CentOS release 5.4 (Final) on a VPS:
. broker -> amqp://guest@localhost:5672/
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 4
... | [
"same issue on ubuntu 10, even after full rights on shmem are given - problem still here...\nUP- finally done, /dev/shm was not mounted. so \nadd shm to fstab\nmount shm\nset full 777 permissions on /dev/shm\n"
] | [
13
] | [] | [] | [
"celery",
"celery_task",
"django",
"python"
] | stackoverflow_0003314031_celery_celery_task_django_python.txt |
Q:
pretty printer with Python?
I have a list of labels, and data as follows.
['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort']
[1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']
I need to print them into console. And for this, I'm iterating over the list, and print o... | pretty printer with Python? | I have a list of labels, and data as follows.
['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param', 'place_effort']
[1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']
I need to print them into console. And for this, I'm iterating over the list, and print out each element with a tab ('\t')... | [
"Use ljust to stuff the contents before they are printed out.\nimport sys\n\ndef maxwidth(table, index):\n \"\"\"Get the maximum width of the given column index\"\"\"\n return max([len(str(row[index])) for row in table])\n\ndef pprint_table(table):\n colpad = []\n\n for i in range(len(table[0])):\n ... | [
4,
3,
3,
2,
1,
0
] | [] | [] | [
"pretty_print",
"python"
] | stackoverflow_0003697763_pretty_print_python.txt |
Q:
Python bizarre class problem
I have the following piece of code where I try to override a method:
import Queue
class PriorityQueue(Queue.PriorityQueue):
def put(self, item):
super(PriorityQueue, self).put((item.priority, item))
However, when I run it I get TypeError exception:
super() argument 1 must ... | Python bizarre class problem | I have the following piece of code where I try to override a method:
import Queue
class PriorityQueue(Queue.PriorityQueue):
def put(self, item):
super(PriorityQueue, self).put((item.priority, item))
However, when I run it I get TypeError exception:
super() argument 1 must be type, not classobj
What is the... | [
"Queue.PriorityQueue is not a new-style class, and super only works with new-style classes. You must use\nimport Queue\nclass PriorityQueue(Queue.PriorityQueue):\n def put(self, item):\n Queue.PriorityQueue.put(self,(item.priority, item))\n\ninstead.\n"
] | [
7
] | [] | [] | [
"overriding",
"python"
] | stackoverflow_0003699440_overriding_python.txt |
Q:
How can we call the CLI executables commands using Python
How can we call the CLI executables commands using Python
For example i have 3 linux servers which are at the remote location and i want to execute some commands on those servers like finding the version of the operating system or executing any other comman... | How can we call the CLI executables commands using Python | How can we call the CLI executables commands using Python
For example i have 3 linux servers which are at the remote location and i want to execute some commands on those servers like finding the version of the operating system or executing any other commands. So how can we do this in Python. I know this is done throug... | [
"Depends on how you want to design your software.\nYou could do stand-alone scripts as servers listening for requests on specific ports,\nor you could use a webserver which runs python scripts so you just have to access a URL.\nREST is one option to implement the latter.\nYou should then look for frameworks for RES... | [
0,
0,
0
] | [] | [] | [
"api",
"django",
"python",
"soap",
"web_services"
] | stackoverflow_0003699268_api_django_python_soap_web_services.txt |
Q:
How to shallow copy app engine model instance to create new instance?
I want to implement a simple VersionedModel base model class for my app engine app. I'm looking for a pattern that does not involve explicitly choosing fields to copy.
I am trying out something like this, but it is to hacky for my taste and did ... | How to shallow copy app engine model instance to create new instance? | I want to implement a simple VersionedModel base model class for my app engine app. I'm looking for a pattern that does not involve explicitly choosing fields to copy.
I am trying out something like this, but it is to hacky for my taste and did not test it in the production environment yet.
class VersionedModel(BaseMod... | [
"Take a look at the properties static method on Model classes. With this, you can get a list of properties, and use that to get their values, something like this:\n @classmethod\n def clone(cls, other, **kwargs):\n \"\"\"Clones another entity.\"\"\"\n klass = other.__class__\n properties = other.properti... | [
2
] | [] | [] | [
"datastore",
"google_app_engine",
"python",
"shallow_copy"
] | stackoverflow_0003691064_datastore_google_app_engine_python_shallow_copy.txt |
Q:
__init__, inheritance and variadic parameters
I'd like to subclass an existing scons class (named SConsEnvironment) which has the following __init__ prototype:
def __init__(self,
platform=None,
tools=None,
toolpath=None,
variables=None,
... | __init__, inheritance and variadic parameters | I'd like to subclass an existing scons class (named SConsEnvironment) which has the following __init__ prototype:
def __init__(self,
platform=None,
tools=None,
toolpath=None,
variables=None,
parse_flags = None,
**kw):... | [
"In the super(EIDEnvironment, self).__init__(...) call, change kw to **kw. As the code is currently written, you're passing a dictionary containing the keyword args, but not actually passing them as keyword args.\n",
"I guess you need to unpack kw otherwise you pass it as a dictionary:\nsuper(EIDEnvironment, self... | [
3,
1
] | [] | [] | [
"inheritance",
"initialization",
"python",
"variadic_functions"
] | stackoverflow_0003699580_inheritance_initialization_python_variadic_functions.txt |
Q:
SQLAlchemy memory hog on select statement
As per the SQLAlchemy, select statements are treated as iterables in for loops. The effect is that a select statement that would return a massive amount of rows does not use excessive memory.
I am finding that the following statement on a MySQL table:
for row in my_connec... | SQLAlchemy memory hog on select statement | As per the SQLAlchemy, select statements are treated as iterables in for loops. The effect is that a select statement that would return a massive amount of rows does not use excessive memory.
I am finding that the following statement on a MySQL table:
for row in my_connections.execute(MyTable.__table__.select()):
... | [
"The basic MySQLdb cursor fetches the entire query result at once from the server.\nThis can consume a lot of memory and time.\nUse MySQLdb.cursors.SSCursor when you want to make a huge query and\npull results from the server one at a time.\nTherefore, try passing connect_args={'cursorclass': MySQLdb.cursors.SSCurs... | [
14
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003699532_python_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.