content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How does one alter a FileField of an object in Django?
I have a model called ClassFile that takes a FileField (document):
class ClassFile(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, editable=False)
document = models.FileField(upload_to="classFiles/%Y/%m/%d/")
description = model... | How does one alter a FileField of an object in Django? | I have a model called ClassFile that takes a FileField (document):
class ClassFile(models.Model):
timestamp = models.DateTimeField(auto_now_add=True, editable=False)
document = models.FileField(upload_to="classFiles/%Y/%m/%d/")
description = models.TextField('File description', max_length=500)
shown = ... | [
"The key for your file is the field name document (not file), and it's better to use cleaned_data:\ndocument = form.cleaned_data['document']\n\nform.cleaned_data['document'] (or request.FILES['document']) return a UploadedFile object.\n"
] | [
0
] | [] | [] | [
"django",
"django_file_upload",
"python"
] | stackoverflow_0006392668_django_django_file_upload_python.txt |
Q:
Nested Python class needs to access variable in enclosing class
I've seen a few "solutions" to this, but the solution every time seems to be "Don't use nested classes, define the classes outside and then use them normally". I don't like that answer, because it ignores the primary reason I chose nested classes, whi... | Nested Python class needs to access variable in enclosing class | I've seen a few "solutions" to this, but the solution every time seems to be "Don't use nested classes, define the classes outside and then use them normally". I don't like that answer, because it ignores the primary reason I chose nested classes, which is, to have a pool of constants (associated with the base class) a... | [
"Despite my \"bit patronizing\" comment (fair play to call it that!), there are actually ways to achieve what you want: a different avenue of inheritance. A couple:\n\nWrite a decorator that introspects a class just after it's declared, finds inner classes, and copies attributes from the outer class into them.\nDo... | [
11,
7,
2,
1,
0,
0
] | [] | [] | [
"nested_class",
"python",
"scope"
] | stackoverflow_0006391645_nested_class_python_scope.txt |
Q:
Python scatter plot with numpy-masked arrays
I'm stuck trying to mask data for a scatter plot. All data seems to plot.
I'm using numpy arrays as shown in the snippet below. I'm thinking that perhaps I cannot mask on the "c" array. I can't seem to find any documentation for doing this. I'll try with the "s" arr... | Python scatter plot with numpy-masked arrays | I'm stuck trying to mask data for a scatter plot. All data seems to plot.
I'm using numpy arrays as shown in the snippet below. I'm thinking that perhaps I cannot mask on the "c" array. I can't seem to find any documentation for doing this. I'll try with the "s" array.
Any help is greatly appreciated.
yy = NP.ma.a... | [
"Works for me. Each call to scatter() gets its own colorbar since each scatter()'s colors are normalized to its own data. Which version of matplotlib are you using?\nimport pylab as plt\nimport numpy as np\n\nx = np.linspace(0, 1, 100)\ny = x**2\nz = y\nz_masked = np.ma.masked_where(z > 0.5, z)\n\nplt.scatter(x, ... | [
1
] | [] | [] | [
"numpy",
"plot",
"python",
"scatter"
] | stackoverflow_0006392719_numpy_plot_python_scatter.txt |
Q:
linkedin from python : unable to send multiple messages
I want to send messages to multiple friends in linkedin using python.
from docs : http://code.google.com/p/python-linkedin/
Using this one can send that.
result = api.SendMessage("This is a subject", "This is the body", ["ID1", "ID2", "ID3"])
But I am not ... | linkedin from python : unable to send multiple messages | I want to send messages to multiple friends in linkedin using python.
from docs : http://code.google.com/p/python-linkedin/
Using this one can send that.
result = api.SendMessage("This is a subject", "This is the body", ["ID1", "ID2", "ID3"])
But I am not able to use that. Can anyyone tell me what is ID1? ID2? etc?
| [
"You can only message first degree connections. So, to get valid ids, I'm guessing the code looks something like:\n>>> connections = api.Getconnections() # connections is a list of Profile instances\n>>> connections\n>>> [<linkedin.linkedin.Profile object at 0x1a3d510>]\n>>> connections[0].id\n>>> 'js6vz2-D6x'\n>>>... | [
2,
1
] | [] | [] | [
"linkedin",
"python"
] | stackoverflow_0006375938_linkedin_python.txt |
Q:
How to access linkedin from python command
I want to access my linkedin account from command prompt and then i wanted to send mails from my account using command.
Also, I need the delivery reports of the mails.
Can anyone knows how can use that?
A:
The Member to Member API will return a 2xx status code if your m... | How to access linkedin from python command | I want to access my linkedin account from command prompt and then i wanted to send mails from my account using command.
Also, I need the delivery reports of the mails.
Can anyone knows how can use that?
| [
"The Member to Member API will return a 2xx status code if your message is accepted by LinkedIn. And a 4xx status code if there's an error.\nThis means the message was put into the LinkedIn system, not that it has been opened, read, emailed, etc. You cannot get that via the API.\n",
"A simple Google search gives ... | [
4,
1
] | [] | [] | [
"command",
"linkedin",
"python"
] | stackoverflow_0006373779_command_linkedin_python.txt |
Q:
How to install xbmc module for Python
I tried to find the setup script from xbmcscripts.com but apparently that site is down. Neither 'easy_install' gives a desirable result. I'm running Ubuntu 11.04 and xbmc (Media Center) is installed and working alright. What I basically need is the ability to import the xbmc m... | How to install xbmc module for Python | I tried to find the setup script from xbmcscripts.com but apparently that site is down. Neither 'easy_install' gives a desirable result. I'm running Ubuntu 11.04 and xbmc (Media Center) is installed and working alright. What I basically need is the ability to import the xbmc module in Python console/script like this,
i... | [
"I haven't done any XBMC development myself but I thought I'd take a look at this.\nFrom what I can tell XBMC ships with its own Python interpreter (/usr/lib/xbmc/system/python/python24-i486-linux.so) and the xbmc, xbmcgui and xbmcplugin libraries are not available outside of XBMC itself.\nAs for the easiest way to... | [
4
] | [] | [] | [
"api",
"module",
"python",
"xbmc"
] | stackoverflow_0005964110_api_module_python_xbmc.txt |
Q:
How do you use apply_impulse correctly?
I'm just starting out with the PyMunk physics library. I'm having trouble using apply_impulse(). I'm calling it like this:
player.body.apply_impulse(player.body, (10,10), (10,10) )
However, I'm getting this error:
TypeError: apply_impulse() takes at most 3 arguments (4 giv... | How do you use apply_impulse correctly? | I'm just starting out with the PyMunk physics library. I'm having trouble using apply_impulse(). I'm calling it like this:
player.body.apply_impulse(player.body, (10,10), (10,10) )
However, I'm getting this error:
TypeError: apply_impulse() takes at most 3 arguments (4 given)
Why is this and what's the correct way... | [
"When you call a member function on its object you usually don't need to pass the object itself as the first parameter. self is in the function definition of every member function but not in the function call.\nsee this post:\nWhat is the purpose of self?\n"
] | [
2
] | [] | [] | [
"physics",
"pymunk",
"python"
] | stackoverflow_0006393134_physics_pymunk_python.txt |
Q:
Python in Windows: large number of inserts using pyodbc causes memory leak
I am trying to populate a MS SQL 2005 database using python on windows. I am inserting millions of rows, and by 7 million I am using almost a gigabyte of memory. The test below eats up 4 megs of RAM for each 100k rows inserted:
import pyo... | Python in Windows: large number of inserts using pyodbc causes memory leak | I am trying to populate a MS SQL 2005 database using python on windows. I am inserting millions of rows, and by 7 million I am using almost a gigabyte of memory. The test below eats up 4 megs of RAM for each 100k rows inserted:
import pyodbc
connection=pyodbc.connect('DRIVER={SQL Server};SERVER=x;DATABASE=x;UID=x;PWD... | [
"I had the same issue, and it looks like a pyodbc issue with parameterized inserts: http://code.google.com/p/pyodbc/issues/detail?id=145\nTemporarily switching to a static insert with the VALUES clause populated eliminates the leak, until I try a build from the current source.\n",
"Even I had faced the same probl... | [
9,
1,
0,
0,
0
] | [] | [] | [
"memory_leaks",
"pyodbc",
"python"
] | stackoverflow_0004088931_memory_leaks_pyodbc_python.txt |
Q:
Good ways to monitor user "behavior" in Python?
I'm looking for easy APIs to get informations about the user use of his computer in Python.
What would be relevant:
Keypresses, mouse events [PyKeylogger?] # I know this has been debated in SO already
Know information about the processes that are running
Harder, kno... | Good ways to monitor user "behavior" in Python? | I'm looking for easy APIs to get informations about the user use of his computer in Python.
What would be relevant:
Keypresses, mouse events [PyKeylogger?] # I know this has been debated in SO already
Know information about the processes that are running
Harder, know information about the window that has focus (its na... | [
"The question is not so much vague as it is rather broad. Most of the information you're looking for is (as you indicated yourself) spread out over various questions on SO.\nI've done some research on this subject for a productivity tracking application I was thinking about writing. Here's some general advice I can... | [
3
] | [] | [] | [
"python",
"system",
"window_managers"
] | stackoverflow_0005577162_python_system_window_managers.txt |
Q:
Why should you lock threads?
I've read a lot of examples on locking threads.. but why should you lock them?
From my understanding, when you initiate threads without joining them, they will compete with the main thread and all other threads for resources and then execute, sometimes simultaneously, sometimes not.
Do... | Why should you lock threads? | I've read a lot of examples on locking threads.. but why should you lock them?
From my understanding, when you initiate threads without joining them, they will compete with the main thread and all other threads for resources and then execute, sometimes simultaneously, sometimes not.
Does locking ensure that threads DON... | [
"A lock allows you to force multiple threads to access a resource one at a time, rather than all of them trying to access the resource simultaneously.\nAs you note, usually you do want threads to execute simultaneously. However, imagine that you have two threads and they are both writing to the same file. If they t... | [
17,
10
] | [] | [] | [
"locking",
"multithreading",
"python",
"thread_safety"
] | stackoverflow_0006393073_locking_multithreading_python_thread_safety.txt |
Q:
How do I perform math operations on dates and sort them in Python?
I have dates in a Python script that I need to work with that are in a list. I have to keep the format that already exists. The format is YYYY-MM-DD. They are displayed in the form ['2010-05-12', '2011-04-15', 'Date', '2010-04-20', '2010-11-05'] wh... | How do I perform math operations on dates and sort them in Python? | I have dates in a Python script that I need to work with that are in a list. I have to keep the format that already exists. The format is YYYY-MM-DD. They are displayed in the form ['2010-05-12', '2011-04-15', 'Date', '2010-04-20', '2010-11-05'] where the order of the dates appears to be random and they are made into l... | [
"You are asking several questions at the same time, so I'll answer them in order.\nTo filter out the \"Date\" entries, use the filter function like this:\ndates = ['2011-06-18', 'Date', '2010-01-13', '1997-12-01', '2007-08-11']\ndates_filtered = filter(lambda d: d != 'Date', dates)\n\nOr perhaps like this, using Py... | [
4
] | [] | [] | [
"date",
"list",
"python",
"sorting"
] | stackoverflow_0006393563_date_list_python_sorting.txt |
Q:
Can I run pika's connection.ioloop.start() in a daemon?
I'm trying to set up a worker daemon for processing messages from rabbitmq. I'm using pika and its SelectConnection. The code works fine if I don't run it as a daemon. I can use
py worker.py
and
py worker.py &
successfully. However, when I add
import ... | Can I run pika's connection.ioloop.start() in a daemon? | I'm trying to set up a worker daemon for processing messages from rabbitmq. I'm using pika and its SelectConnection. The code works fine if I don't run it as a daemon. I can use
py worker.py
and
py worker.py &
successfully. However, when I add
import daemon
with daemon.DaemonContext():
connection.ioloop.sta... | [
"First, I have no idea where you got this daemon module, but I noticed that you import daemon in your example but not pika.\nimport daemon\nwith daemon.DaemonContext():\n import pika\n # any additional pika code here, maybe the creation of connection?\n connection.ioloop.start()\n\nI strongly suspect that ... | [
3
] | [] | [] | [
"pika",
"python",
"python_daemon",
"rabbitmq"
] | stackoverflow_0006378666_pika_python_python_daemon_rabbitmq.txt |
Q:
ValueError: invalid literal for int() with base 10 -- how to guard against invalid user input?
I made a program where the user enters a number, and the program would count up to that number and display how much time it took. However, whenever I enter letters or decimals (i.e. 0.5), I would get a error. Here is the... | ValueError: invalid literal for int() with base 10 -- how to guard against invalid user input? | I made a program where the user enters a number, and the program would count up to that number and display how much time it took. However, whenever I enter letters or decimals (i.e. 0.5), I would get a error. Here is the full error message:
Traceback (most recent call last):
File "C:\Documents and Settings\Username\D... | [
"Well, there really a way to 'fix' this, it is behaving as expected -- you can't case a letter to an int, that doesn't really make sense. Your best bet (and this is a pythonic way of doing things), is to simply write a function with a try... except block:\ndef get_user_number():\n i = input(\"Enter a number.\\n\... | [
8,
1
] | [] | [] | [
"python",
"user_input",
"validation"
] | stackoverflow_0006393635_python_user_input_validation.txt |
Q:
Split string with caret character in python
I have a huge text file, each line seems like this:
Some sort of general menu^a_sub_menu_title^^pagNumber
Notice that the first "general menu" has white spaces, the second part (a subtitle) each word is separate with "_" character and finally a number (a pag number). I... | Split string with caret character in python | I have a huge text file, each line seems like this:
Some sort of general menu^a_sub_menu_title^^pagNumber
Notice that the first "general menu" has white spaces, the second part (a subtitle) each word is separate with "_" character and finally a number (a pag number). I want to split each line in 3 (obvious) parts, be... | [
">>> \"Some sort of general menu^a_sub_menu_title^^pagNumber\".split(\"^\")\n['Some sort of general menu', 'a_sub_menu_title', '', 'pagNumber']\n\n",
"If you only want three pieces you can accomplish this through a generator expression:\nline = 'Some sort of general menu^a_sub_menu_title^^pagNumber'\npieces = [x ... | [
4,
2,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"split",
"text"
] | stackoverflow_0006393620_python_regex_split_text.txt |
Q:
Split PDF files in python - ValueError: invalid literal for int() with base 10: '' "
I am trying to split a huge pdf file into several small pdfs usinf pyPdf. I was trying with this oversimplified code:
from pyPdf import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(file("document.pdf", "rb"))
for i in x... | Split PDF files in python - ValueError: invalid literal for int() with base 10: '' " | I am trying to split a huge pdf file into several small pdfs usinf pyPdf. I was trying with this oversimplified code:
from pyPdf import PdfFileWriter, PdfFileReader
inputpdf = PdfFileReader(file("document.pdf", "rb"))
for i in xrange(inputpdf.numPages):
output = PdfFileWriter()
output.addPage(inputpdf.getPage(i))... | [
"I think this is a bug in pypdf. Check out the source here. NumberObject.readFromStream expects an integer-like string, and isn't getting one. Probably the pdf in question is malformed in some unexpected way.\n",
"Try it this way\nfor i in xrange(inputpdf.getNumPages()):\n\n"
] | [
2,
0
] | [] | [] | [
"pdf",
"pypdf",
"python"
] | stackoverflow_0006393800_pdf_pypdf_python.txt |
Q:
Only one command line option with argparse
I'm trying to create a CLI with the argparse module but I'd like to have different commands with different argument requirements, I tried this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo', help='foo help')
parser.add_argument('test', nargs... | Only one command line option with argparse | I'm trying to create a CLI with the argparse module but I'd like to have different commands with different argument requirements, I tried this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('foo', help='foo help')
parser.add_argument('test', nargs=1, help='test help')
args = parser.parse_args()... | [
"@crodjer is correct;\nto provide an example: \nimport argparse\nparser = argparse.ArgumentParser()\nsubparsers = parser.add_subparsers(title='subcommands', \n description='valid subcommands',\n help='additional help')\nfoo_parser = subparsers.add_... | [
15,
6,
0
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0006394328_argparse_python.txt |
Q:
Shell script replacement?
I'm starting to get sick of shell scripts to perform automations and glue codes between stuff. I love using it for quick and dirty data processing, but even for simple 3 line code that spawns a process and remembers its process id, it's taking me very long time to program it correctly.
F... | Shell script replacement? | I'm starting to get sick of shell scripts to perform automations and glue codes between stuff. I love using it for quick and dirty data processing, but even for simple 3 line code that spawns a process and remembers its process id, it's taking me very long time to program it correctly.
For every commands, if I don't e... | [
"Have you thought about using \"set -e\" if you can depend on the exit status of the programs you're running?\n",
"Have you looked at using ruby. It has a couple of bits of syntaxtic sugar to make writing shell like scripts easy. In particalar back tick quoted strings work the same way and %x{..} as well. In fact... | [
2,
2,
1,
1,
1
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0006353957_python_shell.txt |
Q:
How to receive the posted values of textbox array in Django?
I have array of textboxes like this
<input type="text" value="" name="key[]" />
<input type="text" value="" name="key[]" />
<input type="text" value="" name="key[]" />
in python access the posted value as
keys = postDict['key[]']
when I print the value... | How to receive the posted values of textbox array in Django? | I have array of textboxes like this
<input type="text" value="" name="key[]" />
<input type="text" value="" name="key[]" />
<input type="text" value="" name="key[]" />
in python access the posted value as
keys = postDict['key[]']
when I print the value of the variable keys it prints only last textbox value. How to re... | [
"Don't call the field key[]. That's a PHP-ism.\nUse request.POST.getlist('key') to get all the values.\n",
"As Daniel says, use request.POST.getlist('key') to get all the values. BUT, from your comment it sounds like the name of the field you're trying to get the data for is the same for all elements, in which ca... | [
1,
1
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0006394663_django_html_python.txt |
Q:
Python SocketServer.TCPServer request
I've been playing around with Python's SocketServer:
#!/usr/bin/python
import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
data=self.request.recv(1024)
self.request.send(data)
HOST, PORT = "localhost", 9999
server = ... | Python SocketServer.TCPServer request | I've been playing around with Python's SocketServer:
#!/usr/bin/python
import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
data=self.request.recv(1024)
self.request.send(data)
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), TCPEch... | [
"In the documentation of RequestHandler.handle.\n"
] | [
2
] | [] | [] | [
"python",
"socketserver"
] | stackoverflow_0006394970_python_socketserver.txt |
Q:
How to Specify URI to a local File in PyGtk LinkButton
I need to create a link button (gtk.LinkButton) with an URI to a local file. Does anyone know what is a valid URI format for a local file ? I want to specify a relative folder example: ../some_folder/file_i_need_to_open.txt
If this is can't be done, I don't mi... | How to Specify URI to a local File in PyGtk LinkButton | I need to create a link button (gtk.LinkButton) with an URI to a local file. Does anyone know what is a valid URI format for a local file ? I want to specify a relative folder example: ../some_folder/file_i_need_to_open.txt
If this is can't be done, I don't mind putting the file in the same folder as the python source ... | [
"Something like: file:///usr/bin/ is generally used for local URI. But maybe just /usr/bin/ works too. Have you tried it?\n"
] | [
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0006395185_pygtk_python.txt |
Q:
How to shift the django admin features to front end
I am making an application in django and python. But i have only one user and its for my personal use.
So I am confused between front end and backend because all will be doing al CRUD operation on Classes. So for me evryting will be on frontend , no backend.
But ... | How to shift the django admin features to front end | I am making an application in django and python. But i have only one user and its for my personal use.
So I am confused between front end and backend because all will be doing al CRUD operation on Classes. So for me evryting will be on frontend , no backend.
But all CRUD operations are done in backend. so is there any ... | [
"You still need some code for the list views, pagination, etc., but most of the CRUD basic logic can be done using ModelForms.\nExample:\nfrom django.forms import ModelForm\n\nclass ArticleForm(ModelForm):\n class Meta:\n model = Article\n\nNow this form contains all the fields of your Article model;\nIf ... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006395312_django_python.txt |
Q:
Installing Mechanize using easy_install
I've installed mechanize using easy_install on Windows 7 Admin account. However, when I try to setup/run another program that needs mechanize on a different account, it doesn't find it.
Any solutions?
A:
What's your Python installation location?
How did you run easy_instal... | Installing Mechanize using easy_install | I've installed mechanize using easy_install on Windows 7 Admin account. However, when I try to setup/run another program that needs mechanize on a different account, it doesn't find it.
Any solutions?
| [
"What's your Python installation location?\nHow did you run easy_install?\neasy_install probably uses the default user account permissions and you need to manually change file permissions / ownership so that non-admins can see the files. \nGenerally, easy_install is designed for single user installations (developme... | [
0
] | [] | [] | [
"easy_install",
"mechanize",
"python"
] | stackoverflow_0006394305_easy_install_mechanize_python.txt |
Q:
Check overwrite in File Save dialog in WxPython
I need to check if the same file exists when I try to save a file in File Save Dialog. İf it does,
it shouldnt allow me to do it and force me to change the name. How can I do this in WxPython?
Thanks in advance.
Here is my save code:
#Dosya tipi filtreleri
... | Check overwrite in File Save dialog in WxPython | I need to check if the same file exists when I try to save a file in File Save Dialog. İf it does,
it shouldnt allow me to do it and force me to change the name. How can I do this in WxPython?
Thanks in advance.
Here is my save code:
#Dosya tipi filtreleri
wildcard = "BENGI files (*.bengi)|*.bengi|" ... | [
"SOLVED:\nI added \"wx.OVERWRITE_PROMPT\" flag to the style.\n"
] | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006120595_python_wxpython.txt |
Q:
Irc-bot using twisted with periodical printing
The problem I'm having is really quite small but I've been trying to figure it out for two days and I've gotten nowhere.
Basically I'm building an IRC bot using twisted and yes there are many examples on the web but none of them handle what you do when you want to sen... | Irc-bot using twisted with periodical printing | The problem I'm having is really quite small but I've been trying to figure it out for two days and I've gotten nowhere.
Basically I'm building an IRC bot using twisted and yes there are many examples on the web but none of them handle what you do when you want to send messages periodically.
I want my bot to run a loop... | [
"This is very similar to a question answered in the Twisted FAQ, http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#HowdoImakeinputononeconnectionresultinoutputonanother\nAlso, I think your question summary is a little confused. You describe a scenario where you want to generate IRC output ''in response t... | [
1
] | [] | [] | [
"irc",
"python",
"twisted"
] | stackoverflow_0006395396_irc_python_twisted.txt |
Q:
Something wrong with wtforms FieldList && validation
Something wrong with wtforms FieldList && validation...
It should say that field must have Int value, not This field is required
Why f.data has [None, 2, None] value, not ['def', 2, 'abc'] ?
from webob.multidict import MultiDict
from wtforms import Form
from wt... | Something wrong with wtforms FieldList && validation | Something wrong with wtforms FieldList && validation...
It should say that field must have Int value, not This field is required
Why f.data has [None, 2, None] value, not ['def', 2, 'abc'] ?
from webob.multidict import MultiDict
from wtforms import Form
from wtforms import FieldList, IntegerField
from wtforms import v... | [
"It looks like there is a try... except block in the IntegerField ancestry which will place all non ints into the process_errors property and that the class is specifically prevented from allowing you to have data populated with anything but valid data. I believe you can still get the values you seek in the raw_dat... | [
1
] | [] | [] | [
"python",
"wtforms"
] | stackoverflow_0006395520_python_wtforms.txt |
Q:
How can I wrap a non-Traits model for use with Python Traits?
I would like to wrap a non-Traits model class for use with Python Traits. My goal is to write a Traits-based UI to manipulate an "external" model class. The external model class has been generated by SWIG and so I cannot add enthought.traits.api.HasTr... | How can I wrap a non-Traits model for use with Python Traits? | I would like to wrap a non-Traits model class for use with Python Traits. My goal is to write a Traits-based UI to manipulate an "external" model class. The external model class has been generated by SWIG and so I cannot add enthought.traits.api.HasTraits as an ancestor (I think, though I may be wrong).
My current be... | [
"from enthought.traits.api import HasStrictTraits, Instance, Property\n\nclass ExternalModel(object):\n foo = 'foo'\n\nclass TraitsModel(HasStrictTraits):\n _e = Instance(ExternalModel, ExternalModel())\n\n def __init__(self):\n '''\n >>> wrapper = TraitsModel()\n >>> wrapper.foo\n ... | [
2
] | [] | [] | [
"enthought",
"model_view_controller",
"python",
"swig",
"traits"
] | stackoverflow_0006113822_enthought_model_view_controller_python_swig_traits.txt |
Q:
Yahoo Option Data with R but has error? Better examples in Python or C#?
I am trying to run a R script from:
http://www.math.tu-berlin.de/~mkeller/R-progs/yahoo_opt.R
Description at:
http://www.math.tu-berlin.de/~mkeller/index.php?target=rcode
I am new at R but I get a really strange error when I run the followi... | Yahoo Option Data with R but has error? Better examples in Python or C#? | I am trying to run a R script from:
http://www.math.tu-berlin.de/~mkeller/R-progs/yahoo_opt.R
Description at:
http://www.math.tu-berlin.de/~mkeller/index.php?target=rcode
I am new at R but I get a really strange error when I run the following as instructed:
opt <- yahoo.getAllOptions("IBM")
The error is:
trying URL... | [
"Have you heard of the YQL Console and datatables.org? It provides access to a lot of Yahoo (and other) data tables using REST requests returning XML or JSON objects. There is a nice options table you can easily access using Python's urllib. Consider the following example:\n>>> import urllib2\n>>> import json\n>>> ... | [
0
] | [] | [] | [
"c#",
"python",
"r",
"yahoo"
] | stackoverflow_0006396144_c#_python_r_yahoo.txt |
Q:
Using DVCS for an RDBMS audit trail
I'm looking to implement an audit trail for a reasonably complicated relational database, whose schema is prone to change. One avenue I'm thinking of is using a DVCS to track changes.
(The benefits I can imagine are: schemaless history, snapshots of entire system's state, standa... | Using DVCS for an RDBMS audit trail | I'm looking to implement an audit trail for a reasonably complicated relational database, whose schema is prone to change. One avenue I'm thinking of is using a DVCS to track changes.
(The benefits I can imagine are: schemaless history, snapshots of entire system's state, standard tools for analysis, playback and migra... | [
"I've looked into this a little on my own, and here are some comments to share.\nAlthough I had thought using mercurial from python would make things easier, there's a lot of functionality that the DVCS's have that aren't necessary (esp branching, merging). I think it would be easier to simply steal some design dec... | [
2,
0,
0
] | [] | [] | [
"audit_trail",
"git",
"mercurial",
"python",
"rdbms"
] | stackoverflow_0006380623_audit_trail_git_mercurial_python_rdbms.txt |
Q:
Python and arrays
I know that python is a crazy language because of it's cycles constructions :)
So, I have an array of numbers but in string type:
a = ['1', '40', '356', '...']
I need this or a copy of this array but with float type instead of string. The only thing is that the code should be in one line.
Help m... | Python and arrays | I know that python is a crazy language because of it's cycles constructions :)
So, I have an array of numbers but in string type:
a = ['1', '40', '356', '...']
I need this or a copy of this array but with float type instead of string. The only thing is that the code should be in one line.
Help me, please :)
| [
"You can use map()[docs] and float()[docs]:\nb = map(float, a)\n\n",
" a = ['1', '40', '356', '...']\n b = [float(x) for x in a]\n\nThis is called a list comprehension. It's a very powerful feature of Python, and you can read more about list comprehensions here:\nhttp://docs.python.org/tutorial/datastructures.ht... | [
11,
8
] | [] | [] | [
"arrays",
"cycle",
"python"
] | stackoverflow_0006396733_arrays_cycle_python.txt |
Q:
python iterating over list
I try to iterate over each item in the list. But iterator does not go through all objects.
Here is my function code(dirs and root comes from os.walk)
def remove_hidden_dirs(dirs,root):
"""
Function remove hidden directories . .. in unix
"""
logging.debug("\n\n remove hidd... | python iterating over list | I try to iterate over each item in the list. But iterator does not go through all objects.
Here is my function code(dirs and root comes from os.walk)
def remove_hidden_dirs(dirs,root):
"""
Function remove hidden directories . .. in unix
"""
logging.debug("\n\n remove hidden" )
logging.debug('Start r... | [
"Don't modify lists while iterating over them. Instead, produce a new list with just the items that you want to keep. \ndirs = [d for d in dirs if not d.startswith('.')]\n\nIs an efficient simple and readable technique for doing it.\n",
"Very simple: you are removing the current item from dirs while iterating ove... | [
9,
4
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0006396800_iteration_list_python.txt |
Q:
Does a derived class automatically have all the attributes of the base class?
There seems to be no good online documentation on this:
If I make a derived class, will it automatically have all the attributes of the base class? But what's the BaseClass.__init() for, do you also need to do it to other base class meth... | Does a derived class automatically have all the attributes of the base class? | There seems to be no good online documentation on this:
If I make a derived class, will it automatically have all the attributes of the base class? But what's the BaseClass.__init() for, do you also need to do it to other base class methods? Does BaseClass.__init__() need arguments? If you have arguments for your base ... | [
"If you implement __init__ in a class derived from BaseClass, then it will overwrite the inherited __init__ method and so BaseClass.__init__ will never be called. If you need to call the __init__ method for BaseClass (as is normally the case), then its up to you to do that, and its done explicitly by calling BaseCl... | [
62,
11
] | [] | [] | [
"attributes",
"class",
"derived",
"inheritance",
"python"
] | stackoverflow_0006396452_attributes_class_derived_inheritance_python.txt |
Q:
Parsing html using BeautifulSoup in Python
I wrote some code to parse html, but the result was not what I wanted:
import urllib2
html = urllib2.urlopen('http://dummy').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for definition in soup.findAll('span', {"class":'d'}):
definition = defin... | Parsing html using BeautifulSoup in Python | I wrote some code to parse html, but the result was not what I wanted:
import urllib2
html = urllib2.urlopen('http://dummy').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for definition in soup.findAll('span', {"class":'d'}):
definition = definition.renderContents()
print "<meaning>", defini... | [
"yes, you can get all of the spans in the html, then for each check for a class of \"d\" or \"x\", and if they do, print them. \nsomething like this might work (untested):\nfor span in soup.findAll('span'):\n if span.find(\"span\",\"d\").string:\n print \"<definition>\" + span.find(\"span\",\"d\").string ... | [
5
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0006396655_beautifulsoup_html_python.txt |
Q:
How do I get auto-suggestions for array options when typing in Vim?
Let's say I type
a = [1, 2]
in a .py file in vim and when I type "a." and hit TAB, I would like to get suggestion menu that is related to lists.
Edit 1 in response to Robin's comment:
I think it's possible in vim, because there is a plugin that c... | How do I get auto-suggestions for array options when typing in Vim? |
Let's say I type
a = [1, 2]
in a .py file in vim and when I type "a." and hit TAB, I would like to get suggestion menu that is related to lists.
Edit 1 in response to Robin's comment:
I think it's possible in vim, because there is a plugin that checks if a given python code is a valid code (I don't know what the plug... | [
"Recent versions of vim come with an omnicompletion script called pythoncomplete.\nOpen up a python file, and type\n:set completefunc?\n\nto check what the current completion function is. If you get back\ncompletefunc=\n\nthen no completionfunction is currently set. You can set pythoncomplete to be the completion f... | [
7,
3
] | [] | [] | [
"autocomplete",
"intellisense",
"python",
"vim"
] | stackoverflow_0006396880_autocomplete_intellisense_python_vim.txt |
Q:
Can I sniff UDP packets addressed another Linux machine using Python?
I have a Python process on one Linux machine server1 that receives and processes raw UDP packets. I want to have another Linux machine server2 capable of listening to the same UDP packets server1 is receiving.
Is there any Python solution capabl... | Can I sniff UDP packets addressed another Linux machine using Python? | I have a Python process on one Linux machine server1 that receives and processes raw UDP packets. I want to have another Linux machine server2 capable of listening to the same UDP packets server1 is receiving.
Is there any Python solution capable of sniffing UDP packets addressed to the another (Linux) machine?
| [
"This not depends on Python but on your network architecture. If server1 and server2 are connected (probably they are) through a switch then you can't do it, because the packet passing through the router will be sent only to the requested IP.\nSo first of all, tell us how is composed your network architecture. Whe... | [
3,
3,
1
] | [] | [] | [
"linux",
"network_programming",
"networking",
"python",
"ubuntu"
] | stackoverflow_0006215997_linux_network_programming_networking_python_ubuntu.txt |
Q:
Disregarding python variables
Possible Duplicate:
how can i get around declaring an unused variable in a for loop
In Python, particularly with a for-loop, is there a way to not create a variable if you don't care about it, ie the i in this example which isn't needed:
for i in range(10):
print('Hello')
A:
N... | Disregarding python variables |
Possible Duplicate:
how can i get around declaring an unused variable in a for loop
In Python, particularly with a for-loop, is there a way to not create a variable if you don't care about it, ie the i in this example which isn't needed:
for i in range(10):
print('Hello')
| [
"No, but often you will find that _ is used instead:\nfor _ in range(10):\n print('Hello')\n\nYou only have to be careful when you use gettext.\n",
"A for-loop always creates a name. If you don't want to use it, just make this clear by its name, for example call it dummy. Some people also use the name _ for ... | [
8,
5,
4,
3,
2,
2
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0006397487_python_variables.txt |
Q:
Object vs. Dictionary: how to organise a data tree?
I am programming some kind of simulation with its data organised in a tree. The main object is World which holds a bunch of methods and a list of City objects. Each City object in turn has a bunch of methods and a list of Population objects. Population objects ha... | Object vs. Dictionary: how to organise a data tree? | I am programming some kind of simulation with its data organised in a tree. The main object is World which holds a bunch of methods and a list of City objects. Each City object in turn has a bunch of methods and a list of Population objects. Population objects have no method of their own, they merely hold attributes.
M... | [
"As you've seen yourself, there is little practical difference - the main difference, in my opinion, is that using individual, hard-coded attributes is slightly easier with objects (no need to quote the name) while dicts easily allow treating all values as one collection (e.g. summing them). This is why I'd go for ... | [
2,
2,
2,
1
] | [] | [] | [
"dictionary",
"object",
"python",
"resources",
"tree"
] | stackoverflow_0006397246_dictionary_object_python_resources_tree.txt |
Q:
where can I find good reference document on python exception
It doesn't seem easy to find good reference document that details all python exceptions.
For example, whenever I got IOError exception, it has a different message format but I could not find any good reference:
IOError: ('http protocol error', 0, 'got a ... | where can I find good reference document on python exception | It doesn't seem easy to find good reference document that details all python exceptions.
For example, whenever I got IOError exception, it has a different message format but I could not find any good reference:
IOError: ('http protocol error', 0, 'got a bad status line', None)
or
IOError: [Errno socket error] [Errno 1... | [
"Built-in Exceptions are documented, here's IOException. Check errno documentation for symbol definition, errno.errorcode is a dict containing a mapping between error code/symbols.\nimport errno\nerrno.errorcode[numeric_code]\n\n",
"I guess that you are looking for errno:\ntry:\n open('file_dont_exist')\nexcep... | [
3,
1
] | [] | [] | [
"exception",
"python",
"reference"
] | stackoverflow_0006397463_exception_python_reference.txt |
Q:
Generator methods, deepcopy and copy
I am trying to avoid the use of deepcopy in a custom class (a Graph class)
The graphs have few attributes, such as vertices, edges, etc. and several generator methods (methods with yield).
I need to copy the graph: e.g. H = deepcopy(G) but not using deepcopy in order to speed ... | Generator methods, deepcopy and copy | I am trying to avoid the use of deepcopy in a custom class (a Graph class)
The graphs have few attributes, such as vertices, edges, etc. and several generator methods (methods with yield).
I need to copy the graph: e.g. H = deepcopy(G) but not using deepcopy in order to speed up the program.
Then:
If I do not use dee... | [
"I'm pretty sure I understand what you're getting at. Here's a simple example:\nclass Graph:\n def __init__(self, nodes):\n self.nodes = list(nodes)\n self.nodegen = self.iternodes()\n def iternodes(self):\n for node in self.nodes:\n yield node\n def copy(self):\n ret... | [
2
] | [] | [] | [
"deep_copy",
"generator",
"python"
] | stackoverflow_0006396497_deep_copy_generator_python.txt |
Q:
Finding minimum value in an array of dicts
I have an array like the following:
people = [{'node': 'john', 'dist': 3},
{'node': 'mary', 'dist': 5},
{'node': 'alex', 'dist': 4}]
I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3.
I w... | Finding minimum value in an array of dicts | I have an array like the following:
people = [{'node': 'john', 'dist': 3},
{'node': 'mary', 'dist': 5},
{'node': 'alex', 'dist': 4}]
I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3.
I wrote the following code:
min = 99999
for e in pe... | [
"Use the min function:\nminimum = min(e['dist'] for e in people)\n# Don't call the variable min, that would overshadow the built-in min function\nprint ('minimum is ' + str(minimum))\n\n",
"min(x['dist'] for x in people)\n\n",
"You could use a generator expression to create a list with all keys and then use the... | [
8,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006395716_python.txt |
Q:
Instant search with Whoosh - Index and search a MySQL table using Whoosh outputing JSON results
I want to index a MySQL table using Whoosh and create an instant search page, so I need the results of the Whoosh search to be in JSON. Is there a script or a project that implements this already? I've tried searching b... | Instant search with Whoosh - Index and search a MySQL table using Whoosh outputing JSON results | I want to index a MySQL table using Whoosh and create an instant search page, so I need the results of the Whoosh search to be in JSON. Is there a script or a project that implements this already? I've tried searching but I only find Haystack search for Django.
If not can I get some broad pointers how I should go abou... | [
"The Whoosh Results object is basically a list of dictionaries. From the examples:\n>>> # Show the best hit's stored fields\n>>> results[0]\n{\"title\": u\"Hello World in Python\", \"path\": u\"/a/b/c\"}\n>>> results[0:2]\n[{\"title\": u\"Hello World in Python\", \"path\": u\"/a/b/c\"}, {\"title\": u\"Foo\", \"path... | [
4
] | [] | [] | [
"json",
"mysql",
"python",
"search",
"whoosh"
] | stackoverflow_0006397824_json_mysql_python_search_whoosh.txt |
Q:
Verifying Authentication to a Telnet Session in Python
I am trying to telnet into a Cisco Switch and run a couple of commands on it. I am able to check if the host doesn't exist, not sure how to check if the username or password is correct. This is what I got so far(This is part of my class)
def login(self):
... | Verifying Authentication to a Telnet Session in Python | I am trying to telnet into a Cisco Switch and run a couple of commands on it. I am able to check if the host doesn't exist, not sure how to check if the username or password is correct. This is what I got so far(This is part of my class)
def login(self):
if self.user_name and self.password:
try:
... | [
"You could also try Exscript:\nfrom Exscript.util.start import quickstart\n\ndef do_something(conn):\n conn.autoinit()\n conn.execute('show version')\n\nquickstart('telnet://localhost', do_something)\n\nThe quickstart() function asks the user for username and password (use start() if that is not what you want... | [
1,
0
] | [] | [] | [
"authentication",
"cisco",
"python",
"telnet",
"verification"
] | stackoverflow_0006205842_authentication_cisco_python_telnet_verification.txt |
Q:
Python script to remove blank pages using pyPDF
I am trying to write a couple of python scripts using pyPDF to split PDF pages into six separate pages, order them correctly (usually printed front and back, so every other page needs to have its subpages ordered differently), and remove resulting blank pages at the ... | Python script to remove blank pages using pyPDF | I am trying to write a couple of python scripts using pyPDF to split PDF pages into six separate pages, order them correctly (usually printed front and back, so every other page needs to have its subpages ordered differently), and remove resulting blank pages at the end of the output document.
I wrote the following scr... | [
"PdfFileReader has a method, getPage(self, page number) that returns an object, PageObject, that in turn has a method getContents, which will return None if the page is blank. So, with your pdf object, getNumPages(), iterate with if getPage(i).getContents():, collecting the hits into a list of page numbers to outpu... | [
6
] | [] | [] | [
"crop",
"pdf",
"pypdf",
"python"
] | stackoverflow_0006310251_crop_pdf_pypdf_python.txt |
Q:
LinkedIn - cannot send messages
I am using Python API for sending messages in LinkedIn.
I found that
api.SendMessage("This is a test subject", "This is the test body", [pid])
can send messages only to the ones who are in our connected list and not others.
How do you send messages to anyone who is not in our... | LinkedIn - cannot send messages | I am using Python API for sending messages in LinkedIn.
I found that
api.SendMessage("This is a test subject", "This is the test body", [pid])
can send messages only to the ones who are in our connected list and not others.
How do you send messages to anyone who is not in our connect list?
| [
"As I answered elsewhere, this is how LinkedIn behaves, whether you use the API or not. You can only message first degree connections.\nThere is an InMail feature that allows for messaging outside your first degree network, but that is a paid product. Is that something you're interested in?\nOr the other option is ... | [
1
] | [] | [] | [
"linkedin",
"message",
"python"
] | stackoverflow_0006393817_linkedin_message_python.txt |
Q:
How to insert DTD DOCTYPE content when using SAX to generate XML output in Python
I am trying to generate a large XML file using python(actually jython) xml.sax.saxutils.XMLGenerator.
I would like to include DTD information but I could not figure out how to pass the DTD string to SAX. Here is the sample SAX writer... | How to insert DTD DOCTYPE content when using SAX to generate XML output in Python | I am trying to generate a large XML file using python(actually jython) xml.sax.saxutils.XMLGenerator.
I would like to include DTD information but I could not figure out how to pass the DTD string to SAX. Here is the sample SAX writer class:
from xml.sax.saxutils import XMLGenerator
class xml_writer:
def __init__(s... | [
"You could subclass XMLGenerator and add a write() method. Here is an example:\nimport sys\nfrom xml.sax.saxutils import XMLGenerator\n\nclass MyXMLGenerator(XMLGenerator):\n def __init__(self, out=sys.stdout, encoding=\"UTF-8\"):\n XMLGenerator.__init__(self, out, encoding)\n self.out = out\n\n ... | [
3
] | [] | [] | [
"dtd",
"jython",
"python",
"xml"
] | stackoverflow_0006375200_dtd_jython_python_xml.txt |
Q:
Scala: recursively modify lists of elements/lists
I was hoping someone could provide me with some basic code help in Scala. I've written some demo code in Python.
Consider a list of elements, where an element can hold either an integer or a list of other elements. I'd like to recursively examine this structure an... | Scala: recursively modify lists of elements/lists | I was hoping someone could provide me with some basic code help in Scala. I've written some demo code in Python.
Consider a list of elements, where an element can hold either an integer or a list of other elements. I'd like to recursively examine this structure and modify it while keeping the overall structure.
To rep... | [
"I would rather not call that a List of List, as that does not tell what those lists contains. The structure is a tree, more precisely a leafy tree, where there are data only in the leaves. That would be : \nsealed trait Tree[+A]\ncase class Node[+A](children: Tree[A]*) extends Tree[A]\ncase class Leaf[+A](value: A... | [
11,
3,
3
] | [] | [] | [
"python",
"recursion",
"scala"
] | stackoverflow_0006395119_python_recursion_scala.txt |
Q:
Unmap of NumPy memmap
I can't find any documentation on how numpy handles unmapping of previously memory mapped regions: munmap for numpy.memmap() and numpy.load(mmap_mode).
My guess is it's done only at garbage collection time, is that correct?
A:
Yes, it's only closed when the object is garbage-collected; memm... | Unmap of NumPy memmap | I can't find any documentation on how numpy handles unmapping of previously memory mapped regions: munmap for numpy.memmap() and numpy.load(mmap_mode).
My guess is it's done only at garbage collection time, is that correct?
| [
"Yes, it's only closed when the object is garbage-collected; memmap.close method does nothing.\nYou can call x._mmap.close(), but keep in mind that any further access to the x object will crash python.\n"
] | [
16
] | [] | [] | [
"mmap",
"numpy",
"python"
] | stackoverflow_0006397495_mmap_numpy_python.txt |
Q:
how to use a non-european language with a python library
I'm relatively new to programming and recently I've started playing around with pygame (set of modules to write games in python). I'm looking to create a program/game in which some of the labels, strings, buttons, etc are in Arabic. I'm guessing that pygam... | how to use a non-european language with a python library | I'm relatively new to programming and recently I've started playing around with pygame (set of modules to write games in python). I'm looking to create a program/game in which some of the labels, strings, buttons, etc are in Arabic. I'm guessing that pygame has to support Arabic letters and it probably doesn't? Or c... | [
"Well Python itself uses Unicode for everything so that's not the problem. A quick googling also shows that PyGame should be able to render Unicode fonts just fine. So I assume the problem is more that it can't find fonts for the specific language to use for rendering.\nHere is a short example for PyGame and especi... | [
5,
0,
0
] | [] | [] | [
"arabic",
"pygame",
"python"
] | stackoverflow_0006397888_arabic_pygame_python.txt |
Q:
python check if utf-8 string is uppercase
I am having trouble with .isupper() when I have a utf-8 encoded string. I have a lot of text files I am converting to xml. While the text is very variable the format is static. words in all caps should be wrapped in <title> tags and everything else <p>. It is considerably ... | python check if utf-8 string is uppercase | I am having trouble with .isupper() when I have a utf-8 encoded string. I have a lot of text files I am converting to xml. While the text is very variable the format is static. words in all caps should be wrapped in <title> tags and everything else <p>. It is considerably more complex then this, but this should be suff... | [
"The primary reason that your published code fails (even with only ascii characters!) is that re.split() will not split on a zero-width match. r'\\b' matches zero characters:\n>>> re.split(r'\\b', 'foo-BAR_baz')\n['foo-BAR_baz']\n>>> re.split(r'\\W+', 'foo-BAR_baz')\n['foo', 'BAR_baz']\n>>> re.split(r'[\\W_]+', 'fo... | [
9,
2,
0
] | [] | [] | [
"python",
"unicode",
"utf_8"
] | stackoverflow_0006391442_python_unicode_utf_8.txt |
Q:
how to edit console output in python
I'm looking for a way to edit the existing content of the console output.
I came across this question which is basically what i want, but i was hoping for something a little bit more sophisticated. Does anyone know of a module or anything else that enables editing the console b... | how to edit console output in python | I'm looking for a way to edit the existing content of the console output.
I came across this question which is basically what i want, but i was hoping for something a little bit more sophisticated. Does anyone know of a module or anything else that enables editing the console buffer?
Thank you.
| [
"Look at this library called urwid and look at example applications built using that.\n"
] | [
0
] | [] | [] | [
"console_application",
"python"
] | stackoverflow_0006399135_console_application_python.txt |
Q:
Python - Most efficient way to compare # of words sequenced in "right" order across two strings/lists
I was wondering what the most computationally efficient Python way of cracking this problem would be.
Say you have two strings (or lists from splitting those strings--doesn't matter), "this is the right string" vs... | Python - Most efficient way to compare # of words sequenced in "right" order across two strings/lists | I was wondering what the most computationally efficient Python way of cracking this problem would be.
Say you have two strings (or lists from splitting those strings--doesn't matter), "this is the right string" vs. "this is right the string."
We're assuming that the first string is always right, and a score will be ass... | [
"This sounds very much like homework. Try thinking about it for a bit. Would it suffice to traverse the list of correct words once, and check if the corresponding word in the second list is equal to the word in the correct list?\nI would probably zip the lists in python and compare the pairs for equality.\n",
"a ... | [
2,
0,
0,
0
] | [] | [] | [
"comparison",
"list",
"python",
"sequence",
"string"
] | stackoverflow_0004009251_comparison_list_python_sequence_string.txt |
Q:
Help in scapy and pcapy
I am new to scapy and pcapy. As a project I have to send an ICMP packet using scapy and capture it using pcapy. I have to compare timestamp between sender and receiver to calculate delay in network.
I have no clue how can I do this. Any help will be greatly appreciated.
Thank you.
Following... | Help in scapy and pcapy | I am new to scapy and pcapy. As a project I have to send an ICMP packet using scapy and capture it using pcapy. I have to compare timestamp between sender and receiver to calculate delay in network.
I have no clue how can I do this. Any help will be greatly appreciated.
Thank you.
Following command i used to send ICMP ... | [
"Basically, insert the current time at the sender into your payload and then compare it with the time when the packet was received. This will require the clocks on the two machines to be synchronised (e.g., with NTP). You will also need to take into account the time it takes the OS on the sender to take the packet ... | [
2
] | [] | [] | [
"libpcap",
"packet_capture",
"python",
"scapy"
] | stackoverflow_0006399351_libpcap_packet_capture_python_scapy.txt |
Q:
Read a multielement list, look for an element and print it out in python
I am writing a python script in order to write a tex file. But I had to use some information from another file. Such file has names of menus in each line that I need to use. I use split to have a list for each line of my "menu".
For example,... | Read a multielement list, look for an element and print it out in python | I am writing a python script in order to write a tex file. But I had to use some information from another file. Such file has names of menus in each line that I need to use. I use split to have a list for each line of my "menu".
For example, I had to write a section with the each second element of my lists but after r... | [
"I don't quite follow your question. But I see several errors in your code. Most importantly:\n for line in infile.readlines():\n ...\n ...\n for i in range(1,len(infile.readlines())):\n\nOnce you read a file, it's gone. (You can get it back, but in this case there's no point.) That means that the s... | [
2
] | [] | [] | [
"latex",
"lines",
"multiline",
"python",
"split"
] | stackoverflow_0006399394_latex_lines_multiline_python_split.txt |
Q:
libxslt's applyStylesheet() produces broken XHTML
I've got an XML data file that I'm applying an XSL stylesheet to, using libxslt in Python. Things are almost perfect, but every instance of <hr/> in the XSL file is being turned into <hr> in the output from unicode(applyStylesheet()). This is pretty much all I'm ... | libxslt's applyStylesheet() produces broken XHTML | I've got an XML data file that I'm applying an XSL stylesheet to, using libxslt in Python. Things are almost perfect, but every instance of <hr/> in the XSL file is being turned into <hr> in the output from unicode(applyStylesheet()). This is pretty much all I'm doing:
style = libxslt.parseStylesheetDoc(libxml2.parse... | [
"Can we see the template.xsl file? Does it contain the <xsl:output/> tag? Is the method attribute of this tag set to html?\nIf it is, then libxsl automatically strips all / from self closing tags.\nBeware that, xml output method does not always output correct html, refer to xml, html or xhtml in <xsl:output>: Which... | [
2
] | [] | [] | [
"libxml2",
"libxslt",
"python",
"xhtml",
"xhtml_1.0_strict"
] | stackoverflow_0006399278_libxml2_libxslt_python_xhtml_xhtml_1.0_strict.txt |
Q:
Updating old django/twisted python code
Well I have some old python code that seems to not work right, I have researched to the ends of the internet trying to find a fix.
def getURL(self, context):
# Make this an absolute URL- currently it's required for
# links placed in the RSS and XML feeds, and won't
... | Updating old django/twisted python code | Well I have some old python code that seems to not work right, I have researched to the ends of the internet trying to find a fix.
def getURL(self, context):
# Make this an absolute URL- currently it's required for
# links placed in the RSS and XML feeds, and won't
# hurt elsewhere.
req = context['reque... | [
"It seems to me like Context['request'] doesn't fit on there... where does Context come from? As param you get context all lowercase. Probably you sould use the param 'context' instead, so ...\na) make Context['request'] to context['request']\n... or, if your are already using context in lowercase, and it's only a ... | [
0
] | [] | [] | [
"django",
"python",
"twisted",
"twisted.internet",
"twisted.web"
] | stackoverflow_0006399311_django_python_twisted_twisted.internet_twisted.web.txt |
Q:
Getting newest S3 keys first
I am writing an app that stores (potentially millions of) objects in an S3 bucket. My app will take the most recent object (roughly), process it, and write it back to the same bucket. I need a way of accessing keys and naming new objects so that the app can easily get to the newest obj... | Getting newest S3 keys first | I am writing an app that stores (potentially millions of) objects in an S3 bucket. My app will take the most recent object (roughly), process it, and write it back to the same bucket. I need a way of accessing keys and naming new objects so that the app can easily get to the newest objects.
I know I can do this properl... | [
"s3 versioning really helps out here. If these are really the same \"thing\" you can turn on versioning for you bucket, get the data from your key, modify it and store it back to the same key.\nyou'll need to use boto's \nbucket.get_all_versions( prefix='yourkeynamehere' )\n\nyou get versions out, most recent first... | [
1
] | [] | [] | [
"amazon_s3",
"boto",
"python"
] | stackoverflow_0006399612_amazon_s3_boto_python.txt |
Q:
Windows progress bar in python's Tkinter
Is there any way in python's Tkinter, bwidget or anything similar to show a Windwos' default progress bar?
I already know the bwidget.ProgressBar, but it produces an ugly progress bar while I mean showing a valid windows progress bar - the green, glowing one:
http://imagesh... | Windows progress bar in python's Tkinter | Is there any way in python's Tkinter, bwidget or anything similar to show a Windwos' default progress bar?
I already know the bwidget.ProgressBar, but it produces an ugly progress bar while I mean showing a valid windows progress bar - the green, glowing one:
http://imageshack.us/photo/my-images/853/unledtph.png/
I nee... | [
"If you are using a modern (2.7+) version of Tkinter you can try the ttk.ProgressBar which is part of Tkinter. \n",
"You can install the pyttk module separately.\nfrom Tkinter import *\nimport ttk\nroot = Tk()\nprogressbar = ttk.Progressbar(orient=HORIZONTAL, length=200, mode='determinate')\nprogressbar.pack(side... | [
10,
8,
0
] | [] | [] | [
"progress_bar",
"python",
"python_2.6",
"tkinter",
"windows"
] | stackoverflow_0006398437_progress_bar_python_python_2.6_tkinter_windows.txt |
Q:
Registering per-class handlers
I'm trying to find a good way to easily register handlers of some commands in a Python class. Those handlers would be registered for subclasses of SomeBaseClass and only available there. Unfortunately I'm starting to think I'm doing way more work than necessary. Right now, I've got:
... | Registering per-class handlers | I'm trying to find a good way to easily register handlers of some commands in a Python class. Those handlers would be registered for subclasses of SomeBaseClass and only available there. Unfortunately I'm starting to think I'm doing way more work than necessary. Right now, I've got:
def register_handlers(cls):
cls.... | [
"You're overthinking the problem. If you have one handler per action, then just make up a naming convention for them, like this:\nclass SomeBaseClass(object):\n def run_action(self, name, *args):\n getattr(self, name + '_handler')(*args)\n\nclass SubClass(SomeBaseClass):\n def foo_handler(self):\n ... | [
2
] | [] | [] | [
"decorator",
"handler",
"python"
] | stackoverflow_0006399765_decorator_handler_python.txt |
Q:
Fastest way to handle a submit button with a variable in it?
I've got a form with a bunch of items. Beside each item is a "Remove" button. When one of buttons is pressed, I need to know which one so that I know which item to remove.
The way I have it now, each button is named remove-# where # is the index of the i... | Fastest way to handle a submit button with a variable in it? | I've got a form with a bunch of items. Beside each item is a "Remove" button. When one of buttons is pressed, I need to know which one so that I know which item to remove.
The way I have it now, each button is named remove-# where # is the index of the item. In order to grab the # though I have to loop over every POST ... | [
"An option would be to put each remove button in a separate form, with a hidden value with a constant name and the value indicating which item to remove.\n",
"If the POST values are stored in a dict you could turn this around and instead of looking for something that looks like a remove-# you generate all remove-... | [
1,
1,
0
] | [] | [] | [
"forms",
"html",
"python"
] | stackoverflow_0006399975_forms_html_python.txt |
Q:
could anyone give a simple python for explaining the "Hollywood principle"/inversion of control
I'm very interested in the Twisted web framework. As far as I know the framework
uses the Hollywood principle. I just know the term but totally have no
idea about this design pattern.
I have done a lot of Google searchi... | could anyone give a simple python for explaining the "Hollywood principle"/inversion of control | I'm very interested in the Twisted web framework. As far as I know the framework
uses the Hollywood principle. I just know the term but totally have no
idea about this design pattern.
I have done a lot of Google searching on the implementation of the
Hollywood principle in Python. But there were few results.
Could any ... | [
"I've actually never heard the phrase \"Hollywood principle\" before, nor am I familiar with Twisted (though I feel I should be). But the concept of inversion of control isn't so difficult. I think GUI programming is a good way to introduce it. Consider the following from here (slightly modified).\nimport Tkinter\n... | [
6,
2,
2
] | [] | [] | [
"inversion_of_control",
"python",
"twisted"
] | stackoverflow_0006389248_inversion_of_control_python_twisted.txt |
Q:
Django markup templatetags error
I am getting the following errors in a django app:
TemplateSyntaxError at /
'markup' is not a valid tag library: Template library markup not found, tried django.templatetags.markup,django.contrib.admin.templatetags.markup
I have tried to following the solutions form this website w... | Django markup templatetags error | I am getting the following errors in a django app:
TemplateSyntaxError at /
'markup' is not a valid tag library: Template library markup not found, tried django.templatetags.markup,django.contrib.admin.templatetags.markup
I have tried to following the solutions form this website which suggests that that 'django.contri... | [
"Try calling render_to_response from python manage.py shell on the template in question, and please give a clip of the template file in question.\nFixed itself? Spooky. I hate those \"fixes\" because there's no guarantee that it won't break again or that the same \"fix\" will work again.\nThe only things I can thi... | [
2
] | [] | [] | [
"django",
"markup",
"python"
] | stackoverflow_0006399649_django_markup_python.txt |
Q:
Arrow keys, home, and end not functioning in django terminal
I'm using django 1.2.5 and python 2.7. For some reason the terminal type is wrong in the django shell and it is annoying the crap out of me. If I press up, down, right, left I get this:
>>> ^[[A^[[B^[[C^[[D
This only happens in ./manage.py shell. It's n... | Arrow keys, home, and end not functioning in django terminal | I'm using django 1.2.5 and python 2.7. For some reason the terminal type is wrong in the django shell and it is annoying the crap out of me. If I press up, down, right, left I get this:
>>> ^[[A^[[B^[[C^[[D
This only happens in ./manage.py shell. It's not a problem in the normal python interpreter and it happens indep... | [
"If you are using Ubuntu, you might just need to restart the terminal. I've had the Terminal start to act funny for no apparent reason. Though in my case the mouse clicks and movements would be printed as odd character strings.\n"
] | [
0
] | [] | [] | [
"django",
"python",
"shell"
] | stackoverflow_0006337299_django_python_shell.txt |
Q:
Wrapping C++ classes that contain wxString with Cython
I'm working on a Python extension to tie in with a C++ application written using wxWidgets for the GUI. I'm using Cython, and have the basic system (build tools, plus a starter extension with appropriate version details etc) happily working.
I'm only intereste... | Wrapping C++ classes that contain wxString with Cython | I'm working on a Python extension to tie in with a C++ application written using wxWidgets for the GUI. I'm using Cython, and have the basic system (build tools, plus a starter extension with appropriate version details etc) happily working.
I'm only interested in making backend (non-GUI) functionality available, such ... | [
"I got it to work by using the static wxString::FromUTF8() function to convert from Python to wxString, and the wxString.ToUTF8() to go in the other direction. The following is the code I came up with:\n# Import the parts of wxString we want to use.\ncdef extern from \"wx/string.h\":\n cdef cppclass wxString:\n ... | [
2,
0
] | [] | [] | [
"cython",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0006370560_cython_python_wxpython_wxwidgets.txt |
Q:
Python Help with Pygame and Multiprocessing
I'm using pygame to blit an image to screen, while it does the mainloop. I'm using multiprocessing for threads, but there seems to be a problem. Please don't chew me out over the weird wannabe xml comments, as I'm fairly new at this.
Here's my code.
#Import libraries
i... | Python Help with Pygame and Multiprocessing | I'm using pygame to blit an image to screen, while it does the mainloop. I'm using multiprocessing for threads, but there seems to be a problem. Please don't chew me out over the weird wannabe xml comments, as I'm fairly new at this.
Here's my code.
#Import libraries
import pygame
import os, sys
import multiprocessin... | [
"Here's what I believe is happening. Basically, the multiprocessing module works by sending copies of everything that the target needs to a brand new interpreter; that's how it skirts the GIL. But that means that side-effects (changes to global vars, changes to objects passed in but not returned) don't get propagat... | [
2
] | [] | [] | [
"audio",
"multiprocessing",
"pygame",
"python"
] | stackoverflow_0006400241_audio_multiprocessing_pygame_python.txt |
Q:
How do I use sorted dates in a list as keys for a dictionary in Python?
I have some Python code where I need to call upon a dictionary entry with a key that is a date.
start = (date_objects[0])
end = (date_objects[-1])
print "The study's first trading day was", start, "and the last day was", end,"."
... | How do I use sorted dates in a list as keys for a dictionary in Python? | I have some Python code where I need to call upon a dictionary entry with a key that is a date.
start = (date_objects[0])
end = (date_objects[-1])
print "The study's first trading day was", start, "and the last day was", end,"."
print ""
print histodict['2011-06-15']['Close']
print histodict[st... | [
"A date object is hashable. That's why you can use it as a dictionary key. But that doesn't mean a date object is hashed to the human-readable string representation you use (or see when you print the date object) because __hash__ and __str__ methods of date which do the hashing and converting to string are not nece... | [
1
] | [] | [] | [
"date",
"dictionary",
"key",
"list",
"python"
] | stackoverflow_0006400608_date_dictionary_key_list_python.txt |
Q:
How to reload/recompile the code in Python without closing the shell
Possible Duplicate:
reload (update) a .py file in the interpreter
I test some of my classes from Python in a terminal and I came across this issue.
If I test something and find a bug in a code, when I correct it in any text editor, then I find ... | How to reload/recompile the code in Python without closing the shell |
Possible Duplicate:
reload (update) a .py file in the interpreter
I test some of my classes from Python in a terminal and I came across this issue.
If I test something and find a bug in a code, when I correct it in any text editor, then I find myself closing the python shell where I did my testing, then removing the... | [
"this question is very similar and the answers tell you how do do the auto reloading stuff with ipython:\nreload (update) a module file in the interpreter\n",
"If your code is simple, your best bet is making changes in an editor, and re-running the program from scratch each time.\nIf you happen to have input/raw_... | [
3,
0
] | [] | [] | [
"load",
"python",
"testing"
] | stackoverflow_0006401050_load_python_testing.txt |
Q:
read text file (colon-separated words) and get a list of tuples
I have a text file called words.txt of word & description pairs separated by a colon, example:
word1:description 1 bla bla bla
word2:description 2 blah blah
...
I want a structure like this one:
[('word1', 'description 1 bla'), ('word2', 'description... | read text file (colon-separated words) and get a list of tuples | I have a text file called words.txt of word & description pairs separated by a colon, example:
word1:description 1 bla bla bla
word2:description 2 blah blah
...
I want a structure like this one:
[('word1', 'description 1 bla'), ('word2', 'description 2 blah')]
if you think another structure different than a list of t... | [
"How about just:\n[line.split(':', 1) for line in open('words.txt')]\n\nor\ndict(line.split(':', 1) for line in open('words.txt'))\n\n",
"data = []\nfor line in open('file.txt'):\n data.append(tuple(line.strip().split(':')))\n\nThe 'tuple' is only there to change the list returned by split to a tuple.\nOptionall... | [
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006380644_python.txt |
Q:
Best way to know if http request is GET or POST with DPKT?
I'm using the function dpkt.http.Request(), but sometimes the http flow is not a request.
Is there a quick way in python or dpkt to know if my request is GET or POST?
A:
Try parsing it as a HTTP request and catch dpkt.UnpackError so your program doesn't ... | Best way to know if http request is GET or POST with DPKT? | I'm using the function dpkt.http.Request(), but sometimes the http flow is not a request.
Is there a quick way in python or dpkt to know if my request is GET or POST?
| [
"Try parsing it as a HTTP request and catch dpkt.UnpackError so your program doesn't die if it's not a HTTP request.\nIf no exception was thrown, you can use .method of the Request object to get the method that was used.\n",
">>> import dpkt\n>>> r = dpkt.Request('GET / HTTP/1.0\\r\\n\\r\\n')\n\nFinding the HTTP ... | [
1,
1
] | [] | [] | [
"http",
"python"
] | stackoverflow_0006401232_http_python.txt |
Q:
How do I pass a fraction to python as an exponent in order to calculate the nth root of an integer?
I'm attempting to write a simple python script that will calculate the squareroot of a number. heres the code i've come up with and it works. but i would like to learn how to use fractional exponents instead.
var1 ... | How do I pass a fraction to python as an exponent in order to calculate the nth root of an integer? | I'm attempting to write a simple python script that will calculate the squareroot of a number. heres the code i've come up with and it works. but i would like to learn how to use fractional exponents instead.
var1 = input('Please enter number:')
var1 = int(var1)
var2 = var1**(.5)
print(var2)
thanks for the help
| [
"You can use fractional exponents with the help of fractions module.\nIn this module there is a class Fraction which works similar to our inbuilt int class.\nHere is a link to the documentation of the class - http://docs.python.org/library/fractions.html (just go through its first few examples to understand how it ... | [
11,
6
] | [] | [] | [
"fractions",
"math",
"python"
] | stackoverflow_0006401167_fractions_math_python.txt |
Q:
Why does this function add a border to all my images?
I'm using PIL.
im = im.rotate(angle=-90, expand = True)
When I do this, it adds a greyish border to my image.
Why?
Here's m full code. Note that if I don't rotate, it adds no borders
def fixRotation(f, quality=96, image_type="JPEG"):
#http://sylvana.net/jp... | Why does this function add a border to all my images? | I'm using PIL.
im = im.rotate(angle=-90, expand = True)
When I do this, it adds a greyish border to my image.
Why?
Here's m full code. Note that if I don't rotate, it adds no borders
def fixRotation(f, quality=96, image_type="JPEG"):
#http://sylvana.net/jpegcrop/exif_orientation.html
d =getEXIF(f)
if d:
... | [
"I made some experiment and indeed image size is altered but I didn't understad the exact behavior. To me looks like a bug in PIL... you should report it.\nIf you only need k*90 degrees then to do the rotation you can also use numpy...\nimg = Image.fromarray(numpy.rot90(numpy.array(img), n))\n\nn is the number of t... | [
1,
0,
0
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0004777263_image_python_python_imaging_library.txt |
Q:
conditional python with
I have a five or six resources that have nice 'with' handlers, and normally I'd do this:
with res1, res2, res3, res4, res5, res6:
do1
do2
However, sometimes one or more of these resources should not be activated. Which leads to very ugly repetitive code:
with res1, res3, res4, res6... | conditional python with | I have a five or six resources that have nice 'with' handlers, and normally I'd do this:
with res1, res2, res3, res4, res5, res6:
do1
do2
However, sometimes one or more of these resources should not be activated. Which leads to very ugly repetitive code:
with res1, res3, res4, res6: # these always acquired
... | [
"You could create a wrapper object that supports the with statement, and do the checking in there. Something like:\nwith wrapper(res1), wrapper(res2), wrapper(res3):\n ...\n\nor a wrapper than handles all of them:\nwith wrapper(res1, res2, res3):\n ...\n\nThe definition for you wrapper would be:\nclass wrapper(... | [
6,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0006399577_python.txt |
Q:
What is difference between crawling, Parsing, Indexing, Search from Python libraries perspective
I am confused between these terms. They somehow looks same to me.
Can someone please Explain me the steps in which order they perform and which libraries can do the work. To me its all look the same.
I want to know at... | What is difference between crawling, Parsing, Indexing, Search from Python libraries perspective | I am confused between these terms. They somehow looks same to me.
Can someone please Explain me the steps in which order they perform and which libraries can do the work. To me its all look the same.
I want to know at each step what is the input and what is the output e,g
Crawling
Input = URL
Output = ?
Indexing
Inpu... | [
"I'll give you a general discription, algorithmically, make the modifications to your python libs.\nCrawling: starting from a set of URLs and its goal is to expand the set's size, it actually follows out links and try to expand the graph as much as it can (until it covers the net-graph connected to the initial set ... | [
7,
0
] | [] | [] | [
"django",
"information_retrieval",
"python",
"search"
] | stackoverflow_0006400823_django_information_retrieval_python_search.txt |
Q:
Java applet or a custom browser plugin?
We're writing a platform for building apps that are able to run on any browser and we were thinking, is there a way to do this with Python? Or should we better go with Java and Java Applets?
I was also wondering, how hard is it to write a custom browser plugin? How long wou... | Java applet or a custom browser plugin? | We're writing a platform for building apps that are able to run on any browser and we were thinking, is there a way to do this with Python? Or should we better go with Java and Java Applets?
I was also wondering, how hard is it to write a custom browser plugin? How long would it take e.g. in man-hours?
Thank you!
| [
"The universal API for browser addons is javascript. It is well supported in Firefox, Chromium/Chrome, and Opera at least; it is the only extension API available on the last two. Intersting API subsets are firefox's Fuel, Chromium's trimmed down extension api, and the very portable GreaseMonkey functions.\nA second... | [
1
] | [] | [] | [
"applet",
"java",
"python"
] | stackoverflow_0006401415_applet_java_python.txt |
Q:
Connecting to MS Access 2007 (.accdb) database using pyodbc
I am on Win7 x64, using Python 2.7.1 x64. I am porting an application I created in VC++ to Python for educational purpouses.
The original application has no problem connecting to the MS Access 2007 format DB file by using the following connection string:
... | Connecting to MS Access 2007 (.accdb) database using pyodbc | I am on Win7 x64, using Python 2.7.1 x64. I am porting an application I created in VC++ to Python for educational purpouses.
The original application has no problem connecting to the MS Access 2007 format DB file by using the following connection string:
OleDbConnection^ conn = gcnew OleDbConnection("Provider=Microsoft... | [
"\nTry to use something like the following instead of using the same string as the one for OLeDb:\n\"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\DB.accdb;\"\nYou may not be able to talk to the driver directly from your x64 Python application: Access 2007 and its ACE driver are 32 bits only.\nInstead, ... | [
13
] | [] | [] | [
"64_bit",
"ms_access",
"pyodbc",
"python"
] | stackoverflow_0006396429_64_bit_ms_access_pyodbc_python.txt |
Q:
Google App Engine BlobProperty returns stale content
I store thumbnail images in Google App engine entities as BlobStoreProperties. Over time thumbnails need to be updated, which I do by updating the content of these entities with fresh image data. However I found out that any subsequent retrieval of these images ... | Google App Engine BlobProperty returns stale content | I store thumbnail images in Google App engine entities as BlobStoreProperties. Over time thumbnails need to be updated, which I do by updating the content of these entities with fresh image data. However I found out that any subsequent retrieval of these images still returns the same old copy that was saved first time ... | [
"In your SaveImageHandler you are creating a new Image entity each time you POST your image data, then you are just fetching the first image with that uid in your LoadImageHandler\nChange it to 'find or create' the image like:\nclass SaveImageHandler(webapp.RequestHandler):\n def post(self, uid):\n image = Imag... | [
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006401267_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python: Redefining function from within the function
I have some expensive function f(x) that I want to only calculate once, but is called rather frequently. In essence, the first time the function is called, it should compute a whole bunch of values for a range of x since it will be integrated over anyway and the... | Python: Redefining function from within the function | I have some expensive function f(x) that I want to only calculate once, but is called rather frequently. In essence, the first time the function is called, it should compute a whole bunch of values for a range of x since it will be integrated over anyway and then interpolate that one with splines, and cache the coeffic... | [
"This is overly complicated. Instead, use memoization: \ndef memoized(f):\n res = []\n def resf():\n if len(res) == 0\n res.append(f())\n return res[0]\n return resf\n\nand then simply\n@memoized\ndef f():\n # expensive calculation here ...\n return calculated_value\n\nIn Python 3... | [
6,
5,
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006401640_python.txt |
Q:
Celery asynchronous tasks in django project. How it works?
I need in my django project run long tasks. Desided to use celery with redis as broker. Installed redis runs:
The server is now ready to accept connections on port 6379
Than I install django-celery, configure:
import djcelery
djcelery.setup_loader()
BROK... | Celery asynchronous tasks in django project. How it works? | I need in my django project run long tasks. Desided to use celery with redis as broker. Installed redis runs:
The server is now ready to accept connections on port 6379
Than I install django-celery, configure:
import djcelery
djcelery.setup_loader()
BROKER_HOST = "localhost"
BROKER_PORT = 6379 #redis
BROKER_USER = "g... | [
"The BROKER_BACKEND setting is missing. Here is a example config for using Redis:\nimport djcelery\ndjcelery.setup_loader()\n\nCELERY_RESULT_BACKEND = 'database'\n\nBROKER_BACKEND = 'redis'\nBROKER_HOST = 'localhost'\nBROKER_PORT = 6379\nBROKER_VHOST = '1'\n\n",
"Don't know what this is, but I do know that Rabbit... | [
2,
0
] | [] | [] | [
"celery",
"django",
"django_celery",
"python",
"redis"
] | stackoverflow_0006397094_celery_django_django_celery_python_redis.txt |
Q:
pattern matching check if greater than symbol is not preceded by smaller than symbol
i would like to check if the greater sign is preceded by the smaller than sign.
what i really need is to check i there are more than one word seprated by space between the > and <.
for example :
<a v >
should be found because the... | pattern matching check if greater than symbol is not preceded by smaller than symbol | i would like to check if the greater sign is preceded by the smaller than sign.
what i really need is to check i there are more than one word seprated by space between the > and <.
for example :
<a v >
should be found because there are more than one "word" inside
and this :
< a >
should not
here is my python code
t... | [
"The match is: a >. This section matches your regex perfectly - it doesn't start with <, then it's got \"a \", which matches the bit in square brackets, and then there's a >.\nAre you trying to match the whole string? If you are, try re.match instead of re.search.\nOr you might want to try this code. It searches ... | [
4,
2
] | [] | [] | [
"pattern_matching",
"python",
"regex"
] | stackoverflow_0006401263_pattern_matching_python_regex.txt |
Q:
Unit Test Design
few days back i wrote a code as a part of my interview process. The question was given a text find if a query text is present in the given text or not. I used hashtable to save the given text (keys were the words present in the text and value was the position of that word in the text). So now give... | Unit Test Design | few days back i wrote a code as a part of my interview process. The question was given a text find if a query text is present in the given text or not. I used hashtable to save the given text (keys were the words present in the text and value was the position of that word in the text). So now given the query string, I ... | [
"I'd say if you know what your code is supposed to do, then you can write a unit test. In your test search case, I think it is safe to say that you can identify the expected output for a set of given inputs. Your interviewer might have had issues more with the coding of the text matcher and tests than with the prin... | [
1,
0
] | [] | [] | [
"algorithm",
"python",
"unit_testing"
] | stackoverflow_0006400234_algorithm_python_unit_testing.txt |
Q:
Getting error headers with urllib2
I need to send a PUT request to a web service and get some data out of error headers that is the expected result of the request. The code goes like this:
Request = urllib2.Request(destination_url, headers=headers)
Request.get_method = lambda: 'PUT'
try:
Response = urllib2.url... | Getting error headers with urllib2 | I need to send a PUT request to a web service and get some data out of error headers that is the expected result of the request. The code goes like this:
Request = urllib2.Request(destination_url, headers=headers)
Request.get_method = lambda: 'PUT'
try:
Response = urllib2.urlopen(Request)
except urllib2.HTTPError, ... | [
"e has undocumented headers and hdrs properties that contains the HTTP headers sent by the server.\nBy the way, 308 is not a valid HTTP status code.\n"
] | [
7
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0006402051_python_urllib2.txt |
Q:
Apache, mod_wsgi, Django, and a Python user agent
I am having a problem with a user agent written in Python that I am now trying to use with a Bitnami Amazon Web Service that has Apache, mod_wsgi (for Python), and Django pre-installed. I am having a problem when trying to POST data to the Django site from the Pyth... | Apache, mod_wsgi, Django, and a Python user agent | I am having a problem with a user agent written in Python that I am now trying to use with a Bitnami Amazon Web Service that has Apache, mod_wsgi (for Python), and Django pre-installed. I am having a problem when trying to POST data to the Django site from the Python user agent.
For instance, when I assemble an URL wi... | [
"As a start, check your Apache access and error logs and see if you find something fishy over there:\n\nHow to debug errors? \nOnce Apache\n starts, it will create two log files,\n the access_log and the error_log\n /installdir/apache2/logs directory.\n You can change these files to see the\n exact error in th... | [
0
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006390759_apache_django_mod_wsgi_python.txt |
Q:
Running a python script from a command line in Windows
I'm currently following the book, "Learning Python The Hard Way" and I am stuck trying to make a script run from the command line.
I have saved this text:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Y... | Running a python script from a command line in Windows | I'm currently following the book, "Learning Python The Hard Way" and I am stuck trying to make a script run from the command line.
I have saved this text:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable i... | [
"It looks like you are typing the line\npython ex13.py first 2nd 3rd\n\ninto the python interpreter. You are supposed to type that at the cmd prompt.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0006402411_python.txt |
Q:
Python mutually dependent classes (circular dependencies)
I've searched a lot, but what I find is mainly examples of recursive programming in python. So here goes the question:
How can I achieve this?
class A:
b = B()
class B:
a = A()
A:
Everything is dynamic in Python - even the class declarations. Th... | Python mutually dependent classes (circular dependencies) | I've searched a lot, but what I find is mainly examples of recursive programming in python. So here goes the question:
How can I achieve this?
class A:
b = B()
class B:
a = A()
| [
"Everything is dynamic in Python - even the class declarations. There's nothing to stop you modifying the contents of a class after the initial declaration:\nclass A:\n pass\n\nclass B:\n a = A()\n\nA.b = B()\n\nNB: If you're not that familiar with Python, the pass keyword simply allows you to say 'nothing h... | [
10
] | [] | [] | [
"circular_dependency",
"class",
"python"
] | stackoverflow_0006402522_circular_dependency_class_python.txt |
Q:
Better way to test several functions for the same thing in python
Assuming a python file with a whole bunch of functions I want to write tests for the functions using doctest. For example every function takes a string and a connection object (httplib.HTTPConnection(...)). So I want to test every function if the st... | Better way to test several functions for the same thing in python | Assuming a python file with a whole bunch of functions I want to write tests for the functions using doctest. For example every function takes a string and a connection object (httplib.HTTPConnection(...)). So I want to test every function if the string is empty or None. The tests would look like this.
def function_1(m... | [
"Never used doctest.\ndef genDocText(func_name):\n return r'''\n >>> conn = httplib.HTTPConnection(...)\n >>> %(func_name)s(None, conn)\n Traceback (most recent call last):\n NoneAsInputError: `mystring` should be a string and not `None`!\n\n >>> %(func_name)s(\"\", conn)\n Traceback (most rece... | [
4,
1
] | [] | [] | [
"doctest",
"python",
"repeat"
] | stackoverflow_0006402573_doctest_python_repeat.txt |
Q:
Django ForeignKey to Generic Python Data Type?
I am trying to create a django model which has as one of its fields a reference to some sort of python type, which could be either a integer, string, date, or decimal.
class MyTag(models.Model):
name = models.CharField(max_length=50)
object = (what goes here??... | Django ForeignKey to Generic Python Data Type? | I am trying to create a django model which has as one of its fields a reference to some sort of python type, which could be either a integer, string, date, or decimal.
class MyTag(models.Model):
name = models.CharField(max_length=50)
object = (what goes here??)
I know that if I want a foreign key to any other ... | [
"Since you want to filter, you would need some kind of DB support for your field and json field won't be that valuable for you. You can use some different solution with different \ncomplication levels according to your actual need. One suggestion is to serialize your data to string. Pad with enough zeros for str... | [
2,
0,
0
] | [] | [] | [
"django",
"foreign_keys",
"models",
"python"
] | stackoverflow_0006393733_django_foreign_keys_models_python.txt |
Q:
String adjustment in for-loop
Just a simple question:
str = ['blah','blah']
for word in str:
word = word * 2
print str
This just prints ['blah','blah']. Why (I know how to do this, just wondering why this isn't allowed)?
A:
When you assign a name a new value, it never changes the old value of the name:
word... | String adjustment in for-loop | Just a simple question:
str = ['blah','blah']
for word in str:
word = word * 2
print str
This just prints ['blah','blah']. Why (I know how to do this, just wondering why this isn't allowed)?
| [
"When you assign a name a new value, it never changes the old value of the name:\nword = word * 2\n\nThis takes the value of word, doubles it, and makes it the new value of word. The old value is unchanged.\n",
"The issue is that you have created a new string, but not updated the reference in the str list. This ... | [
1,
1,
0,
0
] | [] | [] | [
"for_loop",
"list",
"loops",
"python",
"string"
] | stackoverflow_0006402778_for_loop_list_loops_python_string.txt |
Q:
filter map vs list comprehension
Is filter/map equivalent to list comprehension?
Suppose I have the following function
def fib_gen():
a,b = 0,1
yield 0
yield 1
while True:
a,b = b,a+b
yield b
Now I can use list comprehension to list fib numbers:
a = fib_gen()
print [a.next() for i ... | filter map vs list comprehension | Is filter/map equivalent to list comprehension?
Suppose I have the following function
def fib_gen():
a,b = 0,1
yield 0
yield 1
while True:
a,b = b,a+b
yield b
Now I can use list comprehension to list fib numbers:
a = fib_gen()
print [a.next() for i in range(int(sys.argv[1]))]
Suppose I... | [
"\nIs filter/map equivalent to list comprehension?\n\nYes, map(f, L) is equivalent to [f(x) for x in L]. filter(f, L) is equivalent to [x for x in L if f(x)]. But, since list comprehensions with side effects are generally bad (and here you modify the state of the generator), you can use itertools for a bit cleaner ... | [
13,
10,
7,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006402824_python.txt |
Q:
problem: how to verify affiliation of object in the collection of objects
I have a collection of objects. Objects are instance of the same class. I need to verify that the variable reviewed_object_name occurs in the object_name field of any object in the collection.
When I have a simple collection the solution is ... | problem: how to verify affiliation of object in the collection of objects | I have a collection of objects. Objects are instance of the same class. I need to verify that the variable reviewed_object_name occurs in the object_name field of any object in the collection.
When I have a simple collection the solution is obvious:
reviewed_object_name = "Hotel Roma"
reviewed_objects_collection = ["Ho... | [
"any() with a genex.\nany(reviewed_object_name == reviewed_object.name for reviewed_object in reviewed_objects_collection)\n\n"
] | [
2
] | [] | [] | [
"iterator",
"lambda",
"python"
] | stackoverflow_0006403133_iterator_lambda_python.txt |
Q:
Google app engine(python) ImportError: No module named oauth2 in google app engine
I have used python twitter script from http://code.google.com/p/python-twitter/
and oauth2 from https://github.com/simplegeo/python-oauth2
A:
To import third-party modules in App Engine, they need to be included (or symlinked) in ... | Google app engine(python) ImportError: No module named oauth2 in google app engine | I have used python twitter script from http://code.google.com/p/python-twitter/
and oauth2 from https://github.com/simplegeo/python-oauth2
| [
"To import third-party modules in App Engine, they need to be included (or symlinked) in the project directory. Your regular PYTHONPATH isn't checked, as modules installed on your local machine most likely won't be available on the production servers.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"oauth_2.0",
"python",
"twitter"
] | stackoverflow_0006403000_google_app_engine_oauth_2.0_python_twitter.txt |
Q:
Extract URL where text matches a regex - with XPath 1.0
I would like to extract the URL of this type (link text is a number with any number of digits and href is a random text) using an XPath in Scrapy.
<a href="http://www.example.com/link_to_some_page.html>3</a>
<a href="http://www.example.com/another_link-abcd... | Extract URL where text matches a regex - with XPath 1.0 | I would like to extract the URL of this type (link text is a number with any number of digits and href is a random text) using an XPath in Scrapy.
<a href="http://www.example.com/link_to_some_page.html>3</a>
<a href="http://www.example.com/another_link-abcd.html>45</a>
I could think of something like
HtmlXPathSelec... | [
".select('//a[. != \"\" and translate(., \"0123456789\", \"\") = \"\"]/@href')\n\n"
] | [
3
] | [] | [] | [
"lxml",
"python",
"regex",
"scrapy",
"xpath"
] | stackoverflow_0006402980_lxml_python_regex_scrapy_xpath.txt |
Q:
Function bound to resize event of wxpython widget gets called more than once while resizing
I have made a small app with a GUI in python using the wxpython toolkit. It consists of a frame as the top window and 100 StaticText child widgets. I have bind their size events (wx.EVT_SIZE) to a OnResize function which ch... | Function bound to resize event of wxpython widget gets called more than once while resizing | I have made a small app with a GUI in python using the wxpython toolkit. It consists of a frame as the top window and 100 StaticText child widgets. I have bind their size events (wx.EVT_SIZE) to a OnResize function which changes their font according to the size of the StaticText widgets. (This helps to increase or decr... | [
"Consider an alternative approach.\nKeep a variable of the previously processed size. Then, in your size handler, only change the font size if the size of the widget actually changed since the last size event.\ndef OnResize(self, event):\n w, h = size = self.GetSize()\n if size != self.previous_size:\n ... | [
5
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006402125_python_wxpython.txt |
Q:
NoneType when changing a value in Python class dictionary
I'm trying to change the dictionary of a python class so that everytime a function object is added to the dictionary I add an instance of my class where I redefine __call__ instead.
I use a custom dictionary for the metaclass and in __setitem__ of the dicti... | NoneType when changing a value in Python class dictionary | I'm trying to change the dictionary of a python class so that everytime a function object is added to the dictionary I add an instance of my class where I redefine __call__ instead.
I use a custom dictionary for the metaclass and in __setitem__ of the dictionary class I'm instantiating the class that I use to change th... | [
"I am not sure what you have done exactly, but you might find setdefault useful:\n\nsetdefault(key[, default])\n\nIf key is\n in the dictionary, return its value.\n If not, insert key with a value of\n default and return default. default\n defaults to None.\n\n\nDetailed info: Use cases for the 'setdefa... | [
2,
2
] | [] | [] | [
"dictionary",
"metaclass",
"prepare",
"python"
] | stackoverflow_0006403259_dictionary_metaclass_prepare_python.txt |
Q:
Python - run through a loop in non linear fashion
SO,
I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. i.e. I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for al... | Python - run through a loop in non linear fashion | SO,
I am searching for a way to loop through a list of items in a for loop fashion, except I want the loop to iterate in a 'random' way. i.e. I dont want the loop to go 0,1,2,3,m+1...n, I want it to pick it in some random order and still run through the loop for all items.
Here is my current looping code:
for singleSel... | [
"If listOfItems can be shuffled, then\nimport random\nrandom.shuffle(listOfItems)\nfor singleSelectedItem in listOfItems:\n blahblah\n\notherwise\nimport random\nrandomRange = range(len(listOfItems))\nrandom.shuffle(randomRange)\nfor i in randomRange:\n singleSelectedItem = listOfItems[i]\n blahblah\n\nEdi... | [
9,
1,
1,
0
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0006403607_for_loop_list_python.txt |
Q:
classmethod as self-creating object constructor
'm working with code to manage objects on a remote store, which means I can either create objects as the result of a read from the store, or create objects which are sent to the store at creation time. The real goal here is to only create objects when the representat... | classmethod as self-creating object constructor | 'm working with code to manage objects on a remote store, which means I can either create objects as the result of a read from the store, or create objects which are sent to the store at creation time. The real goal here is to only create objects when the representation of the object on the remote store exists - if the... | [
"No need.\nclass myClass(object):\n def __new__(cls, parameter1, parameter2):\n if SendToRemoteStore(parameter1, parameter2):\n return super(myClass, cls).__new__(cls)\n else:\n return None\n\n def __init__(self, parameter1, parameter2):\n self.param1 = parameter1\n self.param2 = parameter2\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006403797_python.txt |
Q:
find position of item in for loop over a sequence
Possible Duplicate:
Accessing the index in Python for loops
list = [1,2,2,3,5,5,6,7]
for item in mylist:
...
How can I find the index of the item I am looking at, at some point in my loop? I can see there is a index() method for lists but it will always giv... | find position of item in for loop over a sequence |
Possible Duplicate:
Accessing the index in Python for loops
list = [1,2,2,3,5,5,6,7]
for item in mylist:
...
How can I find the index of the item I am looking at, at some point in my loop? I can see there is a index() method for lists but it will always give me the first index of a value, so it won't work for ... | [
"Have a look at enumerate\n>>> for i, season in enumerate('Spring Summer Fall Winter'.split(), start=1):\n print i, season\n1 Spring\n2 Summer\n3 Fall\n4 Winter\n\n",
"Use an enumerator object:\nfor index, item in enumerate(mylist):\n ...\n\n"
] | [
16,
6
] | [] | [] | [
"python"
] | stackoverflow_0006404129_python.txt |
Q:
Python urllib2 and connection refused on google maps geocoding
I am doing a simple geocoding of addresses using Google maps api.
Here is a snipped and getting a "[Errno 61] Connection refused":
import urllib2
url='http://maps.googleapis.com/maps/api/geocode/json?address=800+S.+Pacific+Coast+Hwy,+Redondo+Beach,+C... | Python urllib2 and connection refused on google maps geocoding | I am doing a simple geocoding of addresses using Google maps api.
Here is a snipped and getting a "[Errno 61] Connection refused":
import urllib2
url='http://maps.googleapis.com/maps/api/geocode/json?address=800+S.+Pacific+Coast+Hwy,+Redondo+Beach,+CA&sensor=false'
req = urllib2.Request(url)
print vars(req)
response=... | [
"Code is fine. I think you just exceed: Google geocoding limits\n"
] | [
1
] | [] | [] | [
"google_maps",
"python",
"urllib"
] | stackoverflow_0006404487_google_maps_python_urllib.txt |
Q:
PyGTK TreeView showing blank rows from ListStore
I'm trying to show several rows from database in a TreeView but all I am getting are some dummy rows as you can see in the image below.
class SettingsDialog(gtk.Dialog):
def __init__(self):
gtk.Dialog.__init__(self, "Server Settings", self, gtk.DIALOG_M... | PyGTK TreeView showing blank rows from ListStore | I'm trying to show several rows from database in a TreeView but all I am getting are some dummy rows as you can see in the image below.
class SettingsDialog(gtk.Dialog):
def __init__(self):
gtk.Dialog.__init__(self, "Server Settings", self, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
# Inst... | [
"You have to set an attribute mapping on the column. For example, the cellrenderer's text attribute value will be displayed in the treeview cell. It is taken from the values on the data model (self.liststore). The column number on the model where the value is taken from is specified in the attribute mapping.\n## Ta... | [
4
] | [] | [] | [
"gtk",
"gtktreeview",
"python"
] | stackoverflow_0006404739_gtk_gtktreeview_python.txt |
Q:
php regular expression convert to python code
i have this code written in php, and i want to convert it into python code
$title_regex = "/<title>(.+)<\/title>/i";
preg_match_all($title_regex, $string, $title, PREG_PATTERN_ORDER);
$url_title = $title[1];
/// fecth decription
$tags = get_meta_tags($url);
// fetch... | php regular expression convert to python code | i have this code written in php, and i want to convert it into python code
$title_regex = "/<title>(.+)<\/title>/i";
preg_match_all($title_regex, $string, $title, PREG_PATTERN_ORDER);
$url_title = $title[1];
/// fecth decription
$tags = get_meta_tags($url);
// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*... | [
"the regular expression probably did not find anything.\ntry this :\nalso remove the /Ui at the end\nimport re\nout=Data #web site html page ..\ntitle_regex = \"/<title>(.+)<\\/title>/i\" #no need for this .. un used \nif m is not None: # NEW <----------------\n m = re.search(\"<title>(.+)<\\/title>\", out)\np... | [
2,
0
] | [] | [] | [
"php",
"python",
"regex"
] | stackoverflow_0006397021_php_python_regex.txt |
Q:
Window and system tray icon does not appear when referenced from resources
This is testTray.py
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import imgAgent_rc
class Window(QDialog):
def __init__(self):
super(Window, self).__init__()
self.trayIcon = QSystemTrayIcon(self)
ic... | Window and system tray icon does not appear when referenced from resources | This is testTray.py
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import imgAgent_rc
class Window(QDialog):
def __init__(self):
super(Window, self).__init__()
self.trayIcon = QSystemTrayIcon(self)
icon = QIcon(':/images/logo/image_16x16.png') # Problem
#icon = QIcon(... | [
"Try with this resource file code:\n<RCC>\n <qresource>\n <file>images/logo/image_16x16.png</file>\n </qresource>\n</RCC>\n\n"
] | [
2
] | [] | [] | [
"pyqt",
"python",
"python_3.x",
"resources"
] | stackoverflow_0006404797_pyqt_python_python_3.x_resources.txt |
Q:
mysqldb db host is not being accepted?
I do :
db=_mysql.connect(host="83.101.*.*",port=****,passwd="mypassword",user="myuser",db="myDB")
and I get this error message :
OperationalError: (1045, "Access denied for user 'myuser'@'91.176.*.*' (using password: YES)")
the 91.176.. is my home IP the 83.101.. is my ser... | mysqldb db host is not being accepted? | I do :
db=_mysql.connect(host="83.101.*.*",port=****,passwd="mypassword",user="myuser",db="myDB")
and I get this error message :
OperationalError: (1045, "Access denied for user 'myuser'@'91.176.*.*' (using password: YES)")
the 91.176.. is my home IP the 83.101.. is my server I am trying to reach. I can't seem to fi... | [
"If you have SSH to your server, from the server shell login as root in mysql, and set host to '%' in the mysql.users table for the myuser record.\nIf this is a paid hosting / server, ask your support to enable remote login.\n",
"That combination of username and host does not have that password. Either the userna... | [
2,
0
] | [] | [] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0006405093_mysql_mysql_python_python.txt |
Q:
What's the pythonic way to deal with worker processes that must coordinate their tasks?
I'm currently learning Python (from a Java background), and I have a question about something I would have used threads for in Java.
My program will use workers to read from some web-service some data periodically. Each worker ... | What's the pythonic way to deal with worker processes that must coordinate their tasks? | I'm currently learning Python (from a Java background), and I have a question about something I would have used threads for in Java.
My program will use workers to read from some web-service some data periodically. Each worker will call on the web-service at various times periodically.
From what I have read, it's prefe... | [
"Delegate the retrieval to a separate process which queues the requests until it is their turn.\n",
"I think that you'll find that the multiprocessing module will provide you with some fairly familiar constructs.\nYou might find that multiprocessing.Queue is useful for connecting your worker threads back to a man... | [
2,
2,
0
] | [] | [] | [
"concurrency",
"multiprocessing",
"python"
] | stackoverflow_0006404872_concurrency_multiprocessing_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.