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:
pyparsing setParseAction no tokens passed
I very new to pyparsing and Python so this is a warning that I might be doing something really wrong.
What I am trying to do is build a SQL parser and build up tree with nodes that I can then walk.
I'm trying to copy this kind of thing from a yacc/bison grammer file:
| sca... | pyparsing setParseAction no tokens passed | I very new to pyparsing and Python so this is a warning that I might be doing something really wrong.
What I am trying to do is build a SQL parser and build up tree with nodes that I can then walk.
I'm trying to copy this kind of thing from a yacc/bison grammer file:
| scalar_exp '^' scalar_exp
{ $$ = new Q... | [
"Your first entry in the operatorPrecedence operations list should be RIGHT-associative, not left. After making that change (and enabling packrat parsing), this parser starts working for me.\nBut as for building a syntax tree, I would let pyparsing build the tree for you. Attach parse actions to different syntax el... | [
2
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0006528931_parsing_pyparsing_python.txt |
Q:
Race condition in Django
In Django, I have ran into some serious race condition. The trouble starts when two runners try to execute some_method() at the same time. The logging created is as follows:
Job 3: Candidate
Job 3: Already taken
Job 3: Candidate
Job 3: Already taken
Job 3: Candidate
Job 3: Already taken
(e... | Race condition in Django | In Django, I have ran into some serious race condition. The trouble starts when two runners try to execute some_method() at the same time. The logging created is as follows:
Job 3: Candidate
Job 3: Already taken
Job 3: Candidate
Job 3: Already taken
Job 3: Candidate
Job 3: Already taken
(et cetera for 18 MB)
The follo... | [
"The problem has been fixed by manually updating the transaction. It seems that the QuerySet did not update since the start of the transaction. When two QuerySets would somehow start at the same time, and one job would occur in both QuerySets, it would break up the runners.\nAfter reading this answer, I came up wit... | [
0
] | [] | [] | [
"django",
"python",
"race_condition"
] | stackoverflow_0005343700_django_python_race_condition.txt |
Q:
Special JS operators in python
I'm 'hacking' my router, and I need to rewrite one JS function that takes date in hexdec format and convert it into Y m d
JS code looks like:
return [(((n >> 16) & 0xFF) + 1900), ((n >>> 8) & 0xFF), (n & 0xFF)];
where n is variable in format 0x123456 (e.g. 6 hexdec digits after 0x ... | Special JS operators in python | I'm 'hacking' my router, and I need to rewrite one JS function that takes date in hexdec format and convert it into Y m d
JS code looks like:
return [(((n >> 16) & 0xFF) + 1900), ((n >>> 8) & 0xFF), (n & 0xFF)];
where n is variable in format 0x123456 (e.g. 6 hexdec digits after 0x sign)
found that python has operator... | [
"Use >>. You are removing the sign anyway with the & 0xFF. Note, that you cannot leave out the & part, i.e., (n >> 8) & 0xff, or you'll get the wrong result, as you have already noted.\n",
"First thing you should know is that the bitwise operator for JS is operating on 32bit data. While for python, it's assuming ... | [
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0006535373_python.txt |
Q:
Displaying numpy arrays with matplotlib inside wx
I have a huge numpy ndarray with shape (M x N x 3) and datatype float32. I want the image to simply display in a wx.Frame that has a wx.ScrolledWindow attached. I want the image at 100% zoom and it is VERY important that no data loss occurs. These are super hi-r... | Displaying numpy arrays with matplotlib inside wx | I have a huge numpy ndarray with shape (M x N x 3) and datatype float32. I want the image to simply display in a wx.Frame that has a wx.ScrolledWindow attached. I want the image at 100% zoom and it is VERY important that no data loss occurs. These are super hi-res x-ray images that NEED to stay as floating point val... | [
"I found a solution: \n\nclass View(wx.Frame): \n def __init__(self):\n wx.Frame.__init__(self, \n parent=None, \n title=\"DICOM Viewer\", \n size=(1280, 750), \n pos=(0,0)) \n self.scroll = wx.ScrolledWindow(self, ... | [
1
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"wxwidgets"
] | stackoverflow_0006524053_matplotlib_numpy_python_wxwidgets.txt |
Q:
Creating a simple scripting language in Python
I'm creating a GUI application that can monitor and manipulate a stream of messages. I'm trying to create a simple means to let the user script some of this functionality and I'm looking for possible candidates. Initially I wanted to use XML since it can naturally tak... | Creating a simple scripting language in Python | I'm creating a GUI application that can monitor and manipulate a stream of messages. I'm trying to create a simple means to let the user script some of this functionality and I'm looking for possible candidates. Initially I wanted to use XML since it can naturally take care of embedded code:
<if>
<condition>
<... | [
"How about Python itself?\nFor example:\n>>> import code\n>>> def host_func():\n... print(\"Hello old chap!\")\n...\n>>> c = code.compile_command(\"print(\\\"Script says hello!\\\"); host_func()\")\n>>> exec(c)\nScript says hello!\nHello old chap!\n\nexec let's you be explicit about what from the host environme... | [
16,
5,
3
] | [] | [] | [
"python",
"scripting",
"xml"
] | stackoverflow_0006535748_python_scripting_xml.txt |
Q:
What exactly is the benifit of using Punjab
I've been working with XMPP related stuff now and here's what I've assimilated so far. XMPP and HTTP are two different protocols but when you're trying to implement a browser-based XMPP client, the XMPP traffic would piggyback on HTTP which is called XMPP-over-BOSH.
I ca... | What exactly is the benifit of using Punjab | I've been working with XMPP related stuff now and here's what I've assimilated so far. XMPP and HTTP are two different protocols but when you're trying to implement a browser-based XMPP client, the XMPP traffic would piggyback on HTTP which is called XMPP-over-BOSH.
I came across Punjab which seems to be a pretty popu... | [
"Many of the servers with direct BOSH support did not have that support early on. It's also sometimes handy to move the BOSH proxy closer to your web infrastructure, particularly before CORS was as well-understood.\n"
] | [
1
] | [] | [] | [
"python",
"xmpp"
] | stackoverflow_0006532072_python_xmpp.txt |
Q:
Django low level cache views
I have an index view which validates a form containing various data. Even though the thankyou.html page doesn't have complex calculations to kill the server, I would like to render a slightly different html page if thankyou.html is already low level cached. To tell you the truth, I don... | Django low level cache views | I have an index view which validates a form containing various data. Even though the thankyou.html page doesn't have complex calculations to kill the server, I would like to render a slightly different html page if thankyou.html is already low level cached. To tell you the truth, I don't know what key to pass it...
H... | [
"I think, in this case, you should use string ('thankyou' + form.cleaned_data['code']) as key.\n"
] | [
4
] | [] | [] | [
"caching",
"django",
"django_views",
"low_level",
"python"
] | stackoverflow_0006536054_caching_django_django_views_low_level_python.txt |
Q:
lxml XMLSyntaxError: Namespace default prefix was not found
I am using lxml to read my xml file. I am using a code something like below. It works just fine with lxml2.3 beta1, but with lxml2.3 it gives me zn xml syntax error as shown below. I went through the release notes for both versions, but could not figure o... | lxml XMLSyntaxError: Namespace default prefix was not found | I am using lxml to read my xml file. I am using a code something like below. It works just fine with lxml2.3 beta1, but with lxml2.3 it gives me zn xml syntax error as shown below. I went through the release notes for both versions, but could not figure out what could have caused this error or how to fix it. Please hel... | [
"Ok, so I finally figured out what was going on. Following a good advice to clean up used elements, I was clearing up all the elements, including the root node. The root node is the one with the default namespace prefix which applies to all nodes within that root. Since I cleared off my root node, the default names... | [
2,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0006511408_lxml_python.txt |
Q:
Python json memory bloat
import json
import time
from itertools import count
def keygen(size):
for i in count(1):
s = str(i)
yield '0' * (size - len(s)) + str(s)
def jsontest(num):
keys = keygen(20)
kvjson = json.dumps(dict((keys.next(), '0' * 200) for i in range(num)))
kvpairs = ... | Python json memory bloat | import json
import time
from itertools import count
def keygen(size):
for i in count(1):
s = str(i)
yield '0' * (size - len(s)) + str(s)
def jsontest(num):
keys = keygen(20)
kvjson = json.dumps(dict((keys.next(), '0' * 200) for i in range(num)))
kvpairs = json.loads(kvjson)
del kvp... | [
"Put this at the top of your program\nimport gc\ngc.set_debug(gc.DEBUG_STATS)\n\nand you'll get printed output whenever there's a collection. You'll see that in your example code there is no collection after jsontest completes, until the program exits.\nYou can put\nprint gc.get_count()\n\nto see the current counts... | [
3
] | [] | [] | [
"garbage_collection",
"json",
"python"
] | stackoverflow_0006536510_garbage_collection_json_python.txt |
Q:
Wait Serial response from magstrip card
I'm new programing in Python, and what I need a little help with this little aplication.
I write a little aplication that generate a random code and write it to the magstrip card.
The card reader is a MSR206u and is connected by serial port, I can read & write to the card e... | Wait Serial response from magstrip card | I'm new programing in Python, and what I need a little help with this little aplication.
I write a little aplication that generate a random code and write it to the magstrip card.
The card reader is a MSR206u and is connected by serial port, I can read & write to the card encoder, but I need to wait for the confirmati... | [
"You can wait for the response by simply doing a read on the serial port with an appropriate timeout configured. Both the read and inter-character timeouts may be specified in the constructor of the serial.Serial class from pyserial.\n"
] | [
0
] | [] | [] | [
"magnetic_cards",
"python"
] | stackoverflow_0006533943_magnetic_cards_python.txt |
Q:
Accessing SQL Server 2005 with PYODBC
I build an application to do some number crunching with wxpython. I have to access the data from SQL Server 2005 for my purpose. I am using PYODBC and when I asked my server adminstrator, he provided me the server name and unique data ID for the database.
I don't see the synta... | Accessing SQL Server 2005 with PYODBC | I build an application to do some number crunching with wxpython. I have to access the data from SQL Server 2005 for my purpose. I am using PYODBC and when I asked my server adminstrator, he provided me the server name and unique data ID for the database.
I don't see the syntax to access database with unique data ID in... | [
"Try to look at the following link: http://code.google.com/p/pyodbc/wiki/GettingStarted\nLink to connect method: http://code.google.com/p/pyodbc/wiki/Module#connect\nUsing the link above you can find the following sample code:\n#Make a direct connection to a database and create a cursor.\n\ncnxn = pyodbc.connect('D... | [
2
] | [] | [] | [
"database",
"pyodbc",
"python",
"sql",
"sql_server"
] | stackoverflow_0006536701_database_pyodbc_python_sql_sql_server.txt |
Q:
Python: how to create many constraints for fmin_cobyla optimization using lambda functions
I have a vector of a few hundred numerical entries (like this: Xo = [x1, y1, x2, y2,..., xN, yN]) where N is an arbitrary number. I need to pass this vector to the scipy fmin_cobyla optimizer with simple simple constraints o... | Python: how to create many constraints for fmin_cobyla optimization using lambda functions | I have a vector of a few hundred numerical entries (like this: Xo = [x1, y1, x2, y2,..., xN, yN]) where N is an arbitrary number. I need to pass this vector to the scipy fmin_cobyla optimizer with simple simple constraints on each of the entries:
1. All of the x's (ie. x1, x2, ..., xN) are such that -1
I've tried to u... | [
"try this\neven = lambda x: (x < 1 and x > -1)\nodd = lambda x: (x < 2 and x > -2)\nconstraint = lambda index: (index % 2) and odd or even\nfiltered = [x for index, x in enumerate(Xo) if constraint(index)(x)]\n\nHonestly, I have no idea what fmin_cobyla, but this is another try after reading David's comment\neven =... | [
1,
1
] | [] | [] | [
"constraints",
"lambda",
"optimization",
"python"
] | stackoverflow_0006536161_constraints_lambda_optimization_python.txt |
Q:
How to format a string into a two column list
I have a python string in the following format:
"x1 y1\n x2 y2\n x3 y3\n ..."
I would like to transform this into a list points = [p1, p2, p3,...], where p1, p2 and p3 are [x1,y1], [x2,y2] and [x3,y3] etc.
Thanks
A:
Think you can use the following:
inputText = "x1 y... | How to format a string into a two column list | I have a python string in the following format:
"x1 y1\n x2 y2\n x3 y3\n ..."
I would like to transform this into a list points = [p1, p2, p3,...], where p1, p2 and p3 are [x1,y1], [x2,y2] and [x3,y3] etc.
Thanks
| [
"Think you can use the following:\ninputText = \"x1 y1\\n x2 y2\\n x3 y3\\n\"\nprint [line.split() for line in inputText.split('\\n') if line]\n\n",
"obviously, many ways to do this.\nI would use list comprehension for its brevitiy. \n>>> str = 'x1 y1\\n x2 y2\\n x3 y3\\n'\n>>> [p.split() for p in str.split('\\n'... | [
6,
2,
0,
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0006537177_list_python_string.txt |
Q:
cgi.parse_qsl causing weird error with GAE
I wish to build a facebook app using GAE. The following code
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from urllib import urlopen, quote
import cgi
from django.utils import simplejson as json
class fbcheck(web... | cgi.parse_qsl causing weird error with GAE | I wish to build a facebook app using GAE. The following code
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from urllib import urlopen, quote
import cgi
from django.utils import simplejson as json
class fbcheck(webapp.RequestHandler):
def get(self):
... | [
"should be response = cgi.parse_qsl(urlopen(tokenurl).read()); urlopen returns an instance of class addinfourl which can be read from, not the contents of the URL.\n"
] | [
2
] | [] | [] | [
"cgi",
"google_app_engine",
"python"
] | stackoverflow_0006468985_cgi_google_app_engine_python.txt |
Q:
How to replace the full content of a node using any xml lib?
I'm trying to parse a xml file using Python but I have some tags that might contain xml data. For example:
<code>
<?xml version="1.0" encoding="utf-8"?>
</code>
I want to write CDATA tags like this:
<code><![CDATA[
<?xml version="1.0" encoding="utf... | How to replace the full content of a node using any xml lib? | I'm trying to parse a xml file using Python but I have some tags that might contain xml data. For example:
<code>
<?xml version="1.0" encoding="utf-8"?>
</code>
I want to write CDATA tags like this:
<code><![CDATA[
<?xml version="1.0" encoding="utf-8"?>
]]>
</code>
I tried (with lxml):
a = etree.fromstring(da... | [
"Your replacement code finds the <code> element and serializes it as the new text of the element. It seems like you want to include only the children of the <code> element, though.\nTry setting e.text to CDATA(e.text) instead of to the result of serializing e.\n",
"(I'm the OP i registered after posting)\nWith \... | [
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0006520752_python_xml.txt |
Q:
Django: Model __init__() is called on every update
I'm having a rather mystifying problem in one of my models. I've overridden __init__ as follows:
class Program(models.Model)
...
def __init__(self, *args, **kwargs):
super(Program, self).__init__(*args, **kwargs)
for m in Milestone.objects.... | Django: Model __init__() is called on every update | I'm having a rather mystifying problem in one of my models. I've overridden __init__ as follows:
class Program(models.Model)
...
def __init__(self, *args, **kwargs):
super(Program, self).__init__(*args, **kwargs)
for m in Milestone.objects.all():
try:
ProgramMilestone... | [
"If I got you correctly, you want to run some code when a program is created.\nYou can use the post_save signal and check for the created flag.\nhttps://docs.djangoproject.com/en/dev/ref/signals/#post-save\nBy having your code listen to that signal, you can run your code whenever a Program is created, and not chang... | [
9,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006537239_django_python.txt |
Q:
debugging python's "error: can't start new thread"
Rarely I receive the following error:
Exception in thread Thread-1240:
Traceback (most recent call last):
File "C:\Python26\lib\threading.py", line 534, in __bootstrap_inner
self.run()
File "C:\Python26\lib\threading.py", line 738, in run
self.function... | debugging python's "error: can't start new thread" | Rarely I receive the following error:
Exception in thread Thread-1240:
Traceback (most recent call last):
File "C:\Python26\lib\threading.py", line 534, in __bootstrap_inner
self.run()
File "C:\Python26\lib\threading.py", line 738, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\MyUser\Docu... | [
"It is a normal exception, actually it's thread.error (\"thread\" is the module which does all the low-level stuff). It's aliased in the \"threading\" module as ThreadError, so just catch threading.ThreadError.\n"
] | [
4
] | [] | [] | [
"exception",
"multithreading",
"python",
"timer"
] | stackoverflow_0006537010_exception_multithreading_python_timer.txt |
Q:
efficient way to change the header of a file in Python
I am trying to write a python script to update the header (only the first line) of some huge files, but as the new header is not necessary to be the same size (in bytes) as the original one, is there anyway I could change the header without touching the rest o... | efficient way to change the header of a file in Python | I am trying to write a python script to update the header (only the first line) of some huge files, but as the new header is not necessary to be the same size (in bytes) as the original one, is there anyway I could change the header without touching the rest of the huge file? or I have to read through them all and writ... | [
"No, the only operations you can do on files without touching the whole file are truncation, replacement of same size, and appending.\nYou can, however, buffer relatively small parts of the file and write them after you've read all data currently residing in the new position, to avoid memory exhaustion. If speed is... | [
5,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0006537727_file_python.txt |
Q:
Breaking at a member function in the Python debugger
This should be a trivial question, but my search so far has been fruitless:
I'm using the Python debugger (pdb) for the first time, and was quite pleased to find most of the commands familiar from using gdb.
However, when I went to set a breakpoint in the parse(... | Breaking at a member function in the Python debugger | This should be a trivial question, but my search so far has been fruitless:
I'm using the Python debugger (pdb) for the first time, and was quite pleased to find most of the commands familiar from using gdb.
However, when I went to set a breakpoint in the parse() member of class JamParser with the statement:
(Pdb) b Ja... | [
"You need to import names before you can refer to them in the debugger.\n(Pdb) from jam2dot import JamParser\n(Pdb) b JamParser.parse\n\n"
] | [
25
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0006537662_debugging_python.txt |
Q:
Python - How to catch a broken pipe
I have just learned about SIGPIPE, and then read about how to handle these in Python.
Among other sources, I have read: How to handle a broken pipe (SIGPIPE) in python?
Let's say that the pipe reading script exits, then all the answers suggest that the writing script wrappes it... | Python - How to catch a broken pipe | I have just learned about SIGPIPE, and then read about how to handle these in Python.
Among other sources, I have read: How to handle a broken pipe (SIGPIPE) in python?
Let's say that the pipe reading script exits, then all the answers suggest that the writing script wrappes its write calls in a try clause.
However, ... | [
"Since you are writing such a small amount of data, it is all buffered and nothing is actually written to the pipe until the file is closed. During the close, an attempt is made to write data to the pipe, which fails, but your try/except clause is already done. If you flush stdout during your try/except, you shou... | [
5
] | [] | [] | [
"pipe",
"python",
"sigpipe"
] | stackoverflow_0006537178_pipe_python_sigpipe.txt |
Q:
Security question relating to executing server-side script
I've written a python script using selenium to imitate a browser logging in and buying some stuff from a website. Therefore, the python script contains log-in information along with payment information (checking account info, etc). If i configure my apac... | Security question relating to executing server-side script | I've written a python script using selenium to imitate a browser logging in and buying some stuff from a website. Therefore, the python script contains log-in information along with payment information (checking account info, etc). If i configure my apache webserver to be able to execute python scripts, so that when ... | [
"it is usually a good idea to put such information in an external config file which can't be served by the webserver directly and read this file in your script. in case of a configuration error the client might see your sourcecode but not the sensitive information\n"
] | [
0
] | [] | [] | [
"apache",
"python",
"security",
"server_side"
] | stackoverflow_0006538018_apache_python_security_server_side.txt |
Q:
Static html Files in Cherrypy
I am having an issue with what should be a basic concept in cherrypy but as yet I have been unable to find a tutorial or example on how to do this (I am a Cherrypy newbie, be gentle).
The Problem.
(This is a Test piece hence the lack of robust authentication and sessions in the code)
... | Static html Files in Cherrypy | I am having an issue with what should be a basic concept in cherrypy but as yet I have been unable to find a tutorial or example on how to do this (I am a Cherrypy newbie, be gentle).
The Problem.
(This is a Test piece hence the lack of robust authentication and sessions in the code)
The user goes to the index.html pag... | [
"You have basically two options. If you want the user to visit /request and get that network.html content back, then just return it:\nclass LoginPage(object):\n ...\n @cherrypy.expose\n def request(self, username, password):\n auth = SiteAuth()\n if not auth.isAuthorizedUser(username,password... | [
5
] | [] | [] | [
"cherrypy",
"python",
"web_applications"
] | stackoverflow_0006531963_cherrypy_python_web_applications.txt |
Q:
python string error
dir = "C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
print dir
using the code above, i get this... i know that \t is tab
C:\Users\Geraldes\Desktop\media (espacamento) este\ASMS_TapeA01A1691329.mxf
but, to fix this i do:
dir1 = dir.replace("\\", "\\\\")
print "dir:",dir1
... | python string error | dir = "C:\Users\Geraldes\Desktop\media\teste\ASMS_TapeA01A1691329.mxf"
print dir
using the code above, i get this... i know that \t is tab
C:\Users\Geraldes\Desktop\media (espacamento) este\ASMS_TapeA01A1691329.mxf
but, to fix this i do:
dir1 = dir.replace("\\", "\\\\")
print "dir:",dir1
and i get
C:\\Users\\Ger... | [
"escape your original string's backslashes, or use raw strings.\nThat is,\ndir = \"C:\\\\Users\\\\Geraldes\\\\Desktop\\\\media\\\\teste\\\\ASMS_TapeA01A1691329.mxf\"\n\nor\ndir = r\"C:\\Users\\Geraldes\\Desktop\\media\\teste\\ASMS_TapeA01A1691329.mxf\"\n\nBUT: be careful with the second choice, because raw strings ... | [
5,
4,
3,
3,
0
] | [] | [] | [
"filepath",
"python",
"string"
] | stackoverflow_0006533850_filepath_python_string.txt |
Q:
Am I using super() correctly?
I made a small chunk of code because I'm still trying to figure out the specifics of using super(). Why does this chunk run to this TypeError?
a = SecondClass()
TypeError: __init__() takes exactly 2 arguments (1 given)
Then, the SecondClass.meth() function is supposed to print the s... | Am I using super() correctly? | I made a small chunk of code because I'm still trying to figure out the specifics of using super(). Why does this chunk run to this TypeError?
a = SecondClass()
TypeError: __init__() takes exactly 2 arguments (1 given)
Then, the SecondClass.meth() function is supposed to print the string, but I'm clearly missing some... | [
"This isn't anything to do with super. You don't define an __init__ for SecondClass explicitly - but, because it inherits from FirstClass, it inherits FirstClass's __init__. So you can't instantiate the object without passing in the value parameter.\nEdit OK. The first point, as others have mentioned, is that you m... | [
8,
3,
2,
1,
1
] | [] | [] | [
"inheritance",
"oop",
"python",
"super"
] | stackoverflow_0006538147_inheritance_oop_python_super.txt |
Q:
Documentation on PyQt Phonon backend audio effect 'speed'
When I look at the output of the function
Phonon.BackendCapabilities.availableAudioEffects()
I get this as one of the options:
>>> speed_effect = Phonon.BackendCapabilities.availableAudioEffects()[3]
>>> speed_effect.name()
PyQt4.QtCore.QString(u'speed')
>... | Documentation on PyQt Phonon backend audio effect 'speed' | When I look at the output of the function
Phonon.BackendCapabilities.availableAudioEffects()
I get this as one of the options:
>>> speed_effect = Phonon.BackendCapabilities.availableAudioEffects()[3]
>>> speed_effect.name()
PyQt4.QtCore.QString(u'speed')
>>> speed_effect.__doc__
'Phonon.EffectDescription()\nPhonon.Eff... | [
"Well, not too many people were looking at this so I kept going and finally figured it out. Note that all of this is specific to my particular backend media player, gstreamer, for Phonon. If you have a different backend, you'll need to do some tinkering to see what effects you need to play around with.\nThe way thi... | [
3
] | [] | [] | [
"phonon",
"pyqt",
"python"
] | stackoverflow_0006527507_phonon_pyqt_python.txt |
Q:
Loading modules at runtime from functions
I would like to load modules at runtime.
If I do it like this it works:
a = __import__('datetime',globals(),locals(),[],-1)
for e in a.__dict__:
if not e.startswith("__"):
globals()[e] = a.__dict__[e]
But if I try to do this it doesn't work:
def module_loader... | Loading modules at runtime from functions | I would like to load modules at runtime.
If I do it like this it works:
a = __import__('datetime',globals(),locals(),[],-1)
for e in a.__dict__:
if not e.startswith("__"):
globals()[e] = a.__dict__[e]
But if I try to do this it doesn't work:
def module_loader(modname,g,l):
a = __import__(modname,g(),l... | [
"Your snippet above works for me if I call it as\nmodule_loader('datetime', globals, locals)\n\n",
"def module_loader(modname,g,l):\n a = __import__(modname,g(),l(),[],-1)\n\n for e in a.__dict__:\n if not e.startswith(\"__\"):\n g()[e] = a.__dict__[e]\n\nmodule_loader('datetime', globals,... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006538522_python.txt |
Q:
Running git commands using subprocess.Popen in python
I am writing a small python script that needs to execute git commands from inside a given directory
The code is as follows:
import subprocess, os
pr = subprocess.Popen(['/usr/bin/git', 'status'],
cwd=os.path.dirname('/path/to/dir/'), ... | Running git commands using subprocess.Popen in python | I am writing a small python script that needs to execute git commands from inside a given directory
The code is as follows:
import subprocess, os
pr = subprocess.Popen(['/usr/bin/git', 'status'],
cwd=os.path.dirname('/path/to/dir/'),
stdout=subprocess.PIPE,
stderr=subprocess.P... | [
"subprocess.Popen:\n\nOn Unix, with shell=True: […] If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.\n\nYou don't want shell=True and also a list of arguments. Set shell=False.\n"
] | [
7
] | [] | [] | [
"git",
"popen",
"python"
] | stackoverflow_0006538734_git_popen_python.txt |
Q:
(Python/Pyramid) Better ways to have standard list/form editors?
I'm working on a number of Pyramid (former Pylons) projects, and often I have the need to display a list of some content (let's say user accounts, log entries or simply some other data). A user should be able to paginate through the list, click on a ... | (Python/Pyramid) Better ways to have standard list/form editors? | I'm working on a number of Pyramid (former Pylons) projects, and often I have the need to display a list of some content (let's say user accounts, log entries or simply some other data). A user should be able to paginate through the list, click on a row and get a form where he/she can edit the contents of that row.
Rig... | [
"is this what youre looking for?\npypi --> http://pypi.python.org/pypi/pyramid_formalchemy\ndocs --> http://docs.formalchemy.org/pyramid_formalchemy/\ndemo!! --> http://demo.formalchemy.org/\ncode --> https://github.com/FormAlchemy/pyramid_formalchemy and https://github.com/FormAlchemy/fa.jquery\nNote: \n\nonly wor... | [
1
] | [] | [] | [
"forms",
"helpers",
"pyramid",
"python"
] | stackoverflow_0006531421_forms_helpers_pyramid_python.txt |
Q:
A question about sites downtime updates
I've a server when I run a Django application but I've a little problem:
when with mercurial I commit and pushing new changes on the server, there's a micro time (like 1 microsec) where the home page is unreachable.
I have apache on the server.
How can I solve this?
A:
Y... | A question about sites downtime updates | I've a server when I run a Django application but I've a little problem:
when with mercurial I commit and pushing new changes on the server, there's a micro time (like 1 microsec) where the home page is unreachable.
I have apache on the server.
How can I solve this?
| [
"You could run multiple instances of the django app (either on the same machine with different ports or on different machines) and use apache to reverse proxy requests to each instance. It can failover to instance B whilst instance A is rebooting. See mod_proxy.\nIf the downtime is as short as you say though, it is... | [
4,
1,
0,
0
] | [
"i think it's normal, since django may be needing to restart its server after your update\n"
] | [
-1
] | [
"apache",
"django",
"python"
] | stackoverflow_0006535333_apache_django_python.txt |
Q:
Matching lines in Python
I need to match some string in a text file and want to get return the matching line. Let's say, I have string in 2D array as follows:
[['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
['My Cherie Amour (song)', 'Stevie Wonder'],
["Signed, Sealed, Delivered I'm Yours", 'Stevie Wonder]]
So t... | Matching lines in Python | I need to match some string in a text file and want to get return the matching line. Let's say, I have string in 2D array as follows:
[['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
['My Cherie Amour (song)', 'Stevie Wonder'],
["Signed, Sealed, Delivered I'm Yours", 'Stevie Wonder]]
So that I can search in a text fil... | [
"How about this:\ndef search(sentences, words):\n return [s for s in sentences if all([w in s for w in words])]\n\n",
"This should work:\ndef search(patterns, sentences):\n for sentence in sentences:\n if any(all(p in sentence for p in pattern) for pattern in patterns):\n yield sentence\n\nm... | [
2,
1
] | [] | [] | [
"python",
"string_matching"
] | stackoverflow_0006538763_python_string_matching.txt |
Q:
problem: how to reference to objects/variables created in decorator from injected method?
I encountered a problem with the availability of objects created within the decorator, and needed in the test_case method. My code presenting below:
def execute_results_navigation(test_case):
def wrapper(self,*args,**kwar... | problem: how to reference to objects/variables created in decorator from injected method? | I encountered a problem with the availability of objects created within the decorator, and needed in the test_case method. My code presenting below:
def execute_results_navigation(test_case):
def wrapper(self,*args,**kwargs):
result=Result()
pagination=Pagination()
results_page_index=1
... | [
"You won't be able to access local variables defined in wrapper within test_case.\nLooks like test_check_availability_of_search_results is an instance method, so one way to solve your problem is to assign those variables to attributes of 'self'. \n"
] | [
3
] | [] | [] | [
"decorator",
"python",
"reference"
] | stackoverflow_0006538810_decorator_python_reference.txt |
Q:
How to improve performance of this recursive function?
I'm trying to write a function which will search str for a substr, taking into account different possibilities to write weird letters, such as æ, ø, å in danish language. For example you can search 'Ålborg' and the function will return true if there is, say 'A... | How to improve performance of this recursive function? | I'm trying to write a function which will search str for a substr, taking into account different possibilities to write weird letters, such as æ, ø, å in danish language. For example you can search 'Ålborg' and the function will return true if there is, say 'Aalborg' in the str.
The function below works, but performanc... | [
"I think you should eliminate the recursion altogether. Instead of doing all that find and replace, you could, for example, decide upon a \"normal form\" of your input strings, convert them accordingly (i.e. replace those \"ambiguous\" characters) and do a simple\nreturn substring in string_\n\nNote also that you d... | [
3,
3,
1
] | [] | [] | [
"performance",
"python",
"recursion"
] | stackoverflow_0006538661_performance_python_recursion.txt |
Q:
Creating and fetching child records n Django
I have two models like:
class Manager(models.Model)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=65535, null=False)
class Employee(models.Model)
id = models.AutoField(primary_key=True)
manager = models.ForeignKey(Manager)
... | Creating and fetching child records n Django | I have two models like:
class Manager(models.Model)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=65535, null=False)
class Employee(models.Model)
id = models.AutoField(primary_key=True)
manager = models.ForeignKey(Manager)
name = models.CharField(max_length=65535, null=... | [
"Neither =)\nmgr = Manager.objects.get(id=1)\nemps = mgr.employee_set.all()\n\nAnd for your second one. No you'll need them seperately and like so:\nmgr = Manager.objects.create(name='John')\nemp = Employee.objects.create(name='Johns Slave', manager=mgr)\n\n",
"For the first one, you could just do\nemps = Employ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006538708_django_python.txt |
Q:
Problem setting up a virtualenv
I'm trying to set up a virtualenv on Ubuntu 10.04 with Python 2.6.5 but having some issues.
After having installed virtualenv and virtualenv wrapper with pip, I'm running the command: virtualenv mysite-env --verbose
I get the following error:
Creating mysite-env/lib/python2.6
Symlin... | Problem setting up a virtualenv | I'm trying to set up a virtualenv on Ubuntu 10.04 with Python 2.6.5 but having some issues.
After having installed virtualenv and virtualenv wrapper with pip, I'm running the command: virtualenv mysite-env --verbose
I get the following error:
Creating mysite-env/lib/python2.6
Symlinking Python bootstrap modules
Symli... | [
"For anyone else having the same problem, I got it working - I ended up re-installing everything from a clean image.\n"
] | [
0
] | [] | [] | [
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0005893514_python_virtualenv_virtualenvwrapper.txt |
Q:
Need help splitting a string into 3 variables
I would like to split a string of characters into 3 variables. When I just run a .split() I get ['AAA00000011']. I would like this to be split like:
var1 = AAA
var2 = 0000001
var3 = 1
The user is typing in these values into the command line on windows machine.
My Cod... | Need help splitting a string into 3 variables | I would like to split a string of characters into 3 variables. When I just run a .split() I get ['AAA00000011']. I would like this to be split like:
var1 = AAA
var2 = 0000001
var3 = 1
The user is typing in these values into the command line on windows machine.
My Code:
barcode = raw_input('Please enter your barcode')... | [
"Are you looking for this?\nvar1 = barcode[:3] # first three characters\nvar2 = barcode[3:-1] # all characters from third to next-to-last\nvar3 = barcode[-1] # last character\n\n",
"I think you want to use substrings here.\nvar1 = barcode[:3]\n\netc.\n",
"Could also do it with an re (apologies, my re usage ... | [
6,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006539299_python.txt |
Q:
Marshaling a Python PIL Image using SWIG
I've got a library that takes in a very simple C image structure:
// Represents a one-channel 8-bit image
typedef struct simple_image_t {
uint32 rows;
uint32 cols;
uint8 *imgdata;
} simple_image;
I didn't create this library, nor this structure, so I can't chan... | Marshaling a Python PIL Image using SWIG | I've got a library that takes in a very simple C image structure:
// Represents a one-channel 8-bit image
typedef struct simple_image_t {
uint32 rows;
uint32 cols;
uint8 *imgdata;
} simple_image;
I didn't create this library, nor this structure, so I can't change it. I'm responsible for wrapping this libra... | [
"PIL's Image.tostring() returns a string of the exact data you need for imgdata. The typemap I used is fairly simple, but not perfect, which I'll note below. Here is the sample code I created on Windows that worked for me:\nsample.h\ntypedef unsigned int uint32;\ntypedef unsigned char uint8;\n\ntypedef struct sim... | [
5,
1,
0
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"swig"
] | stackoverflow_0006480862_image_python_python_imaging_library_swig.txt |
Q:
How to configue apache and mode_wsgi for local django development on windows
The team I currently work with has outgrown the django development server for running django applications within our local development environments. The environment itself (server 2008 vm) is a mix of .net applications backed off of IIS7 ... | How to configue apache and mode_wsgi for local django development on windows | The team I currently work with has outgrown the django development server for running django applications within our local development environments. The environment itself (server 2008 vm) is a mix of .net applications backed off of IIS7 coupled with several django applications.
We have a need for being able to have ou... | [
"Your problem has to do with compiled modules and mod_wsgi. \nPython from Python.org has an embedded manifest that allows it to load DLL files. When compiling C modules python used to embed the manifest in the compiled modules, however since has started stripping them out by default. The issue here is that mod_wsgi... | [
4
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"windows"
] | stackoverflow_0006538216_apache_django_mod_wsgi_python_windows.txt |
Q:
How to create properties at runtime with Python?
So I'm trying to figure out if what I want to do is even possible. I am writing some test code for an application, and I have objects that contain properties representing some of the elements we have in the interface for our product. What I want to do is be able to ... | How to create properties at runtime with Python? | So I'm trying to figure out if what I want to do is even possible. I am writing some test code for an application, and I have objects that contain properties representing some of the elements we have in the interface for our product. What I want to do is be able to pass in the application runner and the data object to ... | [
"Not sure that's what you want. But you could define dynamic read-only property with getattr and setattr method. Here is an example:\nclass X(object):\n data = {'x' : 123, 'y' : 456}\n def __getattr__(self, name):\n if name in self.data:\n return self.data[name]\n raise AttributeError... | [
0
] | [] | [] | [
"properties",
"python",
"reflection",
"setattr",
"setattribute"
] | stackoverflow_0006538733_properties_python_reflection_setattr_setattribute.txt |
Q:
When should the save method be called in Django?
Should the save method be called after every create method or does calling the create method automatically call the save method?
If the save method is called automatically after creating an object then what would be a good use-case for the save method?
Thanks.
A:
... | When should the save method be called in Django? | Should the save method be called after every create method or does calling the create method automatically call the save method?
If the save method is called automatically after creating an object then what would be a good use-case for the save method?
Thanks.
| [
"No save() does not need to be called after create().\nfrom the docs for create:\n\nA convenience method for creating an object and saving it all in one step\n\nits to be used in place of creating an object the normal way then saving with object.save()\n",
"The save method should be used when you modify an object... | [
10,
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006534038_django_python.txt |
Q:
Perceptual hash function for text
Does anyone knows a simple perceptual hash algorithm for text ? I took a look in the pHash function ph_texthash but I want a more simple algorithm.
Preferably in Python. Thank you !
A:
A blog post about perceptual hash functions (in the imaging context):
http://www.hackerfactor... | Perceptual hash function for text | Does anyone knows a simple perceptual hash algorithm for text ? I took a look in the pHash function ph_texthash but I want a more simple algorithm.
Preferably in Python. Thank you !
| [
"A blog post about perceptual hash functions (in the imaging context):\n\nhttp://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html\n\nand some related python code (dealing with images, not text, but may be adaptable):\n\nhttp://sprunge.us/WcVJ?py (53 LOC)\n\n\nAs I understand this short presentat... | [
2
] | [] | [] | [
"algorithm",
"hash",
"python"
] | stackoverflow_0006539524_algorithm_hash_python.txt |
Q:
How do I use django db API to save all the elements of a given column in a dictionary?
I've used a raw SQL Query to access them, and it seems to have worked. However, I can't figure out a way to actually print the results to an array. The only thing that I can find is the cursor.fetchone() command, which gives ... | How do I use django db API to save all the elements of a given column in a dictionary? | I've used a raw SQL Query to access them, and it seems to have worked. However, I can't figure out a way to actually print the results to an array. The only thing that I can find is the cursor.fetchone() command, which gives me a single row.
Is there any way that I can return an entire column in a django query set?
| [
"dict(MyModel.objects.values_list('id', 'my_column')) will return a dictionary with all elements of my_column with the row's id as the key. But probably you're just looking for a list of all the values, which you should receive via MyModel.objects.values_list('my_column', flat=True)!\n",
"You can use cursor.fetch... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006539687_django_python.txt |
Q:
How can I have attributes that get extracted for i18n in ZPT macros?
I'm using Pyramid with ZPT templates to make a web app. I'm attempting to make a form template macro library to make life easier for things like setting current values of form fields, etc. I'm also using the lingua message extractors to automatic... | How can I have attributes that get extracted for i18n in ZPT macros? | I'm using Pyramid with ZPT templates to make a web app. I'm attempting to make a form template macro library to make life easier for things like setting current values of form fields, etc. I'm also using the lingua message extractors to automatically pick up strings for localization. I can't figure out how to make the ... | [
"You need to use [lingua] to version 2 (or later) to extract messages from templates for this to work.\n"
] | [
1
] | [] | [] | [
"chameleon",
"internationalization",
"pyramid",
"python",
"template_tal"
] | stackoverflow_0006372681_chameleon_internationalization_pyramid_python_template_tal.txt |
Q:
Remove horizontal grid lines only on wxgrid
On the wxwidgets docs, I only found the EnableGridLines, which is set to false, removes both the horizontal and vertical lines, what I wish, is to remove only the horizontal lines on the grid. Is there a possible way to do this?
A:
As far as I can tell, you either have... | Remove horizontal grid lines only on wxgrid | On the wxwidgets docs, I only found the EnableGridLines, which is set to false, removes both the horizontal and vertical lines, what I wish, is to remove only the horizontal lines on the grid. Is there a possible way to do this?
| [
"As far as I can tell, you either have all the lines or none of them. Feel free to try cross-posting on the wxPython mailing list to make doubly sure though.\n",
"I agree with Mike. Unfortunately wx.grid.Grid.Get[Col|Row]GridLinePen() isn't hooked to the wxPython level, so you can't override those functions in yo... | [
3,
0
] | [] | [] | [
"grid",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0006527640_grid_python_wxpython_wxwidgets.txt |
Q:
How do I keep score in a rock paper scissors game?
I'm just starting Python and writing a simple rock paper scissors game. Here's what I have so far. I can play a game with another player perfectly. What I want to know is how to keep score of the wins, so if Player 1 wins the first game it would say:
Player 1 = 1
... | How do I keep score in a rock paper scissors game? | I'm just starting Python and writing a simple rock paper scissors game. Here's what I have so far. I can play a game with another player perfectly. What I want to know is how to keep score of the wins, so if Player 1 wins the first game it would say:
Player 1 = 1
Player 2 = 0
And so on. Also if there's any tips to make... | [
"Consider this pseudo-code for suggestions (some parts need to be implemented):\n# a Player class. it should have a Name and a Score\nclass Player():\n def __init__(name):\n self.name = name\n self.score = 0\n\n# displays a prompt and reads in the players name returning a string\ndef getPlayerName():\n ... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006539860_python.txt |
Q:
Why does json.dumps() throw a 500 internal server error when using variables?
I've tested this out thoroughly and I have no idea why it's doing this, so I was wondering if someone could explain...
json.dumps() is throwing a 500 internal server error when I try to use a variable instead of a string.
For example:
er... | Why does json.dumps() throw a 500 internal server error when using variables? | I've tested this out thoroughly and I have no idea why it's doing this, so I was wondering if someone could explain...
json.dumps() is throwing a 500 internal server error when I try to use a variable instead of a string.
For example:
error = 'Login Failed: Your username or password is incorrect.'
test = json.dumps({'... | [
"Turning DEBUG on in settings, and going through traceback may be useful.\nJust of the wall, i may assume that before this check (if(errors == True):) You may forgot to initialize errors with initial value so it throws NameError... But it's just an assumption. \nUPD: Sorry ajax part slipped my mind - +1 to waitinfo... | [
0
] | [] | [] | [
"django",
"jquery",
"json",
"python"
] | stackoverflow_0006539825_django_jquery_json_python.txt |
Q:
How to install pyobjc on activepython 2.6 for snow leopard?
I need json, pyobjc and ideally psyco as well.
I got all but pyobjc working on active python 2.6. How do I successfully install pyobjc properly?
Thank you.
A:
To install pyobjc in ActivePython 2.6:
/usr/local/bin/pip-2.6 install --user pyobjc
A:
I end... | How to install pyobjc on activepython 2.6 for snow leopard? | I need json, pyobjc and ideally psyco as well.
I got all but pyobjc working on active python 2.6. How do I successfully install pyobjc properly?
Thank you.
| [
"To install pyobjc in ActivePython 2.6:\n/usr/local/bin/pip-2.6 install --user pyobjc\n\n",
"I ended up installing it with easy install:\neasy_install-2.6 pyobjc==2.2\nThat worked.\n"
] | [
1,
0
] | [] | [] | [
"activepython",
"pyobjc",
"python",
"python_2.6"
] | stackoverflow_0006508456_activepython_pyobjc_python_python_2.6.txt |
Q:
Should I use threading programming for mixing 2 audio stream?
I'd like to write a program that capture audio stream from the microphone and in the same time mix this stream with a playing audio file.
I'm lookig for library, api, etc..etc... but my concern is about the implementation, should I use threading program... | Should I use threading programming for mixing 2 audio stream? | I'd like to write a program that capture audio stream from the microphone and in the same time mix this stream with a playing audio file.
I'm lookig for library, api, etc..etc... but my concern is about the implementation, should I use threading programming? I don't know how to use a thread yet.
The operating system is... | [
"I think you will need some kind of threading, in order to make capturing and playback run smoothly side-by-side.\nBe aware that multi-threading in Python is limited by the GIL. In C++, you can use something like Boost.Thread.\nIn general, getting multi-threading right is hard, and you should take your time to get ... | [
1,
0,
0,
0
] | [] | [] | [
"audio",
"c++",
"multithreading",
"python",
"windows"
] | stackoverflow_0006467651_audio_c++_multithreading_python_windows.txt |
Q:
Is it time.time() a safe approach when creating content types on plone programatically?
I have to use _createObjectByType on Plone. I have as an argument the id of the object. Is it going to be safe, in this scenario, to create an id based on time.time() to avoid collisions? Can two requests have exactly the same ... | Is it time.time() a safe approach when creating content types on plone programatically? | I have to use _createObjectByType on Plone. I have as an argument the id of the object. Is it going to be safe, in this scenario, to create an id based on time.time() to avoid collisions? Can two requests have exactly the same timestamp as shown by time.time()?
| [
"You'll be perfectly safe doing this, even in the unlikely event two requests are processed at exactly the same time, in event of a conflict the ZODB will raise a ConflictError and retry your request.\nResponding to the discussion below:\nOn a single computer then by defition both transactions must overlap (you got... | [
5
] | [] | [] | [
"collision",
"plone",
"python",
"race_condition",
"time"
] | stackoverflow_0006540330_collision_plone_python_race_condition_time.txt |
Q:
How do I get setup.py test to use a specific fortran compiler?
I am trying to test a package that includes some f90 files. If I build or install and specify the fortran compiler, it works fine. However, when I try to test I get the following error:
C:\Users\jsalvatier\workspace\scikits.bvp_solver>python setup.py c... | How do I get setup.py test to use a specific fortran compiler? | I am trying to test a package that includes some f90 files. If I build or install and specify the fortran compiler, it works fine. However, when I try to test I get the following error:
C:\Users\jsalvatier\workspace\scikits.bvp_solver>python setup.py config_fc --fcompiler=gfortran test
running config_fc
unifing config_... | [
"I think the issue is that the 'test' command requires building inplace. \npython setup.py config --fcompiler=gfortran build_ext --inplace\n\nwas generating the same error as before, but \npython setup.py config --fcompiler=gfortran build_ext\n\nwas not. \nI was able to work around the problem by\n\nRunning setup ... | [
3,
2
] | [] | [] | [
"distutils",
"fortran",
"python",
"setuptools"
] | stackoverflow_0006523767_distutils_fortran_python_setuptools.txt |
Q:
Connecting to socket with authentication in python
I'm trying to connect to a mongodb instance through a python socket. The url looks like this
username:password@host.com:port
how can I connect to this with a python socket?
The following code gives me this error: [Errno -5] No address associated with hostname
impo... | Connecting to socket with authentication in python | I'm trying to connect to a mongodb instance through a python socket. The url looks like this
username:password@host.com:port
how can I connect to this with a python socket?
The following code gives me this error: [Errno -5] No address associated with hostname
import socket
import tornado
full_url = '%s:%s@%s' % (usern... | [
"You should use a driver to connect to mongodb. If you are using Tornado (it looks like you intend to do so), try asyncmongo; if you are using a threaded web server/application framework (Django, Pylons, etc) you can use PyMongo directly.\n\nEdit: As for why this code doesn't work, the socket module doesn't accept ... | [
2
] | [] | [] | [
"http_authentication",
"mongodb",
"python",
"sockets"
] | stackoverflow_0006540515_http_authentication_mongodb_python_sockets.txt |
Q:
Only one line of this batch file will run
gdal_merge -o C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_merged.tif -seperate -q -v C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_merged.tif C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_nn10.tif C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_... | Only one line of this batch file will run | gdal_merge -o C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_merged.tif -seperate -q -v C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_merged.tif C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_nn10.tif C:\test\RasterMerge\p023r027\p023r027_7t20010623_z16_nn20.tif
gdal_merge -o C:\test\RasterMerge\p02... | [
"is gdal_merge a batch file itself? \nIn that case you need to enter call before each line to prompt the batch file to return on exit from the called batch file, otherwise the exit call in the new batch file will be treated as a real exit so shall exit completely:\ncall gdal_merge -o C:\\test\\RasterMerge\\p023r027... | [
4
] | [] | [] | [
"batch_file",
"gdal",
"python"
] | stackoverflow_0006538897_batch_file_gdal_python.txt |
Q:
How Can I Allow Object Editing in the Django Admin For Specific Objects ONLY?
I'm currently writing a site which uses django-guardian to assign object-level permissions which are used throughout the site.
Here is the desired functionality:
I'd like for a user to have permissions to edit a single object (or multipl... | How Can I Allow Object Editing in the Django Admin For Specific Objects ONLY? | I'm currently writing a site which uses django-guardian to assign object-level permissions which are used throughout the site.
Here is the desired functionality:
I'd like for a user to have permissions to edit a single object (or multiple objects). For example, if there is a user named "Joe", and a model named "Partyli... | [
"I've asked a similar question to Lukazs (guardian's author) and he told me that this feature is coming on a future release (see user_can_access_owned_objects_only property on this commit and the related issue). If you're not willing to wait, maybe you can just install the source on the master branch.\nHave you tho... | [
4,
2
] | [] | [] | [
"django",
"django_admin",
"django_authentication",
"python"
] | stackoverflow_0005218110_django_django_admin_django_authentication_python.txt |
Q:
Help with creating a custom create and a custom get method
I have two models like so:
class Visit(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=65535, null=False)
class Session:
id = models.AutoField(primary_key=True)
visit = models.ForeignKey(Visit)
... | Help with creating a custom create and a custom get method | I have two models like so:
class Visit(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=65535, null=False)
class Session:
id = models.AutoField(primary_key=True)
visit = models.ForeignKey(Visit)
sequence_no = models.IntegerField(null = False)
I'd like two ... | [
"This would be in a Manager for Sessions. It would look something like (untested):\nclass SessionManager(models.Manager):\n def new_session(self, visit, **kwargs):\n vs = self.model.objects.filter(visit=visit).order_by(\"-sequence_no\")[:1]\n if len(vs):\n kwargs.update({\"sequence_no\":... | [
2,
1
] | [] | [] | [
"django",
"django_managers",
"django_models",
"python"
] | stackoverflow_0006540539_django_django_managers_django_models_python.txt |
Q:
Updating a TKinter GUI from a multiprocessing calculation
I'm creating a GUI for a python simulator. The GUI provides tools to set up the simulation and run it. While the simulation is running I want to pass progress information to the GUI and have it displayed on a Label in my simulation_frame. Because the simula... | Updating a TKinter GUI from a multiprocessing calculation | I'm creating a GUI for a python simulator. The GUI provides tools to set up the simulation and run it. While the simulation is running I want to pass progress information to the GUI and have it displayed on a Label in my simulation_frame. Because the simulations need to be run with multiprocessing, I'm using a Queue to... | [
"This may or may not be helpful to you, but it is possible to make tkinter thread-safe by ensuring that its code and methods are executed on the particular thread the root was instantiated on. One project that experimented with the concept can be found over on the Python Cookbook as recipe 577633 (Directory Pruner ... | [
2
] | [] | [] | [
"multiprocessing",
"python",
"tkinter"
] | stackoverflow_0006540412_multiprocessing_python_tkinter.txt |
Q:
Blank postscript files from plot
I have a matplotlib figure inside of a wxmpl panel, and am trying to print it to a Postscript file. The best I can get is a blank file - by 'blank' I don't mean empty, but rather a .ps file with headers and whatnot but displays as just a blank page.
The code to print is:
printer =... | Blank postscript files from plot | I have a matplotlib figure inside of a wxmpl panel, and am trying to print it to a Postscript file. The best I can get is a blank file - by 'blank' I don't mean empty, but rather a .ps file with headers and whatnot but displays as just a blank page.
The code to print is:
printer = self.GetPrinter() # wxmpl.FigurePrint... | [
"The problem was that wxmpl had no call to HasPage -- the entirety of the changes above didn't matter, after all. Adding in this code in class FigurePrintout fixed the issue with not printing:\ndef HasPage(self, page):\n return page <= 1\n\nYep... two lines. Based on the documentation for the wxPython printin... | [
0
] | [] | [] | [
"matplotlib",
"python",
"wxmpl",
"wxpython"
] | stackoverflow_0006524843_matplotlib_python_wxmpl_wxpython.txt |
Q:
Python: Inserting row into database with formatting
I'm trying to insert a row into a table that I've set up in a database.
My Code:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",[(prefix, code_id, answer, station)])
I'm getting for an error t... | Python: Inserting row into database with formatting | I'm trying to insert a row into a table that I've set up in a database.
My Code:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station) VALUES(%s, %s, %s, %s, timestamp, comport)""",[(prefix, code_id, answer, station)])
I'm getting for an error that is saying that it doesn't like what is in "[]".
I don... | [
"Why do you have the parameters inside two sets of brackets? The second argument should be a sequence containing four items, to match the four %ss in your query. Instead, you have given it a list containing one item: that item is a sequence with four items in it.\nInstead, try:\ncursor.execute(\"\"\"INSERT INTO s... | [
2,
0
] | [
"You can use Python's new 'format' string method:\ncursor.execute(\"\"\"INSERT INTO scan (prefix, code_id, answer, station) VALUES({}, {}, {}, {}, timestamp, comport)\"\"\".format(prefix, code_id, answer, station))\n\nYou can also number the parameters, like \"{0}\", \"{1}\", and so on. This might be required depen... | [
-1
] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0006540724_mysql_mysql_python_python.txt |
Q:
Multiple splits on a single line in Python
I would like to know if there is a more compact (or Pythonic) way of doing several splits of some input string. Now I'm doing:
[a,bc,de] = 'a,b:c,d/e'.split(',')
[b,c] = bc.split(':')
[d,e] = de.split('/')
A:
I'd use the regular expression library. You don't need to use... | Multiple splits on a single line in Python | I would like to know if there is a more compact (or Pythonic) way of doing several splits of some input string. Now I'm doing:
[a,bc,de] = 'a,b:c,d/e'.split(',')
[b,c] = bc.split(':')
[d,e] = de.split('/')
| [
"I'd use the regular expression library. You don't need to use lists for unpacking, you can use tuples as below.\nimport re\nregex = re.compile(r'[,:/]')\na, b, c, d, e = regex.split('a,b:c,d/e')\n\n",
"You're better of with regex split method probably. Don't do this, it will be crazy slow, but just to add the an... | [
8,
1
] | [] | [] | [
"python",
"split"
] | stackoverflow_0006540957_python_split.txt |
Q:
Python rpg adivce?
I started coding an RPG engine in python and I want it to be very scripted(buffs, events). I am experimenting with events and hooking. I would appreciate if you could tell me some matured opensource projects(so i can inspect the code) to learn from. Not necessarily python, but it would be ideal.... | Python rpg adivce? | I started coding an RPG engine in python and I want it to be very scripted(buffs, events). I am experimenting with events and hooking. I would appreciate if you could tell me some matured opensource projects(so i can inspect the code) to learn from. Not necessarily python, but it would be ideal.
Thanks in advance.
| [
"As Daenyth suggested, pygame is a great place to start. There are plenty of projects linked to on their page.\nThe other library that is quite lovely for this type of thing is Panda3D. Though I haven't yet used it, the library comes with samples, and it looks like there is a list of projects using it somewhere.\... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006539267_python.txt |
Q:
UnicodeDecodeError: 'ascii' codec can't decode
I'm reading a file that contains Romanian words in Python with file.readline().
I've got problem with many characters because of encoding.
Example :
>>> a = "aberație" #type 'str'
>>> a -> 'abera\xc8\x9bie'
>>> print sys.stdin.encoding
UTF-8
I've tried encode() with... | UnicodeDecodeError: 'ascii' codec can't decode | I'm reading a file that contains Romanian words in Python with file.readline().
I've got problem with many characters because of encoding.
Example :
>>> a = "aberație" #type 'str'
>>> a -> 'abera\xc8\x9bie'
>>> print sys.stdin.encoding
UTF-8
I've tried encode() with utf-8, cp500 etc, but it doesn't work.
I can't find... | [
"What are you trying to do?\nThis is a set of bytes:\nBYTES = 'abera\\xc8\\x9bie'\n\nIt's a set of bytes which represents a utf-8 encoding of the string \"aberație\". You decode the bytes to get your unicode string:\n>>> BYTES \n'abera\\xc8\\x9bie'\n>>> print BYTES \naberaÈ›ie\n>>> abberation = BYTES.decode('utf-8'... | [
15
] | [] | [] | [
"decoding",
"encoding",
"file",
"python",
"representation"
] | stackoverflow_0006541256_decoding_encoding_file_python_representation.txt |
Q:
Is POS tagging deterministic?
I have been trying to wrap my head around why this is happening but am hoping someone can shed some light on this. I am trying to tag the following text:
ae0.475 X mod
ae0.842 X mod
ae0.842 X mod
ae0.775 X mod
using the following code:
import nltk
file = o... | Is POS tagging deterministic? | I have been trying to wrap my head around why this is happening but am hoping someone can shed some light on this. I am trying to tag the following text:
ae0.475 X mod
ae0.842 X mod
ae0.842 X mod
ae0.775 X mod
using the following code:
import nltk
file = open("test", "r")
for line in file:... | [
"My best effort to understand uncovered this from someone not using the whole Brown corpus:\n\nNote that words that the tagger has\n not seen before, such as decried,\n receive a tag of None.\n\nSo, I guess something that looks like ae1.111 must appear in the corpus file, but nothing like ae0.842. That's kind of ... | [
8,
3
] | [] | [] | [
"machine_learning",
"nlp",
"nltk",
"python"
] | stackoverflow_0006541141_machine_learning_nlp_nltk_python.txt |
Q:
How can I subclass a modelform (extend with extra fields from the model)?
I have a model and a form:
class MyModel(models.Model):
field_foo = models.CharField(_("Foo"), max_length=50)
field_bar = models.IntegerField(_("Bar"))
class MyFormOne(forms.ModelForm):
class Meta:
model=MyModel
... | How can I subclass a modelform (extend with extra fields from the model)? | I have a model and a form:
class MyModel(models.Model):
field_foo = models.CharField(_("Foo"), max_length=50)
field_bar = models.IntegerField(_("Bar"))
class MyFormOne(forms.ModelForm):
class Meta:
model=MyModel
fields = ('field_foo', )
widgets = {'field_foo': forms.TextInput(attrs=... | [
"You shouldn't have to explicitly declare the entire widget, just modify the attrs which are different.\nOr if you have custom widgets in the real code, I would either\n\nCreate a custom model field class as well which uses that widget by default, if it's a general condition, so in the form class it just works \"au... | [
4,
3,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006541140_django_django_forms_python.txt |
Q:
How to OAuth Twitter with httplib2 and Python 3.x?
I know there are a lot of Python Twitter API and OAuth wrappers out there, but I don't want to use them. I want to use nothing more than httplib2 and Python 3.x standard library. Could you please demonstrate simple code examples on how to achieve that? Thanks in a... | How to OAuth Twitter with httplib2 and Python 3.x? | I know there are a lot of Python Twitter API and OAuth wrappers out there, but I don't want to use them. I want to use nothing more than httplib2 and Python 3.x standard library. Could you please demonstrate simple code examples on how to achieve that? Thanks in advance.
| [
"You can look at python-oauth2. The main implementation code is very readable. Since there are a lot of thorny issues here like precisely how you encode your forms it is tricky to get right. I would recommend just using the oauth2 library, that is what I've done to integrate with Twitter (httplib2 + oauth2 + Twitte... | [
0
] | [] | [] | [
"httplib2",
"oauth",
"python",
"python_3.x",
"twitter"
] | stackoverflow_0006540992_httplib2_oauth_python_python_3.x_twitter.txt |
Q:
Help parsing between tags using BeautifulSoup
I am attempint to parse out information from a website using BeautifulSoup and python. The html looks like the following. I am wanting my parsed data to look like:
ID Definition
Lysine.biosynthesis - Burkholderia psuedomallei 17
... rest of data in similar place (wi... | Help parsing between tags using BeautifulSoup | I am attempint to parse out information from a website using BeautifulSoup and python. The html looks like the following. I am wanting my parsed data to look like:
ID Definition
Lysine.biosynthesis - Burkholderia psuedomallei 17
... rest of data in similar place (within the "pre" tags and outside the "a" tags.
How ca... | [
"BeautifulSoup() and its search methods return you a hierarchical parse-tree object, not just a string. Iterating through findChildren() on the node found does what you want (and skips the header line):\nfor a in soup.find('pre').findChildren():\n z = a.string\n\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0006540502_beautifulsoup_html_parsing_python.txt |
Q:
Parse XML using lxml
I have the following XML I need to parse. Much of my issue seems to be that I can't get StingIO to work. It looks like I can't load the module; I guess I'm not even sure how to show that it's loaded properly? Below is the xml, returned as a response to an http request:
<response method="swi... | Parse XML using lxml | I have the following XML I need to parse. Much of my issue seems to be that I can't get StingIO to work. It looks like I can't load the module; I guess I'm not even sure how to show that it's loaded properly? Below is the xml, returned as a response to an http request:
<response method="switchvox.currentCalls.getLis... | [
"from lxml import etree\n\nxml_string = \"\"\"\n<response method=\"switchvox.currentCalls.getList\">\n <result>\n <current_calls total_items=\"3\">\n <current_call id=\"SIP/6525-b59313c8\" from_caller_id_name=\"user1\" from_caller_id_number=\"user1_ext\" to_caller_id_name=\"... | [
4
] | [] | [] | [
"iteration",
"lxml",
"python",
"xml"
] | stackoverflow_0006541570_iteration_lxml_python_xml.txt |
Q:
python scipy Delaunay plotting point cloud
I have a pointlist=[p1,p2,p3...]
where p1 = [x1,y1],p2=[x2,y2] ...
I want to use scipy.spatial.Delaunay to do trianglation on these point clouds and then plot it
How can i do this ?
The documentation for the Delaunay is really scarce
so far i have this code
from subproces... | python scipy Delaunay plotting point cloud | I have a pointlist=[p1,p2,p3...]
where p1 = [x1,y1],p2=[x2,y2] ...
I want to use scipy.spatial.Delaunay to do trianglation on these point clouds and then plot it
How can i do this ?
The documentation for the Delaunay is really scarce
so far i have this code
from subprocess import Popen, PIPE
import os
os.environ['poi... | [
"EDIT: plot also the convex hull\nimport numpy as np\nfrom scipy.spatial import Delaunay\n\npoints = np.random.rand(30, 2) # 30 points in 2-d\ntri = Delaunay(points)\n\n# Make a list of line segments: \n# edge_points = [ ((x1_1, y1_1), (x2_1, y2_1)),\n# ((x1_2, y1_2), (x2_2, y2_2)),\n# ... | [
18
] | [] | [] | [
"delaunay",
"python",
"scipy",
"triangulation"
] | stackoverflow_0006537657_delaunay_python_scipy_triangulation.txt |
Q:
Facebook Redirect Query
This is a followup to a previous question I asked. I have the URL encoded in a Facebook ad, and I want my python program to get the end URL that it redirects to using javascript. Because it uses javascript, the normal urllib2/mechanize ways of tracking redirects don't work, and I'm a litt... | Facebook Redirect Query | This is a followup to a previous question I asked. I have the URL encoded in a Facebook ad, and I want my python program to get the end URL that it redirects to using javascript. Because it uses javascript, the normal urllib2/mechanize ways of tracking redirects don't work, and I'm a little lost as to what my next st... | [
"document.location.replace() is how you perform a redirect using JavaScript. If you parse out the URL within that method call, then you could follow that URL manually within your code.\n"
] | [
0
] | [] | [] | [
"facebook",
"html",
"javascript",
"python"
] | stackoverflow_0006540747_facebook_html_javascript_python.txt |
Q:
Looping through lists with different number of elements
I have the right result in C=[ ] but I can´t get Tx equal to: [42, 68, 86]
[23, 45, 59]
[40, 68, 85]
[30, 56, 72]
This is the loop I can´t do. I think it´s easy but I´m new in this, and I can´t find a solution, every thing I ... | Looping through lists with different number of elements |
I have the right result in C=[ ] but I can´t get Tx equal to: [42, 68, 86]
[23, 45, 59]
[40, 68, 85]
[30, 56, 72]
This is the loop I can´t do. I think it´s easy but I´m new in this, and I can´t find a solution, every thing I need to do depends on this type of aproach. Give me a light ... | [
"Ts = [T0]\nTx = []\ncounter = 1\nfor T in Ts:\n for t in T:\n Ts.append([s[0] * s[1] + s[2] for s in izip(Ts[-1], C, QIN)])\n\nI haven't tested this, so comment if it doesn't work\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006541641_python.txt |
Q:
Fullscreen with pyqt4?
I'm new to pyqt and I've been looking for some docs about pyqt and fullscreen mode. but I couldn't find nothing. So here is my question:
is there any way to run a PyQT 4 application on fullscreen?
A:
use showFullScreen() on your widget.
| Fullscreen with pyqt4? | I'm new to pyqt and I've been looking for some docs about pyqt and fullscreen mode. but I couldn't find nothing. So here is my question:
is there any way to run a PyQT 4 application on fullscreen?
| [
"use showFullScreen() on your widget.\n"
] | [
47
] | [] | [] | [
"fullscreen",
"pyqt",
"python"
] | stackoverflow_0006541771_fullscreen_pyqt_python.txt |
Q:
Using Scrapy to parse site, follow Next Page, write as XML
My script works wonderfully when I comment one piece of code: return items.
Here is my code, changing to http://example.com since it appears that is what other people to possibly to preserve the 'scraping' legality issues.
class Vfood(CrawlSpider):
... | Using Scrapy to parse site, follow Next Page, write as XML | My script works wonderfully when I comment one piece of code: return items.
Here is my code, changing to http://example.com since it appears that is what other people to possibly to preserve the 'scraping' legality issues.
class Vfood(CrawlSpider):
name = "example.com"
allowed_domains = [ "example.com"... | [
"You're returning a list of items (probably in the wrong place) and later in the same function you are using yield to yield requests. You can't mix yield and return like this in python.\nEither add everything to a list and return it at the end of your parse method or use yield everywhere. My suggestion is to replac... | [
4,
3,
1
] | [] | [] | [
"python",
"request",
"scrapy",
"yield"
] | stackoverflow_0006529630_python_request_scrapy_yield.txt |
Q:
Help me finish this Python 3.x self-challenge
This is not homework.
I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion.
After half hour of dabbing with Python I failed. Please finish where I left off. Also... | Help me finish this Python 3.x self-challenge | This is not homework.
I saw this article praising Linq library and how great it is for doing combinatorics stuff, and I thought to myself: Python can do it in a more readable fashion.
After half hour of dabbing with Python I failed. Please finish where I left off. Also, do it in the most Pythonic and efficient way poss... | [
"Here's a short solution, using itertools.permutations:\nfrom itertools import permutations\n\ndef is_solution(seq):\n return all(int(seq[:i]) % i == 0 for i in range(2, 9))\n\nfor p in permutations('123456789'):\n seq = ''.join(p)\n if is_solution(seq):\n print(seq)\n\nI've deliberately omitted the... | [
23,
3,
2,
1
] | [] | [] | [
"combinatorics",
"puzzle",
"python",
"python_3.x"
] | stackoverflow_0002649513_combinatorics_puzzle_python_python_3.x.txt |
Q:
Python Multi-Processing Question?
I have a folder with 500 input files (total size of all files is ~ 500[MB]).
I'd like to write a python script that does the following:
(1) load all of the input files to memory
(2) initializes an empty python list that will later be used ... see bullet (4)
(3) start 15 different... | Python Multi-Processing Question? | I have a folder with 500 input files (total size of all files is ~ 500[MB]).
I'd like to write a python script that does the following:
(1) load all of the input files to memory
(2) initializes an empty python list that will later be used ... see bullet (4)
(3) start 15 different (independent) processes: each of these... | [
"ok I just whipped this up using zeromq to demonstrate a single subscriber to multiple publishers. You could probably do the same with queues but you would need to manage them a bit more. zeromq sockets just work which makes it nice for things like this IMO.\n\"\"\"\ndemo of multiple processes doing processing and ... | [
6
] | [] | [] | [
"python",
"zeromq"
] | stackoverflow_0006542192_python_zeromq.txt |
Q:
Making a table of words and numbers from a file along with information from a webpage
I'm having trouble finishing this program. The goal of the program is to read a file that contains the abbreviation of a stock and a number that stands for the amount of shares. I am then going to put the full company name, pri... | Making a table of words and numbers from a file along with information from a webpage | I'm having trouble finishing this program. The goal of the program is to read a file that contains the abbreviation of a stock and a number that stands for the amount of shares. I am then going to put the full company name, price of the stock, number of shares, and total investments in an html file in a table. I am ... | [
"You said you are \"having trouble separating the abbreviation of the company from the number of shares in the text file.\" What trouble, exactly? \nTo read in 2 columns of whitespace-separated data from a textfile, just do:\nimport fileinput\nfor line in fileinput.input(yourinputfile):\n (abbrev,shares) = line.... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005864410_python.txt |
Q:
How to put html in django template variables?
I want to put in pieces of html in template variables. Something like this:
>>>t = django.template.Template("<ul>{{ title }}<\ul>: {{ story }}")
>>>c = django.template.Context({"title":"This is the title",r"Line 1.<br />Line 2."})
>>>print t.render(c)
<ul>This is the t... | How to put html in django template variables? | I want to put in pieces of html in template variables. Something like this:
>>>t = django.template.Template("<ul>{{ title }}<\ul>: {{ story }}")
>>>c = django.template.Context({"title":"This is the title",r"Line 1.<br />Line 2."})
>>>print t.render(c)
<ul>This is the title<\ul>: Line 1.<br />Line 2.
I expected a... | [
"Use the safe filter to inhibit encoding.\n",
"Use the safe filter, e.g.:\n\n\n\nt = django.template.Template(\"{{ title|safe }}<\\ul>: {{ story|safe }}\")\n\n\n\n"
] | [
1,
1
] | [] | [] | [
"django",
"django_templates",
"escaping",
"html",
"python"
] | stackoverflow_0006542626_django_django_templates_escaping_html_python.txt |
Q:
Google app engine - Users, Lists and Products a Join question on effiency
Let's take this models:
User
- name
Product
- name
- category
List
- name
- creation_date
- user (reference)
Product_List
- list ( reference)
- product ( reference)
How can I retrieve a list of the products that remain ... | Google app engine - Users, Lists and Products a Join question on effiency | Let's take this models:
User
- name
Product
- name
- category
List
- name
- creation_date
- user (reference)
Product_List
- list ( reference)
- product ( reference)
How can I retrieve a list of the products that remain out of the list?
Should I retrieve them all and then delete them programmatica... | [
"If you structure your data like this:\nclass Product(db.Model):\n # ...\n\nclass UserInfo(db.Model):\n # ...\n\nclass ProductList(db.Model):\n owner = db.ReferenceProperty(UserInfo)\n products = db.ListProperty(db.Key)\n\nThen you can retrieve the products not in a list like this:\nproduct_keys = set(Product.a... | [
2,
0
] | [] | [] | [
"google_app_engine",
"join",
"performance",
"python"
] | stackoverflow_0006528083_google_app_engine_join_performance_python.txt |
Q:
Sorting columns in a table (list of lists) whilst preserving the correspondence of the rows
For example:
list1 = ['c', 'b', 'a']
list2 = [3, 2, 1]
list3 = ['11', '10', '01']
table = [list1, list2, list3]
I'd like to sort with respect to the first column (list1), but I'd like the final ordering to still preserve t... | Sorting columns in a table (list of lists) whilst preserving the correspondence of the rows | For example:
list1 = ['c', 'b', 'a']
list2 = [3, 2, 1]
list3 = ['11', '10', '01']
table = [list1, list2, list3]
I'd like to sort with respect to the first column (list1), but I'd like the final ordering to still preserve the lines (so after sorting I'd still have a line 'b', 2, '10'). In this example I could just sort... | [
"One quick way would be to use zip:\n>>> from operator import itemgetter\n>>> transpose = zip(*table)\n>>> transpose.sort(key=itemgetter(0))\n>>> table = zip(*transpose)\n>>> table\n[('a', 'b', 'c'), (1, 2, 3), ('01', '10', '11')]\n\n",
"# Get a list of indexes (js), sorted by the values in list1.\njs = [t[1] for... | [
6,
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0006542399_list_python_sorting.txt |
Q:
Check to ensure a string does not contain multiple values
**Note- I will not just be testing at the end of a string-- need to locate particular substrings anywhere in the string
What is the fastest way to check to make sure a string does not contain multiple values. My current method is inefficient and unpythonic... | Check to ensure a string does not contain multiple values | **Note- I will not just be testing at the end of a string-- need to locate particular substrings anywhere in the string
What is the fastest way to check to make sure a string does not contain multiple values. My current method is inefficient and unpythonic:
if string.find('png') ==-1 and sring.find('jpg') ==-1 and str... | [
"Try:\nif not any(extension in string for extension in ('jpg', 'png', 'gif')):\n\nwhich is basically the same as your code, but more elegantly written.\n",
"if you're testing just the end of the string, remember that str.endswith can accept a tuple.\n>>> \"test.png\".endswith(('jpg', 'png', 'gif'))\nTrue\n\nother... | [
16,
8
] | [
"You could also do something like this if the values to test for didn't need to be managed by a tuple/list.\n>>> ('png' or 'jpg' or 'foo') in 'testpng.txt'\nTrue\n>>> ('png' or 'jpg' or 'foo') in 'testpg.txt'\nFalse\n\nEDIT\nI see the error of my ways now, it only checks the first.\n>>> ('bees' or 'png' or 'jpg' or... | [
-4
] | [
"algorithm",
"python",
"string"
] | stackoverflow_0006542801_algorithm_python_string.txt |
Q:
Is there a more "Pythonic" way to combine CSV elements?
Basically I am using a python cron to read data from the web and place it in a CSV list in the form of:
.....
###1309482902.37
entry1,36,257.21,16.15,16.168
entry2,4,103.97,16.36,16.499
entry3,2,114.83,16.1,16.3
entry4,130.69,15.6737,16.7498
entry5,5.20,14.4,... | Is there a more "Pythonic" way to combine CSV elements? | Basically I am using a python cron to read data from the web and place it in a CSV list in the form of:
.....
###1309482902.37
entry1,36,257.21,16.15,16.168
entry2,4,103.97,16.36,16.499
entry3,2,114.83,16.1,16.3
entry4,130.69,15.6737,16.7498
entry5,5.20,14.4,17
$$$
###1309482902.37
entry1,36,257.21,16.15,16.168
entry2,... | [
"I'd use Python's csv module to read in the CSV file, fix the broken rows as I encountered them, then use csv.writer to write the CSV back out. Like so (assuming your original file, with commas in the wrong place, is ugly.csv, and the new, cleaned up output file will be pretty.csv):\nimport csv\n\ninputCsv = csv.r... | [
2,
0,
0,
0
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0006542850_csv_list_python.txt |
Q:
Querying a many-to-many relationship in SQLAlchemy
I have a pretty standard many-to-many relationship, similar to the Blog -> Keyword relationship in the ORM tutorial.
I would like to query for a list of Keywords, returning Blog posts where any of them match. However, I can't work out if there is a simple way to d... | Querying a many-to-many relationship in SQLAlchemy | I have a pretty standard many-to-many relationship, similar to the Blog -> Keyword relationship in the ORM tutorial.
I would like to query for a list of Keywords, returning Blog posts where any of them match. However, I can't work out if there is a simple way to do this. If I add multiple filters, repeatedly doing
.fil... | [
"I think you just want\n.filter(Blog.keywords.any(Keyword.name.in_(['keyword1', 'keyword2', ...])))\n\nI'm using http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators for reference\n"
] | [
22
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006542967_python_sqlalchemy.txt |
Q:
How to get Trac (CommitTicketUpdater) w/Mercurial to close|resolve tickets on commit?
My Quick Question is this: Everything seems to be working, except that Trac tickets don't get status updates upon commit. Change-set notes are appended to the ticket, but the tickets themselves are not being resolved
I've just ... | How to get Trac (CommitTicketUpdater) w/Mercurial to close|resolve tickets on commit? | My Quick Question is this: Everything seems to be working, except that Trac tickets don't get status updates upon commit. Change-set notes are appended to the ticket, but the tickets themselves are not being resolved
I've just done this setup:
Windows 7 x64
IIS 7.5
isapi-wsgi 0.4.2
Python27 32
Mercurial 1.8
Trac ... | [
"Phew! Got it...\nFollowing, to the 'T', the directions from the Trac site was my error.\nWell kind of, I guess. \nI had, basically, copied this from the above site into my trac.ini file: \n\ncommit_ticket_update_envelope = []\ncommit_ticket_update_commands.close =\n commit_ticket_update_commands.refs = \n comm... | [
4
] | [] | [] | [
"mercurial",
"python",
"trac"
] | stackoverflow_0006539760_mercurial_python_trac.txt |
Q:
ConfigParser problem Python
I'm having problem to append to config file. Here's what I want to create;
[section1]
val1 = val2
val3 = val4
but when I run the following code I see ConfigParser.NoSectionError: No section: 'section1'
import ConfigParser
cfg = ConfigParser.RawConfigParser()
cfg.set("section1", "val1"... | ConfigParser problem Python | I'm having problem to append to config file. Here's what I want to create;
[section1]
val1 = val2
val3 = val4
but when I run the following code I see ConfigParser.NoSectionError: No section: 'section1'
import ConfigParser
cfg = ConfigParser.RawConfigParser()
cfg.set("section1", "val1", "val2")
f = open("example.cfg"... | [
"I fleshed out the code you put up a bit. Are you reading the existing file before checking for the section? Also, you should be writing the whole file at once. Don't append.\nimport ConfigParser\n\ncfg = ConfigParser.ConfigParser()\ncfg.read('example.cfg')\n\nif not cfg.has_section('section1'):\n cfg.add_sec... | [
5
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0006543194_configparser_python.txt |
Q:
NameError -- not definied
Main Program
# import statements
import random
import winning
# Set constants
win = 0
lose = 0
tie = 0
ROCK = 1
PAPER = 2
SCISSOR = 3
# Main Program for the Rock Paper Scissor game.
def main():
# set variable for loop control
again = 'y'
while again == 'y':
# Displ... | NameError -- not definied | Main Program
# import statements
import random
import winning
# Set constants
win = 0
lose = 0
tie = 0
ROCK = 1
PAPER = 2
SCISSOR = 3
# Main Program for the Rock Paper Scissor game.
def main():
# set variable for loop control
again = 'y'
while again == 'y':
# Display menu
display_menu()
... | [
"Don't take the negative comments the wrong way. Just be sure to mark your homework as homework and be sure to paste the actual error generated by the code that you've posted. This error doesn't match the code you posted. \nYou might also ask your question in a slightly calmer-seeming way :)\nThe problem is very si... | [
2
] | [] | [] | [
"definition",
"nameerror",
"python",
"variables"
] | stackoverflow_0006543212_definition_nameerror_python_variables.txt |
Q:
combining two lists into a new list and sorting
shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1
output [50, 100, 75, 200, 100, 100, 300, 500]
What I want is to assign a variable to the merged list and sort the list. See my incorrect attempt below Any sugges... | combining two lists into a new list and sorting | shares_1 = [50, 100, 75, 200]
shares_2 = [100, 100, 300, 500]
shares_1.extend(shares_2)
print shares_1
output [50, 100, 75, 200, 100, 100, 300, 500]
What I want is to assign a variable to the merged list and sort the list. See my incorrect attempt below Any suggestions?
shares_3.sort() = shares_1.extend(shares_2)
T... | [
"shares_3 = sorted(shares_1 + shares_2)\n\n",
"shares_3 = shares_1 + shares_2\nshares_3.sort()\n\nAlternatively,\nshares_1.extend(shares_2)\nshares_1.sort()\n\n",
"Josh Matthews' answer offers two good methods. There are some general principles to understand here, though: First, generally, when you call a metho... | [
9,
5,
5
] | [] | [] | [
"list",
"merge",
"python",
"sorting"
] | stackoverflow_0006543590_list_merge_python_sorting.txt |
Q:
Python - how to a open remote file in binary read mode?
I'm trying to use the mutagen module to read the metadata of an mp3 file. The problem is that the module is expecting a local mp3 file, but my mp3 files are on a remote server.
This is the line in the module that raises an error when I send a remote mp3 URL a... | Python - how to a open remote file in binary read mode? | I'm trying to use the mutagen module to read the metadata of an mp3 file. The problem is that the module is expecting a local mp3 file, but my mp3 files are on a remote server.
This is the line in the module that raises an error when I send a remote mp3 URL as the first parameter.
fp = file(f, "rb")
How can I alter th... | [
"fp = urllib2.urlopen(\"http://remotedomain.com/file.mp3\")\n\nbinary mode is default\n",
"file() can not be used to fetch arbitrary URLs.\nSee\nhttp://docs.python.org/dev/howto/urllib2.html\n"
] | [
7,
4
] | [] | [] | [
"binary",
"io",
"metadata",
"mutagen",
"python"
] | stackoverflow_0006543737_binary_io_metadata_mutagen_python.txt |
Q:
Color matplotlib plot_surface command with surface gradient
I would like to convert surf command from MATLAB to plot_surface command in matplotlib.
The challenge I am facing is when using cmap function in plot_surface command to color the surface with gradient.
Here is the matlab script
% Matlab Commands
x = -5:.2... | Color matplotlib plot_surface command with surface gradient | I would like to convert surf command from MATLAB to plot_surface command in matplotlib.
The challenge I am facing is when using cmap function in plot_surface command to color the surface with gradient.
Here is the matlab script
% Matlab Commands
x = -5:.25:5; y = x
[x,y] = meshgrid(x);
R = sqrt(x.^2 + y.^2);
Z = sin(R)... | [
"First, it looks like you want the colors mapped from gradient magnitude. You are trying to use the gradient vectors which is why you are getting the 'list' error.\nSecond, you can supply a cmap, but it only defines how you want the Z values mapped to a color. If you want new face colors then use the facecolors a... | [
50
] | [] | [] | [
"matlab",
"matplotlib",
"python"
] | stackoverflow_0006539944_matlab_matplotlib_python.txt |
Q:
Structure for large volume of semi-persistent data?
I need to track a large volume of inotify messages for a set of files that, during their lifetime, will move between several specific directories, with inodes intact; I need to track the movement of these inodes, as well as create/delete and changes to a file's c... | Structure for large volume of semi-persistent data? | I need to track a large volume of inotify messages for a set of files that, during their lifetime, will move between several specific directories, with inodes intact; I need to track the movement of these inodes, as well as create/delete and changes to a file's content. There will be many hundreds of changes per secon... | [
"Why not a database? Say SQLite.\nWhile SQLite isn't the most efficient storage mechanism in terms of space there are a number of advantages -- the first and foremost is that is an SQL RDBMS. The amount of memory SQLite uses (to temporarily cache data) can be configured through the cache_size pragma.\nIf SQLite isn... | [
0
] | [] | [] | [
"inotify",
"python"
] | stackoverflow_0006543833_inotify_python.txt |
Q:
Where is the best place to do initVM and attachCurrentThread when using pylucene in Django
I'm using pylucene in a django based site and I was wondering if anyone knew where the best place to start up the jvm and attach threads would be. I don't want to have to start a new jvm every time someone loads a page, but... | Where is the best place to do initVM and attachCurrentThread when using pylucene in Django | I'm using pylucene in a django based site and I was wondering if anyone knew where the best place to start up the jvm and attach threads would be. I don't want to have to start a new jvm every time someone loads a page, but I was occasionally getting the cryptic "Cannot Import Name" error in django when I was attachin... | [
"I never used pylucene in Django, though initVM() should be called in a file which is pretty much loaded when the Django server starts (settings.py would be a good place). \nAbout attachCurrentThread: The question is where are you using the lucene module. If it is in views.py then of course do it in views.py. Thoug... | [
4
] | [] | [] | [
"django",
"jvm",
"pylucene",
"python"
] | stackoverflow_0006536179_django_jvm_pylucene_python.txt |
Q:
Using re module in python to extract data between two brackets
this is a test string
"transparent url(http://www.google.com/chart?chs=630x100&cht=bvs&chxt=x&chxl=0:%7C1840%7C1860%7C1880%7C1900%7C1920%7C1940%7C1960%7C1980%7C2000%7C&chxr=0,0,100&chxs=0,676767,11.3000002,0,tl,676767,676767&chd=e:D9AACPFjGWAAGDLfCeFg... | Using re module in python to extract data between two brackets | this is a test string
"transparent url(http://www.google.com/chart?chs=630x100&cht=bvs&chxt=x&chxl=0:%7C1840%7C1860%7C1880%7C1900%7C1920%7C1940%7C1960%7C1980%7C2000%7C&chxr=0,0,100&chxs=0,676767,11.3000002,0,tl,676767,676767&chd=e:D9AACPFjGWAAGDLfCeFgBvHLLSCZGED5GOKwDKCxJmF2FwFfERFwEZGcEJHlENJDJ9I0HQDjE-MAK2J9NMI9IAFt... | [
"jcomeau@intrepid:/tmp$ python\nPython 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) \n[GCC 4.6.1 20110608 (prerelease)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import re\n>>> re.compile('\\(([^)]*)\\)').search(\"transparent url(http://www.google.com/chart?chs=630x... | [
1
] | [] | [] | [
"html_parsing",
"python",
"regex"
] | stackoverflow_0006544045_html_parsing_python_regex.txt |
Q:
Validating URL paramaters
How should one validate URL parameters in a view? Would this be accomplished using a a bunch of ìf statements or is there a better way to go about it? I'd like to validate the parameters when the request comes in rather than having it scattered across my view, model and manager.
When I sa... | Validating URL paramaters | How should one validate URL parameters in a view? Would this be accomplished using a a bunch of ìf statements or is there a better way to go about it? I'd like to validate the parameters when the request comes in rather than having it scattered across my view, model and manager.
When I say validation I'm referring to b... | [
"I think in this case it depends on the scale of your application\nif it's just a small application doing data validation via simple if statements\nwould be the easiest route, but django does have features to support nicer form validation(https://docs.djangoproject.com/en/1.3/ref/forms/validation/), so it \nmight b... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006544127_django_python.txt |
Q:
Zip a set of blobs from appengine datastore
I need to zip a set of blobs available in data store.
These can of different types like some html/images/swf/ etc.
where all these are available in datastore as blob.
I tried to implement this solution:
Zipping dynamic files in App Engine (Python)?
Tried with some static... | Zip a set of blobs from appengine datastore | I need to zip a set of blobs available in data store.
These can of different types like some html/images/swf/ etc.
where all these are available in datastore as blob.
I tried to implement this solution:
Zipping dynamic files in App Engine (Python)?
Tried with some static texts it worked great, I am also able to create ... | [
"Per the zipfile documentation:\n\nThere is no official file name encoding for ZIP files.\n If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to write().\n\nTry to encode your filename in UTF-8 for example with:\nclass filesDB(db.model) \n ... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"zip"
] | stackoverflow_0006537957_google_app_engine_python_zip.txt |
Q:
python app engine restful service using DAL
I am building a restful service in python for app engine and I would like to be able to separate datastore operations (like queries) from the request handlers.
I can build my own DAL, but I'm wondering if there are libraries already out there. Anyone know of any or have ... | python app engine restful service using DAL | I am building a restful service in python for app engine and I would like to be able to separate datastore operations (like queries) from the request handlers.
I can build my own DAL, but I'm wondering if there are libraries already out there. Anyone know of any or have suggestions on how to build one? Thanks for your ... | [
"If you want something portable outside Google App Engine you could try the Web2Py DAL Api.\nYou would code something like this:\ndb = DAL('gae')\nrows = db(db.mytable.myfield!=None).select()\n\nfor row in rows:\n print row.myfield\n\nWeb2py currently supports these db flavors:\n\nGoogle App Engine\n SQLite\n My... | [
0
] | [] | [] | [
"data_access_layer",
"google_app_engine",
"python",
"rest"
] | stackoverflow_0006541207_data_access_layer_google_app_engine_python_rest.txt |
Q:
howto create a multidimensional Array of floats with Pythonnet
I'm using pythonnet (http://pythonnet.sf.net) to bind together a python framework and a .NET library (I know if IronPython but this is not the question).
Using pythonnet, I can create an Array of floats, and initialize it from a sequence of values:
>>... | howto create a multidimensional Array of floats with Pythonnet | I'm using pythonnet (http://pythonnet.sf.net) to bind together a python framework and a .NET library (I know if IronPython but this is not the question).
Using pythonnet, I can create an Array of floats, and initialize it from a sequence of values:
>>> from System import *
>>> Array[float]([1., 2.])
<System.Double[] o... | [
"Use Array.CreateInstance:\n>>> a = Array.CreateInstance(Double, 3, 3)\n\nreference: http://msdn.microsoft.com/en-us/library/system.array.createinstance%28v=VS.90%29.aspx\n"
] | [
4
] | [] | [] | [
".net",
"ironpython",
"multidimensional_array",
"python",
"python.net"
] | stackoverflow_0006545069_.net_ironpython_multidimensional_array_python_python.net.txt |
Q:
How to access variable values of a php script from a python script?
How can I access my php script from a Python script?
I need my Python script to be able to access the variables within the php script. (By the way, I'm new to php and Python.)
Thanks in advance.
A:
If I understand it correctly, you have a servic... | How to access variable values of a php script from a python script? | How can I access my php script from a Python script?
I need my Python script to be able to access the variables within the php script. (By the way, I'm new to php and Python.)
Thanks in advance.
| [
"If I understand it correctly, you have a service in PHP, and want to communicate with another one in Python.\nNow, this is not really related to PHP or Python: this is quite a classic issue of integration and there are several ways to accomplish it; without more details about your problem, it may be very difficult... | [
0
] | [
"Elaborate. Is the PHP file local? On a webserver? Where's the python file?\nIf the php file is on a server with the python file, use an exec statement.\nIf the python file is local and the php file is on a server, then you need to use urllib.\nIf both are local, write an interpreter...\n"
] | [
-1
] | [
"import",
"php",
"python"
] | stackoverflow_0006530663_import_php_python.txt |
Q:
Plugs and Sockets in python PyGTK
I'm just learning PyGTK and I came across the plug and sockets section. I don't really understand what they are used for - could anyone give me a real life example of a program where they would be used to illustrate what it is that they do?
A:
Ok ... I can't seem to find any rea... | Plugs and Sockets in python PyGTK | I'm just learning PyGTK and I came across the plug and sockets section. I don't really understand what they are used for - could anyone give me a real life example of a program where they would be used to illustrate what it is that they do?
| [
"Ok ... I can't seem to find any real life application which is already there but I can think of an example( which has been in my wishlist and to-do list since some time now ) . \nSuppose you are using stackoverflow and you want to type a reply to a question. And suppose you are also a vim user. So wouldn't you jus... | [
3,
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"sockets"
] | stackoverflow_0006525148_gtk_pygtk_python_sockets.txt |
Q:
Get index of recently appended item
Is there a straightforward way to get the index of an item I just appended to a list? I need to keep track of the last added item.
I came up with two possible solutions:
# Workaround 1
# The last added is the one at index len(li) - 1
>> li = ['a', 'b', 'c',]
>> li.append('d')
>>... | Get index of recently appended item | Is there a straightforward way to get the index of an item I just appended to a list? I need to keep track of the last added item.
I came up with two possible solutions:
# Workaround 1
# The last added is the one at index len(li) - 1
>> li = ['a', 'b', 'c',]
>> li.append('d')
>> last_index = len(li) - 1
>> last_item = ... | [
"li[-1] is the last item in the list, and hence the one that was most recently appended to its end:\n>>> li = [1, 2, 3]\n>>> li.append(4)\n>>> li[-1]\n4\n\nIf you need the index, not the item, then len(li) - 1 is just fine, and very efficient (since len(li) is computed in constant time - see below)\n\nIn the source... | [
33,
4,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006545426_list_python.txt |
Q:
trying to install lxml on max osx leopard
I have tried lots of different guides.. this one gets me the furthest..
CFLAGS="$CFLAGS -lgcrypt -fPIC" STATIC_DEPS=true easy_install-2.6 lxml
however after installing all dependencies I get this error message over and over again:
install-NRDNAB/lxml-2.3/build/tmp/lib... | trying to install lxml on max osx leopard | I have tried lots of different guides.. this one gets me the furthest..
CFLAGS="$CFLAGS -lgcrypt -fPIC" STATIC_DEPS=true easy_install-2.6 lxml
however after installing all dependencies I get this error message over and over again:
install-NRDNAB/lxml-2.3/build/tmp/libxml2/lib/pkgconfig"
/usr/bin/install -c -m 644... | [
"This worked for me:\nsudo env ARCHFLAGS=\"-arch i386 -arch x86_64\" easy_install lxml\n\n"
] | [
4
] | [] | [] | [
"django",
"lxml",
"python",
"unix"
] | stackoverflow_0006341087_django_lxml_python_unix.txt |
Q:
Updating Dictionaries in Python
I am trying to have my dictionary continuously update for as long as the loop is running, with the x and y values changing as needed. This is how I initially tried it before getting the error message and coming here.
params = urllib.urlencode({'name':'xxxxx', 'pass':'xxxxxxx', 'amo... | Updating Dictionaries in Python | I am trying to have my dictionary continuously update for as long as the loop is running, with the x and y values changing as needed. This is how I initially tried it before getting the error message and coming here.
params = urllib.urlencode({'name':'xxxxx', 'pass':'xxxxxxx', 'amount':'x', 'price':'y'})
x = math.floo... | [
"urllib.urlencode [docs] returns a string, not a dictionary. You have to call it after your loop.\nSomething like:\nparams = {'name':'xxxxx', 'pass':'xxxxxxx'}\n\nfor .....:\n params['amount'] = math.floor(first)\n params['price'] = last*1.007-last*.003\n\nparams = urllib.urlencode(params)\n\nEven better if y... | [
4,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006545862_dictionary_python.txt |
Q:
Name 'variable_name' used both as a parameter and as a global. How to fix?
The code I am working with is
build_data = {}
# Code that adds data to build_data
build_data_filtered = {}
if flag:
# Code that adds subset of build_data to build_data_filtered
global build_data
build_data = build_data_filte... | Name 'variable_name' used both as a parameter and as a global. How to fix? | The code I am working with is
build_data = {}
# Code that adds data to build_data
build_data_filtered = {}
if flag:
# Code that adds subset of build_data to build_data_filtered
global build_data
build_data = build_data_filtered
The line "global build_data" shows a code hint in pycharm
Name 'build_data'... | [
"Why are you using the global statement outside of a function?\nJust remove the line global build_data and this should work.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006546019_python.txt |
Q:
Problem in spliting columns in a row if it contains semicolon and double quote in text
I want to import few rows from csv file. The problem is there are few columns that contain semicolon and double quote in the middle of text.
And since my delimeter is ; and csv quote is ", so it splits the columns as soon as it ... | Problem in spliting columns in a row if it contains semicolon and double quote in text | I want to import few rows from csv file. The problem is there are few columns that contain semicolon and double quote in the middle of text.
And since my delimeter is ; and csv quote is ", so it splits the columns as soon as it sees ; and " in the middle of text.
My sample csv file is :
"hello";"<SPAN onmouseup="__doP... | [
"I think you have a problem with the input format, which is not proper CSV:\nQuoted from wikipedia:\n\nFields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes. [...] If a field's value contains a double quote character it is escaped by placing another double quot... | [
5
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0006545888_csv_python.txt |
Q:
Incorrect number of bindings supplied for CSV Sqlite Python script
I'm try to insert values into my sqlite table using a python script.
It was working perfectly until I tried to add another column called 'information' - it then threw the following error:
You must not use 8-bit bytestrings unless you use a text_fa... | Incorrect number of bindings supplied for CSV Sqlite Python script | I'm try to insert values into my sqlite table using a python script.
It was working perfectly until I tried to add another column called 'information' - it then threw the following error:
You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings
So I added:
conn.text_factor... | [
"It seems you are trying to re-invent the wheel a bit here :)\nTry using python's csv module; I've used it extensively and it works very well:\nhttp://docs.python.org/library/csv.html\nIt works perfectly well with properly formed csv files that have multi-line texts.\nEDIT:\nFor example, you can use the csv rows (w... | [
1
] | [] | [] | [
"csv",
"insert",
"python",
"sqlite"
] | stackoverflow_0006545847_csv_insert_python_sqlite.txt |
Q:
Drawing my own object on a layout: problem with subclassing gtk.drawable
I want to draw my own object on a layout, so I'm trying to subclass gdk.drawable,
class link(gtk.gdk.Drawable):
def __init__(self,comp1,comp2,layout):
super(link, self).__init__()
self.x1=comp1.xpos
self.y1=comp1.ypos
... | Drawing my own object on a layout: problem with subclassing gtk.drawable | I want to draw my own object on a layout, so I'm trying to subclass gdk.drawable,
class link(gtk.gdk.Drawable):
def __init__(self,comp1,comp2,layout):
super(link, self).__init__()
self.x1=comp1.xpos
self.y1=comp1.ypos
self.x2=comp2.xpos
self.y2=comp2.ypos
self.layout=layout
error... | [
"\nany alternative?\n\nIf I understand you correctly, what you want to do is not subclassing gtk.gdk.Drawable but populating a gtk.DrawingArea widget with your own content. The description of that widget is:\n\nThe gtk.DrawingArea widget is used for creating custom user interface elements. It's essentially a blank ... | [
1
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0006546447_gtk_pygtk_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.