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:
Graph, that crosses y axis
How can I draw such a graph with matplotlib?
A:
Check this example from this group
For example:
from matplotlib import pyplot as plt
import numpy as np
def line(x, slope=1, zero=0):
return zero + slope * x
x = np.array([-4,10])
y1 = line(x, 2, 2)
y2 = line(x, 1, 3)
fig = plt.fi... | Graph, that crosses y axis | How can I draw such a graph with matplotlib?
| [
"Check this example from this group\nFor example:\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ndef line(x, slope=1, zero=0):\n return zero + slope * x\n\nx = np.array([-4,10])\ny1 = line(x, 2, 2)\ny2 = line(x, 1, 3)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x,y1)\nax.plot(x,y2)\n\... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008582043_matplotlib_python.txt |
Q:
Python: calling external functions within functions
I am new to Python, and am having a problem: I want to write a function (Jacobian) which takes a function and a point as arguments, and returns the jacobian of that function at the given point.
Unsurprisingly, Jacobian relies on NumPy and SciPy. When I call Jaco... | Python: calling external functions within functions | I am new to Python, and am having a problem: I want to write a function (Jacobian) which takes a function and a point as arguments, and returns the jacobian of that function at the given point.
Unsurprisingly, Jacobian relies on NumPy and SciPy. When I call Jacobian from another script, I get either:
An error that sa... | [
"You can import at the module level and then use the imported names from inside any functions.\nOr you can import any required names directly inside a function.\nThere is one situation where you cannot use import inside a function: you are not allowed to do from somemodule import * because the Python compiler wants... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008582177_python_python_3.x.txt |
Q:
pyusb: cannot set configuration
I am trying to make a script (on linux) that can turn a light in my mouse on or off.
This is the code I have so far:
import usb.core
import usb.util
import sys
interface = 0
dev = usb.core.find(idVendor=0x1532, idProduct=0x0017)
def main():
if dev is None:
prin... | pyusb: cannot set configuration | I am trying to make a script (on linux) that can turn a light in my mouse on or off.
This is the code I have so far:
import usb.core
import usb.util
import sys
interface = 0
dev = usb.core.find(idVendor=0x1532, idProduct=0x0017)
def main():
if dev is None:
print "device not found"
else:
... | [
"Not sure if this will solve, but are the udev rules for your mouse being set up correctly? I had a similar problem with a custom device a friend did for me and I solved by adding a rule like:\nSUBSYSTEM !=\"usb_device\", ACTION !=\"add\", GOTO=\"device_rules_end\"\nSYSFS{idVendor} ==\"1532\", SYSFS{idProduct} ==\"... | [
6,
4
] | [] | [] | [
"libusb",
"python",
"pyusb",
"usb"
] | stackoverflow_0008218683_libusb_python_pyusb_usb.txt |
Q:
importing wxpython module into python
I just installed wxPython 2.8 with the following:
./configure
make
make install
Everything was installed but when I do:
import wx
in python, I get
ImportError: No module named wx
I do realize that wx is not on python's path. How can I get it on python's path? I've tried sy... | importing wxpython module into python | I just installed wxPython 2.8 with the following:
./configure
make
make install
Everything was installed but when I do:
import wx
in python, I get
ImportError: No module named wx
I do realize that wx is not on python's path. How can I get it on python's path? I've tried sys.path.append, but for some reason that doe... | [
"Since you're on Linux Mint, you can run the command sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-i18n, and that should get you going.\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008581024_python_wxpython.txt |
Q:
Error using httlib's HTTPSConnection with PKCS#12 certificate
I'm trying to use httplib's HTTPSConnection for client validation, using a PKCS #12 certificate. I know the certificate is good, as I can connect to the server using it in MSIE and Firefox.
Here's my connect function (the certificate includes the priv... | Error using httlib's HTTPSConnection with PKCS#12 certificate | I'm trying to use httplib's HTTPSConnection for client validation, using a PKCS #12 certificate. I know the certificate is good, as I can connect to the server using it in MSIE and Firefox.
Here's my connect function (the certificate includes the private key). I've pared it down to just the basics:
def connect(self, ... | [
"This is no surprise. The Python library reference docs are pretty clear about this. From http://docs.python.org/library/httplib.html:\n\nclass httplib.HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, source_address]]]]]])\n\nA subclass of HTTPConnection that uses SSL for communication with s... | [
5,
4
] | [] | [] | [
"authentication",
"certificate",
"httplib",
"pkcs#12",
"python"
] | stackoverflow_0002630011_authentication_certificate_httplib_pkcs#12_python.txt |
Q:
groking command line parameters in a python script
I am relatively new to python. I want to write a script and pass it parameters like this:
myscript.py --arg1=hello --arg2=world
In the script, I want to access the arguments arg1 and arg2. Can anyone explains how to access command line parameters in this way?
A:... | groking command line parameters in a python script | I am relatively new to python. I want to write a script and pass it parameters like this:
myscript.py --arg1=hello --arg2=world
In the script, I want to access the arguments arg1 and arg2. Can anyone explains how to access command line parameters in this way?
| [
"Argparse is part of the standard library (as of versions 2.7 and 3.2). This is the module I use to handle all my command line parsing although there is also optparse (which is now deprecated) and getopt.\nThe following is a simple example of how to use argparse:\nimport sys, argparse\n\ndef main(argv=None):\n\n ... | [
5,
2,
1,
1
] | [] | [] | [
"argparse",
"optparse",
"python"
] | stackoverflow_0008582288_argparse_optparse_python.txt |
Q:
Python ElementTree: Parsing a string and getting ElementTree instance
I have a string containing XML data that is returned from an http request.
I am using ElementTree to parse the data, and I want to then search recursively for an element.
According to this question, I can only search recursively with result.find... | Python ElementTree: Parsing a string and getting ElementTree instance | I have a string containing XML data that is returned from an http request.
I am using ElementTree to parse the data, and I want to then search recursively for an element.
According to this question, I can only search recursively with result.findall() if result is of type ElementTree rather than type Element.
Now xml.et... | [
"When you use ElementTree.fromstring() what you're getting back is basically the root of the tree, so if you create a new tree like this ElementTree.ElementTree(root) you'll get you're looking for.\nSo, to make it clearer:\nfrom xml.etree import ElementTree\ntree = ElementTree.ElementTree(ElementTree.fromstring(<yo... | [
32,
8
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0008580234_elementtree_python_xml.txt |
Q:
Transparent colormap
I would like to get a density distribution plot like this density http://www.nicolacarlon.it/out.png
with the alpha channel instead of the blue channel like this density http://www.nicolacarlon.it/out2.png
I found this code but it doesn't works :(
theCM = cm.get_cmap()
theCM._init()
... | Transparent colormap | I would like to get a density distribution plot like this density http://www.nicolacarlon.it/out.png
with the alpha channel instead of the blue channel like this density http://www.nicolacarlon.it/out2.png
I found this code but it doesn't works :(
theCM = cm.get_cmap()
theCM._init()
alphas = np.abs(np.linsp... | [
"This is a bug with the Colormap class of matplotlib. It exists in 0.99.x versions of matplotlib, but has been fixed as of 1.x. See the bug fix for a description of how it was fixed. Upgrade to the latest version and this problem should be fixed. There is not a work around for this bug, so upgrading is the only opt... | [
2
] | [] | [] | [
"color_mapping",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0008580631_color_mapping_matplotlib_numpy_python.txt |
Q:
Node.js vs Python
I'm rewriting my server and deciding between using Node.js and Python.
I prefer Javascript (as I'm extremely well versed in it) but this article is giving me pause. I'm curious if anyone has had any problems but also, I'm curious if there are any platform related virtues to one over the other. ... | Node.js vs Python | I'm rewriting my server and deciding between using Node.js and Python.
I prefer Javascript (as I'm extremely well versed in it) but this article is giving me pause. I'm curious if anyone has had any problems but also, I'm curious if there are any platform related virtues to one over the other.
Specifically, do eithe... | [
"There are two issues here:\n\nThe choice of language. You'll need to decide for yourself if you prefer python or javascript, and which one offers the libraries you want. I can't help you with that part of the decision.\nThe choice of IO model.\n\nUnlike what the article suggests a single threaded non blocking IO m... | [
19
] | [] | [] | [
"node.js",
"python",
"web_services"
] | stackoverflow_0008582127_node.js_python_web_services.txt |
Q:
Determining frequency of an array in Python
I have a sample file filled with floating point numbers as follows:
-0.02 3.04 3.04 3.02 3.02 3.06 3.04 3.02 3.04 3.02 3.04 3.02
3.04 3.02 3.04 3.04 3.04 3.02 3.04 3.02 3.04 3.02 3.04 3.02
3.06 3.02 3.04 3.02 3.04 3.02 3.02 3.06... | Determining frequency of an array in Python | I have a sample file filled with floating point numbers as follows:
-0.02 3.04 3.04 3.02 3.02 3.06 3.04 3.02 3.04 3.02 3.04 3.02
3.04 3.02 3.04 3.04 3.04 3.02 3.04 3.02 3.04 3.02 3.04 3.02
3.06 3.02 3.04 3.02 3.04 3.02 3.02 3.06 3.04 3.02 3.04 3.02
3.04 3.02 3.04 3... | [
"It's not clear from your question exactly what the values in the file represent. But assuming that they indicate consecutive voltage samples, you can load the file into a Numpy array using\nimport numpy as np\ndata = np.array([float(f) for f in file(filename).read().split()])\n\nand then compute the Fourier transf... | [
22
] | [] | [] | [
"fft",
"python",
"text_processing",
"transform"
] | stackoverflow_0008582559_fft_python_text_processing_transform.txt |
Q:
Class wrapper around file -- proper way to close file handle when no longer referenced
I've got a class that wraps some file handling functionality I need. Another class creates an instance of the filehandler and uses it for an indeterminate amount of time. Eventually, the caller is destroyed, which destroys the o... | Class wrapper around file -- proper way to close file handle when no longer referenced | I've got a class that wraps some file handling functionality I need. Another class creates an instance of the filehandler and uses it for an indeterminate amount of time. Eventually, the caller is destroyed, which destroys the only reference to the filehandler.
What is the best way to have the filehandler close the fil... | [
"__del__ is not, by itself, a bad thing. You just have to be extra careful to not create reference cycles in objects that have __del__ defined. If you do find yourself needing to create cycles (parent refers to child which refers back to parent) then you will want to use the weakref module.\nSo, __del__ is okay, ... | [
23,
8
] | [] | [] | [
"garbage_collection",
"python",
"resource_cleanup"
] | stackoverflow_0008582076_garbage_collection_python_resource_cleanup.txt |
Q:
Error: No module named staticfiles
I'm newbie with django, I'm trying to deploy my project on a production server but I'm getting this error:
Error: No module named staticfiles
When trying to start the server:
python manage.py runfcgi host=127.0.0.1 port=8081 --settings=settings
with the fastCGI + nginx
Any idea... | Error: No module named staticfiles | I'm newbie with django, I'm trying to deploy my project on a production server but I'm getting this error:
Error: No module named staticfiles
When trying to start the server:
python manage.py runfcgi host=127.0.0.1 port=8081 --settings=settings
with the fastCGI + nginx
Any idea?
Thanks!
| [
"You're probably using older version of Django. staticfiles app has been available from version 1.3 only.\n",
"You most likely need to upgrade your version of django by using setuptools\nsudo easy_install --upgrade django\n\n",
"I just remove the whole server and installed everything again, that solved everythi... | [
30,
6,
4,
3,
3
] | [] | [] | [
"deployment",
"django",
"nginx",
"python"
] | stackoverflow_0004987333_deployment_django_nginx_python.txt |
Q:
Python: instantiating new instance of class from list of classes
Disclaimer: This may be a terribly simple question but I'm attempting to learn Python.
Essentially, I have a list of classes and given a random number, I'd like to construct a new instance of the class indexed at that random number.
#The members ... | Python: instantiating new instance of class from list of classes | Disclaimer: This may be a terribly simple question but I'm attempting to learn Python.
Essentially, I have a list of classes and given a random number, I'd like to construct a new instance of the class indexed at that random number.
#The members of the list below are class objects
SHAPES = [I_shape, J_shape, L_... | [
"Given your SHAPES array, you can simply call the class object:\nnew_obj = random.choice(SHAPES)()\n\nThe random.choice(SHAPES) picks one of your I_shape, J_shape, etc, and the final () calls the constructor for that class object, just as if you had written I_shape() or whatever.\n",
"Try:\nobj = SHAPES[your_rand... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0008583175_python.txt |
Q:
Check if two math answers are equivalent
I'm writing a small app in python which lets users answer math questions. The problem I'm having is checking their answers.
Say there's a question like: "Factorise x^2 + 3x +2"
There are different ways to answer this; for example:
(x + 1)(x + 2)
(x + 2)(x + 1)
(2 + x)(x + ... | Check if two math answers are equivalent | I'm writing a small app in python which lets users answer math questions. The problem I'm having is checking their answers.
Say there's a question like: "Factorise x^2 + 3x +2"
There are different ways to answer this; for example:
(x + 1)(x + 2)
(x + 2)(x + 1)
(2 + x)(x + 1)
etc.
Is there a library which will check i... | [
"You could try using a symbolic math library like sympy.\nCall the simplify logic on both your answer and the one supplied by the user. Running the logic on both addresses this issue noted in the documentation:\n\nexact strategies this function tries can change in the future versions\n of SymPy\n\n",
"Yeah Wolf... | [
1,
0,
0,
0,
0
] | [] | [] | [
"math",
"python",
"wolframalpha"
] | stackoverflow_0008583301_math_python_wolframalpha.txt |
Q:
Interacting with 3D objects in Python 3?
I am currently in the planing stage of building an interactive periodic table of the elements program in python 3. It won't be a super advanced program, since I am only a beginner in python 3 (4-5 months of self-training).
Basically, when you click on an element of the peri... | Interacting with 3D objects in Python 3? | I am currently in the planing stage of building an interactive periodic table of the elements program in python 3. It won't be a super advanced program, since I am only a beginner in python 3 (4-5 months of self-training).
Basically, when you click on an element of the periodic table, you will look at its properties in... | [
"The easiest could be to use images and videos.\nBut if you want to manipulate 3D, there are PyOpenGL and VPython.\n",
"PyOpenGL provides low level interface to display 3D objects.\nPyOpenGL can be used with PyQt or PyGame to have a 3D display within a 2D GUI.\nEdit: there is also a build of vpython for 32bit pyt... | [
1,
0
] | [] | [] | [
"3d",
"python",
"python_3.x"
] | stackoverflow_0008583403_3d_python_python_3.x.txt |
Q:
mod_wsgi directory outside of DocumentRoot?
Should my wsgi directory be completely outside of www?
DocumentRoot /usr/local/www/
WSGIScriptAlias / /usr/local/wsgi/
Something like that, yeah?
A:
You don't need a DocumentRoot when using a WSGIScriptAlias /.
The answer to your actual question: it's probably best, y... | mod_wsgi directory outside of DocumentRoot? | Should my wsgi directory be completely outside of www?
DocumentRoot /usr/local/www/
WSGIScriptAlias / /usr/local/wsgi/
Something like that, yeah?
| [
"You don't need a DocumentRoot when using a WSGIScriptAlias /.\nThe answer to your actual question: it's probably best, yeah. I usually set the DocumentRoot to a 404 folder (folder with an index.html that shows a 404 page) and the WSGIScriptAlias to the actual script. Whether the 404 folder is actually useful? No i... | [
1
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"wsgi"
] | stackoverflow_0008583541_django_mod_wsgi_python_wsgi.txt |
Q:
Efficient way to read/write/parse large text files (python)
Say I have an absurdly large text file. I would not think my file would grow larger than ~500mb, but for the sake of scalability and my own curiosity, let's say it is on the order of a few gig.
My end goal is to map it to an array of sentences (separated ... | Efficient way to read/write/parse large text files (python) | Say I have an absurdly large text file. I would not think my file would grow larger than ~500mb, but for the sake of scalability and my own curiosity, let's say it is on the order of a few gig.
My end goal is to map it to an array of sentences (separated by '?' '!' '.' and for all intents and purposes ';') and each sen... | [
"My first thought would be to use a stream parser: basically you read in the file a piece at a time and do the statistical analysis as you go. This is typically done with markup languages like HTML and XML, so you'll find a lot of parsers for those languages out there, including in the Python standard library. A si... | [
5
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0008583136_parsing_python_regex.txt |
Q:
Convert a gray scal imageto bilevel
I'm trying to convert an image to a binary image (bilevel) using the method "point" of PIL as following:
def mappoint (i):
if i > 1: return 1
else: return 0
if __name__=="__main__":
img = Image.open('no.tif')
img = img.point(mappoint)
img.save('ok.tif')
but it g... | Convert a gray scal imageto bilevel | I'm trying to convert an image to a binary image (bilevel) using the method "point" of PIL as following:
def mappoint (i):
if i > 1: return 1
else: return 0
if __name__=="__main__":
img = Image.open('no.tif')
img = img.point(mappoint)
img.save('ok.tif')
but it gives me a black image !
EDIT: If I do def... | [
"The function did work, you've generated an image with 0s and 1s. The reason it looks black is because standard images have intensities from 0 to 255.\nAn intensity of 1 such as you've done looks black because on a scale of 0 to 255, 1 is very close to 0.\nChange your mappoint to do if i>1: return 255 if you wanted... | [
1
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0008583642_image_python_python_imaging_library.txt |
Q:
google appengine giving me DownloadError
import urllib
img = urllib.urlopen('http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|testinf foobar').read()
I am trying above code using google appengine.
Local: It is running fine.
On Delpyment: Its giving me error
Exception Type: Download... | google appengine giving me DownloadError | import urllib
img = urllib.urlopen('http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|testinf foobar').read()
I am trying above code using google appengine.
Local: It is running fine.
On Delpyment: Its giving me error
Exception Type: DownloadError
Exception Value:
ApplicationError: 2... | [
"DownloadError 2 is a timeout. Use urlfetch directly, and set a longer timeout using the deadline argument.\n"
] | [
0
] | [] | [] | [
"django",
"google_app_engine",
"python",
"urllib"
] | stackoverflow_0008582671_django_google_app_engine_python_urllib.txt |
Q:
Python Windows7: Odd behaviour opening file for append
I am seeing odd behaviour when I open a file in append mode ('a+') under Windows 7 using Python.
I was wondering whether the behaviour is in fact incorrect or I am misunderstanding how to use the following code:
log_file= open(log_file_path, "a+")
return_code ... | Python Windows7: Odd behaviour opening file for append | I am seeing odd behaviour when I open a file in append mode ('a+') under Windows 7 using Python.
I was wondering whether the behaviour is in fact incorrect or I am misunderstanding how to use the following code:
log_file= open(log_file_path, "a+")
return_code = subprocess.call(["make", target], stdout=log_file, stderr=... | [
"It looks like your problem is in the use of shell=True. From Python documentation for POpen:\n\nOn Unix, with shell=True: If args is a string, it specifies the\n command string to execute through the shell. This means that the\n string must be formatted exactly as it would be when typed at the\n shell prompt. ... | [
1,
1
] | [] | [] | [
"file_io",
"python",
"subprocess",
"windows_7"
] | stackoverflow_0007881458_file_io_python_subprocess_windows_7.txt |
Q:
circular import dependencies in a package with inheritances
I have basically the following setup in my package:
thing.py:
from otherthing import *
class Thing(Base):
def action(self):
...do something with Otherthing()...
subthing.py:
from thing import *
class Subthing(Thing):
pass
otherthing.py... | circular import dependencies in a package with inheritances | I have basically the following setup in my package:
thing.py:
from otherthing import *
class Thing(Base):
def action(self):
...do something with Otherthing()...
subthing.py:
from thing import *
class Subthing(Thing):
pass
otherthing.py:
from subthing import *
class Otherthing(Base):
def action(... | [
"This is treading into the dreaded Python circular imports argument but, IMHO, you can have an excellent design and still need circular references.\nSo, try this approach:\nthing.py:\nclass Thing(Base):\n def action(self):\n ...do something with otherthing.Otherthing()...\n\nimport otherthing\n\nsubthing.... | [
8
] | [
"Stop writing circular imports. It's simple. thing cannot possible depend on everything that's in otherthing. \n1) search for other questions exactly like yours.\n2) read those answers.\n3) rewrite otherthing so that thing depends on part of otherthing, not all of otherthing. \n"
] | [
-6
] | [
"python"
] | stackoverflow_0008582863_python.txt |
Q:
What is wrong with this matplotlib code?
I am trying to plot datetime on y axis and time on x-axis using a bar graph. I need to specify the heights in terms of datetime of y-axis and I am not sure how to do that.
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import datetime as dt
# M... | What is wrong with this matplotlib code? | I am trying to plot datetime on y axis and time on x-axis using a bar graph. I need to specify the heights in terms of datetime of y-axis and I am not sure how to do that.
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import datetime as dt
# Make a series of events 1 day apart
y = mpl.dat... | [
"I think it could be your y range.\nWhen I do your code I get a plot with the y axis ranging from about 11/Dec/2011 to 21/Dec/2011.\nHowever, you've generated dates ranging from 1/10/2009 to 15/1/2010.\nWhen I adjusted my y limits to take this into account it worked fine. I added this after the ax.bar.\nplt.ylim( (... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008584127_matplotlib_python.txt |
Q:
How can I check the syntax of Python code in Emacs without actually executing it?
Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?
A:
python -m py_compile scr... | How can I check the syntax of Python code in Emacs without actually executing it? | Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?
| [
"python -m py_compile script.py\n\n",
"You can use Pyflakes together with Flymake in order to get instant notification when your python code is valid (and avoids a few common pitfalls as well).\n",
"Or from emacs (or vim) you could run python -c 'import x' where x is the name of your file minus the .py extensio... | [
18,
8,
2,
0,
0
] | [] | [] | [
"emacs",
"python",
"syntax",
"validation"
] | stackoverflow_0000205704_emacs_python_syntax_validation.txt |
Q:
Stop pygtk GUI from locking up during long-running process
I have a process that will take a while (maybe a minute or two) to complete. When I call this from my pygtk GUI the window locks up (darkens and prevents user action) after about 10 seconds.
I'd like to stop this from happening, but I'm not sure how. I tho... | Stop pygtk GUI from locking up during long-running process | I have a process that will take a while (maybe a minute or two) to complete. When I call this from my pygtk GUI the window locks up (darkens and prevents user action) after about 10 seconds.
I'd like to stop this from happening, but I'm not sure how. I thought multithreading would be the answer, but it doesn't seem to ... | [
"Please find below a modified version of the second example that works for me:\nimport threading\nimport time\nimport gtk, gobject, glib\n\ngobject.threads_init()\n\nclass Test():\n def __init__(self):\n self.counter = 0\n self.label = gtk.Label()\n self.progress_bar = gtk.ProgressBar()\n ... | [
7,
0
] | [] | [] | [
"multithreading",
"pygtk",
"python"
] | stackoverflow_0008583975_multithreading_pygtk_python.txt |
Q:
Why can't I get the static text to print in my panel using wxpython
Here is my code
import wx
class justin(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'frame', size=(800, 500))
panel=wx.Panel(self)
panel.SetBackgroundColour("red")
self.box1=wx.Te... | Why can't I get the static text to print in my panel using wxpython | Here is my code
import wx
class justin(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'frame', size=(800, 500))
panel=wx.Panel(self)
panel.SetBackgroundColour("red")
self.box1=wx.TextCtrl(panel, -1, "type number")
self.box2=wx.TextCtrl(panel, -1... | [
"There are a few problems with your code:\n\npanel: The panel doesn't exist error is because in your code it's a variable inside the __init__ method that is no longer available in the yesitstrue method. To fix that, you have to assign it as an instance attribute in the __init__ method like this: self.panel = panel... | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008584285_python_wxpython.txt |
Q:
Python sum on keys for List of Dictionaries
Possible Duplicate:
How to sum dict elements
I have a list of dictionaries as following:
[{'Name': 'A', 'amt':100},
{'Name': 'B', 'amt':200},
{'Name': 'A', 'amt':300},
{'Name': 'C', 'amt':400},
{'Name': 'C', 'amt':500},
{'Name': 'A', 'amt':600}]
I want to sum amt... | Python sum on keys for List of Dictionaries |
Possible Duplicate:
How to sum dict elements
I have a list of dictionaries as following:
[{'Name': 'A', 'amt':100},
{'Name': 'B', 'amt':200},
{'Name': 'A', 'amt':300},
{'Name': 'C', 'amt':400},
{'Name': 'C', 'amt':500},
{'Name': 'A', 'amt':600}]
I want to sum amt for each name and get following result in list ... | [
"from collections import defaultdict\n\nc = defaultdict(int)\nfor d in list_of_dictionaries:\n c[d['Name']] += d['amt']\n\nIt produces c:\n{'A': 1000, 'C': 900, 'B': 200}\n\nTo convert it to list of dictionaries:\n[{'Name': name, 'amt': amt} for name, amt in c.items()]\n\nResult:\n[{'Name': 'A', 'amt': 1000}, {'... | [
19,
7,
2,
2,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0008584504_dictionary_list_python.txt |
Q:
Use an SQL-like function with GAE's datastore
I have a property (isFull) in a model whose value depends on other properties in that same model (counter).
So far I've been setting the property's value myself whenever any of the properties it depends on change. I wrote a function isFull() that checks the counter an... | Use an SQL-like function with GAE's datastore | I have a property (isFull) in a model whose value depends on other properties in that same model (counter).
So far I've been setting the property's value myself whenever any of the properties it depends on change. I wrote a function isFull() that checks the counter and returns True or False. But I can't use it with a ... | [
"Use a ComputedProperty to store your computed value as a property in the datastore that you can filter on.\n",
"I don't know how to automatically recalculate a property when another has changed. While you could hide some of the updating by creating a custom property you would still have to manually update it whe... | [
4,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"gql",
"python"
] | stackoverflow_0008582833_google_app_engine_google_cloud_datastore_gql_python.txt |
Q:
Is there a memory difference between single and multiple db.put_async() in a transaction?
class A(db.Model):
d = db.DateTimeProperty(auto_now=True)
class B(db.Model):
c = db.TextProperty()
def store(): #1
db.put_async(A(key_name=x,parent=key) for x in x_list) #x_list: 5000
db.put_async(B(c=y,parent=key) ... | Is there a memory difference between single and multiple db.put_async() in a transaction? | class A(db.Model):
d = db.DateTimeProperty(auto_now=True)
class B(db.Model):
c = db.TextProperty()
def store(): #1
db.put_async(A(key_name=x,parent=key) for x in x_list) #x_list: 5000
db.put_async(B(c=y,parent=key) for y in y_list) #y_list: 2500*1KB
def store(): #2
db.put_async([A(key_name=x,parent=key) fo... | [
"Since you're making asynchronous calls, and not yielding the result, neither of them will do anything. If you use synchronous calls, option 1 will theoretically use less memory, but you should test this if it's important.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008576384_google_app_engine_python.txt |
Q:
OpenCV 2.0: where is adaptors.py?
I am trying to use OpenCV 2.0 in python on a Mac. I need to be able to convert between the OpenCV IPL format and the PIL Python Imaging Library format.
The top answer on this question How do I create an OpenCV image from a PIL image? suggests using a module called "opencv.adaptors... | OpenCV 2.0: where is adaptors.py? | I am trying to use OpenCV 2.0 in python on a Mac. I need to be able to convert between the OpenCV IPL format and the PIL Python Imaging Library format.
The top answer on this question How do I create an OpenCV image from a PIL image? suggests using a module called "opencv.adaptors" to do the conversion, but since I am ... | [
"The answer you have linked is quite outdated. The reason adaptors is gone now is because it is no longer needed. Python bindings for OpenCV images now support the array interface (__array_struct__ and __array_interface__), so you should be able to just use Image.fromarray method from PIL to go one way, and cv.fr... | [
2,
0
] | [] | [] | [
"computer_vision",
"opencv",
"python"
] | stackoverflow_0008584674_computer_vision_opencv_python.txt |
Q:
Scipy label erosion
How can I keep a ring of pixels around labeled regions in a numpy array?
In a simple case, I'd subtract the erosion. That approach doesn't work when the labels touch. How can I get get B from A?
A = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0],
... | Scipy label erosion | How can I keep a ring of pixels around labeled regions in a numpy array?
In a simple case, I'd subtract the erosion. That approach doesn't work when the labels touch. How can I get get B from A?
A = array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0],
[0, 0, 2, 2, 2, ... | [
"New Answer\nActually, I just thought of a better way:\nB = A * (np.abs(scipy.ndimage.laplace(A)) > 0)\n\nAs a full example:\nimport numpy as np\nimport scipy.ndimage\n\nA = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0],\n [0, 0, 2, 2, 2, 2, 2, 2, 2... | [
2
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0008580518_numpy_python_scipy.txt |
Q:
python:class attribute/variable inheritance with polymorphism?
In my endeavours as a python-apprentice i got recently stuck at some odd (from my point of view) behaviour if i tried to work with class attributes. I'm not complaining, but would appreciate some helpful comments to shed some light on this issue.
To re... | python:class attribute/variable inheritance with polymorphism? | In my endeavours as a python-apprentice i got recently stuck at some odd (from my point of view) behaviour if i tried to work with class attributes. I'm not complaining, but would appreciate some helpful comments to shed some light on this issue.
To reduce a complex matter into a more concise question i would formulate... | [
"a1.classvar = 'aaa'\n\nThis is not a \"reference\" to a class variable.\nThat is a new instance variable in the object 'a1'. \nAn expression like A.classvar is the class variable. The class object (and it's superclasses) all have a class level dictionary (A.__dict__) with class-level objects defined in it. Name... | [
3,
1
] | [] | [] | [
"class",
"python",
"singleton"
] | stackoverflow_0008576620_class_python_singleton.txt |
Q:
error in insertion into SQL table in python because string contains %
I am writing some data into Mysql database
one of the attribute is a link for example : "http://dbpedia.org/resource/Madigan%27s_Millions"
for some insertion there is an error: error is
Error 1064: You have an error in your SQL syntax; check th... | error in insertion into SQL table in python because string contains % | I am writing some data into Mysql database
one of the attribute is a link for example : "http://dbpedia.org/resource/Madigan%27s_Millions"
for some insertion there is an error: error is
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax... | [
"Your MySQL is not having a problem with %, but with an apostrophe. Check again what exactly you're inserting (I'm pretty sure it isn't what you thought it was) by printing to stderr and inspecting the server logs, or by using your framework's logging mechanism. If I'm right, use the mysql escape function or parame... | [
2
] | [] | [] | [
"mysql_python",
"python"
] | stackoverflow_0008585470_mysql_python_python.txt |
Q:
An interpretation error for a python multithreading and multiprocessing
I want to compare multithreading and multiprocessing python program. But, I got interpretation error:
File "./parallelPython.py", line 23
time fornorm(g,range(100))
^
SyntaxError: invalid syntax
The code is as follows:
#!/... | An interpretation error for a python multithreading and multiprocessing | I want to compare multithreading and multiprocessing python program. But, I got interpretation error:
File "./parallelPython.py", line 23
time fornorm(g,range(100))
^
SyntaxError: invalid syntax
The code is as follows:
#!/usr/bin/python -tt
import numpy as np
import math
def f(x):
print x
... | [
"It looks like an Indentation error here :\ndef fornorm(f,l):\nfor i in l:\n f(i)\n\nAfter your def python is expecting an indented block.\nBy the way, time something is an IPython \"magic\" function and it won't work in a script file. You should import timeit module and use that instead. \n",
"It doesn't sa... | [
1,
1,
0
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0008585504_multiprocessing_multithreading_python.txt |
Q:
Python lists of lists order of operations
Here's a list of lists:
a = [[1,2,3],[4,5,6],[7,8,9]]
To get the number 4 from the variable 'a', I would call a[1][0] but if instead of numbers what if they were lists:
a = [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]]
To get the number 4 now, would it be a[0][1][0] or a... | Python lists of lists order of operations | Here's a list of lists:
a = [[1,2,3],[4,5,6],[7,8,9]]
To get the number 4 from the variable 'a', I would call a[1][0] but if instead of numbers what if they were lists:
a = [[[1],[2],[3]], [[4],[5],[6]], [[7],[8],[9]]]
To get the number 4 now, would it be a[0][1][0] or a[1][0][0]?
I know I can play around with it to ... | [
"Python evaluates expressions like a[1][0][0] from left to right. The parts of this expression are:\n\na which is the list [[[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]]\na[1] which is the list [[4],[5],[6]]\na[1][0] which is the list [4]\na[1][0][0] which is the integer 4.\n\n",
"Outermost to innermost -\na[1] is [... | [
8,
3,
2
] | [] | [] | [
"list",
"matrix",
"python"
] | stackoverflow_0008585614_list_matrix_python.txt |
Q:
How do I clean data from a file and get it in a dictionary?
I'm new to python and trying to read /sys/devices/system/cpu/cpuX/cpufreq/vdd_levels from a Linux system and get it into a dictionary. But how do I get rid of all the newlines, spaces and colons?
The returned data look something like this (The first numbe... | How do I clean data from a file and get it in a dictionary? | I'm new to python and trying to read /sys/devices/system/cpu/cpuX/cpufreq/vdd_levels from a Linux system and get it into a dictionary. But how do I get rid of all the newlines, spaces and colons?
The returned data look something like this (The first number is unique):
1: 11111
2: 22222
3: 33333
I have tried in every w... | [
"This takes your data in string s and puts it into a dictionary, d.\ns = '1: 11111\\n2: 22222\\n3: 33333' \nd = dict([line.split(': ') for line in s.splitlines()])\n\n",
"Something like:\ns = '1: 11111\\n2: 22222\\n3: 33333'\nd = {}\nfor e in s.split( '\\n' ):\n k, v = e.split( ': ' )\n d[ k ] = v\nprint... | [
3,
0,
0
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0008584971_python_python_2.6.txt |
Q:
How to receive/get C struct from Python
I have a standalone Python module used to perform analysis on some raw data. The module is working great.
Now I need the output generated by the Python module in C source that will do further processing on output.
Here is the rough idea of flow:
C source will call the Pytho... | How to receive/get C struct from Python | I have a standalone Python module used to perform analysis on some raw data. The module is working great.
Now I need the output generated by the Python module in C source that will do further processing on output.
Here is the rough idea of flow:
C source will call the Python module.
Python module will fill the results... | [
"I don't think you'll want to use the ctypes module — that module is for accessing DLLs and shared objects from Python code, not the other way around.\nYou don't specify how the C program is going to invoke the Python module. Will it\n\ninvoke the Python script using something like popen from C? If so, then you can... | [
3
] | [] | [] | [
"ctypes",
"python",
"struct"
] | stackoverflow_0008585910_ctypes_python_struct.txt |
Q:
pickup "unique item" of a field in a django model using python
I am learning to use django and python now and I have a little task as below:
I regular keep record of my monthly investment data, and create a django model as below:
class money_tx(models.Model):
tx_date = models.DateField()
investment_plan = ... | pickup "unique item" of a field in a django model using python | I am learning to use django and python now and I have a little task as below:
I regular keep record of my monthly investment data, and create a django model as below:
class money_tx(models.Model):
tx_date = models.DateField()
investment_plan = models.ForeignKey(investment_plan)
tx_type_choice = (
("... | [
"Here's your dataset:\nfrom itertools import groupby\n\nmoney = money_tx.objects.order_by('-tx_date')\nplans = investment_plan.objects.select_related()\nresult = []\n\nfor date, group in groupby(money, lambda x: x.tx_date):\n plans_for_date = set(x.investment_plan_id for x in group)\n for plan in plans:\n ... | [
2
] | [] | [] | [
"django",
"python",
"r",
"unique"
] | stackoverflow_0008585848_django_python_r_unique.txt |
Q:
Change the start of the year in the datetime module of Python?
Is there a way to change the start of the year in the datetime module of Python, from January to February?
I need the change because Wal-Mart starts their year the first week of February. I am writing a script that gets my schedule from their site and ... | Change the start of the year in the datetime module of Python? | Is there a way to change the start of the year in the datetime module of Python, from January to February?
I need the change because Wal-Mart starts their year the first week of February. I am writing a script that gets my schedule from their site and all their weeks are 4 weeks from the actual calender week.
| [
"You can use timedelta\nfrom datetime import datetime, timedelta\nfourweeks = datetime.now() + timedelta(weeks=4)\n\n",
"If the thing you are really looking for is to implement Chinese lunar calendar there is already an implementation called lunardate.\n"
] | [
3,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0008585367_datetime_python.txt |
Q:
How to create a custom webpage?
I am new to web designing. I want to create a web page which runs a python script in the background. The script based on the IP address of the client requesting the page will generate some urls which must be embedded in the webpage. What is the best way to do this?
Also, how can I f... | How to create a custom webpage? | I am new to web designing. I want to create a web page which runs a python script in the background. The script based on the IP address of the client requesting the page will generate some urls which must be embedded in the webpage. What is the best way to do this?
Also, how can I find the client's IP address?
| [
"You want to take a look at PEP 333, the WebServer Gateway Interface. It's what is generally used for Python scripts to communicate with webservers. You need this in order to run a python webapp.\nOn top of that you might want to use a framework like Django or Flask. There are numerous WSGI frameworks for Python, i... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0008586005_python.txt |
Q:
pylint giving a number of errors with maximum recursion depth reached
Pylint gives me an error like this very frequently.
shabda@jazzy ~/uswaretech_uswaretechsite> pylint -e utpages/forms.py
No config file found, using default configuration
Exception RuntimeError: 'maximum recursion depth exceeded while calling a ... | pylint giving a number of errors with maximum recursion depth reached | Pylint gives me an error like this very frequently.
shabda@jazzy ~/uswaretech_uswaretechsite> pylint -e utpages/forms.py
No config file found, using default configuration
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.RuntimeError'> ignored
The logalib mai... | [
"There's an open ticket about this bug. The bug report contains details about the cause.\n",
"This bug has been killed in the repository of logilab.astng (dependency of Pylint). You may want to update from source. \nlogilab-astng mercurial repository at http://www.logilab.org/cgi-bin/hgwebdir.cgi/logilab/astng\n@... | [
5,
1,
0
] | [] | [] | [
"pylint",
"python"
] | stackoverflow_0002108723_pylint_python.txt |
Q:
How to check if a line has one of the strings in a list?
Possible Duplicate:
Check if multiple strings exist in another string
I am trying to find out if there is a nice and clean way to test for 3 different strings.
Basically I am looping trough a file using a for loop; then I have to check if it contains 1 of ... | How to check if a line has one of the strings in a list? |
Possible Duplicate:
Check if multiple strings exist in another string
I am trying to find out if there is a nice and clean way to test for 3 different strings.
Basically I am looping trough a file using a for loop; then I have to check if it contains 1 of the 3 strings that I have set in a list.
So far I have found ... | [
"strings = (\"string1\", \"string2\", \"string3\")\nfor line in file:\n if any(s in line for s in strings):\n print \"yay!\"\n\n",
"This still loops through the cartesian product of the two lists, but it does it one line:\n>>> lines1 = ['soup', 'butter', 'venison']\n>>> lines2 = ['prune', 'rye', 'turkey... | [
74,
14,
4
] | [] | [] | [
"python"
] | stackoverflow_0008583615_python.txt |
Q:
global upload_to overriding in django
Let's say i have many models like that:
class ExampleModel(models.Model):
photo = models.ImageField(upload_to='photos/')
image = models.ImageField(upload_to='images/')
class AnotherExampleClass(models.Model):
another_image = models.ImageField(upload_to='another_im... | global upload_to overriding in django | Let's say i have many models like that:
class ExampleModel(models.Model):
photo = models.ImageField(upload_to='photos/')
image = models.ImageField(upload_to='images/')
class AnotherExampleClass(models.Model):
another_image = models.ImageField(upload_to='another_images/')
So, it's many different models wit... | [
"upload_to can be a callable. You know what to do next. :-)\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0008586953_django_django_models_python.txt |
Q:
webapp2 routing returns 404
I am trying to use webapp2 routing and this is currently failing. It does not seem to match the routing rules I set up and as a result returns a 404 for certain rules.
My code is like:
main.py
import webapp2, urls
app = webapp2.WSGIApplication(urls.SITE_URL_PATTERNS, debug=True... | webapp2 routing returns 404 | I am trying to use webapp2 routing and this is currently failing. It does not seem to match the routing rules I set up and as a result returns a 404 for certain rules.
My code is like:
main.py
import webapp2, urls
app = webapp2.WSGIApplication(urls.SITE_URL_PATTERNS, debug=True)
urls.py
from webapp2 impor... | [
"Okay, I found my stupid error (yes, a real \"DOH!\" moment):\nRoute(r'/<action_three:\\w+>'\n\nShould be\nRoute(r'/<action_three:[^/]+>'\n\nIt had problems matching the datastore keys as these can include other characters that are represented by \\w. Going for everything else but / will normally solve this problem... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"webapp2"
] | stackoverflow_0008579496_google_app_engine_python_webapp2.txt |
Q:
I'm tailing a file in python for any changes and it is not picking up a change to the file
Here is my script:
def tail(file, delay=0.5):
f = open(file, 'r')
f.seek(0, 2)
while True:
line = f.readline()
print 'line: ' + line
if not line:
time.sleep(delay)
... | I'm tailing a file in python for any changes and it is not picking up a change to the file | Here is my script:
def tail(file, delay=0.5):
f = open(file, 'r')
f.seek(0, 2)
while True:
line = f.readline()
print 'line: ' + line
if not line:
time.sleep(delay)
else:
print 'line found!'
When i open the file and add some lines to it, this scrip... | [
"use open('filename', 'a') instead of open('filename', 'r') for adding lines to the file ... I think you actually want to append to the file rather than reading it.\n",
"The code looks fine so there is likely a buffering issue. Try using f.read(100) instead of readline so that you read whatever is available rath... | [
1,
0
] | [] | [] | [
"file",
"python",
"readline",
"tail"
] | stackoverflow_0007931338_file_python_readline_tail.txt |
Q:
How does variable swapping work internally?
Simple and short question. Swapping two variables in Python is very easy: a, b = b, a. That's ok, I have no objections :) But I'm interested how it works internally? Does it create some temporary variable by itself or it is something more interesting (I bet so)?
A:
Pyt... | How does variable swapping work internally? | Simple and short question. Swapping two variables in Python is very easy: a, b = b, a. That's ok, I have no objections :) But I'm interested how it works internally? Does it create some temporary variable by itself or it is something more interesting (I bet so)?
| [
"Python source code is converted to bytecode before it is executed. You can see how the swap works internally by using the disassembler dis to see what the bytecode looks like:\nimport dis\n>>> def f(a,b): a, b = b, a\n>>> dis.dis(f)\n 1 0 LOAD_FAST 1 (b)\n 3 LOAD_FAST ... | [
39
] | [] | [] | [
"python"
] | stackoverflow_0008587236_python.txt |
Q:
How can I display output in a pager after a git command?
I build a script that should be used with git, so that output is sent to a pager after a git command. I would like to do this using Python.
I have a python script that writes to stdout. Now I would like to display its output in the pager the user has set in... | How can I display output in a pager after a git command? | I build a script that should be used with git, so that output is sent to a pager after a git command. I would like to do this using Python.
I have a python script that writes to stdout. Now I would like to display its output in the pager the user has set in git.
I know I could always provide a wrapper script that does... | [
"git likes to write stuff to temporary files, and then pass the name of the file on to git hooks. So following that pattern, you could just write your output to a temporary file, and call less with subprocess.Popen:\nimport subprocess\nimport tempfile\n\nlines=(str(i) for i in range(1000))\nf=tempfile.NamedTemporar... | [
2,
2
] | [] | [] | [
"git",
"pager",
"python"
] | stackoverflow_0008138206_git_pager_python.txt |
Q:
Import file by file path entered by user
I am writing tester that run user scripts:
tester d:\scripts\test_scripts_list.txt
The test_scripts_list.txt looks like this:
test1
d:\123\test2
My program reads the command line with argparse module, reads each line of the test_scripts_list.txt and import each test file ... | Import file by file path entered by user | I am writing tester that run user scripts:
tester d:\scripts\test_scripts_list.txt
The test_scripts_list.txt looks like this:
test1
d:\123\test2
My program reads the command line with argparse module, reads each line of the test_scripts_list.txt and import each test file with __import__ (that actually runs the test f... | [
"See the imp module, in particular the imp.load_module and imp.load_source functions. Here's one way you can use them (from Mercurial's source code, slightly simplified):\ndef loadpath(path):\n module_name = os.path.basename(path)[:-3]\n if os.path.isdir(path):\n # module/__init__.py style\n d, ... | [
3
] | [] | [] | [
"environment_variables",
"python",
"python_import"
] | stackoverflow_0008587146_environment_variables_python_python_import.txt |
Q:
How to correctly include javascript code in chameleon/zpt template (pyramid)?
I'm trying to embed some code between <script> </script> tags, pyramid however doesn't like it and gives me
ExpatError: not well-formed (invalid token)
Probably because i have && in my code. I tried using & instead, but then it didn... | How to correctly include javascript code in chameleon/zpt template (pyramid)? | I'm trying to embed some code between <script> </script> tags, pyramid however doesn't like it and gives me
ExpatError: not well-formed (invalid token)
Probably because i have && in my code. I tried using & instead, but then it didn't get interpreted in the browser.
The same thing happens when i try to put it in C... | [
"I think you're supposed to put && (i.e. two times the HTML entity code).\n",
"This should work:\n<script type=\"text/javascript\">\n //<![CDATA[\n // my javascript\n //]]>\n</script>\n\n",
"Have you tried adding a type attribute to your script tag?:\n<script type=\"text/javascript\">\n...\n</scrip... | [
1,
1,
0,
0
] | [] | [] | [
"javascript",
"pyramid",
"python",
"template_tal"
] | stackoverflow_0005176499_javascript_pyramid_python_template_tal.txt |
Q:
Redirecting old urls to cleaner urls
Just having some problems redirecting urls.
urls.py
url(r'^index\.asp$', views.Redirect, name='redirect'),
views.py
pageID = {
"2145841371" : "/home",
"2145887330" : "/club",
}
def Redirect(request):
pageID = request.GET.get('pageID')
return HttpResponseRedirect(redirect(pa... | Redirecting old urls to cleaner urls | Just having some problems redirecting urls.
urls.py
url(r'^index\.asp$', views.Redirect, name='redirect'),
views.py
pageID = {
"2145841371" : "/home",
"2145887330" : "/club",
}
def Redirect(request):
pageID = request.GET.get('pageID')
return HttpResponseRedirect(redirect(pageID))
Basically what I want it to do is ... | [
"A clean way to do it:\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect\n\n\n# constant name should be uppercased\nREDIRECTIONS = {\n '2145841371': reverse('home'),\n '2145887330': reverse('club'),\n 'default': '/' # put here the URL to redirect to if mismatc... | [
4,
2,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0008582434_django_django_views_python.txt |
Q:
UnboundLocalError: local variable 'conn' referenced before assignment
I have an error (shown in title) which occurs when I run this script:
import psycopg2
conn = None
conn_string = "host='localhost' dbname='localdb' user='someuser' password='abracadabra'"
def connectDb():
if conn is ... | UnboundLocalError: local variable 'conn' referenced before assignment | I have an error (shown in title) which occurs when I run this script:
import psycopg2
conn = None
conn_string = "host='localhost' dbname='localdb' user='someuser' password='abracadabra'"
def connectDb():
if conn is not None: # Error occurs on this line
return
# print the co... | [
"In python you have to declare your global variables which you want to alter in functions with the global keyword:\ndef connectDb():\n global conn\n if conn is not None: # Error occurs on this line\n return\n ...\n\nMy guess is that you are going to assign some value to conn somewhere later in the... | [
12
] | [] | [] | [
"python"
] | stackoverflow_0008587610_python.txt |
Q:
Multiprocessing Queue maxsize limit is 32767
I'm trying to write a Python 2.6 (OSX) program using multiprocessing, and I want to populate a Queue with more than the default of 32767 items.
from multiprocessing import Queue
Queue(2**15) # raises OSError
Queue(32767) works fine, but any higher number (e.g. Queue(32... | Multiprocessing Queue maxsize limit is 32767 | I'm trying to write a Python 2.6 (OSX) program using multiprocessing, and I want to populate a Queue with more than the default of 32767 items.
from multiprocessing import Queue
Queue(2**15) # raises OSError
Queue(32767) works fine, but any higher number (e.g. Queue(32768)) fails with OSError: [Errno 22] Invalid argum... | [
"One approach would be to wrap your multiprocessing.Queue with a custom class (just on the producer side, or transparently from the consumer perspective). Using that you would queue up items to be dispatched to the Queue object that you're wrapping, and only feed things from the local queue (Python list() object) ... | [
4,
2
] | [
"Working for me on MacOSX\n>>> import Queue\n>>> Queue.Queue(30000000)\n<Queue.Queue instance at 0x1006035f0>\n\n"
] | [
-2
] | [
"max_size",
"multiprocessing",
"python",
"queue"
] | stackoverflow_0005900985_max_size_multiprocessing_python_queue.txt |
Q:
django dynamic filtered form
I am converting a project from php to Django and have run into the issue of filtered menus. I have a form:
class SearchForm(forms.Form):
genus = forms.CharField(max_length=100)
# species
species = forms.CharField(max_length=100)
# island group
island_group = fo... | django dynamic filtered form | I am converting a project from php to Django and have run into the issue of filtered menus. I have a form:
class SearchForm(forms.Form):
genus = forms.CharField(max_length=100)
# species
species = forms.CharField(max_length=100)
# island group
island_group = forms.ModelChoiceField(queryset=Loca... | [
"you need to have a view for your ajax script to hit to ask for a list of names based on a group, e.g.\n# views.py\ndef ajax_endpoint(request):\n # leaving error checking to you\n group = request.GET.get('group')\n names_list = avalable_names(group) # some function or db call\n return HttpResponse(json.... | [
1,
1,
0
] | [] | [] | [
"django",
"forms",
"javascript",
"menu",
"python"
] | stackoverflow_0008579098_django_forms_javascript_menu_python.txt |
Q:
How to parse JSF style XHTML
We have a Java project which uses JSF. In our view layer we didn't use ids in all our XHTML files. What I want to do is to parse XHTML files and check for tags like
<h:inputText id="username" value="#{identity.username}"/>
The constant part is <h:input...>
The rest can be anything li... | How to parse JSF style XHTML | We have a Java project which uses JSF. In our view layer we didn't use ids in all our XHTML files. What I want to do is to parse XHTML files and check for tags like
<h:inputText id="username" value="#{identity.username}"/>
The constant part is <h:input...>
The rest can be anything like <h:inputSecret <h:inputWHATELSE... | [
"Using Beautifulsoup, you could do this as follows:\nfrom BeautifulSoup import BeautifulSoup\nimport re\n\nsoup = BeautifulSoup(<your_xml_here>)\nnodes = soup.findAll(name=re.compile('^h:input'))\nfor node in nodes:\n if 'id' not in dict(node.attrs):\n node['id'] = <whatever you need>\n\nAs it can be seen... | [
1
] | [] | [] | [
"jsf",
"parsing",
"python",
"xhtml",
"xml"
] | stackoverflow_0008587208_jsf_parsing_python_xhtml_xml.txt |
Q:
Linear X Logarithmic scale
Given a line X pixels long like:
0-------|---V---|-------|-------|-------max
If 0 <= V <= max, in linear scale V position would be X/max*V pixels.
How can I calculate the pixel position for a logarithmic scale, and starting from the pixel position how can I get back the value of V?
It... | Linear X Logarithmic scale | Given a line X pixels long like:
0-------|---V---|-------|-------|-------max
If 0 <= V <= max, in linear scale V position would be X/max*V pixels.
How can I calculate the pixel position for a logarithmic scale, and starting from the pixel position how can I get back the value of V?
It is not homework
I want to know... | [
"So you've got some arbitrary value V, and you know that 0 <= V <= Vmax. You want to calculate the x-coordinate of a pixel, call it X, where your \"screen\" has x-coordinates from 0 to Xmax. As you say, to do this the \"normal\" way, you'd do\nX = Xmax * V / Vmax\nV = Vmax * X / Xmax\n\nI like to think of it like I... | [
14,
2,
2
] | [] | [] | [
"math",
"python"
] | stackoverflow_0008586216_math_python.txt |
Q:
Google API OAuth - getting 401 (Unauthorized) when trying to upload to YouTube
The last days I've been banging my head against the wall trying to upload a movie to YouTube using its official Python Wrapper lib.
What I've succeeded till now:
Building an Request Access URL
Saving the returned OAuth Secret for a lat... | Google API OAuth - getting 401 (Unauthorized) when trying to upload to YouTube | The last days I've been banging my head against the wall trying to upload a movie to YouTube using its official Python Wrapper lib.
What I've succeeded till now:
Building an Request Access URL
Saving the returned OAuth Secret for a later use (getting the actual Access Token)
Getting an Access Token and its coupled Sec... | [
"I solved it at the end.\nOn my case it was sending an escaped token to a method which expect a raw string.\nJust make sure you have your token \"not escaped\" prior to sending them as parameters.\ngoogles OAuth tokens may include a slash which escapes as %2F \nsending such a token will bring you to a 401\n"
] | [
2
] | [] | [] | [
"gdata",
"google_api",
"python"
] | stackoverflow_0008574474_gdata_google_api_python.txt |
Q:
Django reverse url with parameters to a class based view
I just started learning python and django and I have a question.
I got the assignment to turn function views into class based views. But my links wont work now.
these are from urls.py:
url(r'^$', ContactIndex.as_view()),
url(r'^add$', ContactAdd.as_view()),
... | Django reverse url with parameters to a class based view | I just started learning python and django and I have a question.
I got the assignment to turn function views into class based views. But my links wont work now.
these are from urls.py:
url(r'^$', ContactIndex.as_view()),
url(r'^add$', ContactAdd.as_view()),
url(r'^([0-9]+)/update$', ContactUpdate.as_view()),
url(r'^([0... | [
"To make url reversing easy, I recommend that you always name your url patterns.\nurl(r'^$', ContactIndex.as_view(), name=\"contact_index\"),\nurl(r'^add$', ContactAdd.as_view(), name=\"contact_add\"),\nurl(r'^([0-9]+)/update$', ContactUpdate.as_view(), name=\"contact_update\"),\nurl(r'^([0-9]+)/view$', ContactView... | [
18
] | [] | [] | [
"django",
"django_class_based_views",
"hyperlink",
"python"
] | stackoverflow_0008588522_django_django_class_based_views_hyperlink_python.txt |
Q:
Can I enable TCPKeepAlive with paramiko?
How can I get paramiko to do the equivalent of setting "TCPKeepAlive yes" in ~/.ssh/config?
A:
Got it: Transport.set_keepalive. Use in conjunction with the timeout argument to SSHClient.connect to set the socket timeout.
| Can I enable TCPKeepAlive with paramiko? | How can I get paramiko to do the equivalent of setting "TCPKeepAlive yes" in ~/.ssh/config?
| [
"Got it: Transport.set_keepalive. Use in conjunction with the timeout argument to SSHClient.connect to set the socket timeout.\n"
] | [
2
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0008588506_paramiko_python_ssh.txt |
Q:
Using python how to execute this code concurrently for multiple files?
I want to tail multiple files concurrently and push the logs to scribe.
I am reading the files from a Config file then I want to tail each file and send the logs to scribe.
What I have tried is sends log for only the first file and doesn't fo... | Using python how to execute this code concurrently for multiple files? | I want to tail multiple files concurrently and push the logs to scribe.
I am reading the files from a Config file then I want to tail each file and send the logs to scribe.
What I have tried is sends log for only the first file and doesn't for the others.
I want to run the tailing concurrently for each file and send... | [
"Try something like this (Inspired by this)\nimport threading\n\ndef monitor_file(l): \n\n print l[0]\n print l[1]\n filename = l[1]\n file = open(filename,'r')\n st_results = os.stat(l[1])\n st_size = st_results[6]\n file.seek(st_size)\n while 1:\n where = file.tell()\n line = fil... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008588147_python.txt |
Q:
Does a Python object which doesn't override comparison operators equals itself?
class A(object):
def __init__(self, value):
self.value = value
x = A(1)
y = A(2)
q = [x, y]
q.remove(y)
I want to remove from the list a specific object which was added before to it and to which I still have a reference... | Does a Python object which doesn't override comparison operators equals itself? | class A(object):
def __init__(self, value):
self.value = value
x = A(1)
y = A(2)
q = [x, y]
q.remove(y)
I want to remove from the list a specific object which was added before to it and to which I still have a reference. I do not want an equality test. I want an identity test. This code seems to work in... | [
"Yes. In your example q.remove(y) would remove the first occurrence of an object which compares equal with y. However, the way the class A is defined, you shouldn't† ever have a variable compare equal with y - with the exception of any other names which are also bound to the same y instance. \nThe relevant sect... | [
11,
2
] | [
"The answer is yes and no.\nConsider the following example\n>>> class A(object):\n def __init__(self, value):\n self.value = value \n>>> x = A(1)\n>>> y = A(2)\n>>> z = A(3)\n>>> w = A(3)\n>>> q = [x, y,z]\n>>> id(y) #Second element in the list and y has the same reference\n46167248\n>>> id(q[1]) #... | [
-1
] | [
"equality",
"python"
] | stackoverflow_0008588890_equality_python.txt |
Q:
Is there an easy way to add permissions to a user or a group in Django?
I'm currently adding permissions to users and groups like this:
permissions = list(
Permission.objects.filter(
Q(codename='add_server', content_type=ContentType.objects.get(app_label='bildverteiler', name='server'))
| Q(codename='cha... | Is there an easy way to add permissions to a user or a group in Django? | I'm currently adding permissions to users and groups like this:
permissions = list(
Permission.objects.filter(
Q(codename='add_server', content_type=ContentType.objects.get(app_label='bildverteiler', name='server'))
| Q(codename='change_server', content_type=ContentType.objects.get(app_label='bildverteiler', ... | [
"This solution has less characters:\nquery=Q()\nfor app_labe, name in [\n ('bildverteiler', 'server'),\n ('bildverteiler', 'group'),\n ('auth', 'user')]:\n query|=Q(content_type__app_label=app_label, content_type__name=name, codname__in=['%s_%s' % (perm_name, name) for perm_name in ['change', 'add', delete'])\... | [
3
] | [] | [] | [
"authentication",
"django",
"permissions",
"python"
] | stackoverflow_0008589086_authentication_django_permissions_python.txt |
Q:
How to edit a python file in eclipse when in C++ perspective?
I use eclipse (cdt) for c++ projects. It contains some test scripts in python. Is there anyway I could get syntax highlighting and auto completion(if possible) when viewing a python script? Or should I load the complete python perspective?
A:
You can ... | How to edit a python file in eclipse when in C++ perspective? | I use eclipse (cdt) for c++ projects. It contains some test scripts in python. Is there anyway I could get syntax highlighting and auto completion(if possible) when viewing a python script? Or should I load the complete python perspective?
| [
"You can just open your python file in the C/C++ perspective and get full syntax highlighting and auto completion.\n\nIf that does not work for you, then perhaps you don't have PyDev installed. Find it and install it using Help > Eclipse Marketplace.\nIf that still does not work for you (if you double-click it the ... | [
2,
0
] | [] | [] | [
"eclipse_cdt",
"python"
] | stackoverflow_0008562189_eclipse_cdt_python.txt |
Q:
SQLAlchemy or psycopg2?
I am writing a quick and dirty script which requires interaction with a database (PG).
The script is a pragmatic, tactical solution to an existing problem. however, I envisage that the script will evolve over time into a more "refined" system. Given the fact that it is currently being put t... | SQLAlchemy or psycopg2? | I am writing a quick and dirty script which requires interaction with a database (PG).
The script is a pragmatic, tactical solution to an existing problem. however, I envisage that the script will evolve over time into a more "refined" system. Given the fact that it is currently being put together very quickly (i.e. I ... | [
"SQLAlchemy is a ORM, psycopg2 is a database driver. These are completely different things: SQLAlchemy generates SQL statements and psycopg2 sends SQL statements to the database. SQLAlchemy depends on psycopg2 or other database drivers to communicate with the database!\nAs a rather complex software layer SQLAlchem... | [
120,
11
] | [] | [] | [
"postgresql",
"psycopg2",
"python",
"sqlalchemy"
] | stackoverflow_0008588126_postgresql_psycopg2_python_sqlalchemy.txt |
Q:
Logging in Python?
I have used log4J and log4N on previous not-pythonic projects. I like heirachy of warnings,errors and escalations. The ability to log the error and if it is serious email the support team. Also automatic log file cycling is important as the it will be running on a small LINUX device.
Can I do th... | Logging in Python? | I have used log4J and log4N on previous not-pythonic projects. I like heirachy of warnings,errors and escalations. The ability to log the error and if it is serious email the support team. Also automatic log file cycling is important as the it will be running on a small LINUX device.
Can I do this with the standard Pyt... | [
"Yes, the logging module has log levels DEBUG, INFO, WARNING, ERROR and CRITICAL. You can setup a SMTPHandler to send mail when the logging level is, say, CRITICAL, and you can setup a RotatingFileHandler to limit the number and size of the log files.\n",
"The standard Python logging module is explicitly inspired... | [
11,
7
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0008589064_logging_python.txt |
Q:
How to check which checkboxes are checked or unchecked in django template?
I'm doing a small project in Django by using Python.
In that, I am dynamically populating a table with data of pending tasks. Each row of the table contains a checkbox field. According to the priority level, number of rows can be less or mo... | How to check which checkboxes are checked or unchecked in django template? | I'm doing a small project in Django by using Python.
In that, I am dynamically populating a table with data of pending tasks. Each row of the table contains a checkbox field. According to the priority level, number of rows can be less or more.
I Have to stop postback operation on submit button click event if none of th... | [
"html\n<form method=\"post\" class=\"myform\" action=\".\">\n <table>\n <tbody>\n <tr>\n <th><label for=\"checkbox1\">Checkbox 1</label></th>\n <td><input type=\"checkbox\" id=\"checkbox1\" name=\"checkbox1\" /></td>\n </tr>\n <tr>\n ... | [
0
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0008589636_django_javascript_python.txt |
Q:
How to iterate over a dictionary
In [1]: test = {}
In [2]: test["apple"] = "green"
In [3]: test["banana"] = "yellow"
In [4]: test["orange"] = "orange"
In [5]: for fruit, colour in test:
....: print(fruit)
....:
---------------------------------------------------------------------------
ValueErro... | How to iterate over a dictionary | In [1]: test = {}
In [2]: test["apple"] = "green"
In [3]: test["banana"] = "yellow"
In [4]: test["orange"] = "orange"
In [5]: for fruit, colour in test:
....: print(fruit)
....:
---------------------------------------------------------------------------
ValueError Trace... | [
"In Python 2 you'd do:\nfor fruit, color in test.iteritems():\n # do stuff\n\nIn Python 3, use items() instead (iteritems() has been removed):\nfor fruit, color in test.items():\n # do stuff\n\nThis is covered in the tutorial.\n",
"Change\nfor fruit, colour in test:\n print \"The fruit %s is the colour %... | [
31,
13,
4
] | [] | [] | [
"python"
] | stackoverflow_0008589812_python.txt |
Q:
Avoiding raw_input to take keys pressed while in a loop for windows
I am trying to make a program which has a raw_input in a loop, if anyone presses a key while the long loop is running the next raw_input takes that as input, how do I avoid that?
I don't know what else to add to this simple question. Do let me kno... | Avoiding raw_input to take keys pressed while in a loop for windows | I am trying to make a program which has a raw_input in a loop, if anyone presses a key while the long loop is running the next raw_input takes that as input, how do I avoid that?
I don't know what else to add to this simple question. Do let me know if more is required.
EDIT
Some code
for i in range(1000):
var = raw_i... | [
"This works for me with Windows 7 64bit, python 2.7.\nimport msvcrt\n\ndef flush_input():\n while msvcrt.kbhit():\n msvcrt.getch()\n\n",
"\nI put the OS in the title, window 7 64 bit to be specific. I saw the\n answers there. They do apply but by god they are so big. Aren't there\n other n00b friendly and s... | [
3,
1,
1
] | [] | [] | [
"python",
"raw_input",
"windows"
] | stackoverflow_0008587933_python_raw_input_windows.txt |
Q:
Google app engine gives me 400 bad request status code?
In google appengine:
urlfetch.fetch('http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|Tested: 21 Dec') works fine.
But when i do this way:
text = 'Tested: 21 Dec' // This ia a variable
my_url = 'http://chart.apis.google.com/c... | Google app engine gives me 400 bad request status code? | In google appengine:
urlfetch.fetch('http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|Tested: 21 Dec') works fine.
But when i do this way:
text = 'Tested: 21 Dec' // This ia a variable
my_url = 'http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|'+text
url... | [
"Not sure if this is the problem, but you should encode your strings before constructing url with them:\nimport urllib\ntext = urllib.quote_plus('Tested: 21 Dec') // This ia a variable\nmy_url = 'http://chart.apis.google.com/chart?chst=d_text_outline&chld=000000|12|h|FFFFFF|_|%s' % text\nurlfetch.fetch(my_url)\n\n... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"urllib"
] | stackoverflow_0008587712_google_app_engine_python_urllib.txt |
Q:
Unable to reference an imported module in __del__()
I'm using an object's __del__() to unsubscribe it from an event (using an event scheme similar to this):
import my_enviroment
class MyClass():
def __del__(self):
my_environment.events.my_event -= self.event_handler_func
Oddly I received the following... | Unable to reference an imported module in __del__() | I'm using an object's __del__() to unsubscribe it from an event (using an event scheme similar to this):
import my_enviroment
class MyClass():
def __del__(self):
my_environment.events.my_event -= self.event_handler_func
Oddly I received the following error at the end of the program's run:
Exception Attribu... | [
"According to the python doc about __del__ : \n\n[...] other globals referenced by the __del__() method may already have been\n deleted or in the process of being torn down (e.g. the import\n machinery shutting down). For this reason, __del__() methods should do\n the absolute minimum needed to maintain external... | [
7,
4
] | [] | [] | [
"del",
"import",
"python"
] | stackoverflow_0008590238_del_import_python.txt |
Q:
Setting a Select control in a form with Mechanize using Python
I'm trying to use mechanize to select a form
browser.select_form('frmChangeLanguage')
.. got that.
But I'm struggling with changing a drop down box within the form and then submitting the form with the new value. The control looks like this:
<table>
<... | Setting a Select control in a form with Mechanize using Python | I'm trying to use mechanize to select a form
browser.select_form('frmChangeLanguage')
.. got that.
But I'm struggling with changing a drop down box within the form and then submitting the form with the new value. The control looks like this:
<table>
<tr>
<td>
<select id="controlID" class="select" name="selectLang">
<o... | [
"According to the docs, the following should work:\nform[\"selectLang\"] = [\"1\"]\nmechanize.urlopen(form.click())\n\n"
] | [
7
] | [] | [] | [
"controls",
"forms",
"mechanize",
"python"
] | stackoverflow_0008590172_controls_forms_mechanize_python.txt |
Q:
Retrain a pybrain neural network after adding to the dataset
I have a pybrain NN up and running, and it seems to be working rather well. Ideally, I would like to train the network and obtain a prediction after each data point (the previous weeks figures, in this case) has been added to the dataset.
At the moment I... | Retrain a pybrain neural network after adding to the dataset | I have a pybrain NN up and running, and it seems to be working rather well. Ideally, I would like to train the network and obtain a prediction after each data point (the previous weeks figures, in this case) has been added to the dataset.
At the moment I'm doing this by rebuilding the network each time, but it takes an... | [
"It dependes of what is your objective. If you need an updated NN-model you can perform an online training, i.e. performing a single step of back-propagation with the sample acquired at time $t$ starting from the network you had at time $t-1$. Or maybe you can discard the older samples in order to have a fixed amou... | [
1
] | [] | [] | [
"neural_network",
"pybrain",
"python"
] | stackoverflow_0008582498_neural_network_pybrain_python.txt |
Q:
Iteration count in python?
Let's say I have a list of tuples l, and I do something like this:
for (a,b) in l:
do something with a,b, and the index of (a,b) in l
Is there an easy way to get the index of (a,b)? I can use the index method of list, but what if (a,b) is not unique? I can also iterate on the index... | Iteration count in python? | Let's say I have a list of tuples l, and I do something like this:
for (a,b) in l:
do something with a,b, and the index of (a,b) in l
Is there an easy way to get the index of (a,b)? I can use the index method of list, but what if (a,b) is not unique? I can also iterate on the indexes in the first place, but its c... | [
"Use enumerate.\nfor i, (a, b) in enumerate(l):\n # i will be the index of (a, b) in l\n\n",
"Use enumerate():\nfor i,(a,b) in enumerate(l):\n ... # `i` contains the index\n\n"
] | [
17,
16
] | [] | [] | [
"python"
] | stackoverflow_0008590810_python.txt |
Q:
Python: Does an iteration through 'list[a:b]' first copy that part of the list (which could be expensive)?
When I iterate through the values of list1 from start to stop, as in:
for value in list1[start:stop]:
....
Does python first copy that part of the list (as is done when doing list2 = list1[:])? This coul... | Python: Does an iteration through 'list[a:b]' first copy that part of the list (which could be expensive)? | When I iterate through the values of list1 from start to stop, as in:
for value in list1[start:stop]:
....
Does python first copy that part of the list (as is done when doing list2 = list1[:])? This could get very expensive for large lists!
If it doesn't copy it in the above example, does that always hold true? I... | [
"list1[start:stop] creates a new list, period. This is always the case, regardless of whether you're iterating over the result directly or have a function in between or use it in any other context (you'd need a moderately static language, or sophisticated type inference, to optimize even for simple instances of the... | [
8,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008590781_python.txt |
Q:
Do logging handlers use separate threads?
Python's logging handlers are great. Some of them, such as the SMTPHandler may take a long while to execute (contacting an SMTP server and all). Are they executed on a separate thread as to not block the main program?
A:
SMTPHandler uses smtplib and when sending an email... | Do logging handlers use separate threads? | Python's logging handlers are great. Some of them, such as the SMTPHandler may take a long while to execute (contacting an SMTP server and all). Are they executed on a separate thread as to not block the main program?
| [
"SMTPHandler uses smtplib and when sending an email with this library, your process is blocked until it have been correctly sent, no thread created.\nIf you do not want to block your process when sending an email, you'll have to implement your own SMTPHandler and override the emit(self, record) method.\nThe less bl... | [
2,
0
] | [] | [] | [
"handlers",
"logging",
"multithreading",
"python"
] | stackoverflow_0008590928_handlers_logging_multithreading_python.txt |
Q:
Using array to generate random text
I am trying to generate random text using letter frequencies that I have obtained. First, I succeeded with the following code:
for i in range(450):
outcome=random.random()
if 0<outcome<0.06775:
sys.stdout.write('a')
if 0.06775<outcome<0.07920:
sys.std... | Using array to generate random text | I am trying to generate random text using letter frequencies that I have obtained. First, I succeeded with the following code:
for i in range(450):
outcome=random.random()
if 0<outcome<0.06775:
sys.stdout.write('a')
if 0.06775<outcome<0.07920:
sys.stdout.write('b')
if 0.07920<outcome<0.0... | [
"import random\nimport sys\nimport bisect\n\nf_list = [0, 0.06775, 0.08242, 0.10199, 0.13522, 0.23703, 0.25514, 0.27324, 0.32793, 0.38483, 0.38577, 0.39278, 0.42999, 0.45023, 0.50728, 0.56756, 0.58256, 0.58391, 0.62924, 0.68509, 0.7616, 0.78481, 0.79229, 0.81161, 0.81251, 0.82718, 0.82773, 0.99998]\nalphabet = 'abc... | [
17,
2
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0008589297_arrays_python.txt |
Q:
Run a repeating task for a web app
This seems like a simple question, but I am having trouble finding the answer.
I am making a web app which would require the constant running of a task.
I'll use sites like Pingdom or Twitterfeed as an analogy. As you may know, Pingdom checks uptime, so is constantly checking web... | Run a repeating task for a web app | This seems like a simple question, but I am having trouble finding the answer.
I am making a web app which would require the constant running of a task.
I'll use sites like Pingdom or Twitterfeed as an analogy. As you may know, Pingdom checks uptime, so is constantly checking websites to see if they are up and Twitterf... | [
"If you need a repeatable running of the task which can be run from command line - that's what the cron is ideal for.\nI don't see any demerits of this approach.\nUpdate:\nOkay, I saw the issue somewhat different. Now I see several solutions: \n\nrun the cron task at set intervals, let it process the data once per ... | [
1,
1
] | [] | [] | [
"cron",
"python"
] | stackoverflow_0008591076_cron_python.txt |
Q:
python get file folder location and file with glob
hello im doing a search in my views for .opt.php files that are compiled.
currently im doing something like this
for x in glob.glob(PATH_VIEWS + '*.opt.php'):
# Get file names
segment1 = x.split('/')
filename = segment1[-1]
realname = filename.spl... | python get file folder location and file with glob | hello im doing a search in my views for .opt.php files that are compiled.
currently im doing something like this
for x in glob.glob(PATH_VIEWS + '*.opt.php'):
# Get file names
segment1 = x.split('/')
filename = segment1[-1]
realname = filename.split('.opt.php')
appfolder = segment1[-4]
folder =... | [
"If you want to get the basename and the dirname you can use os.path.split():\nhttp://docs.python.org/library/os.path.html#os.path.split\nBTW: glob() only works if directory depth is fixed. Use os.walk() if you want something like the unix \"find\" command (recursive directory walk).\nimport os, glob\nmagic='.log'\... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008590813_python.txt |
Q:
How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link?
I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but ... | How do I scroll a wxPython wx.html.HtmlWindow back down to where it was when the user clicked a link? | I am using a wxPython wx.html.HtmlWindow to display part of my interface. The user can scroll down a list of links in a window smaller than the list. When they click on a link, I need to repaint the web page, but I want to return the page position back to where they clicked it.
I've tried MouseEvent.GetLogicalPosition... | [
"how about having a look at the source of wxHtmlWindow for inspiration? for example at wxHtmlWindow::LoadPage(): it\n// store[s the current] scroll position into history item:\nint x, y;\nGetViewStart(&x, &y);\n(*m_History)[m_HistoryPos].SetPos(y);\n\nthis saved scroll position is used in wxHtmlWindow::HistoryBack(... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001400179_python_wxpython.txt |
Q:
Python/Gridspec height_ratio issue
I'm very new to python and matplotlib and having trouble with adjusting the height of a 2 plot subplot window. I'm trying to make the subplots aligned vertically, with one directly on top of the other. The subplot on the bottom should be half the height as the one on top. If I... | Python/Gridspec height_ratio issue | I'm very new to python and matplotlib and having trouble with adjusting the height of a 2 plot subplot window. I'm trying to make the subplots aligned vertically, with one directly on top of the other. The subplot on the bottom should be half the height as the one on top. If I try and use width_ratios I get exactly ... | [
"These two have a ratio 3:1:\nimport matplotlib.pyplot as plt\n\n# left bott width height\nrect_bot = [0.1, 0.1, 0.8, 0.6]\nrect_top = [0.1, 0.75, 0.8, 0.2]\n\nplt.figure(1, figsize=(8,8))\n\nbot = plt.axes(rect_bot)\ntop = plt.axes(rect_top)\n\nbot.plot([3, 2, 60, 4, 7])\ntop.plot([2, 3, 5, 3, 2, 4, 6... | [
3,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008583281_matplotlib_python.txt |
Q:
NLTK context-free grammars
I am just wondering how would you add an optional grammer in the rule
>>> import nltk
>>> nltk.app.rdparser()
For example, the normal way to add a optional grammer is by putting it in parentheses: NP -> NP (PP)
But in the program how would you do it? parentheses doesnt work.
S Þ NP ... | NLTK context-free grammars | I am just wondering how would you add an optional grammer in the rule
>>> import nltk
>>> nltk.app.rdparser()
For example, the normal way to add a optional grammer is by putting it in parentheses: NP -> NP (PP)
But in the program how would you do it? parentheses doesnt work.
S Þ NP VP
NP Þ NP PP | Det N
VP Þ V N... | [
"NP -> NP | NP PP\n\nBut note that, with this rule, you can stack NP nodes indefinitely in the parse tree.\n"
] | [
2
] | [] | [] | [
"context_free_grammar",
"nlp",
"nltk",
"python"
] | stackoverflow_0008591562_context_free_grammar_nlp_nltk_python.txt |
Q:
Learn GIS with Python
I've been wanting to learn GIS, I already know lots of python, so I've been looking for online free sources to learn GIS.
Anyone one out there knows any good information to start with? tutorials? excercises?
Thank you!
A:
Youll be glad to know that there is a Stack exchange site dedicated t... | Learn GIS with Python | I've been wanting to learn GIS, I already know lots of python, so I've been looking for online free sources to learn GIS.
Anyone one out there knows any good information to start with? tutorials? excercises?
Thank you!
| [
"Youll be glad to know that there is a Stack exchange site dedicated to GIS (Here), you could ask more specific questions there.\nAs for a specific answer to your very broad question - Have you got an idea what GIS Program do you plan to learn (do you plan on buying for yourself a full-cost program (which can be qu... | [
4,
1,
1,
1,
0
] | [] | [] | [
"geocoding",
"geolocation",
"geospatial",
"python"
] | stackoverflow_0005249952_geocoding_geolocation_geospatial_python.txt |
Q:
Catch SysLogHandler's output
Following advice, I'm planning to log errors from several time critical python processes (clients) to a single logging process (server). SysLogHandler seems to be the correct choice as it uses UDP (I rather be system-agnostic) and does not wait for any confirmation, and as I'm using lo... | Catch SysLogHandler's output | Following advice, I'm planning to log errors from several time critical python processes (clients) to a single logging process (server). SysLogHandler seems to be the correct choice as it uses UDP (I rather be system-agnostic) and does not wait for any confirmation, and as I'm using localhost so there should practicall... | [
"Well, to continue with advices ( ;) ), take a look to rsyslog, this is the most powerfull syslog server I know. \nIt support threaded logging facilities, massive load and mail sending.\n"
] | [
2
] | [] | [] | [
"connection",
"handlers",
"logging",
"multiprocessing",
"python"
] | stackoverflow_0008591567_connection_handlers_logging_multiprocessing_python.txt |
Q:
python pyinotify event from externally created file
I have a pyinotify instance watching a mounted network drive (mounted with CIFS) for IN_WRITE_CLOSE events which picks up the system created events (sudo cp, sudo mv, etc.) flawlessly if the server itself puts files in this directory.
However, I would like to pic... | python pyinotify event from externally created file | I have a pyinotify instance watching a mounted network drive (mounted with CIFS) for IN_WRITE_CLOSE events which picks up the system created events (sudo cp, sudo mv, etc.) flawlessly if the server itself puts files in this directory.
However, I would like to pick up the events for files that are created on this networ... | [
"According to this thread on the linux cifs client, this wasn't implemented (nor really scheduled) in 2009.\nFor the NFS part, well, it works on NFS mount, but only if the listener is the same machine than the creater/modifer/deleter of the file.... :( (source here)\nLast, I ended by founding a hook (just here), th... | [
1
] | [] | [] | [
"inotify",
"network_drive",
"python"
] | stackoverflow_0008591510_inotify_network_drive_python.txt |
Q:
Automatically expand canvas for long lines
How to expand (vertically) figure/plot/figure when adding text using figtext()?
The code is something like this:
plt.figtext(0.5 ,0, u'first line\nsecond line\nthird line', ha='center')
So I need to image automatically expanded to fit plot, x-axis label and the figtext. ... | Automatically expand canvas for long lines | How to expand (vertically) figure/plot/figure when adding text using figtext()?
The code is something like this:
plt.figtext(0.5 ,0, u'first line\nsecond line\nthird line', ha='center')
So I need to image automatically expanded to fit plot, x-axis label and the figtext. Currently text first line\nsecond line\nthird li... | [
"There is no automatic way to do this, as of yet, because there are many possible questions to consider, e.g. which Artists belonging to the figure should be considered when adjusting the subplots?\nThis is something you can do manually, for now, on a case by case basis. You need to know the size of the box contain... | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008587543_matplotlib_python.txt |
Q:
Decompress stdout from a subprocess Popen call using gzip
is it possible to directly decompress, using gzip, the stdout of a command fired via subprocess.Popen ?
I've tried this, but it's not working :
import subprocess
pipe = subprocess.Popen(["cat tmp.txt | gzip --stdout"], stdout=subprocess.PIPE)
import gzip
o... | Decompress stdout from a subprocess Popen call using gzip | is it possible to directly decompress, using gzip, the stdout of a command fired via subprocess.Popen ?
I've tried this, but it's not working :
import subprocess
pipe = subprocess.Popen(["cat tmp.txt | gzip --stdout"], stdout=subprocess.PIPE)
import gzip
output = gzip.open(pipe.stdout)
while output.readline().rstrip(... | [
"One can pass an open file instead of a filename to Python's gzip library by creating\na gzip.GzipFile instance directly, instead of using the helper gzip.open function. However, Python's gzip needs a seekable file, and will fail on the stream used by subprocess.\nThe way to create the GzipFile instance is\noutput ... | [
2
] | [] | [] | [
"gzip",
"iostream",
"pipe",
"python",
"subprocess"
] | stackoverflow_0008591017_gzip_iostream_pipe_python_subprocess.txt |
Q:
I cannot scrape anything with BeautifulSoup
Im using BeautifulSoup to scrape some web contents.
Im learning with this example code,but I always get a "None" response.
Code:
import urllib2
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-p... | I cannot scrape anything with BeautifulSoup | Im using BeautifulSoup to scrape some web contents.
Im learning with this example code,but I always get a "None" response.
Code:
import urllib2
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://www.velocidadcuchara.com/2011/08/helado-platano-light.html').read())
post = soup.find('di... | [
"Something weird with your HTML. BeautifulSoup tries its best, but sometimes it just can't parse it.\nTry moving the first <link> element inside the <head>, that might help.\n",
"I don't think you are doing anything wrong.\nIt is the second script tag that is confusing BeautifulSoup. The tag looks like this:\n<sc... | [
1,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0007106578_beautifulsoup_python.txt |
Q:
deploying a python web application
hi every one I was wondering how to go about deploying a small time python database web application. Is buying some cheap hardware and installing a server good on it a good route to go?
A:
You can get a virtual server instance on amazon or rackspace or many others for a very sm... | deploying a python web application | hi every one I was wondering how to go about deploying a small time python database web application. Is buying some cheap hardware and installing a server good on it a good route to go?
| [
"You can get a virtual server instance on amazon or rackspace or many others for a very small fee per month, $20 - $60. This will give you a clean install of the OS of your choice. No need to invest in hardware. From there you can follow any of the many many tutorials on deploying a django app.\n"
] | [
0
] | [] | [] | [
"python",
"web"
] | stackoverflow_0008591602_python_web.txt |
Q:
OpenSSL in Python 2.5.2 not working
I am attempting to build Python 2.5.2 with SSL as a separate binary using
./configure
make
make altinstall (with and without the -lssl option)
I did check first that I have openSSL both the regular and development package:
$ dpkg --get-selections | grep ssl
libio-socket... | OpenSSL in Python 2.5.2 not working | I am attempting to build Python 2.5.2 with SSL as a separate binary using
./configure
make
make altinstall (with and without the -lssl option)
I did check first that I have openSSL both the regular and development package:
$ dpkg --get-selections | grep ssl
libio-socket-ssl-perl
libnet-ssleay-perl
libssl-d... | [
"SSL support in httplib.HTTPSConnection (and others) and the ssl module are two different things.\nYou probably have enabled SSL for the SSL-enabled libraries. However, there is no ssl module for Python 2.5. Instead, you may want to use the OpenSSL module, which provides similar features.\nIf you want the code that... | [
0
] | [] | [] | [
"linux",
"openssl",
"python",
"ssl"
] | stackoverflow_0008585375_linux_openssl_python_ssl.txt |
Q:
PyQt QTreeWidget.clear() causes crash
I've got python 2.5 and PyQt 4.8.6 installed. Os - Windows Xp Sp2. I use the following code to fill TreeWidget:
def updateTreeWidget(self, widget, results):
""" Updates the widget with given results """
widget.clear()
for item in results:
te... | PyQt QTreeWidget.clear() causes crash | I've got python 2.5 and PyQt 4.8.6 installed. Os - Windows Xp Sp2. I use the following code to fill TreeWidget:
def updateTreeWidget(self, widget, results):
""" Updates the widget with given results """
widget.clear()
for item in results:
temp = QtGui.QTreeWidgetItem()
j ... | [
"Updating GUI elements from a thread that is not the same as Qt's event loop is a big no-no.\nThe customary way to solve this is to used a queued signal/slot connection or a singleshot QTimer to pass thread boundaries and execute your function on the main thread.\n"
] | [
3
] | [] | [] | [
"crash",
"pyqt",
"python",
"qt",
"qtreewidget"
] | stackoverflow_0008590459_crash_pyqt_python_qt_qtreewidget.txt |
Q:
Conditionally continuing with Python unit tests
I have a test rig with three sets of tests for a sudoku solver:
Test most functions individually
Test the final few functions, which use those in step 1
Test the final few functions with 95 harder puzzles
As step 3 takes a while, I'm looking for a way to only go to... | Conditionally continuing with Python unit tests | I have a test rig with three sets of tests for a sudoku solver:
Test most functions individually
Test the final few functions, which use those in step 1
Test the final few functions with 95 harder puzzles
As step 3 takes a while, I'm looking for a way to only go to the next step if all the previous steps passed. Is i... | [
"Using doctest\nIf you wish to use doctest, then treat it just as Python IDLE (see doctest documentation for tips on how to prepare tests), assign results of the previous tests to some variables and then use conditional checks for determining whether you wish to execute other tests. Just like that.\nUnfortunately i... | [
8,
3
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0008590850_python_unit_testing.txt |
Q:
Role-based access control with Pyramid
I am considering using Pyramid to build a middle sized web application. I would need to implement RBAC. What would be the best choice? Would it be possible to use Zope components?
A:
Well Pyramid implements an ACL authorization policy which maps principals to permissions.
... | Role-based access control with Pyramid | I am considering using Pyramid to build a middle sized web application. I would need to implement RBAC. What would be the best choice? Would it be possible to use Zope components?
| [
"Well Pyramid implements an ACL authorization policy which maps principals to permissions. \n\nPrincipals are configurable by you to mean whatever you like and are derived from the request (user) itself.\nA permission is a string attached to an individual view or \"operation\".\n\nMaybe I'm wrong, but RBAC seems to... | [
3
] | [] | [] | [
"pyramid",
"python",
"rbac",
"zope"
] | stackoverflow_0008592444_pyramid_python_rbac_zope.txt |
Q:
Capturing x,y Coordinates with Python PIL
I want to display an image to the user with PIL and when the user clicks anywhere on this image, I want a def onmousedown(x,y) to be called. I will do some extra stuff in this function. How can I do this in PIL?
Thanks,
A:
PIL won't do it alone -- PIL is an image manip... | Capturing x,y Coordinates with Python PIL | I want to display an image to the user with PIL and when the user clicks anywhere on this image, I want a def onmousedown(x,y) to be called. I will do some extra stuff in this function. How can I do this in PIL?
Thanks,
| [
"PIL won't do it alone -- PIL is an image manipulation library with no User Interfaces - it does have a showmethod, which does open an external program which displays the image, but does not communicate back with the Python process.\nTherefore, in order to be able to get a user to interact with an image, one does h... | [
10,
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0008590234_python_python_imaging_library.txt |
Q:
Changing foreign key to another model
I have a model:
class myModels(model.Model):
handler = models.ForeignKey(User, blank=True, null=True)
The foreign key hasn't been used so it's always null. Now I want to use it as a foreign key to another model, like this:
handler = models.ForeignKey(Something, blank=Tr... | Changing foreign key to another model | I have a model:
class myModels(model.Model):
handler = models.ForeignKey(User, blank=True, null=True)
The foreign key hasn't been used so it's always null. Now I want to use it as a foreign key to another model, like this:
handler = models.ForeignKey(Something, blank=True, null=True)
I'm using MySQL.The handler... | [
"You can do ./manage.py reset yourapp which will drop the tables of your app, then you'd syncdb again. That's what I do during development because it's quick and easy.\nThere are many other ways: you can install django-extensions, run command ./manage.py sqldiff yourapp, and then run the generated SQL, which will m... | [
3
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0008592700_django_mysql_python.txt |
Q:
data cache for python package
I have a python module which generates large data files which I want to cache on disk for future use. The cache is likely to end up some hundreds of MB for a normal user, but save a lot of computation time.
The files aren't distributed with the module, but are generated the first time... | data cache for python package | I have a python module which generates large data files which I want to cache on disk for future use. The cache is likely to end up some hundreds of MB for a normal user, but save a lot of computation time.
The files aren't distributed with the module, but are generated the first time the code is run with a given set o... | [
"You can use the standard library module ConfigParser to parse an ini file (or .rc file depending on your culture). To find the file, os.path.expanduser is a useful function that does the right thing on all platforms for paths like \"~/.mytoolrc\". To let the user override the location of things, you can use envi... | [
3,
2
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0001874737_distutils_python.txt |
Q:
Python: os.system() without return or error
I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window. Is there a way to do this? I guess it's sort of like silent commands, running to their full extent, but not returning any text. I can't use 'try... | Python: os.system() without return or error | I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window. Is there a way to do this? I guess it's sort of like silent commands, running to their full extent, but not returning any text. I can't use 'try', because it's not a Python error.
| [
"You could redirect the command's standard error away from the terminal. For example:\n# without redirect\nIn [2]: os.system('ls xyz')\nls: cannot access xyz: No such file or directory\nOut[2]: 512\n\n# with redirect\nIn [3]: os.system('ls xyz 2> /dev/null')\nOut[3]: 512\n\nP.S. As pointed out by @Spencer Rathbun, ... | [
4,
2
] | [] | [] | [
"bash",
"error_handling",
"python",
"subprocess",
"system"
] | stackoverflow_0008592762_bash_error_handling_python_subprocess_system.txt |
Q:
Matplotlib.pyplot on OS X with 64-bit Python from Python.org
I just installed numpy and matplotlib on my OS X 10.6.6. I have Python 2.7 from Python.org. When I do an import matplotlib.pyplot, I get the following error:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-package... | Matplotlib.pyplot on OS X with 64-bit Python from Python.org | I just installed numpy and matplotlib on my OS X 10.6.6. I have Python 2.7 from Python.org. When I do an import matplotlib.pyplot, I get the following error:
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/_path.so, 2): no suitable image found. Did find:
... | [
"If you want an easy, out of the box solution: The Enthought Python Distribution 7.0 (64-bit academic version) worked great for me on Mac OS X Leopard, including Python 2.7, numpy, and matplotlib: https://www.enthought.com/products/epd.php\n",
"According to this mailing list message, the current matplotlib versio... | [
2,
1,
0,
0
] | [] | [] | [
"macos",
"matplotlib",
"python"
] | stackoverflow_0005419439_macos_matplotlib_python.txt |
Q:
Multiple instances of subprocess.Popen
Hi I have just started programming in python and I am trying to use subprocess.Popen to run multiple instances of a program that i compile using "make". But before i do a "make", I have to do some text processing and generate a set of files that "make" will use. Now I would l... | Multiple instances of subprocess.Popen | Hi I have just started programming in python and I am trying to use subprocess.Popen to run multiple instances of a program that i compile using "make". But before i do a "make", I have to do some text processing and generate a set of files that "make" will use. Now I would like to run the same program with different g... | [
"If your system has multiple processors or cores you can take advantage of that by using the multiprocessing module to run Python functions concurrently:\nimport multiprocessing as mp\n\ndef run_mc(mC):\n print \"Simulation Number\", str(mC+1), \"of\", str(monteCarlo)\n ...\n call([\"make\"])\n fRate = ... | [
1
] | [] | [] | [
"multiprocess",
"popen",
"python",
"subprocess"
] | stackoverflow_0008592813_multiprocess_popen_python_subprocess.txt |
Q:
Python - RelaxNG object model generator / parser
Say I have this XML:
<domain type='qemu' xmlns:qemu='http://libirt.org/schemas/domain/qemu/1.0'>
<name>QEmu-fedora-i686</name>
<memory>219200</memory>
<os>
<type arch='i686' machine='pc'>hvm</type>
</os>
<devices>
<emulator>/usr/bin/qemu-system-x86... | Python - RelaxNG object model generator / parser | Say I have this XML:
<domain type='qemu' xmlns:qemu='http://libirt.org/schemas/domain/qemu/1.0'>
<name>QEmu-fedora-i686</name>
<memory>219200</memory>
<os>
<type arch='i686' machine='pc'>hvm</type>
</os>
<devices>
<emulator>/usr/bin/qemu-system-x86_64</emulator>
</devices>
<qemu:commandline>
<... | [
"If you're able to convert rng to xsd (check out the conversions links on relaxng website), you could use generateDS project.\n\nUse generateDS to convert xsd files into an importable python file containing all the classes.\nIn the generate python file, you can use parse(), and it will give you a root python object... | [
1,
0
] | [] | [] | [
"lxml",
"python",
"relaxng",
"xsd"
] | stackoverflow_0008592081_lxml_python_relaxng_xsd.txt |
Q:
Retrieve ONLY new message from email
I am trying to retrieve messages from an email address using Imaplib, so far i have been able to retrieve the messages, however, i am only interested in the original message, meaning that if the message is a "Re:" then i don't want the previous messages, i want only the new one... | Retrieve ONLY new message from email | I am trying to retrieve messages from an email address using Imaplib, so far i have been able to retrieve the messages, however, i am only interested in the original message, meaning that if the message is a "Re:" then i don't want the previous messages, i want only the new one, is this possible ?
heres what i get from... | [] | [] | [
"Google comes up with\nimport imaplib\nconn = imaplib.IMAP4_SSL(host='mail.example.com')\n# or conn =imaplib.IMAP4(host='mail.example.com') for no SSL \ntry: \n (retcode, capabilities) = conn.login('user', 'pass') \nexcept: \n # cannot login\nconn.select(readonly=1) # Select inbox or default namespace \n(retc... | [
-1
] | [
"imap",
"imaplib",
"python"
] | stackoverflow_0008381262_imap_imaplib_python.txt |
Q:
Issue in build and install python3.2 in mac osx lion
I using Mac OSX Lion and I could easily install python3.2 using DMG installer setup available in python.org site.
But i want to write some python-C functions and create a binary for it.
So for this purpose i tried to install python3.2 zip available in python.org... | Issue in build and install python3.2 in mac osx lion | I using Mac OSX Lion and I could easily install python3.2 using DMG installer setup available in python.org site.
But i want to write some python-C functions and create a binary for it.
So for this purpose i tried to install python3.2 zip available in python.org site.
Instead stuck with installation errors when I use f... | [
"Works for me. It seems very suspicious that you are seeing a syntax error on an Apple-supplied OS X header file. What version of Xcode do you have installed and which C compiler are you using (gcc --version)? Also, if your purpose is to build C extension modules there is normally no reason to build a Python fro... | [
0
] | [] | [] | [
"installation",
"python",
"python_3.2"
] | stackoverflow_0008592228_installation_python_python_3.2.txt |
Q:
How to print a string without including '\n' in Python
Suppose my string is:
' Hai Hello\nGood eve\n'
How do I eliminate the '\n' in between and make a string print like :
Hai Hello Good eve
?
A:
If you don't want the newline at the end of the print statement:
import sys
sys.stdout.write("text")
A:
You can... | How to print a string without including '\n' in Python | Suppose my string is:
' Hai Hello\nGood eve\n'
How do I eliminate the '\n' in between and make a string print like :
Hai Hello Good eve
?
| [
"If you don't want the newline at the end of the print statement:\nimport sys\nsys.stdout.write(\"text\")\n\n",
"You can use the replace method:\n>>> a = \"1\\n2\"\n>>> print a\n1\n2\n>>> a = a.replace(\"\\n\", \" \")\n>>> print a\n1 2\n\n",
"In Python 2.6:\nprint \"Hello.\",\nprint \"This is on the same line\"... | [
23,
21,
11,
4,
3,
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0000511204_python_string.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.