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:
Checking if first letter of string is in uppercase
I want to create a function that would check if first letter of string is in uppercase. This is what I've came up with so far:
def is_lowercase(word):
if word[0] in range string.ascii_lowercase:
return True
else:
return False
When I try to... | Checking if first letter of string is in uppercase | I want to create a function that would check if first letter of string is in uppercase. This is what I've came up with so far:
def is_lowercase(word):
if word[0] in range string.ascii_lowercase:
return True
else:
return False
When I try to run it I get this error:
if word[0] in range string... | [
"Why not use str.isupper();\nIn [2]: word = 'asdf' \nIn [3]: word[0].isupper()\nOut[3]: False\n\nIn [4]: word = 'Asdf' \nIn [5]: word[0].isupper()\nOut[5]: True\n\n",
"This is built-in for strings:\nword = \"Hello\"\nword.istitle() # True\n\nbut note that str.istitle looks whether every word in the string is ... | [
76,
33
] | [
"The syntax error stems from the fact that you need parentheses:\nrange(string.ascii_lowercase)\n\nBut in fact you shouldn't use range. It's as simple as:\nif word[0] in string.ascii_lowercase\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0007353968_python.txt |
Q:
Getting Blank Lists - No Idea Why?
I use this code:
from __future__ import division
from __future__ import print_function
in_file = open("s:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Authorize Truncated.csv")
text = in_file.readlines()
in_file.close()
header = text[0:1]
text = text[1:]
for ... | Getting Blank Lists - No Idea Why? | I use this code:
from __future__ import division
from __future__ import print_function
in_file = open("s:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Authorize Truncated.csv")
text = in_file.readlines()
in_file.close()
header = text[0:1]
text = text[1:]
for index, line in enumerate(text):
text... | [
"Look at these two lines:\nname = text\ndate = text\n\nThese lines do not make copies of text for name and date to point to; rather, they set both name and date to be in essence alternate names for text. So, after the third for loop (with body name[index] = line[3:5], every line in text is two items long (because t... | [
1
] | [] | [] | [
"enumerate",
"for_loop",
"list",
"python"
] | stackoverflow_0007354047_enumerate_for_loop_list_python.txt |
Q:
How do I replace commas in a string
I want to remove all commas from a string using regular expressions, I want letters, periods and numbers to remain just commas
A:
Why a regex?
mystring = mystring.replace(",", "")
is enough.
Of course, if you insist:
mystring = re.sub(",", "", mystring)
but that's probably ... | How do I replace commas in a string | I want to remove all commas from a string using regular expressions, I want letters, periods and numbers to remain just commas
| [
"Why a regex? \nmystring = mystring.replace(\",\", \"\")\n\nis enough.\nOf course, if you insist:\nmystring = re.sub(\",\", \"\", mystring)\n\nbut that's probably an order of magnitude slower.\n",
"You don't need RE for that trivial operation. just use replace() on string:\na=\"123,asd,wer\"\na.replace(\",\", \"\... | [
43,
7
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007354176_python_regex.txt |
Q:
How can I pass file names to external commands executed from Python?
I am trying to execute a command inside a Python script:
import subprocess
output_process =
subprocess.Popen("javac -cp C:\Users\MyUsername\Desktop\htmlcleaner-2.2.jar Scrapping_lastfm.java",
shell=True, stdout=subprocess.... | How can I pass file names to external commands executed from Python? | I am trying to execute a command inside a Python script:
import subprocess
output_process =
subprocess.Popen("javac -cp C:\Users\MyUsername\Desktop\htmlcleaner-2.2.jar Scrapping_lastfm.java",
shell=True, stdout=subprocess.PIPE)
But I am getting an error package org.htmlcleaner does not exist.
I... | [
"Try\noutput_process = subprocess.Popen([\"javac\", \"-cp\", \n \"C:\\Users\\MyUsername\\Desktop\\htmlcleaner-2.2.jar\", \"Scrapping_lastfm.java\"],\n shell=True, stdout=subprocess.PIPE, env={'ENVIRONMENTAL': '/variables/here'})\n\nwith whatever java-related environmental variables you have when you run javac... | [
1,
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0007354050_python_windows.txt |
Q:
Handling SIGINT in slow system calls
I am very new to Python, so forgive me if this question is very basic.
I am trying to handle a keyboard interrupt while accepting data from a socket using select module. So, I have a select.select() function call to wait for data from the socket, and then output it to console.... | Handling SIGINT in slow system calls | I am very new to Python, so forgive me if this question is very basic.
I am trying to handle a keyboard interrupt while accepting data from a socket using select module. So, I have a select.select() function call to wait for data from the socket, and then output it to console.
When pressing CTRL_C, it seems that somet... | [
"Use errno.EINTR instead. It is safe.\n>>> import errno\n>>> errno.EINTR\n4\n\nHowever, this will not tell you which signal interrupted the system call, only that some signal interrupted it.\nFrom man 2 select:\n\nEBADF An invalid file descriptor was given in one of the sets. (Per‐\n haps a file descripto... | [
1
] | [] | [] | [
"keyboardinterrupt",
"python",
"sigint",
"system_calls"
] | stackoverflow_0007354624_keyboardinterrupt_python_sigint_system_calls.txt |
Q:
python 2.5 error on unzip large dbf file
So, I have a directory of rather large, zipped, shapefiles. I currently have code in python 2.5 that will unzip most of the files (i.e. all of the shapefile component parts .shp, .prj, .dbf...) but I run into occational problems unzipping some .dbf files.
These files area ... | python 2.5 error on unzip large dbf file | So, I have a directory of rather large, zipped, shapefiles. I currently have code in python 2.5 that will unzip most of the files (i.e. all of the shapefile component parts .shp, .prj, .dbf...) but I run into occational problems unzipping some .dbf files.
These files area generally quite large when I have a problem wi... | [
"Two possible candidate problems: the file to extract is either empty, or is larger than 2Gb. Both of these issues were fixed in 2.6 or 2.7.\nIf neither of these is the case, putting one of the culprit zip archives somewhere public would help us track down the issue.\n"
] | [
0
] | [] | [] | [
"dbf",
"python",
"shapefile",
"unzip"
] | stackoverflow_0007164151_dbf_python_shapefile_unzip.txt |
Q:
using a variable whose value is an integer in a regular expression (python)
Suppose I have the following regular expression in Python and I would like to use a variable instead of [1-12]. For example, my variable is currentMonth = 9
How can I plug currentMonth into the regular expression?
r"(?P<speaker>[A-Za-z\s.... | using a variable whose value is an integer in a regular expression (python) | Suppose I have the following regular expression in Python and I would like to use a variable instead of [1-12]. For example, my variable is currentMonth = 9
How can I plug currentMonth into the regular expression?
r"(?P<speaker>[A-Za-z\s.]+): (?P<month>[1-12])"
| [
"Use string formating to insert currentMonth into the regex pattern:\nr\"(?P<speaker>[A-Za-z\\s.]+): (?P<month>{m:d})\".format(m=currentMonth)\n\nBy the way, (?P<month>[1-12]) probably does not do what you expect. The regex [1-12] matches 1 or 2 only. If you wanted to match one through twelve,\nyou'd need (?P<month... | [
5,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007354732_python_regex.txt |
Q:
Int to boolean array python
If I have a char d and a char k, how do I turn each into a bit array (such as True-False-True-True-True-False-False-True) and then combine the arrays into a single array by AND-ing each bit (and then turning the combined array back into a char)? Such as 01100001 (a) and 01100011 (c) co... | Int to boolean array python | If I have a char d and a char k, how do I turn each into a bit array (such as True-False-True-True-True-False-False-True) and then combine the arrays into a single array by AND-ing each bit (and then turning the combined array back into a char)? Such as 01100001 (a) and 01100011 (c) combine to make 01100001 (c)? Also... | [
"no need to make an array:\n>>> chr(ord('c') & ord('a'))\n'a'\n\n"
] | [
4
] | [] | [] | [
"ascii",
"bit",
"bitwise_and",
"byte",
"python"
] | stackoverflow_0007355352_ascii_bit_bitwise_and_byte_python.txt |
Q:
Twisted: how to silence certain log messages?
I have XML-RPC methods in my application that generate a lot of Twisted log messages like this, which are in turn logged through Python's logging module:
2011-09-08 18:00:51.399553 UTC INFO XXX.XXX.XXX.XXX - - [08/Sep/2011:18:00:50 +0000] "POST /RPC2 HTTP/1.0" 200 129 ... | Twisted: how to silence certain log messages? | I have XML-RPC methods in my application that generate a lot of Twisted log messages like this, which are in turn logged through Python's logging module:
2011-09-08 18:00:51.399553 UTC INFO XXX.XXX.XXX.XXX - - [08/Sep/2011:18:00:50 +0000] "POST /RPC2 HTTP/1.0" 200 129 "-" "xmlrpclib.py/1.0.1 (by www.pythonware.com)"
Th... | [
"twisted.web.xmlrpc.Proxy uses a factory to set up its HTTP connection (in the usual way). The noisy attribute of the factories Twisted provides controls whether they log start and stop messages. You can change the noisy attribute of Proxy's factory like this:\nfrom sys import stdout\n\nfrom twisted.web.xmlrpc im... | [
4
] | [] | [] | [
"logging",
"python",
"twisted"
] | stackoverflow_0007352515_logging_python_twisted.txt |
Q:
Translating a declarative DSL into nested function calls
I have a python library which builds special iterators (a behavior tree) out of nested function calls. While the API has a fairly nice and light-weight syntax (due to it being python), it could really use a declarative DSL.
Here's a rough sketch of what I'm ... | Translating a declarative DSL into nested function calls | I have a python library which builds special iterators (a behavior tree) out of nested function calls. While the API has a fairly nice and light-weight syntax (due to it being python), it could really use a declarative DSL.
Here's a rough sketch of what I'm envisioning:
The DSL (using YAML):
tree:
- sequence:
- d... | [
"I think you could let python keep track of the function calls and parameters instead of doing it yourself with a stack.\nSuppose you have a YAML parse tree in which each node represents a function call and each child of this node is a parameter (which is also a function call, so it could potentially have its own p... | [
3
] | [] | [] | [
"behavior_tree",
"dsl",
"parsing",
"python"
] | stackoverflow_0007354958_behavior_tree_dsl_parsing_python.txt |
Q:
Testing REST API with database backend
I want to know the best/different ways to test a REST API which uses a database backend. I've developed my API with Flask in Python and want to use unittest or nose.
But my problem, is that some resources require another resource to create them in the first place. Is there a ... | Testing REST API with database backend | I want to know the best/different ways to test a REST API which uses a database backend. I've developed my API with Flask in Python and want to use unittest or nose.
But my problem, is that some resources require another resource to create them in the first place. Is there a way to say that to test the creation of a bl... | [
"There are 2 standard ways of approaching a test that depends on something else (object, function call, etc).\n\nYou can use mocks in place of the objects the code you are testing depends on.\nYou can load a fixture or do the creation/call in the test setup.\n\nSome people like \"classical\" unit tests where only t... | [
8,
2
] | [] | [] | [
"flask",
"python",
"rest",
"testing",
"unit_testing"
] | stackoverflow_0007336101_flask_python_rest_testing_unit_testing.txt |
Q:
How to change the background color for a QTreeView Header (aka QHeaderView)?
I am trying to change the background color for certain header sections. Some will use the default coloring, others will get a different color.
The HeaderView doesn't accept delegates like the QTreeView does; it does all the painting itse... | How to change the background color for a QTreeView Header (aka QHeaderView)? | I am trying to change the background color for certain header sections. Some will use the default coloring, others will get a different color.
The HeaderView doesn't accept delegates like the QTreeView does; it does all the painting itself. It does this using two methods --
paintEvent
paintSection
My initial attem... | [
"There is no need to implement anythingQHeaderView can be changed through stylesheets like almost all widgets.\nEdit:\nYou mentioned that you wanted to change the background color per column depending on data, the easiest way to do that is probably to derive a new model from QAbstractItemModel or another model clas... | [
2,
0,
0
] | [] | [] | [
"paint",
"pyqt",
"python",
"qt",
"user_interface"
] | stackoverflow_0007342649_paint_pyqt_python_qt_user_interface.txt |
Q:
Why do Python functions get garbage collected?
I have a C++ library which uses Python callbacks. The callback, i.e. PyObject*, is stored in an object of class UnaryFunction, and the constructor Py_INCREFs it. The destuctor Py_XDECREFs it. That's the problem. The interpreter segfaults on that DECREF.
My solution is... | Why do Python functions get garbage collected? | I have a C++ library which uses Python callbacks. The callback, i.e. PyObject*, is stored in an object of class UnaryFunction, and the constructor Py_INCREFs it. The destuctor Py_XDECREFs it. That's the problem. The interpreter segfaults on that DECREF.
My solution is to just not DECREF it, but that seems wrong.
What i... | [
"A crash does not necessary mean that it is trying to GC an used object. It can also mean that you are calling python code without the interpretor lock.\nCalling Py_XDECREF in a destructor leads me to think you have something like this:\nvoid MyCallback(myfunc, myarg)\n{\n ...\n PyGILState_STATE gilstate = Py... | [
1,
0
] | [] | [] | [
"python",
"python_c_api"
] | stackoverflow_0007342102_python_python_c_api.txt |
Q:
Beautiful Soup and Tables
Hi I'm trying to parse an html table using Beautiful Soup.
The table looks something like this:
<table width=100% border=1 cellpadding=0 cellspacing=0 bgcolor=#e0e0cc>
<tr>
<td width=12% height=1 align=center valign=middle bgcolor=#e0e0cc bordercolorlight=#000000 bordercolordark=whit... | Beautiful Soup and Tables | Hi I'm trying to parse an html table using Beautiful Soup.
The table looks something like this:
<table width=100% border=1 cellpadding=0 cellspacing=0 bgcolor=#e0e0cc>
<tr>
<td width=12% height=1 align=center valign=middle bgcolor=#e0e0cc bordercolorlight=#000000 bordercolordark=white> <b><font face="Verdana" size... | [
"The first problem is with this statement: \"t=soup.find(id='table')\" There is nothing with an id of table. I think what you mean is \"t=soup.find('table')\" this finds a table. Unfortunately it only finds the first table.\nYou could do \"t=soup.findAll(table)[1]\" but this would be quite brittle.\nI would suggest... | [
8
] | [] | [] | [
"beautifulsoup",
"html_table",
"python"
] | stackoverflow_0007355806_beautifulsoup_html_table_python.txt |
Q:
get line of a predefined sentence that in a txt file line?
so i have this code:
for line in open('music.txt'):
if 'file : "' in line:
c = line.split('file : "')
del c[0]
d="".join(c)
a=re.sub('"','',d)
e=re.sub(',','',a)
urls.append(e)
Is there a way to ... | get line of a predefined sentence that in a txt file line? | so i have this code:
for line in open('music.txt'):
if 'file : "' in line:
c = line.split('file : "')
del c[0]
d="".join(c)
a=re.sub('"','',d)
e=re.sub(',','',a)
urls.append(e)
Is there a way to do this but without a file?
| [
"If you want to read from standard input (for example, in a pipeline) then you can just write \nimport sys\nfor line in sys.stdin:\n\nAnd the rest will work. (sys.stdin is an open file corresponding to standard input)\nIf you have the lines in a list, then you can just iterate across the list using the same code. \... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0007355894_python.txt |
Q:
python: two versions of def depending on setting
I have a program that runs on two platforms. Each platform has a different set of imported modules. Many of the def statements on one platform need an additional parameter to run with its set of imports. Not every def statement needs to be changed.
If something l... | python: two versions of def depending on setting | I have a program that runs on two platforms. Each platform has a different set of imported modules. Many of the def statements on one platform need an additional parameter to run with its set of imports. Not every def statement needs to be changed.
If something like this worked, it would be make things easier:
if pl... | [
"I wonder why a function should have an argument that it never uses. Wouldn't it be better to fix the surrounding code that forces you into this situation? \nNevertheless, it is possible...\ndef narcissist(func):\n def wrapper(self,*args,**kwargs):\n return func(*args,**kwargs)\n return wrapper\n\ndef ... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0007355931_python.txt |
Q:
Adjust alarm time to match clock time in python
I'm just learning Python, and as one of the basic challenges that were suggested to me by friends I've been working on an alarm clock. I successfully made an alarm clock that played a .wav sound at a predetermined time. Now I've been using Pygame for a GUI, and it al... | Adjust alarm time to match clock time in python | I'm just learning Python, and as one of the basic challenges that were suggested to me by friends I've been working on an alarm clock. I successfully made an alarm clock that played a .wav sound at a predetermined time. Now I've been using Pygame for a GUI, and it all worked great, until I had to set the buttons to adj... | [
"You are looking for strptime() which will convert a string to a datetime instance.\nsee here for how to properly use it.\nComparing two datetime instances will give you a timedelta instance which you can read about here. Essentially it will give you the difference between the two times to the nearest milisecond.\n... | [
1
] | [] | [] | [
"alarm",
"clock",
"pygame",
"python",
"time"
] | stackoverflow_0007356061_alarm_clock_pygame_python_time.txt |
Q:
TemplateDoesNotExist on python app-engine django 1.2 while template rendering absolute paths
Due to App Engine warning
You are using the default Django version (0.96). The default Django version will change in an App Engine release in the near future. Please call use_library() to explicitly select a Django versio... | TemplateDoesNotExist on python app-engine django 1.2 while template rendering absolute paths | Due to App Engine warning
You are using the default Django version (0.96). The default Django version will change in an App Engine release in the near future. Please call use_library() to explicitly select a Django version. For more information see http://code.google.com/appengine/docs/python/tools/libraries.html#Djan... | [
"I had some similar issues, with some fixes which I describe here:\nApp engine default Django version change\nWhen you use app engine's template.render it sets the TEMPLATE_DIRS to the directory of the template you are rendering. The extends tag in Django 1.2 checks that the templates being included are inside the ... | [
1
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0007353355_django_django_templates_google_app_engine_python.txt |
Q:
Facebook Posting to a Page
I am trying to post to the wall of a facebook page that I am administrator (not profile), however no luck. How do I achieve this ? I'm stucked at the page access token retrieval part.
#!/usr/bin/python
# coding: utf-8
import facebook
import urllib
import urlparse
import subprocess
impor... | Facebook Posting to a Page | I am trying to post to the wall of a facebook page that I am administrator (not profile), however no luck. How do I achieve this ? I'm stucked at the page access token retrieval part.
#!/usr/bin/python
# coding: utf-8
import facebook
import urllib
import urlparse
import subprocess
import warnings
# Hide deprecation w... | [
"I would not recommend doing this through the command line with curl as it is less secure and less reliable. You can do all of this with the urllib2 and json modules\nto get the access token you just want to make a call to https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SE... | [
1
] | [] | [] | [
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0007355615_facebook_facebook_graph_api_python.txt |
Q:
trying to get vim to work with python
Im trying to get code completion for python in vim 7.3. When I install vim I use this configuration:
./configure --prefix=${HOME}/vim73 --enable-python3interp=yes --with-python3-config-dir=/home/etobkru/Python3/lib/python3.1/config
make && make install
I copy this file:
http... | trying to get vim to work with python | Im trying to get code completion for python in vim 7.3. When I install vim I use this configuration:
./configure --prefix=${HOME}/vim73 --enable-python3interp=yes --with-python3-config-dir=/home/etobkru/Python3/lib/python3.1/config
make && make install
I copy this file:
http://vim.cybermirror.org/runtime/autoload/pyt... | [
"It depends on your vim version and on how the OS provides Python and Python3, whether python and python3 are supported both. Else if compiled in at all, then the Python version you first use will be activated.\nCheck out the following thread and the one linked from there:\nVim 7.3: Python3 support\n",
"Delete an... | [
2,
2
] | [] | [] | [
"autocomplete",
"code_completion",
"python",
"vim"
] | stackoverflow_0003624788_autocomplete_code_completion_python_vim.txt |
Q:
Periodical tasks for each entity
I often have models that are a local copy of some remote resource, which needs to be periodically kept in sync.
Task(
url="/keep_in_sync",
params={'entity_id':entity_id},
name="sync-%s" % entity_id,
countdown=3600
).add()
Inside keep_in_sync any changes are save... | Periodical tasks for each entity | I often have models that are a local copy of some remote resource, which needs to be periodically kept in sync.
Task(
url="/keep_in_sync",
params={'entity_id':entity_id},
name="sync-%s" % entity_id,
countdown=3600
).add()
Inside keep_in_sync any changes are saved to the model and a new task is sched... | [
"You'll get an exception (TaskAlreadyExistsError) if there already such task in queue (same url and same params). So, don't worry, just all of them into queue, and remember to catch exceptions.\nYou can find full list of exceptions here: http://code.google.com/intl/en/appengine/docs/python/taskqueue/exceptions.html... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007345602_google_app_engine_python.txt |
Q:
Bind to mdns multicast address on mac os x
I want to bind to the multicast DNS group and port on a mac os x machine to prototype some bonjour functionality. However, when I try to bind to the port I get the following error (incidentally this is run from python):
socket.error: [Errno 48] Address already in use
It ... | Bind to mdns multicast address on mac os x | I want to bind to the multicast DNS group and port on a mac os x machine to prototype some bonjour functionality. However, when I try to bind to the port I get the following error (incidentally this is run from python):
socket.error: [Errno 48] Address already in use
It looks like the mDNSResponder binds to the addres... | [
"The error code description may be a little confusing in this situation. When an application binds to a port without setting the SO_REUSEPORT option, if a second application tries to bind to the same port the bind will fail with the above error. The problem is not with the binding address though, but with the port ... | [
5
] | [] | [] | [
"macos",
"mdns",
"multicast",
"python",
"sockets"
] | stackoverflow_0007342322_macos_mdns_multicast_python_sockets.txt |
Q:
Jython(WLST)/Python Communication
I have a want to make a jython and python communcation link. I have a django app and python scripts I use for a front end and do system admin/automation tasks. I use jython for Weblogic 9/10. The thing I want to do is make it so that I can give the jython system a request to do. S... | Jython(WLST)/Python Communication | I have a want to make a jython and python communcation link. I have a django app and python scripts I use for a front end and do system admin/automation tasks. I use jython for Weblogic 9/10. The thing I want to do is make it so that I can give the jython system a request to do. Such as task A with args a,b,c and then ... | [
"Have you considdered Celery or some other standard Queue/Broker messaging system? django-celery is quite mature and well developed and specifically designed for this kind of task.\nDjango -> Celery --> Worker Process (always running)\n ^ |-> Worker Process\n | `-> Worker Process -,\n ... | [
3,
2
] | [
"Pickling is fine, use cPickle for efficiency. However you should not write it to a file. Rather use some other IPC mechanisms, like sockets or pipes (i.e. see https://stackoverflow.com/search?q=python+named+pipes) that avoid the disk-overhead.\n"
] | [
-1
] | [
"django",
"jython",
"python",
"weblogic",
"wlst"
] | stackoverflow_0007342368_django_jython_python_weblogic_wlst.txt |
Q:
Can you authenticate Facebook Graph entirely from command line with Python?
I'm writing a (tabbed) application for Facebook that requires a background process to run on a server and, periodically, upload images to an album on this application's page.
What I'm trying to do is create a script that will:
a) authenti... | Can you authenticate Facebook Graph entirely from command line with Python? | I'm writing a (tabbed) application for Facebook that requires a background process to run on a server and, periodically, upload images to an album on this application's page.
What I'm trying to do is create a script that will:
a) authenticate me with the app
b) upload an image to a specific album
All of this entirely ... | [
"If you only need to authenticate as one user, you can get an access token with the offline_access permission that will last forever and just bake that into the script.\n",
"Does http://blog.carduner.net/2010/05/26/authenticating-with-facebook-on-the-command-line-using-python/ cover what you need(ed)?\n"
] | [
1,
0
] | [] | [] | [
"facebook",
"oauth",
"python"
] | stackoverflow_0002791683_facebook_oauth_python.txt |
Q:
Scraping data from PDF to CSV? Python vs PHP?
I have a bunch of reports that I'm hand-compiling every day and it's taking forever, so I was thinking of automating the whole process. I will be scraping data from: (1) HTML, (2) CSV/XLS, (3) PDF. I have mainly only scraped data from CSV/HTML with PHP and was wonderin... | Scraping data from PDF to CSV? Python vs PHP? | I have a bunch of reports that I'm hand-compiling every day and it's taking forever, so I was thinking of automating the whole process. I will be scraping data from: (1) HTML, (2) CSV/XLS, (3) PDF. I have mainly only scraped data from CSV/HTML with PHP and was wondering if there are any dependable libraries or ways of ... | [
"Beautiful Soup is another good alternative for scraping and PDFminer has been the best PDF parser for Python I have found. I use pdf2txt.py mostly and then re-format from there if needed.\n",
"If you have command line access to a linux server try the pdftotext command\n$ pdftotext file.pdf\n\nIf you're lucky yo... | [
3,
2
] | [] | [] | [
"pdf",
"php",
"python",
"screen_scraping"
] | stackoverflow_0007356552_pdf_php_python_screen_scraping.txt |
Q:
Using PLY to parse SQL statements
I know there are other tools out there to parse SQL statements, but I am rolling out my own for educational purposes. I am getting stuck with my grammar right now.. If you can spot an error real quick please let me know.
SELECT = r'SELECT'
FROM = r'FROM'
COLUMN = TABLE = r'[a-zA... | Using PLY to parse SQL statements | I know there are other tools out there to parse SQL statements, but I am rolling out my own for educational purposes. I am getting stuck with my grammar right now.. If you can spot an error real quick please let me know.
SELECT = r'SELECT'
FROM = r'FROM'
COLUMN = TABLE = r'[a-zA-Z]+'
COMMA = r','
STAR = r'\*'
END = r... | [
"I think your problem is that your regular expressions for t_TABLE and t_COLUMN are also matching your reserved words (SELECT and FROM). In other words, SELECT a FROM b; tokenizes to something like COLUMN COLUMN COLUMN COLUMN END (or some other ambiguous tokenization) and this doesn't match any of your productions... | [
6
] | [] | [] | [
"context_free_grammar",
"parsing",
"ply",
"python",
"sql"
] | stackoverflow_0007355493_context_free_grammar_parsing_ply_python_sql.txt |
Q:
Guidelines for use of the import statement
Possible Duplicate:
Should I use "from package import utils, settings" or "from . import utils, settings"
What are the guidelines about the choice between the following when importing from the python standard library?:
import foo
from foo import bar
What are the consid... | Guidelines for use of the import statement |
Possible Duplicate:
Should I use "from package import utils, settings" or "from . import utils, settings"
What are the guidelines about the choice between the following when importing from the python standard library?:
import foo
from foo import bar
What are the considerations? Is it a footprint thing? Or just a po... | [
"If you use pyflakes, it will complain if you don't use things that you have imported.\nI find, if I only need one or two functions/classes, then I'll import them directly: if I need lots, I may just use the namespaced version (foo.bar).\nThere is a cost to . lookups, so if you had lots of them in a nested loop, it... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007357068_python.txt |
Q:
Django admin: sending signal on field change
I need to trigger a signal if and only if form field "status" is updated. The signal works fine, but is being triggered regardless of any change submissions to the form.
Below is my save_model override from admin.py, for the OrderAdmin class:
def save_model(self, reques... | Django admin: sending signal on field change | I need to trigger a signal if and only if form field "status" is updated. The signal works fine, but is being triggered regardless of any change submissions to the form.
Below is my save_model override from admin.py, for the OrderAdmin class:
def save_model(self, request, obj, form, change):
if not change:
... | [
"You can try overriding ModelAdmin.get_object to add a flag to your instance:\ndef get_object(self, request, object_id):\n o = super(Order, self).get_object(request, object_id)\n if o:\n o._old_status = o.status\n return o\n\nNow you can use if o.status != o._old_status in save_model.\n"
] | [
3
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0007356471_django_django_admin_python.txt |
Q:
Pythonic way to populate numpy array
I find myself parsing lots of data files (usually in a .csv file or similar) using the csv reader and a for loop to iterate over every line. The data is usually a table of floats so for example.
reader = csv.reader(open('somefile.csv'))
header = reader.next()
res_list = [list(... | Pythonic way to populate numpy array | I find myself parsing lots of data files (usually in a .csv file or similar) using the csv reader and a for loop to iterate over every line. The data is usually a table of floats so for example.
reader = csv.reader(open('somefile.csv'))
header = reader.next()
res_list = [list() for i in header]
for line in reader... | [
"There is numpy.loadtxt:\nX = numpy.loadtxt('somefile.csv', delimiter=',')\n\nDocumentation.\n\nEdit: for a list of numpy arrays,\nX = [scipy.array(line.split(','), dtype='float') \n for line in open('somefile.csv', 'r')]\n\n",
"I think it is difficult to improve very much on what you have. Python lists are ... | [
8,
3,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0007356042_arrays_numpy_python.txt |
Q:
Binary buffer in Python
In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java... | Binary buffer in Python | In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream?
The... | [
"You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data:\nfrom io import BytesIO\nbio = BytesIO(b\"some initial binary data: \\x00\\x01\")\n\nStringIO will throw TypeError:\nfrom io import StringIO\nsio = StringIO(b\"some initial binary data: \\x00\\x01\")\... | [
90,
24,
4
] | [] | [] | [
"binary",
"buffer",
"io",
"python"
] | stackoverflow_0000025116_binary_buffer_io_python.txt |
Q:
Django logout() crashes Python
I'm having trouble with logout() while testing my project with the Django web server. This is my logout view:
def logout(request):
logout(request)
return render_to_response('main.html', {})
When I access /logout (which calls this view) I get a popup window that says Python ... | Django logout() crashes Python | I'm having trouble with logout() while testing my project with the Django web server. This is my logout view:
def logout(request):
logout(request)
return render_to_response('main.html', {})
When I access /logout (which calls this view) I get a popup window that says Python crashed. It doesn't give me any trac... | [
"You have a slight problem of recursion there. logout is calling itself, and so on until you get a stack overflow.\nRename the view or the Django logout function when you import it.\n",
"The answer above says it all, but I find it helpful to rename external functions with some sort of unique prefix so you know wh... | [
11,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007357127_django_python.txt |
Q:
Why doesn't this sql script execute?
Hi I have the following python:
c = conn.cursor()
#get the account id for the specific user
actidSQL = "select id from accounts where user_id = (select id from auth_user where username = '%s');" % user
c.execute(actidSQL)
actid = c.fetchone()[0]
print actid
#fill the latenci... | Why doesn't this sql script execute? | Hi I have the following python:
c = conn.cursor()
#get the account id for the specific user
actidSQL = "select id from accounts where user_id = (select id from auth_user where username = '%s');" % user
c.execute(actidSQL)
actid = c.fetchone()[0]
print actid
#fill the latencies table - currently not firing, not sure ... | [
"What do you mean with \"The first sql executes but the second doesn't.\"? You get an error? Or is there no data in the DB? I assume that there is no data in the database and you are using MySQL. This is because you don't commit your changes. A conn.commit() at the end of your script should help.\n",
"It looks li... | [
1,
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0007357995_python_sql.txt |
Q:
Should I use epoll or just blocking recv in threads?
I'm trying to write a scalable custom web server.
Here's what I have so far:
The main loop and request interpreter are in Cython. The main loop accepts connections and assigns the sockets to one of the processes in the pool (has to be processes, threads won't ge... | Should I use epoll or just blocking recv in threads? | I'm trying to write a scalable custom web server.
Here's what I have so far:
The main loop and request interpreter are in Cython. The main loop accepts connections and assigns the sockets to one of the processes in the pool (has to be processes, threads won't get any benefit from multi-core hardware because of the GIL)... | [
"If you're already using multiple threads, epoll doesn't offer you much additional benefit. \nThe point of epoll is that a single thread can listen for activity on many file selectors simultaneously (and respond to events on each as they occur), and thus provide event-driven multitasking without requiring the spawn... | [
11,
1
] | [] | [] | [
"epoll",
"python",
"sockets",
"webserver"
] | stackoverflow_0007358168_epoll_python_sockets_webserver.txt |
Q:
App engine urlfetch issue
Im trying to request https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=[http://www.my-website.dk/]&key=[my-key] using urlfetch from app engine but it's not working.
When I access it and hardcode my-url into the request like this: https://www.googleapis.com/pagespeedonline/v1/... | App engine urlfetch issue | Im trying to request https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=[http://www.my-website.dk/]&key=[my-key] using urlfetch from app engine but it's not working.
When I access it and hardcode my-url into the request like this: https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://www.my-... | [
"First, the urlfetch call has an error because you are passing two parameters to the function.\nYou should use the % between the two strings to pass just one url parameter to the function. \nurlfetch.fetch(\"https://www.goo..e/v1/runPagespeed?url=%s&key=[my-key]\" %\n ... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0007351648_google_app_engine_python_urlfetch.txt |
Q:
Specifying a boolean filter expression to a python script
I have a CSV (comma separated values) file that contains student information. The column headers look like StudentId, StudentFirstName, StudentLastName, StudentZipCode, StudentHeight, StudentCommuteMethod, etc. and the subsequent rows contain the informatio... | Specifying a boolean filter expression to a python script | I have a CSV (comma separated values) file that contains student information. The column headers look like StudentId, StudentFirstName, StudentLastName, StudentZipCode, StudentHeight, StudentCommuteMethod, etc. and the subsequent rows contain the information for individual students. Now, I would like to write a python ... | [
"You are definitely trying to reimplement SQL in Python. I believe it would be better to use a relational database and just run SQL queries.\nHowever, regarding question 1, you can easily let the user enter Python expressions and eval() them on each row of data.\nThis is a working example, which uses exec to bind c... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007357076_python.txt |
Q:
How do I make Varnish to stop caching ESI fragments
I am having problem using ESI with Varnish 3.0 with a repoze.bfg project successfully. I have an ESI fragment that displays a notice for logged in users, included via an ESI tag. However, varnish caches the included ESI fragment, so changes made to the fragment, ... | How do I make Varnish to stop caching ESI fragments | I am having problem using ESI with Varnish 3.0 with a repoze.bfg project successfully. I have an ESI fragment that displays a notice for logged in users, included via an ESI tag. However, varnish caches the included ESI fragment, so changes made to the fragment, either manually, or as a result of a session does not ref... | [
"I'd first try completely skipping the cache for *.esi URLs, i.e. return(pass); instead of set beresp.ttl = 0s;\n"
] | [
0
] | [] | [] | [
"caching",
"http",
"python",
"repoze.bfg",
"varnish"
] | stackoverflow_0007065643_caching_http_python_repoze.bfg_varnish.txt |
Q:
Get url from webbrowser in python
I would like to ask how can I get list of urls which are opened in my webbrowser, from example in firefox. I need it in Python.
Thanks
A:
Try either SeleniumRC - which is very good
or https://github.com/bard/mozrepl/wiki/
You can use it with python as described here
http://www... | Get url from webbrowser in python | I would like to ask how can I get list of urls which are opened in my webbrowser, from example in firefox. I need it in Python.
Thanks
| [
"Try either SeleniumRC - which is very good \nor https://github.com/bard/mozrepl/wiki/\nYou can use it with python as described here\nhttp://www.craigethomas.com/blog/2009/04/get-android-market-stats-with-python-mozrepl-and-beautifulsoup/\nBut I would go the selenium route for anything not trivial\n",
"First I'd... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007358224_python.txt |
Q:
Dealing with legacy django project in new localized projects
I am right now in the situation to plan the internationalization of a django project that contains mainly legacy code. The old project itself has different applications which have a strong dependency to each other, so it is hard to separate them. Looking... | Dealing with legacy django project in new localized projects | I am right now in the situation to plan the internationalization of a django project that contains mainly legacy code. The old project itself has different applications which have a strong dependency to each other, so it is hard to separate them. Looking at the time left it is impossible at all.
The main requirements f... | [
"Start by decoupling the components where possible, and convert the legacy code to (portable) apps if not the case already, and the legacy code should not live under the main project tree.\nAny new features should be well documented and decoupled apps or generic libraries themselves, even if they override/interact/... | [
1
] | [] | [] | [
"dependency_management",
"django",
"legacy_code",
"modularity",
"python"
] | stackoverflow_0006547863_dependency_management_django_legacy_code_modularity_python.txt |
Q:
Python oop question
How do I call method .get_item(Example1()).do_something() in class Base from inside the class Example2?
class Base:
items = []
def add_item(self, item):
self.items.append(item)
def get_item(self, item):
return self.items[0]
class Item:
pass
class Example1(It... | Python oop question | How do I call method .get_item(Example1()).do_something() in class Base from inside the class Example2?
class Base:
items = []
def add_item(self, item):
self.items.append(item)
def get_item(self, item):
return self.items[0]
class Item:
pass
class Example1(Item):
def do_somethin... | [
"If you want such functionality, you need to pass Base to Example2 guy:\nclass Example2(Item):\n\n def __init__(self, base):\n self.base = base\n self.base.get_item(Example1()).do_something()\n\n # or if don't want to store base, and just call its method once:\n base.get_item(Exam... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007359325_python.txt |
Q:
Automating Flash Program with Python using Pywinauto
I am trying to send a couple basic text commands to a flash program running in Firefox on Windows 7, but I am unable to get pywinauto working for me.
Right now, I have just been able to accomplish the very basic task of connecting to Firefox plugin-container by... | Automating Flash Program with Python using Pywinauto | I am trying to send a couple basic text commands to a flash program running in Firefox on Windows 7, but I am unable to get pywinauto working for me.
Right now, I have just been able to accomplish the very basic task of connecting to Firefox plugin-container by directing it to the path using the following code:
from p... | [
"As the author of pywinauto - I think you are going to have a hard time. pywinauto only really helps with standard windows controls, and I don't think that flash controls are implemented as standard windows controls (Buttons, Edit boxes, etc).\nOFf the top of my head - I would think Sikuli may be a better starting ... | [
4
] | [] | [] | [
"firefox",
"flash",
"python",
"pywinauto"
] | stackoverflow_0007356197_firefox_flash_python_pywinauto.txt |
Q:
How to update TreeModel after moving subtree
I have a custom GenericTreeModel, that works just fine. Now I want the user to be able to rearrange the nodes using drag and drop, so I move a node to its new parent in the data model.
However then, the TreeModel wants to be notified using methods like row_has_child_tog... | How to update TreeModel after moving subtree | I have a custom GenericTreeModel, that works just fine. Now I want the user to be able to rearrange the nodes using drag and drop, so I move a node to its new parent in the data model.
However then, the TreeModel wants to be notified using methods like row_has_child_toggled, row_deleted and row_inserted.
So apparently ... | [
"Figured it out: Removing a subtree works fine by removing the subtree’s root node row (notify the model that the path is gone and conditionally toggling parent.has_child). Same goes for insertion of a new subtree, so I don't need to tell the model stuff recursively.\nHowever the combination is critical, so \n\nfir... | [
2,
1
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0007316505_gtktreeview_pygtk_python.txt |
Q:
how to adjust/stretch image size on form resize pyqt4 python
i have a qlabel with an image, it is inside a QGridLayout.
when the form re-sizes the QGridlayout automatically resize but the qlabel with image does not stretch.
A:
Have you tried setting scaledContents property to True?
| how to adjust/stretch image size on form resize pyqt4 python | i have a qlabel with an image, it is inside a QGridLayout.
when the form re-sizes the QGridlayout automatically resize but the qlabel with image does not stretch.
| [
"Have you tried setting scaledContents property to True?\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python",
"qlabel"
] | stackoverflow_0007359326_pyqt4_python_qlabel.txt |
Q:
ImportError: Bad magic number, since OSX Lion
I'm getting this error every time I run any python file in Eclipse using PyDev:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/site.py", line 73, in <module>
__boot()
File "/System/Library/Framewo... | ImportError: Bad magic number, since OSX Lion | I'm getting this error every time I run any python file in Eclipse using PyDev:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/site.py", line 73, in <module>
__boot()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python... | [
"Upgrading Python to 2.7.1, running \"Update Shell Profile\" command file which is located in Python directory and changing the Python settings in Netbeans according to new installation worked for me. \n",
"Yeah, you'll need to regenerate all your *.pyc and *.pyo files from the *.py files.\nHow you do this depend... | [
2,
1,
0
] | [] | [] | [
"magic_numbers",
"osx_lion",
"pyc",
"python"
] | stackoverflow_0007140329_magic_numbers_osx_lion_pyc_python.txt |
Q:
Python loop with int iterator
I seem to recall there is a built-in way of doing this:
i = 0
for value in values:
# ...Stuff
i += 1
but in a neater syntax; something like
for value, i in fn(values):
# ...Stuff
Is my memory correct; and if so, what is the way of doing this?
A:
for i, value in enumera... | Python loop with int iterator | I seem to recall there is a built-in way of doing this:
i = 0
for value in values:
# ...Stuff
i += 1
but in a neater syntax; something like
for value, i in fn(values):
# ...Stuff
Is my memory correct; and if so, what is the way of doing this?
| [
"for i, value in enumerate(values):\n\n"
] | [
13
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0007360633_loops_python.txt |
Q:
Python/Tkinter: Apply .attributes() method to Frame vs. Window?
Does Tkinter or underlying Tk framework support the ability to apply the equivalent of the attributes() method to Frames vs. Windows?
Specifically: I have forms with a message area that I would like to fade away in jquery-like manner, eg. display a no... | Python/Tkinter: Apply .attributes() method to Frame vs. Window? | Does Tkinter or underlying Tk framework support the ability to apply the equivalent of the attributes() method to Frames vs. Windows?
Specifically: I have forms with a message area that I would like to fade away in jquery-like manner, eg. display a non-modal status message that fades away. I know I can fade a Tkinter w... | [
"No, there is no way to do what you want. Tkinter only supports transparency on top-level windows. \n"
] | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004164962_python_tkinter_user_interface.txt |
Q:
reversing dictionary in python
Possible Duplicate:
Python reverse / inverse a mapping
Swap keys for unique values in a dictionary in Python
Hello i want to understand how to reverse and compare dictionary values: for example :
if i have one dictionary with key:value format like this
dicta = [1:2, 9:8, 4:6,... | reversing dictionary in python |
Possible Duplicate:
Python reverse / inverse a mapping
Swap keys for unique values in a dictionary in Python
Hello i want to understand how to reverse and compare dictionary values: for example :
if i have one dictionary with key:value format like this
dicta = [1:2, 9:8, 4:6, 3:2, 0:7, 1:34, 9:90, 1:8, 67:43, ... | [
"dictb = dict ( (v,k) for k, v in dicta.items() )\n\n",
"The syntax for dictionaries is the following:\ndicta = {1:2, 9:8}\n\nThis will do the conversion:\ndictb = {}\nfor k in dicta:\n dictb[dicta[k]] = k\n\n",
"Try this:\ndicatb = {}\nfor x,k in dicta.iteritems():\n dictab[k] = x\n\n",
"\nConvert dict t... | [
10,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007360757_python.txt |
Q:
PIL will not import the _imaging C module: "*** The _imaging C module is not installed"
A bit of background from the PIL setup.py build:
--------------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
--------------------------------------------------------------------
version 1.... | PIL will not import the _imaging C module: "*** The _imaging C module is not installed" | A bit of background from the PIL setup.py build:
--------------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
--------------------------------------------------------------------
version 1.1.7
platform linux2 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.... | [
"It seems that before I installed PIL, I didn't have libjpeg installed. I therefore installed libjpeg-62 and libjpeg62-dev, then reinstalled PIL. The same error occurred\n*** The _imaging C module is not installed\n\nI found a potential solution on another website suggesting that I force rebuild PIL from source:\... | [
5,
2,
0
] | [] | [] | [
"django",
"imaging",
"python",
"python_imaging_library",
"ubuntu"
] | stackoverflow_0004113095_django_imaging_python_python_imaging_library_ubuntu.txt |
Q:
Cherrypy: Can't get my POST data
I write a tiny webapp with CherryPy. But I has a problem - I can't get my POST data, but GET is ok. Hosted on local host (Win 7), viewed with Opera 10, using CherryPy built-in server.
Here is some code:
class Expose:
def __init__(self, fn):
self.fn = fn
@cherrypy.expose()
def ... | Cherrypy: Can't get my POST data | I write a tiny webapp with CherryPy. But I has a problem - I can't get my POST data, but GET is ok. Hosted on local host (Win 7), viewed with Opera 10, using CherryPy built-in server.
Here is some code:
class Expose:
def __init__(self, fn):
self.fn = fn
@cherrypy.expose()
def index(self, login=None):
print 'LO... | [
"Try with: \n<!DOCTYPE html>\n\n<body>\n<p>Create new user</p>\n\n<form action=\"/process_form/\" method=\"post\">\n <input type=\"text\" name=\"login\" value=\"login\" />\n <input type=\"text\" name=\"email\" value=\"me@company.com\" />\n <input type=\"text\" name=\"password\" value=\"123\" />\n <input type=\"... | [
6
] | [
"I don't know if root.processform is something special in CherryPy, if not you need to expose a process_form page \n@cherrypy.expose()\ndef process_form(self, email, login,password):\n ...stuff...\n\nI may be missing something\n"
] | [
-1
] | [
"cherrypy",
"get",
"post",
"python"
] | stackoverflow_0005780542_cherrypy_get_post_python.txt |
Q:
adding to StringListProperty
i have the following
class Image(db.Model):
author = db.UserProperty()
img = db.BlobProperty()
rating = db.RatingProperty()
tags = db.ListProperty()
when the user upload an image , he will enter a list of tags by is choose sperating by comma
so how can I store them i... | adding to StringListProperty | i have the following
class Image(db.Model):
author = db.UserProperty()
img = db.BlobProperty()
rating = db.RatingProperty()
tags = db.ListProperty()
when the user upload an image , he will enter a list of tags by is choose sperating by comma
so how can I store them in the database using the StringLis... | [
"I think you just need to split the string.\nAn example:\ntags = self.request.get('tags').split(',')\nimg_ref.tags.extend(tags)\nimg_ref.put()\n\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"tagging",
"tags"
] | stackoverflow_0007360257_google_app_engine_python_tagging_tags.txt |
Q:
Callback function is not executed with ondestroy
I'm developing an application using python gtk+ and glade. My glade file format is gtk-builder. I've two windows in it - one main window and one login window. Inside __ init __ () I run the login dialog window, so that I can make sure the focus will not be switched ... | Callback function is not executed with ondestroy | I'm developing an application using python gtk+ and glade. My glade file format is gtk-builder. I've two windows in it - one main window and one login window. Inside __ init __ () I run the login dialog window, so that I can make sure the focus will not be switched to the main window until the user emits OK signal from... | [
"It looks like you have a reentry issue. Probably you are running the main window from the onClick of the \"ok\" button in the login dialog. \nMaybe you are calling gtk.main() several times?\nIt is difficult to guess, since your code is not complete.\n"
] | [
0
] | [] | [] | [
"glade",
"gtk",
"python"
] | stackoverflow_0007361334_glade_gtk_python.txt |
Q:
I'm trying to write a general function for adding/multiplying terms in a sequence
I'm trying to write a function with 4 arguments in python
def sequence(operation, start, n, term):
where operation is a function, start is the beginning number of the sequence, and n is th last number of the sequence, term is functi... | I'm trying to write a general function for adding/multiplying terms in a sequence | I'm trying to write a function with 4 arguments in python
def sequence(operation, start, n, term):
where operation is a function, start is the beginning number of the sequence, and n is th last number of the sequence, term is function that manipulates the terms in the sequence.
For example
>>> sequence(add, 2, 10, squ... | [
"reduce(lambda a,b: a+b, map(square, range(2,11)))\n\n",
"def sequence(operation, start, n, term):\n return reduce(operation, map(term, range(start, n+1)))\n\nThe range function in Python is half-open ie. range(start, stop) returns a list of integers from start to stop-1. So, for example:\n>>> range(2,10)\n[2,... | [
2,
1,
0,
0
] | [] | [] | [
"higher_order_functions",
"python",
"sequence"
] | stackoverflow_0007360390_higher_order_functions_python_sequence.txt |
Q:
How to make pycharm break on My Exceptions
Possible Duplicate:
break on unhandled exception in pycharm
I'm new in Python and I'm trying to debug my first python program using PyCharm 1.5.
I want debugger to break when exception occurs in my code (and only in mine).
For now the situation is following: I use (Ct... | How to make pycharm break on My Exceptions |
Possible Duplicate:
break on unhandled exception in pycharm
I'm new in Python and I'm trying to debug my first python program using PyCharm 1.5.
I want debugger to break when exception occurs in my code (and only in mine).
For now the situation is following: I use (Ctrl + Shift + F8 ) Dialog to configure debugger ... | [
"One way to tell apart your exceptions from exceptions coming from a library, is to have them derive from a custom class, e.g. if your module is called Foo, you could have\nclass FooException(Exception):\n pass\n\nand have more specific exceptions derive from this:\nclass MyMathException(FooException):\n # etc.... | [
3
] | [] | [] | [
"debugging",
"pycharm",
"python"
] | stackoverflow_0006643168_debugging_pycharm_python.txt |
Q:
Python: asserting that I'm running on POSIX?
I'm writing some POSIX-specific code, and although I'm not supporting other platforms I'd like to make sure they get a nice clear error at import time rather than strange errors, if they tried to use my code.
Is there a neat way to check that? I guess I could to an imp... | Python: asserting that I'm running on POSIX? | I'm writing some POSIX-specific code, and although I'm not supporting other platforms I'd like to make sure they get a nice clear error at import time rather than strange errors, if they tried to use my code.
Is there a neat way to check that? I guess I could to an import posix and catch the ImportError but that seems... | [
"Take a look at os.name:\n\nThe name of the operating system dependent module imported. The\n following names have currently been registered: 'posix', 'nt', 'os2',\n 'ce', 'java', 'riscos'.\n\nThere are also sys.platform and os.uname() if you require finer granularity.\n",
"you can: \ndef is_posix():\n try:\... | [
12,
3,
0
] | [] | [] | [
"posix",
"python"
] | stackoverflow_0007362225_posix_python.txt |
Q:
Overriding class function with instance function in python
Consider this example:
class master:
@classmethod
def foo(cls):
cls.bar()
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( ... | Overriding class function with instance function in python | Consider this example:
class master:
@classmethod
def foo(cls):
cls.bar()
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( master ):
#def foo(self):
# self.foo()
def __init... | [
"Look closer at the doc for classmethod. Instance methods pass an instance as the first argument, and class methods pass a class as the first argument. Calling slaveType.foo() passes an instance, slaveType, as the first argument of foo(). foo() is expecting a class as the first argument.\n"
] | [
0
] | [] | [] | [
"class_method",
"instance",
"oop",
"python"
] | stackoverflow_0007362161_class_method_instance_oop_python.txt |
Q:
How to count the number of words in a paragraph and exclude some words (from a file)?
I've just started to learn Python so my question might be a bit silly. I'm trying to create a program that would:
- import a text file (got it)
- count the total number of words (got it),
- count the number of words in a specif... | How to count the number of words in a paragraph and exclude some words (from a file)? | I've just started to learn Python so my question might be a bit silly. I'm trying to create a program that would:
- import a text file (got it)
- count the total number of words (got it),
- count the number of words in a specific paragraph, starting with a specific phrase (e.g. "P1", ending with another participant "... | [
"You shouldn't call open ('zery.txt', 'r') with identifier text. It is not the text in the file, it is the handler of the file, described as a \"file-like object\" in the docs (I never understood what it means, \"file-like object\", by the way)\n.\nwith open ('C:/data.txt', 'r') as f:\n ........\n ........\n... | [
2,
2,
2
] | [] | [] | [
"count",
"python",
"text_mining"
] | stackoverflow_0007359510_count_python_text_mining.txt |
Q:
Product of first n terms in a sequence in python
I'm trying to create a function that takes one argument (a number) and returns the factorial of that number.
For example f(5) will return 1*2*3*4*5
What I have so far is
def product(n, term):
"""Return the product of the first n terms in a sequence.
term --... | Product of first n terms in a sequence in python | I'm trying to create a function that takes one argument (a number) and returns the factorial of that number.
For example f(5) will return 1*2*3*4*5
What I have so far is
def product(n, term):
"""Return the product of the first n terms in a sequence.
term -- a function that takes one argument
"""
k, tot... | [
"import math\n\ndef factorial(n):\n return math.factorial(n)\n\nAlternative implementation:\ndef factorial(n):\n return reduce(lambda x,y:x*y,range(1,n+1))\n\nUsing recursion:\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\n",
"Computing the factoria... | [
1,
1,
1,
0
] | [] | [] | [
"higher_order_functions",
"python",
"sequence"
] | stackoverflow_0007361078_higher_order_functions_python_sequence.txt |
Q:
How to handle popovers using Selenium Webdriver + Python
Here is the situation -
On the website that I am testing, the page source changes dynamically i.e. when I move my mouse over an element I see a popover and it has DOM structure and all. I want to capture the DOM elements in the popover.
I am using webdriver... | How to handle popovers using Selenium Webdriver + Python | Here is the situation -
On the website that I am testing, the page source changes dynamically i.e. when I move my mouse over an element I see a popover and it has DOM structure and all. I want to capture the DOM elements in the popover.
I am using webdriver with python. It works well when I use IDLE because the popove... | [
"Use Actions to hover the mouse over the element. The straight-forward approach is something like this (sorry the code is in C#):\nIWebElement element = driver.FindElement(By.Id(\"something\")); \nActions action = new Actions(driver); \nactions.MoveToElement(element);\nactions.Perform();\n\n//get the DOM structure\... | [
0
] | [] | [] | [
"browser_automation",
"python",
"selenium",
"webdriver"
] | stackoverflow_0007359586_browser_automation_python_selenium_webdriver.txt |
Q:
php system, python and utf-8
I have a python program running very well. It connects to several websites and outputs the desired information. Since not all websites are encoded with utf-8, I am requesting the charset from the headers and using unicode(string, encoding) method to decode (I am not sure whether its th... | php system, python and utf-8 | I have a python program running very well. It connects to several websites and outputs the desired information. Since not all websites are encoded with utf-8, I am requesting the charset from the headers and using unicode(string, encoding) method to decode (I am not sure whether its the appropriate way to do this but i... | [
"From the PrintFails wiki:\n\nWhen Python finds its output attached to a terminal, it sets the\n sys.stdout.encoding attribute to the terminal's encoding. The print\n statement's handler will automatically encode unicode arguments into\n str output.\n\nThis is why your program works when called from the terminal... | [
4,
2
] | [] | [] | [
"decoding",
"encoding",
"php",
"python",
"system"
] | stackoverflow_0007362576_decoding_encoding_php_python_system.txt |
Q:
how to use numpy.gradient working for left and right differences?
how to use numpy.gradient working for left and right. It works by default for central difference.
Thanks a lot.
A:
Replace:
slice1[axis] = slice(1, -1)
slice2[axis] = slice(2, None)
slice3[axis] = slice(None, -2)
# 1D equivalent --... | how to use numpy.gradient working for left and right differences? | how to use numpy.gradient working for left and right. It works by default for central difference.
Thanks a lot.
| [
"Replace:\n slice1[axis] = slice(1, -1)\n slice2[axis] = slice(2, None)\n slice3[axis] = slice(None, -2)\n # 1D equivalent -- out[1:-1] = (f[2:] - f[:-2])/2.0\n\nBy:\n slice1[axis] = slice(1, -1)\n slice2[axis] = slice(1, -1)\n slice3[axis] = slice(None, -2)\n # 1D equivalent -- out[1:-1] = ... | [
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0007360465_numpy_python.txt |
Q:
PySVN error: URL doesn't exist
I got a SVN repository copied onto my computer using svnsync. Now when I try to replay it using PySVN it fails at a specific revision (29762) with the message:
pysvn._pysvn_2_6.ClientError: URL 'svn://svn.zope.org/repos/main/ZODB/trunk/src/Persistence' doesn't exist
I can checkout ... | PySVN error: URL doesn't exist | I got a SVN repository copied onto my computer using svnsync. Now when I try to replay it using PySVN it fails at a specific revision (29762) with the message:
pysvn._pysvn_2_6.ClientError: URL 'svn://svn.zope.org/repos/main/ZODB/trunk/src/Persistence' doesn't exist
I can checkout or update until the previous revisio... | [
"Although the error message doesn't hint to that, I believe it was caused by running out of disk space. After deleting other files on the drive and re-running the script it worked fine.\n",
"try:\n client.update(path,revision=pysvn.Revision(pysvn.opt_revision_kind.number,RevNumber),ignore_externals=False)\nexc... | [
0,
0
] | [] | [] | [
"pysvn",
"python",
"svn"
] | stackoverflow_0002241754_pysvn_python_svn.txt |
Q:
splitting a string into a list of 2char strings
I have a hex stream like: 1a2b3c4d5e6f7g but longer
I want to split it into 2char hex values in a list, and then convert them to ascii.
A:
What about binascii.unhexlify(hexstr)?
See the docs for the binascii module : http://docs.python.org/library/binascii.html
A... | splitting a string into a list of 2char strings | I have a hex stream like: 1a2b3c4d5e6f7g but longer
I want to split it into 2char hex values in a list, and then convert them to ascii.
| [
"What about binascii.unhexlify(hexstr)?\nSee the docs for the binascii module : http://docs.python.org/library/binascii.html \n",
"In Python 2.x you can use binascii.unhexlify:\n>>> import binascii\n>>> binascii.unhexlify('abcdef0123456789')\n'\\xab\\xcd\\xef\\x01#Eg\\x89'\n\nIn Python 3 there's a more elegant me... | [
5,
3,
2
] | [] | [] | [
"ascii",
"hex",
"python"
] | stackoverflow_0007362885_ascii_hex_python.txt |
Q:
How to find indices of non zero elements in large sparse matrix?
i have two sq matrix (a, b) of size in order of 100000 X 100000. I have to take difference of these two matrix (c = a-b). Resultant matrix 'c' is a sparse matrix. I want to find the indices of all non-zero elements. I have to do this operation many t... | How to find indices of non zero elements in large sparse matrix? | i have two sq matrix (a, b) of size in order of 100000 X 100000. I have to take difference of these two matrix (c = a-b). Resultant matrix 'c' is a sparse matrix. I want to find the indices of all non-zero elements. I have to do this operation many times (>100).
Simplest way is to use two for loops. But that's computat... | [
"Since you have two dense matrices then the double for loop is the only option you have. You don't need a sparse matrix class at all since you only want to know the list of indices (i,j) for which a[i,j] != b[i,j].\nIn languages like R and Python the double for loop will perform poorly. I'd probably write this in n... | [
4,
3,
2,
1,
1,
1
] | [] | [] | [
"algorithm",
"indices",
"python",
"r",
"sparse_matrix"
] | stackoverflow_0007361447_algorithm_indices_python_r_sparse_matrix.txt |
Q:
How to catch the SMTPRecipientsRefused exception (using a remote SMTP server and django)?
I'm trying to understand how this works.
When I normally send and email and the recipient doesn't exist, or some other error occurs, an email is send back containing the info about the error and the status. This can take some... | How to catch the SMTPRecipientsRefused exception (using a remote SMTP server and django)? | I'm trying to understand how this works.
When I normally send and email and the recipient doesn't exist, or some other error occurs, an email is send back containing the info about the error and the status. This can take some time. My question here is how can smtplib catch this error if this response take time?
When I ... | [
"Yeah, unfortunately SMTP VRFY has been disabled on most servers for many years, precicesly because this can be used by spammers to quickly search a server for valid emails. You'll have to do it by hand or scrape emails. python-imap will help you here. Good luck!\n",
"\nYes this is why you don't get the Exception... | [
0,
0
] | [] | [] | [
"django",
"python",
"smtp"
] | stackoverflow_0007362522_django_python_smtp.txt |
Q:
HTTP referer issue
I have this view rendering a static page, but I cannot seem to catch the referer of the page.
def landing(request, referer='google'):
''' Loads the landing page '''
msg = ''
if request.method == 'GET':
referer = request.META['HTTP_REFERER']
return render_to_response... | HTTP referer issue | I have this view rendering a static page, but I cannot seem to catch the referer of the page.
def landing(request, referer='google'):
''' Loads the landing page '''
msg = ''
if request.method == 'GET':
referer = request.META['HTTP_REFERER']
return render_to_response('index.html',
... | [
"You should be using request.META.get('HTTP_REFERER'). Not every request will have a Referer header, and if one doesn't you will get exactly this exception. Test if the result of get() is not None to see if the header was sent.\n",
"Make this change to fix the key error:\nreferer = request.META.get('HTTP_REFERE... | [
9,
4
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0007364054_django_http_python.txt |
Q:
How to explicitly stop a Google App Engine dynamic backend when the start handler finishes?
I have a backend that consumes a queue in its start handler. When the queue is exhausted the start handler will stop. I want the backend to stop when the start handler finishes. I have other code that will send a request... | How to explicitly stop a Google App Engine dynamic backend when the start handler finishes? | I have a backend that consumes a queue in its start handler. When the queue is exhausted the start handler will stop. I want the backend to stop when the start handler finishes. I have other code that will send a request to the backend if it adds an item to this queue. These requests merely serve to have GAE start ... | [
"Backends can't (currently) be started and stopped programmatically. It sounds like what you want, though, is a regular task queue task, which behaves exactly as described.\n",
"If you configure your backend as a Dynamic backend, then the backend will stop automatically 15 minutes after your \"trigger\" request i... | [
1,
0
] | [] | [] | [
"backend",
"google_app_engine",
"python"
] | stackoverflow_0006945595_backend_google_app_engine_python.txt |
Q:
Understanding the output of cvFilter2d
I have convolved a filter with an image using cvFilter2D. I am using python 2.6 and OpenCV 2.0. The filter is a second spatial derivative similar to the Laplacian. (I would use the Laplacian if the output fit my needs, I want the directional derivatives reported separately). ... | Understanding the output of cvFilter2d | I have convolved a filter with an image using cvFilter2D. I am using python 2.6 and OpenCV 2.0. The filter is a second spatial derivative similar to the Laplacian. (I would use the Laplacian if the output fit my needs, I want the directional derivatives reported separately). My question is about interpreting the output... | [
"There is a \"delta\" parameter you can pass to the function to offset the result if you are writing to an unsigned output image type \nvoid filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1, -1), double delta=0, int borderType=BORDER_DEFAULT)\n\n"
] | [
0
] | [] | [] | [
"filtering",
"opencv",
"python"
] | stackoverflow_0007363445_filtering_opencv_python.txt |
Q:
python ftp retrieve lines -- performance issues
I am trying to retrieve lines from a file through a FTP connection using the ftplib module of python. It takes about 10 mins to read a file of size 1 GB. I was wondering if there are any other ways to read the lines in a faster manner.
I should have included some cod... | python ftp retrieve lines -- performance issues | I am trying to retrieve lines from a file through a FTP connection using the ftplib module of python. It takes about 10 mins to read a file of size 1 GB. I was wondering if there are any other ways to read the lines in a faster manner.
I should have included some code to show what I am doing:
ftp.HostName = 'xxx'
ftp.U... | [
"Retrieving remote resources is usually bound by your bandwidth, and FTP protocol does a decent job of using it all.\nAre you sure you aren't saturating your network connection? (what is the network link between client running ftplib and server you are downloading from?)\nBack of the envelope calc:\n1GB/10mins =~ ... | [
1,
0
] | [] | [] | [
"ftp",
"performance",
"python"
] | stackoverflow_0007364217_ftp_performance_python.txt |
Q:
Graphing the number of elements down based on timestamps start/end
I am trying to graph alarm counts in Python to give some sort of display to give an idea of the peak amount of network elements down between two timespans. The way that our alarms report handles it is in CSV like this:
Name,Alarm Start,Alarm Clear
... | Graphing the number of elements down based on timestamps start/end | I am trying to graph alarm counts in Python to give some sort of display to give an idea of the peak amount of network elements down between two timespans. The way that our alarms report handles it is in CSV like this:
Name,Alarm Start,Alarm Clear
NE1,15:42 08/09/11,15:56 08/09/11
NE2,15:42 08/09/11,15:57 08/09/11
NE3,... | [
"I'd start by parsing your indata to a map indexed by dates with counts as values. Just increase the count for each row with the same date you encounter.\nAfter that, use some plotting module, for instance matplotlib to plot the keys of the map versus the values. That should cover it! \nDo you need any more detaile... | [
1
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0007363997_graph_python.txt |
Q:
How do I keep a python HTTP Server up forever?
I wrote a simple HTTP server in python to manage a database hosted on a server via a web UI. It is perfectly functional and works as intended. However it has one huge problem, it won't stay put. It will work for an hour or so, but if left unused for long periods of ti... | How do I keep a python HTTP Server up forever? | I wrote a simple HTTP server in python to manage a database hosted on a server via a web UI. It is perfectly functional and works as intended. However it has one huge problem, it won't stay put. It will work for an hour or so, but if left unused for long periods of time when returning to use it I have to re-initialize ... | [
"You can write a UNIX daemon in Python using the python-daemon package, or a Windows service using the pywin32.\nUnfortunately, I know of no \"portable\" solution to writing daemon / service processes (in Python, or otherwise).\n",
"Here's one piece of advice in a story about driving. You certainly want to drive ... | [
4,
3,
1,
1,
1
] | [] | [] | [
"http",
"python",
"shutdown"
] | stackoverflow_0007363936_http_python_shutdown.txt |
Q:
Method to Find Out When Users Cancelled Using Dictionaries
I have created a dictionary of either {'username': 'date'} or {'date': 'username'} (I can change the order of the key: value pair to whichever I want). To set the values I need to say...
{'Jacob Rasnip': 'Apr', 'Andrew Alexander': 'Apr', 'Jacob Rasnip': 'M... | Method to Find Out When Users Cancelled Using Dictionaries | I have created a dictionary of either {'username': 'date'} or {'date': 'username'} (I can change the order of the key: value pair to whichever I want). To set the values I need to say...
{'Jacob Rasnip': 'Apr', 'Andrew Alexander': 'Apr', 'Jacob Rasnip': 'May'}
or the opposite...
{'Apr': 'Jacob Rasnip'}
I have about 1... | [
"A dictionary cannot have duplicate keys. For example, it can only have one key 'Jacob Rasnip'. Your example shows two.\nSimilarly, a dictionary could only have one key 'Apr'. \nIf instead you had dictonary of usernames mapping to a list of datetime.dates:\n{'Jacob Rasnip': [datetime.date(2011,4,1),datetime.date(20... | [
4,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007364675_dictionary_python.txt |
Q:
Loading a python dictionary with variables
How do i load a text file full of 10 digit codes separated by a return into a dictionary in python?
Then how do i cross check the variables in the dictionary with my own variables?
Ok, it is simple really. I have a TXT file containing 1000 or so 10 digit sequences looks... | Loading a python dictionary with variables | How do i load a text file full of 10 digit codes separated by a return into a dictionary in python?
Then how do i cross check the variables in the dictionary with my own variables?
Ok, it is simple really. I have a TXT file containing 1000 or so 10 digit sequences looks like this:
121001000
000000000
121212121
I need... | [
"It sounds like you want to store the numbers in a way that makes it easy to look up \"Is this other value already there?\", but you don't actually have \"values\" to associate with these \"keys\" - so you don't really want a dict (associative array), but rather a set.\nPython file objects are iterable, and iterati... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007034369_dictionary_python.txt |
Q:
Why does the Google App Engine warn me 'file referenced by handler not found : dailybasic.py' again and again?
I'm coding with the GAE in python, and I tried to make two script files. So I make the app.yaml like this:
application: mathgirlna
version: 1
runtime: python
api_version: 1
handlers:
- url: /static
sta... | Why does the Google App Engine warn me 'file referenced by handler not found : dailybasic.py' again and again? | I'm coding with the GAE in python, and I tried to make two script files. So I make the app.yaml like this:
application: mathgirlna
version: 1
runtime: python
api_version: 1
handlers:
- url: /static
static_dir: static
- url: /dailybasic/.*
script: /dailybasic.py
login: admin
- url: /.*
script: main.py
And wh... | [
"Remove the '/' in script: /dailybasic.py.\n- url: /dailybasic/.*\n script: dailybasic.py\n login: admin\n\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python",
"yaml"
] | stackoverflow_0007365084_google_app_engine_python_yaml.txt |
Q:
Encoding issue between Django and client
I'm trying to send latin characters (é, è...) to the client side using Django, and I can't get it to work. In Django I tried to write directly latin characters in my python files, but I had errors. I then used unicode (writing 'Soci\u00E9t\u00E9' for 'Société'), but when se... | Encoding issue between Django and client | I'm trying to send latin characters (é, è...) to the client side using Django, and I can't get it to work. In Django I tried to write directly latin characters in my python files, but I had errors. I then used unicode (writing 'Soci\u00E9t\u00E9' for 'Société'), but when sending it to the client side I get the raw unic... | [
"I would generally refrain from putting any non-ascii encoded characters in source code.\nDespite the fact that the python interpreter will honor a source file with the UTF-8 header, the problem is that dumb (meaning non UTF-8 aware) text editors, shells, OSes and some developers :), will eventually corrupt your ca... | [
1,
0
] | [] | [] | [
"character_encoding",
"django",
"python"
] | stackoverflow_0007365035_character_encoding_django_python.txt |
Q:
Run commands sequential from Python
I'm trying to build a LaTeX document using Python but am having problems getting the commands to run in sequence. For those familiar with LaTeX, you'll know that you usually have to run four commands, each completing before running the next, e.g.
pdflatex file
bibtex file
pdfla... | Run commands sequential from Python | I'm trying to build a LaTeX document using Python but am having problems getting the commands to run in sequence. For those familiar with LaTeX, you'll know that you usually have to run four commands, each completing before running the next, e.g.
pdflatex file
bibtex file
pdflatex file
pdflatex file
In Python, I'm th... | [
"os.system shouldn't cause this, but subprocess.Popen should.\nBut I think using subprocess.call is the best choice:\ncommands = ['pdflatex','bibtex','pdflatex','pdflatex']\n\nfor command in commands:\n subprocess.call((command, src_file)) \n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007365319_python.txt |
Q:
Python argpase: Handling unknown amount of parameters/options/etc
in my script I try to wrap the bazaar executable. When I read certain options meant for bzr my script will react on that. In any case all arguments are then given to the bzr executable. Of course I don't want to specify all arguments that bzr can ha... | Python argpase: Handling unknown amount of parameters/options/etc | in my script I try to wrap the bazaar executable. When I read certain options meant for bzr my script will react on that. In any case all arguments are then given to the bzr executable. Of course I don't want to specify all arguments that bzr can handle inside
my script.
So, is there a way to handle an unknown amount o... | [
"The simple answer to this question is the usage of the argparse.ArgumentParser.parse_known_args method. This will parse the arguments that your wrapping script knowns about and ignore the others.\nHere is something I typed up based on the code that you supplied.\n# -*- coding: utf-8 -*-\nimport argparse\n\ndef mai... | [
3
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0004966762_argparse_python.txt |
Q:
Python - Steam User Status
I've been looking for a method to get a steam users status. This includes things like the game they're playing, if they're online or if they're offline. I was originally going to scrape the page, but I figured there must be an easier way to do it.
I looked around for pages which might be... | Python - Steam User Status | I've been looking for a method to get a steam users status. This includes things like the game they're playing, if they're online or if they're offline. I was originally going to scrape the page, but I figured there must be an easier way to do it.
I looked around for pages which might be json of the users current statu... | [
"Start with the Steam Web API. I think you are looking to work with GetPlayerSummaries.\n",
"Did you see:\nhttp://steamcommunity.com/dev\n\nSteam Web API Documentation\nValve provides these APIs so website developers can use data from\n Steam in new and interesting ways. They allow developers to query\n Steam f... | [
3,
1
] | [] | [] | [
"python",
"steam"
] | stackoverflow_0007365339_python_steam.txt |
Q:
How to query a many to many relationship in Django
I have a list of organizations that full under different organization types. I have a table that holds the name, phone, etc... and then another table that has an id fixed to an organization type. Then a table that holds the many to many relationship because an org... | How to query a many to many relationship in Django | I have a list of organizations that full under different organization types. I have a table that holds the name, phone, etc... and then another table that has an id fixed to an organization type. Then a table that holds the many to many relationship because an organization can have many different organization types.
Wh... | [
"Basically you need to do the following steps:\n\nGet the distinct club types\nFor each club type, select the clubs that include that type (also see this)\nSort the selection from #2 alphabetically\n\nThere are many ways to achieve this, and I would not recommend putting this logic into the template for the simple ... | [
5
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007355178_django_django_models_django_templates_django_views_python.txt |
Q:
Python multiprocess/multithreading use for concurrent file copy operation
I am writing python code to copy bunch of big files/folders from one location to other location on desktop (no network, everything is local). I am using shutil module for that.
But the problem is it takes more time so I want to speed up thi... | Python multiprocess/multithreading use for concurrent file copy operation | I am writing python code to copy bunch of big files/folders from one location to other location on desktop (no network, everything is local). I am using shutil module for that.
But the problem is it takes more time so I want to speed up this copy process. I tried using threading and multiprocessing modules. But to my ... | [
"Your problem is likely IO-bound, so more computational parallelization won't help. As you've seen, you're probably making the problem worse by now requiring the IO requests to jump back and forth between the various threads/processes. There are practical limits to how fast you can move data on a computer, especial... | [
8
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0007365174_multithreading_python.txt |
Q:
Python Calls logging. Getting the base class name
I have a Python source:
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
class base_class:
def base_method(self):
logging.debug(" %s:%s() {" % (self.__class__.__name__, (inspect.stack()[0][3])))
# . . .
loggi... | Python Calls logging. Getting the base class name | I have a Python source:
import inspect
import logging
logging.basicConfig(level=logging.DEBUG)
class base_class:
def base_method(self):
logging.debug(" %s:%s() {" % (self.__class__.__name__, (inspect.stack()[0][3])))
# . . .
logging.debug(" } // %s:%s()" % (self.__class__.__name__, (... | [
"Why you are doing this is discutible, but I think your best bet is to manually specify the classname\nclass base_class(object): \n def base_method(self): \n logging.debug(\" %s:%s() {\" % ( base_class.__name__, (inspect.stack()[0][3])))\n # . . .\n logging.debug(\" } // %s:%s()\" % (base_clas... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007362872_python.txt |
Q:
Detecting if a triangle flips when changing a point
I need to change a triangle by replacing one of its points. However, I need to detect if doing so would cause the triangle to flip.
For example, the triangle defined by the points:
[(1.0,1.0), (2.0,3.0), (3.0,1.0)]
would look like this:
If I change the third po... | Detecting if a triangle flips when changing a point | I need to change a triangle by replacing one of its points. However, I need to detect if doing so would cause the triangle to flip.
For example, the triangle defined by the points:
[(1.0,1.0), (2.0,3.0), (3.0,1.0)]
would look like this:
If I change the third point from (3.0,1.0) to (1.0,2.0), it flips, as shown here:... | [
"Compute the cross-product of two vectors generated from your three points.\nIf the direction of the cross product changes sign, the triangle has flipped.\nFor example:\nGiven [(1.0,1.0), (2.0,3.0), (3.0,1.0)]:\nForm two (3D) vectors\n(2-1,3-1,0) = (1,2,0) and (3-1,1-1,0) = (2,0,0)\nTake their cross product:\n(1,2,... | [
8,
0
] | [] | [] | [
"geometry",
"math",
"python"
] | stackoverflow_0007365531_geometry_math_python.txt |
Q:
Django models INNER JOIN issues
How can I get an inner join between two tables unconditionally?
Having models A,B:
class A(models.Model):
pass
class B(models.Model):
a = models.ForeignKey(A)
When I have a condition I can just write:
A.objects.filter(b__pk=1)
But how do I generate the following query:
S... | Django models INNER JOIN issues | How can I get an inner join between two tables unconditionally?
Having models A,B:
class A(models.Model):
pass
class B(models.Model):
a = models.ForeignKey(A)
When I have a condition I can just write:
A.objects.filter(b__pk=1)
But how do I generate the following query:
SELECT * from A INNER JOIN B ON a.b = ... | [] | [] | [
"for a in A.objects.all():\n for b in a.b_set.all():\n # you have the joined pair a and b\n\nOr\nfor b in B.objects.all():\n for a in b.a.all():\n # you have the joined pair a and b\n\n"
] | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0007365833_django_django_models_python.txt |
Q:
Python: Deleting specific strings from file
I am reposting after changing a few things with my earlier post. thanks to all who gave suggestions earlier. I still have problems with it.
I have a data file (un-structed messy file) from which I have to scrub specific list of strings (delete strings).
Here is what I a... | Python: Deleting specific strings from file | I am reposting after changing a few things with my earlier post. thanks to all who gave suggestions earlier. I still have problems with it.
I have a data file (un-structed messy file) from which I have to scrub specific list of strings (delete strings).
Here is what I am doing but with no result:
infile = r"messy_data... | [
"I'm unable to replicate your error; the error I get with your code is the empty mode string - either put \"r\" or delete it, read is the default.\nTraceback (most recent call last):\n File \"test.py\", line 6, in <module>\n fin = open(infile, \"\")\nValueError: empty mode string\n\nOtherwise, seems fine!\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007365941_python.txt |
Q:
Force `setup.py` to use setuptools
I'm using this code:
code = 'import setuptools;__file__={0!r};execfile(__file__)'.format(os.path.join(path, 'setup.py'))
args = ['install', '--single-version-externally-managed']
subprocess.check_call([sys.executable, '-c', code, args])
To execute a setup.py and install the pack... | Force `setup.py` to use setuptools | I'm using this code:
code = 'import setuptools;__file__={0!r};execfile(__file__)'.format(os.path.join(path, 'setup.py'))
args = ['install', '--single-version-externally-managed']
subprocess.check_call([sys.executable, '-c', code, args])
To execute a setup.py and install the package. The problem occurs when setup.py us... | [
"What you have written is basically what pip does. Based on the code you wrote, you will be using setuptools' setup function because you've imported from setuptools. Setuptools paves over Distutils' setup function in its __init__.py. Therefore, it doesn't mater if the setup.py script imports distutils or not. Setup... | [
2
] | [] | [] | [
"distutils",
"installation",
"python",
"setuptools"
] | stackoverflow_0006089078_distutils_installation_python_setuptools.txt |
Q:
How to refactor Python "switch statement"
I'm refactoring some code that a friend wrote and recently stumbled across this function:
def setup_parameters(self, data):
'''Parse raw data to determine game settings.'''
for line in data.split('\n'):
line = line.strip().lower()
if line:
token... | How to refactor Python "switch statement" | I'm refactoring some code that a friend wrote and recently stumbled across this function:
def setup_parameters(self, data):
'''Parse raw data to determine game settings.'''
for line in data.split('\n'):
line = line.strip().lower()
if line:
tokens = line.split()
self.L.debug("tokens:... | [
"Map the keys to the names of the attributes, and use setattr(self, attribute_name, int(tokens[1]) to set the value. E.g.:\nattribute_dict = dict(cols=\"width\", rows=\"height\", turntime=\"turntime\", ...)\n[...]\nvalue = int(tokens[1])\nif key == \"player_seed\":\n random.seed(value)\nelse:\n setattr(self, ... | [
6,
1,
1
] | [] | [] | [
"python",
"switch_statement"
] | stackoverflow_0007366231_python_switch_statement.txt |
Q:
Python: Mechanize Failing to Send Cookies to Second URL
I'm having serious issues trying to get Mechanize to preserve the cookies set by the first requested URL for when requesting the second URL. In order to test if anything was being sent, I put the following file on my server (cookies.php):
<?php
echo "cookies:... | Python: Mechanize Failing to Send Cookies to Second URL | I'm having serious issues trying to get Mechanize to preserve the cookies set by the first requested URL for when requesting the second URL. In order to test if anything was being sent, I put the following file on my server (cookies.php):
<?php
echo "cookies:::";
print_r($_COOKIE);
?>
The following is the python file ... | [
"request1 and request2 are from different domains. It is understandable that cookies from google.com are not sent to '[domain2].com'.\n"
] | [
3
] | [] | [] | [
"cookies",
"mechanize",
"python"
] | stackoverflow_0007355804_cookies_mechanize_python.txt |
Q:
Setting Data Types with Matplotlib and csv2rec
I'm learning Matplotlib, and trying to implement a simple linear regression by hand.
However, I've run into a problem when importing and then working with my data after using csv2rec.
data= matplotlib.mlab.csv2rec('KC_Filtered01.csv',delimiter=',')
x = data['list_pri... | Setting Data Types with Matplotlib and csv2rec | I'm learning Matplotlib, and trying to implement a simple linear regression by hand.
However, I've run into a problem when importing and then working with my data after using csv2rec.
data= matplotlib.mlab.csv2rec('KC_Filtered01.csv',delimiter=',')
x = data['list_price']
y = data['square_feet']
sumx = x.sum()
sumy = ... | [
"x = data['list_price'].astype('int64')\n\nand the same with y.\nAnd: csv2rec has a converterd argument: http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.csv2rec\n",
"Instead of mlab.csv2rec, you can use an equivalent function of numpy, numpy.loadtxt (documentation), to read your data. This fun... | [
2,
2
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007366302_matplotlib_numpy_python.txt |
Q:
SSLError on Google App Engine (local dev-server)
When I try to use boto library on App Engine, I get the next error:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "E:\Probes\prueba... | SSLError on Google App Engine (local dev-server) | When I try to use boto library on App Engine, I get the next error:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\_webapp25.py", line 701, in __call__
handler.get(*groups)
File "E:\Probes\pruebas\pruebasAWS\main.py", line 26, in get
conn = S3Co... | [
"The actual issue here is that AppEngine mucks around with things to make it impossible to import certain standard, builtin python modules such as ssl.\nThere was some conversation about this on the boto IRC and one of the users came up with this patch:\nhttps://github.com/samba/boto/commit/6f1ab73d92ff6fb2589362bb... | [
2
] | [] | [] | [
"amazon_s3",
"boto",
"google_app_engine",
"python"
] | stackoverflow_0007308202_amazon_s3_boto_google_app_engine_python.txt |
Q:
Python: startswith any alpha character
How can I use the startswith function to match any alpha character [a-zA-Z]. For example I would like to do this:
if line.startswith(ALPHA):
Do Something
A:
If you want to match non-ASCII letters as well, you can use str.isalpha:
if line and line[0].isalpha():
A:
You... | Python: startswith any alpha character | How can I use the startswith function to match any alpha character [a-zA-Z]. For example I would like to do this:
if line.startswith(ALPHA):
Do Something
| [
"If you want to match non-ASCII letters as well, you can use str.isalpha:\nif line and line[0].isalpha():\n\n",
"You can pass a tuple to startswiths() (in Python 2.5+) to match any of its elements:\nimport string\nALPHA = string.ascii_letters\nif line.startswith(tuple(ALPHA)):\n pass\n\nOf course, for this sim... | [
58,
13,
9,
3,
0
] | [
"if you don't care about blanks in front of the string, \nif line and line.lstrip()[0].isalpha(): \n\n"
] | [
-1
] | [
"python",
"startswith"
] | stackoverflow_0002395821_python_startswith.txt |
Q:
Python script won't run
I have some scripts in the folder ~/Scripts which I have added to the path. So I tried to test if I can run them, just by calling them. I have python 3.1 over Linux Mint 11.
user@pc ~/Scripts $ python aek.py
AEK
user@pc ~/Scripts $ aek.py
/home/user/Scripts/aek.py: line 1: syntax error ne... | Python script won't run | I have some scripts in the folder ~/Scripts which I have added to the path. So I tried to test if I can run them, just by calling them. I have python 3.1 over Linux Mint 11.
user@pc ~/Scripts $ python aek.py
AEK
user@pc ~/Scripts $ aek.py
/home/user/Scripts/aek.py: line 1: syntax error near unexpected token `'AEK''
... | [
"You need to add the very first line in your script:\n#!/usr/bin/python\n\nOr whatever interpreter you want to use. If not, the shell (probably bash) will think that it is a shell script and choke.\nIf you want to get the python interpreter from the path, do instead:\n#!/usr/bin/env python\n\nFor extra information,... | [
9,
5
] | [] | [] | [
"python"
] | stackoverflow_0007366568_python.txt |
Q:
Django models 'values()' and LEFT OUTER join
Consider the following models:
class Product(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Provider(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
product = models.ForeignKey(Product)
... | Django models 'values()' and LEFT OUTER join | Consider the following models:
class Product(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Provider(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
product = models.ForeignKey(Product)
class Customer(models.Model):
name = models.C... | [
"you can use a filter after the values like this:\nProduct.objects.values('name', 'provider__name', 'customer__name').filter(provider__name__isnull=False)\n\nI am not 100%sure but give it a try! and lemme know!\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007366049_django_django_models_python.txt |
Q:
Sensible Way to Capture Stdout for Later Replay?
As part of trying to test a legacy function's 'print to stdout' side-effect, I want to capture stdout for later replay. I use mock.
goals (fulfill as many as possible!)
stdout still prints where it normally would, but there is an additional recorder
ideally, thi... | Sensible Way to Capture Stdout for Later Replay? | As part of trying to test a legacy function's 'print to stdout' side-effect, I want to capture stdout for later replay. I use mock.
goals (fulfill as many as possible!)
stdout still prints where it normally would, but there is an additional recorder
ideally, this should be 'patched' or only occur in a context
My i... | [
"You don't even need to save the previous stdout python does it for you and yes use cStringIO\nimport sys\nfrom cStringIO import StringIO\n\nsys.stdout = captured = StringIO()\nprint \"test string\"\n# test stuff\ncaptured = captured.getvalue()\nsys.stdout = sys.__stdout__\nprint \"captured\",captured\n\n",
"You ... | [
2,
0
] | [] | [] | [
"mocking",
"python",
"stdout",
"stream"
] | stackoverflow_0007366419_mocking_python_stdout_stream.txt |
Q:
problem printing mount point of usb in python
I have a program written in python that uses dbus to detect inserted usb drives and prints the dir they are mounted on when they are detected. Here is the code:
import dbus
import gobject
import shutil
import os
import subprocess
import time
class DeviceAddedListene... | problem printing mount point of usb in python | I have a program written in python that uses dbus to detect inserted usb drives and prints the dir they are mounted on when they are detected. Here is the code:
import dbus
import gobject
import shutil
import os
import subprocess
import time
class DeviceAddedListener:
def __init__(self):
self.bus = dbus.Syst... | [
"In your original question it seems likely that you're being beaten by a race condition.\nThe device is inserted and your code is executed before the mounting process has completed.\nTry putting the Popen calls in a while loop (see below).\npath = \"\"\ncount = 0\nwhile count < 10 and path == \"\":\n p1 = subpro... | [
1
] | [] | [] | [
"dbus",
"python",
"subprocess",
"usb"
] | stackoverflow_0004373474_dbus_python_subprocess_usb.txt |
Q:
Stop argparse from globbing filepath
I am using python argparse with the following argument definition:
parser.add_argument('path', nargs=1, help='File path to process')
But when I enter my command with a wildcard argument, argparse globs all the file paths and terminates with an error.
How do I get argparse not ... | Stop argparse from globbing filepath | I am using python argparse with the following argument definition:
parser.add_argument('path', nargs=1, help='File path to process')
But when I enter my command with a wildcard argument, argparse globs all the file paths and terminates with an error.
How do I get argparse not to glob the files?
| [
"The shell is expanding the wildcard argument before argparse gets a chance to see it. Put quotes around the wildcard argument to prevent the shell from expanding it.\nYou could later perform the wildcard expansion with glob.glob.\n",
"\nHow do I get argparse not to glob the files?\n\nYou don't.\nYou get the shel... | [
10,
8,
4
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0007366791_argparse_python.txt |
Q:
match part of a string until it reaches the end of the line (python regex)
If I have a large string with multiple lines and I want to match part of a line only to end of that line, what is the best way to do that?
So, for example I have something like this and I want it to stop matching when it reaches the new lin... | match part of a string until it reaches the end of the line (python regex) | If I have a large string with multiple lines and I want to match part of a line only to end of that line, what is the best way to do that?
So, for example I have something like this and I want it to stop matching when it reaches the new line character.
r"(?P<name>[A-Za-z\s.]+)"
I saw this in a previous answer:
$ - i... | [
"Simply use\nr\"(?P<name>[A-Za-z\\t .]+)\"\n\nThis will match ASCII letters, spaces, tabs or periods. It'll stop at the first character that's not included in the group - and newlines aren't (whereas they are included in \\s, and because of that it's irrelevant whether multiline mode is turned on or off).\n",
"Yo... | [
12,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007366563_python_regex.txt |
Q:
Comparing Lists
I have 8 lists (jan, feb, mar, apr, may, jun, jul, aug) each of which contain names in list format, i.e.
['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba', 'Louis le Roy']
etc.
How do I compare these lists in order, and see when a name appeared (i.e. subscribed) and when a name dis... | Comparing Lists | I have 8 lists (jan, feb, mar, apr, may, jun, jul, aug) each of which contain names in list format, i.e.
['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba', 'Louis le Roy']
etc.
How do I compare these lists in order, and see when a name appeared (i.e. subscribed) and when a name disappeared (i.e. unsubs... | [
"Don't use lists, use a set instead.\nYou could find who (un)subscribed between jan and feb simply using set difference:\nsubs = feb - jan\nunsubs = jan - feb\n\nThat being said, you would be better off following Daenyth's suggestion. Put these in a database, add a joined and left date field and you'll have finer g... | [
6,
1,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007365920_list_python.txt |
Q:
introspective code completion with VIM? ... or other lightweight editor with this feature?
I've been all over the web trying to find a way to get VIM to have code completion similar to PyDev. It doesn't seem like it is possible!
-I have tried to use the omnicompletion suggested at this link: http://blog.dispatc... | introspective code completion with VIM? ... or other lightweight editor with this feature? | I've been all over the web trying to find a way to get VIM to have code completion similar to PyDev. It doesn't seem like it is possible!
-I have tried to use the omnicompletion suggested at this link: http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/ .
-I have tried several addons to alleviate the problem, ... | [
"No, the omni completion functionality is EXACTLY what you are looking for.\nYou are using <C-n> instead of <C-x><C-o>:\n\ntype <C-n> & <C-p> to complete with words from the buffer (after and before the cursor respectively)\ntype <C-x><C-o> to complete method/properties names\n\nIt's specifically explained in the a... | [
7,
4,
1
] | [] | [] | [
"autocomplete",
"code_completion",
"ide",
"python",
"vim"
] | stackoverflow_0007366550_autocomplete_code_completion_ide_python_vim.txt |
Q:
can't execute '.read create.sql'
This might be an obvious error but I'm trying to create a database within python from a script I've already created.
conn = sqlite3.connect('testDB')
c = conn.cursor()
c.execute('.read create.sql')
This gives an error "sqlite3.OperationalError: near ".": syntax error"
If I do the ... | can't execute '.read create.sql' | This might be an obvious error but I'm trying to create a database within python from a script I've already created.
conn = sqlite3.connect('testDB')
c = conn.cursor()
c.execute('.read create.sql')
This gives an error "sqlite3.OperationalError: near ".": syntax error"
If I do the same thing at the sqlite3 cmd line it ... | [
"just pass the content of the file to the .execute method:\nconn = sqlite3.connect('testDB')\nc = conn.cursor()\nSQL = open('create.sql').read()\nc.executescript(SQL)\n\n",
"I would suppose that commands starting with . are for the CLI client itself, not for the backend.\nSo you have no chance to do so and would ... | [
3,
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007365311_python_sqlite.txt |
Q:
Verify Amazon Simple Pay w/Python
I've spent two whole days trying to figure out how to verify return signatures using Amazon's simple pay button. It's not feeling so simple anymore. Isn't there just an Amazon URL that I can make a server-side call to? All I can find are difficult to understand APIs and examples t... | Verify Amazon Simple Pay w/Python | I've spent two whole days trying to figure out how to verify return signatures using Amazon's simple pay button. It's not feeling so simple anymore. Isn't there just an Amazon URL that I can make a server-side call to? All I can find are difficult to understand APIs and examples that never show any URLs. Can anyone hel... | [
"Sorry to zombie this question but I had this same problem, ended up writing my own solution: https://gist.github.com/1206481\n"
] | [
1
] | [] | [] | [
"amazon",
"python"
] | stackoverflow_0004913014_amazon_python.txt |
Q:
Filtering on Foreign Keys in Django
I have a few models in Django where I attach a location to each blog published:
class Country(models.Model):
country_name = models.TextField()
class Town(models.Model):
country = models.ForeignKey(Country)
town_name = models.CharField(max_length=192)
class Blog(mod... | Filtering on Foreign Keys in Django | I have a few models in Django where I attach a location to each blog published:
class Country(models.Model):
country_name = models.TextField()
class Town(models.Model):
country = models.ForeignKey(Country)
town_name = models.CharField(max_length=192)
class Blog(models.Model):
town = models.ForeignKey(... | [
"blog_list = Blog.objects.filter( town__country__country_name = 'Canada' ).order_by( '-id' )\n\n"
] | [
18
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0007367368_django_orm_python.txt |
Q:
How do I add data then JOIN tables in DJango
I have a list of players that I would like to gather stats in 3 separate categories. (Rushing, Passing and Receiving).
Every week a player gets new stats for each category.
What I'd like to be able to do is list the top 5 players for each category ordered by who ever ha... | How do I add data then JOIN tables in DJango | I have a list of players that I would like to gather stats in 3 separate categories. (Rushing, Passing and Receiving).
Every week a player gets new stats for each category.
What I'd like to be able to do is list the top 5 players for each category ordered by who ever has the most yards for that particular statistic. I'... | [
"First of all I you have to change the model to use the DecimalField for the stats and then\nquery for each stat the top 5:\nPlayerStat.objects.order_by('receiving_yards')[:5]\n\nYou can also give an order listing more than one field to order from\nPlayerStat.objects.order_by('receiving_yards,receptions,receiving_t... | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007365093_django_django_models_django_templates_django_views_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.