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:
Python socket strangly hanged - sometimes (client connects with flash) - python 3.2
I experience strange behavior of sockets in Python (3.2). Client connects to my application using Flash. Most of the time there is nothing unusual but sometimes python crashes in a way that should not have taken place - enter into ... | Python socket strangly hanged - sometimes (client connects with flash) - python 3.2 | I experience strange behavior of sockets in Python (3.2). Client connects to my application using Flash. Most of the time there is nothing unusual but sometimes python crashes in a way that should not have taken place - enter into infinite loops. Below I attach to the loop code and error message in the log. Python hang... | [
"python's socket module closely matches the BSD socket API.\nwhen the remote side of a socket (here, your flash client) is closed, the recv() call on the local side (here, your python server) will return an empty string (''). there is no need to continue processing, since the client won't send anything more: the ch... | [
0
] | [] | [] | [
"flash",
"python",
"sockets"
] | stackoverflow_0006692618_flash_python_sockets.txt |
Q:
Threading in a django app
I'm trying to create what I call a scrobbler. The task is to read a Delicious user from a queue, fetch all of their bookmarks and put them in the bookmarks queue. Then something should go through that queue, do some parsing and then store the data in a database.
This obviously calls for t... | Threading in a django app | I'm trying to create what I call a scrobbler. The task is to read a Delicious user from a queue, fetch all of their bookmarks and put them in the bookmarks queue. Then something should go through that queue, do some parsing and then store the data in a database.
This obviously calls for threading because most of the ti... | [
"You can not use threading with in memory databases (sqlite3 in this case) in Django see this bug. This might work with PostgreSQL or MySQL.\nI'd recommend something like celeryd instead of threads, message queues are MUCH easier to work with than threading.\n",
"This calls for a task queue, though not necessaril... | [
2,
1,
1,
0
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0002052237_django_multithreading_python.txt |
Q:
reading codec info of a file in python
I have a container file, for eg a .mp4. How do I read the audio codec and video codec info of this file using Python. I just need to find out the codec info. Can anyone please help me?
A:
You can use MediaInfo.
There is a Python wrapper for it. You can also use the dll di... | reading codec info of a file in python | I have a container file, for eg a .mp4. How do I read the audio codec and video codec info of this file using Python. I just need to find out the codec info. Can anyone please help me?
| [
"You can use MediaInfo. \nThere is a Python wrapper for it. You can also use the dll directly\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006693270_python.txt |
Q:
Python - parsing apache config with regexp
I want to parse configuration files like apache2.conf, which looks like this:
<Group group1>
param1 1
<SomeGroup group3>
param3 3
</SomeGroup>
</Group>
<Group group2>
param2 2
</Group>
Regexp:
re.findall(r'\</?[^\>]+\>([\s\S]+)\<//?[^\>]+\>', text, re... | Python - parsing apache config with regexp | I want to parse configuration files like apache2.conf, which looks like this:
<Group group1>
param1 1
<SomeGroup group3>
param3 3
</SomeGroup>
</Group>
<Group group2>
param2 2
</Group>
Regexp:
re.findall(r'\</?[^\>]+\>([\s\S]+)\<//?[^\>]+\>', text, re.MULTILINE)
if I use lazy regexp, it cuts like ... | [
"Augeas has python bindings.\n",
"There is no way to do this with regexp alone. The regexp engine has no state, so you can only parse very simple input. See here for other options: Any python libs for parsing apache config files?\n"
] | [
2,
1
] | [] | [] | [
"apache",
"apache2",
"configuration",
"python",
"regex"
] | stackoverflow_0006693361_apache_apache2_configuration_python_regex.txt |
Q:
Retrieving SQLAlchemy query objects through declaritive_base class methods
I can't help but think that the number of keystrokes required to do a query in SQLAlchemy is a little on the high side.
DBSession.query(User).filter(...).first()
Is there anything wrong with doing something like this?
DBSession = scoped_se... | Retrieving SQLAlchemy query objects through declaritive_base class methods | I can't help but think that the number of keystrokes required to do a query in SQLAlchemy is a little on the high side.
DBSession.query(User).filter(...).first()
Is there anything wrong with doing something like this?
DBSession = scoped_session(sessionmaker())
class BaseWithDBSession(object):
def delete(self):
... | [
"Well, there are many ways of doing this sort of thing - see Mike Bayer's tongue-in-cheek post about Magic, a \"new\" ORM. SQLAlchemy postions itself as a toolkit rather than a framework, so that it can be used in different ways according to the needs of different scenarios. For example, there will be scenarios whe... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006693541_python_sqlalchemy.txt |
Q:
wxpython: Guess if EVT_LIST_ITEM_ACTIVATED was triggered by ENTER or by DOUBLECLICK
In the ListCtrl widget, when a wx.EVT_LIST_ITEM_ACTIVATED event is processed in a callback function...
How can I guess if the event was triggered by DOUBLECLICK or by ENTER KEY?
I need to distinguish them, something like:
def My_Li... | wxpython: Guess if EVT_LIST_ITEM_ACTIVATED was triggered by ENTER or by DOUBLECLICK | In the ListCtrl widget, when a wx.EVT_LIST_ITEM_ACTIVATED event is processed in a callback function...
How can I guess if the event was triggered by DOUBLECLICK or by ENTER KEY?
I need to distinguish them, something like:
def My_List_Item_Activated_CallBack( self, event ):
if EVENT_WAS_TRIGGERED_BY_ENTER:
... | [
"I don't think that event has that kind of information. Why not just bind to EVT_LEFT_DCLICK and set some kind of flag that you can check in the handler for EVT_LIST_ITEM_ACTIVATED? If the flag isn't set, then you can assume the enter key was pressed. Of course, you'll need to reset the flag in the item activated h... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006693314_python_wxpython.txt |
Q:
Execute python code without invoking import statement each time
Here is a sample python script. How do I run this script multiple times from command line so that the import line is not called every time? The import statement takes too long to load.
import arcpy
val = arcpy.GetCellValue_management("D:\dem-merged\li... | Execute python code without invoking import statement each time | Here is a sample python script. How do I run this script multiple times from command line so that the import line is not called every time? The import statement takes too long to load.
import arcpy
val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
print str(v... | [
"This problem has no solution if you strictly want this script \"to be called from another program. by issuing 'python script.py' on command line\".\nIf you want to do the \"heavy import\" only once, you have to start python script only once.\nThink about starting a daemon, which will start once and then process ca... | [
6,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"command_line",
"import",
"python"
] | stackoverflow_0006687363_command_line_import_python.txt |
Q:
How do I get the public dns of an instance in AWS
I get the elb details of a specific region, say Europe. Then I am able to get the instances that are related to the ELB. The problem is I am not able to get the public dns of those instances. What I do is:
conn = regions[3].connect(aws_access_key_id= access, aws_se... | How do I get the public dns of an instance in AWS | I get the elb details of a specific region, say Europe. Then I am able to get the instances that are related to the ELB. The problem is I am not able to get the public dns of those instances. What I do is:
conn = regions[3].connect(aws_access_key_id= access, aws_secret_access_key = secret_key)
loadbalancers = conn.get_... | [
"The \"instances\" attribute of the LoadBalancer class only contains a tiny bit of information about the instance - it's not a full Instance object. To get the full instance object you must use the instanceId, which is available, to query for more info. This code snippet extends yours with the required calls:\n#C... | [
9
] | [] | [] | [
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0006671253_amazon_web_services_boto_python.txt |
Q:
OK/CANCEL order in "custom" dialogs created with wxglade
I've noticed that standard dialogs some CANCEL and OK buttons in different order under Windows and under Linux. Under Linux, you get "[CANCEL] [OK]", and under Windows, "[OK] [CANCEL]".
I have no problem with the standard dialogs, but then my "custom dialogs... | OK/CANCEL order in "custom" dialogs created with wxglade | I've noticed that standard dialogs some CANCEL and OK buttons in different order under Windows and under Linux. Under Linux, you get "[CANCEL] [OK]", and under Windows, "[OK] [CANCEL]".
I have no problem with the standard dialogs, but then my "custom dialogs" must be tweaked to match the same order, dependent of the O.... | [
"The StdDialogButtonSizer is definitely the way to go for custom dialogs. Here's a simple example:\nimport wx\n\n########################################################################\nclass SampleDialog(wx.Dialog):\n \"\"\"\"\"\"\n\n #----------------------------------------------------------------------\n... | [
5
] | [] | [] | [
"python",
"wxglade",
"wxpython"
] | stackoverflow_0006693660_python_wxglade_wxpython.txt |
Q:
Evaluating django paginator with GAE
Is it a good idea to add the django paginator to our google app engine project to enable pagination? It looks tempting since I otherwise fail to implement pagination though there can be hidden disadvantages. For instance the PageQuery class that we tried yesterday couldn't page... | Evaluating django paginator with GAE | Is it a good idea to add the django paginator to our google app engine project to enable pagination? It looks tempting since I otherwise fail to implement pagination though there can be hidden disadvantages. For instance the PageQuery class that we tried yesterday couldn't page SearchableModel(!) but django paginator c... | [
"A friend of mine uses it and has performance problems, I think it uses limit and offset which is not a great fit for AppEngine. The proper solution would be to use a paginator that uses cursors.\n"
] | [
2
] | [] | [] | [
"django",
"google_app_engine",
"pagination",
"python"
] | stackoverflow_0006693121_django_google_app_engine_pagination_python.txt |
Q:
Problem with queries, Redland and python bindings
I'm developing a semantic reverse proxy that extracts metadata. I use Django, dj-revproxy and RDFLib (and for the storage I use MySQL), but i'm switching to redland's framework with the python bindings for the management of the semantic part.
But I have an importa... | Problem with queries, Redland and python bindings | I'm developing a semantic reverse proxy that extracts metadata. I use Django, dj-revproxy and RDFLib (and for the storage I use MySQL), but i'm switching to redland's framework with the python bindings for the management of the semantic part.
But I have an important problem. After the storage of an RDF (The data is in... | [
"I found the problem after upgrading to the GIT version of all the Redland libs (raptor, rasqal...). The problem is when I connect to MySQL database the new=true ruins all the stored data (data remains there, but the queries are null).\nIn other words, to solve the problem you have to update the libs and then the f... | [
2
] | [] | [] | [
"mysql",
"python",
"redland",
"semantics"
] | stackoverflow_0006355557_mysql_python_redland_semantics.txt |
Q:
CRON Job Not Processing
So, I have a CRON job that is simply not working.
For a while (about 5 hours), there was an error in the script myapp.py, because of a password change.
During this time, CRON (understandably) spammed my inbox to death with the same failure notice about 300 times.
So, I fixed the script and ... | CRON Job Not Processing | So, I have a CRON job that is simply not working.
For a while (about 5 hours), there was an error in the script myapp.py, because of a password change.
During this time, CRON (understandably) spammed my inbox to death with the same failure notice about 300 times.
So, I fixed the script and turned the CRON job off (read... | [
"I fixed the issue. For whatever reason, my hosting service requires the command to be wrapped in quotes.\n# canary\nMAILTO=\"pcperini@aim.com\"\n# 1 myapp\n* * * * * \"$HOME/html/cron/app/myapp.py\"\n\n"
] | [
1
] | [] | [] | [
"cron",
"crontab",
"python"
] | stackoverflow_0006438784_cron_crontab_python.txt |
Q:
In python, how to parse a file into lists based on a specific value?
I have a large tab delimited text file, for example, call it john_file:
1 john1 23 54 54
2 john2 34 45 66
3 john3 35 43 54
4 john2 34 54 78
5 john1 12 34 65
6 john3 34 55 66
What's a quick way to parse this file into 3 lists based on name(john1... | In python, how to parse a file into lists based on a specific value? | I have a large tab delimited text file, for example, call it john_file:
1 john1 23 54 54
2 john2 34 45 66
3 john3 35 43 54
4 john2 34 54 78
5 john1 12 34 65
6 john3 34 55 66
What's a quick way to parse this file into 3 lists based on name(john1, 2 or 3)?
fh=open('john_file.txt','r').readlines()
john1_list=[]
for i in... | [
"from collections import defaultdict\n\nd = defaultdict(list)\n\nwith open('john_file.txt') as f:\n for line in f:\n fields = line.split('\\t')\n d[fields[1]].append(line)\n\nThe individual lists are then in d['john1'], d['john2'] etc\n",
"You could do something like:\nfh=open('john_file.txt','r'... | [
6,
0,
0,
0
] | [] | [] | [
"file",
"list",
"parsing",
"python"
] | stackoverflow_0006668401_file_list_parsing_python.txt |
Q:
boost.python and qt
i have written a library with some classes that make use of qt object such as QVector, QColor etc, without inheriting from them. Now I would like to make these objects (partially) available to python. I first tried SIP, but this is so poorly documented that I can't even build the example. Now I... | boost.python and qt | i have written a library with some classes that make use of qt object such as QVector, QColor etc, without inheriting from them. Now I would like to make these objects (partially) available to python. I first tried SIP, but this is so poorly documented that I can't even build the example. Now I am trying boost.python, ... | [
"You need QtGui for QColor, not just QtCore.\n"
] | [
2
] | [] | [] | [
"boost",
"python",
"qt"
] | stackoverflow_0006694803_boost_python_qt.txt |
Q:
trouble using str.center() with unicode characters
I observed this strange behaviour of center method of str objects in python 2.7 -
>>> print '-'.center(5,'.') # '-' is the minus or hyphen key on the keyboard.
..-.. # correctly centered
>>> print '─'.center(5, '.') # '─' ... | trouble using str.center() with unicode characters | I observed this strange behaviour of center method of str objects in python 2.7 -
>>> print '-'.center(5,'.') # '-' is the minus or hyphen key on the keyboard.
..-.. # correctly centered
>>> print '─'.center(5, '.') # '─' is NOT the minus or hyphen key on the keyboard.
.─. ... | [
"In Python 2, there's a distinction between the str and unicode types. A str is a sequence of bytes and is created with un-modified quotes. Your '─' is creating a sequence of 3 bytes which display as a single unicode character; when you ask str.center() to center those bytes in a field 5 bytes wide, it adds a singl... | [
3,
2
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006694428_python_python_2.7.txt |
Q:
Help understanding how this recursive python function works?
i'm a a programmer, i do some C# perl and python,
anyways, i found this recursive code to generate permutations, of a list of symbols and letters, but i can't figure out how it works? can anyone care to explain it please?
#!/usr/bin/env python
#-*- codin... | Help understanding how this recursive python function works? | i'm a a programmer, i do some C# perl and python,
anyways, i found this recursive code to generate permutations, of a list of symbols and letters, but i can't figure out how it works? can anyone care to explain it please?
#!/usr/bin/env python
#-*- coding:utf-8 -*-
def generate(charlist,state,position):
for i in c... | [
"This does not generate permutations. It generates n-dimensional cartesian products. (In the process, it also generates all permutations, but the algorithm to generate only permutations would be different.) \nIt's a bit difficult to explain how it works, but if you look at the output for small input, you can see wh... | [
3,
2,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0006694404_function_python.txt |
Q:
How can you properly read RRD files using Java?
How can you properly read RRD files using Java? We are using tools like JRobin, etc. but my team is having problems with those tools, they don't seem to properly read the RRD files. We need to use RRDTool, and that tool is an importable library for Python.
A:
You c... | How can you properly read RRD files using Java? | How can you properly read RRD files using Java? We are using tools like JRobin, etc. but my team is having problems with those tools, they don't seem to properly read the RRD files. We need to use RRDTool, and that tool is an importable library for Python.
| [
"You could try using JPython to bridge it to Java.\nBut the easiest is probably to either use Python, or fix the bygs in JRobin. It's open source after all.\n",
"use the \"rrdtool -\" pipe interface and use the real rrdtool to access the files.\n",
"Original documetation from RRDTools site describe common way t... | [
1,
1,
1
] | [] | [] | [
"java",
"programming_languages",
"python",
"rrd",
"rrdtool"
] | stackoverflow_0005521165_java_programming_languages_python_rrd_rrdtool.txt |
Q:
Problem with redirection in python appengine
I am trying to create some alias ::
util.run_wsgi_app(webapp.WSGIApplication([
(r"/(.{1,2})", MainPage)
], debug=debug)
class MainPage(webapp.RequestHandler):
def get(self,token):
token_dict = {
'fb':'http://www.facebook.com/anilashanbhag',
'+'... | Problem with redirection in python appengine | I am trying to create some alias ::
util.run_wsgi_app(webapp.WSGIApplication([
(r"/(.{1,2})", MainPage)
], debug=debug)
class MainPage(webapp.RequestHandler):
def get(self,token):
token_dict = {
'fb':'http://www.facebook.com/anilashanbhag',
'+' :'http://plus.google.com/106274357148468411814',
... | [
"The + is a reserved character outlined in RFC 1738 - Uniform Resource Locators (URL) specification. It's reserved because it is used as part of the delimiter syntax in URL's. Try URL Encoding your character (%2B) and see if that helps.\n",
"Ok for the sake of completion : The correct answer is :: \n\"%2B\" is 3 ... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python",
"regex"
] | stackoverflow_0006677733_google_app_engine_python_regex.txt |
Q:
ZODB transaction commit calls __getstate__ multiple times
I'm creating a caching system using ZODB. The objects I am putting in the DB required me to use the __getstate__ and __setstate__ methods because they contain images that I convert to strings and store in Blobs.
I didn't find anyone with a similar problem ... | ZODB transaction commit calls __getstate__ multiple times | I'm creating a caching system using ZODB. The objects I am putting in the DB required me to use the __getstate__ and __setstate__ methods because they contain images that I convert to strings and store in Blobs.
I didn't find anyone with a similar problem so I'm assuming I'm doing something stupid. The problem I'm ha... | [
"After hours and hours of additional research and testing here's my answer to my own question...\nThe simple answer is you MUST subclass from persistent.Persistent.\nI wanted to avoid doing this (and I though I could from some of the research I had done) because of my need for a custom __getstate__ and __setstate__... | [
1
] | [] | [] | [
"python",
"zodb"
] | stackoverflow_0006684241_python_zodb.txt |
Q:
Check in Zope if a Object / image is available / uploaded
im using zope2.10 with python
and i would like to check if a image File is uploaded
I am in my own Product and i have a path as string like:
/Media/News/2010/image
and i want to check if it is image.gif or image.jpg
But i don't know how to check
So it will... | Check in Zope if a Object / image is available / uploaded | im using zope2.10 with python
and i would like to check if a image File is uploaded
I am in my own Product and i have a path as string like:
/Media/News/2010/image
and i want to check if it is image.gif or image.jpg
But i don't know how to check
So it will be just a file checker.
Does the file exist in zope yes/no re... | [
"In normal filesystem Python code, you would use the path to traverse to to container, and then check the two IDs in the container. E.g.:\ncontainer = context.unrestrictedTraverse('/media/news/2010')\nitem_ids = list(container.objectIds())\nfor image_id in ('image.jpg', 'image.gif', 'image.png'):\n if image_id ... | [
2,
0
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0006690895_python_zope.txt |
Q:
Access Denied with Amazon CloudFront private distribution
I'm am trying to setup CloudFront for private content distribution but I keep getting Access Denied errors when I follow the generated URL. To be clear, I have already created the CloudFront distribution, marked it private, created an Origin Access ID which... | Access Denied with Amazon CloudFront private distribution | I'm am trying to setup CloudFront for private content distribution but I keep getting Access Denied errors when I follow the generated URL. To be clear, I have already created the CloudFront distribution, marked it private, created an Origin Access ID which has been given read permission to all the relevant files.
I'v... | [
"Running your method I get an ampersand before the first keywork, Expires. \n>>> GetCloudFrontURL('test123')\nhttp://mydistribution.cloudfront.net/test123&Expires=1297954193&Signature=&Key-Pair-Id=MY-PK-GOES-HERE\n\nDon't know if it solves your whole problem but I suspect you need question mark in the URL to get t... | [
1,
1,
0
] | [] | [] | [
"amazon_cloudfront",
"amazon_s3",
"amazon_web_services",
"python"
] | stackoverflow_0004810854_amazon_cloudfront_amazon_s3_amazon_web_services_python.txt |
Q:
Hashlib hashes not comparing properly
Heres my code:
import hashlib
real = hashlib.sha512("mom")
status = True
while status:
inp = raw_input("What's the password?")
converted = hashlib.sha512(inp)
if converted == real:
print "Access granted!"
status = False
else:
print "... | Hashlib hashes not comparing properly | Heres my code:
import hashlib
real = hashlib.sha512("mom")
status = True
while status:
inp = raw_input("What's the password?")
converted = hashlib.sha512(inp)
if converted == real:
print "Access granted!"
status = False
else:
print "Access denied."
I'm new to hashlib, and I'... | [
"You're comparing two hash objects instead of just comparing their digests.\nChange your if to if converted.digest() == real.digest() and that should work.\nBy doing if converted == real you're actually comparing the two objects, which while they represent a hash object that does hash to the same thing, they are di... | [
14,
4,
2
] | [] | [] | [
"hash",
"hashlib",
"python"
] | stackoverflow_0006695591_hash_hashlib_python.txt |
Q:
What is the difference between FROM random IMPORT* and IMPORT random? (random() and randrange())
In the book has been this codesample:
from random import*
for i in range(15):
print random.randrange(3,13,3)
And it have got result in the book.
But when I run it in the Netbeans. The foll... | What is the difference between FROM random IMPORT* and IMPORT random? (random() and randrange()) | In the book has been this codesample:
from random import*
for i in range(15):
print random.randrange(3,13,3)
And it have got result in the book.
But when I run it in the Netbeans. The following excaption arosed:
*
Traceback (most recent call last): File
"C:\Users\Lacces\Documents\NetB... | [
"When you from random import *, all the definitions from random become part of the current name space. This means you don't have to prefix anything with random., but it also means you may get a name collision without even knowing it.\nThe preferred way is import random.\n",
"Importing everything from a module is ... | [
7,
3,
2,
2
] | [] | [] | [
"import",
"python"
] | stackoverflow_0006695798_import_python.txt |
Q:
wxPython, capturing an output from subprocess in real-time
I'm working on application in wxPython which is a GUI for a command line utility. In the GUI there is a text control which should display the output from the application. I'm launching the shell command using subprocess, but I don't get any output from it ... | wxPython, capturing an output from subprocess in real-time | I'm working on application in wxPython which is a GUI for a command line utility. In the GUI there is a text control which should display the output from the application. I'm launching the shell command using subprocess, but I don't get any output from it until it has completed.
I have tried several solutions but none ... | [
"The problem is because you are trying to wx.Yield and to update the output widgets from the context of the thread running the process, instead of doing the update from the GUI thread.\n\nSince you are running the process from a thread there should be no need to call wx.Yield, because you are not blocking the GUI t... | [
3,
2
] | [] | [] | [
"multithreading",
"python",
"subprocess",
"wxpython"
] | stackoverflow_0006677248_multithreading_python_subprocess_wxpython.txt |
Q:
Subclassing multiple forms in Django
I have two forms like this:
class PersonForm(forms.Form):
name = forms.CharField()
def clean(self):
print "Validating Person"
def save(self):
print "Saving Person"
def InstrumentForm(forms.Form):
instrument = forms.CharField()
def clean(self):
print "V... | Subclassing multiple forms in Django | I have two forms like this:
class PersonForm(forms.Form):
name = forms.CharField()
def clean(self):
print "Validating Person"
def save(self):
print "Saving Person"
def InstrumentForm(forms.Form):
instrument = forms.CharField()
def clean(self):
print "Validating Instrument"
def save(self):
... | [
"Put both forms inside one form tag (see: https://docs.djangoproject.com/en/1.3/ref/forms/api/#prefixes-for-forms), then validate and save them in order you want, for example in view:\nform1 = PersonForm(request.POST or None, prefix='person')\nform2 = InstrumentForm(request.POST or None, prefix='instrument')\n\nif ... | [
1
] | [] | [] | [
"django",
"django_forms",
"python",
"subclassing"
] | stackoverflow_0006695100_django_django_forms_python_subclassing.txt |
Q:
Django django-admin.py import problem (enviroment_variable problem) on Centos
I have try to install Django and Python on my brand new dedicated server.
I made it upto a certain point and I can run django-admin.py startproject mysite and it works well. (I have add the path to django-admin.py to .bash_profile).
How... | Django django-admin.py import problem (enviroment_variable problem) on Centos | I have try to install Django and Python on my brand new dedicated server.
I made it upto a certain point and I can run django-admin.py startproject mysite and it works well. (I have add the path to django-admin.py to .bash_profile).
However, when I try to run django-admin.py syncdb it gives me error like
File "/opt/py... | [
"Although this doesn't answer your question directly, it is an alternative solution.\nYou should be able to use the command\npython manage.py syncdb\n\nwithin the main directory of your project\n"
] | [
3
] | [] | [] | [
"configuration",
"django",
"import",
"python"
] | stackoverflow_0006695015_configuration_django_import_python.txt |
Q:
Creating a Python class that holds its value as an upper case string doesn't work
Why doesn't this work?
>>> class A (unicode):
... def __init__ (self, value):
... super(unicode, self).__init__(str(value).upper())
...
>>> assert A('hello') == u'HELLO'
Traceback (most recent call last):
File "<pyshel... | Creating a Python class that holds its value as an upper case string doesn't work | Why doesn't this work?
>>> class A (unicode):
... def __init__ (self, value):
... super(unicode, self).__init__(str(value).upper())
...
>>> assert A('hello') == u'HELLO'
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
assert A('hello') == u'HELLO'
AssertionError
>>>
I kno... | [
"unicode are immutable object use __new__ instead of __init__:\nclass A (unicode):\n def __new__ (cls, value):\n return unicode.__new__(cls, str(value).upper())\n\nprint A('hello')\nu'HELLO'\n\n",
"Instead of super(unicode, self), you probably want super(A, self) - the former is object.__init__.\nAdditio... | [
4,
2
] | [] | [] | [
"class",
"customization",
"python"
] | stackoverflow_0006696058_class_customization_python.txt |
Q:
How do I exit a Python program that has a thread running?
I'm writing some simple code and I use Pygame for graphics and I have a thread that draws everything. When I call sys.exit() or just ctrl+c, the main program exits but the thread seems to still be alive. I think I need to shut it down before. How do I do t... | How do I exit a Python program that has a thread running? | I'm writing some simple code and I use Pygame for graphics and I have a thread that draws everything. When I call sys.exit() or just ctrl+c, the main program exits but the thread seems to still be alive. I think I need to shut it down before. How do I do that?
Example:
import threading
class Bla(threading.Thread):
... | [
"Python programs exit when all non-daemon threads are done.\nclass Bla(threading.Thread):\n daemon = True # Make the thread daemon\n def run(self):\n print \"I draw here\"\n\n"
] | [
2
] | [] | [] | [
"exit",
"multithreading",
"python"
] | stackoverflow_0006694916_exit_multithreading_python.txt |
Q:
Convert a list into a nested dictionary
For example I have
x = ['a','b','c']
I need to convert it to:
y['a']['b']['c'] = ''
Is that possible?
For the background, I have a config file which contains dotted notation that points to a place in some json data. I'd like to use the dotted notation string to access that... | Convert a list into a nested dictionary | For example I have
x = ['a','b','c']
I need to convert it to:
y['a']['b']['c'] = ''
Is that possible?
For the background, I have a config file which contains dotted notation that points to a place in some json data. I'd like to use the dotted notation string to access that specific data in the json file. For example,... | [
"li = ['a','b','c']\n\nd = reduce(lambda x, y: {y:x}, reversed(li+['']))\n\nprint(d)\nprint(d['a']['b']['c'])\n\n",
"I guess you also want to include a value in the end. This works for that too:\ndef get_value(d, l):\n if len(l) > 1:\n return get_value(d[l[0]], l[1:])\n return d[l[0]]\n\ndef add_keys... | [
6,
4,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0006689536_dictionary_list_python.txt |
Q:
Nginx Tornado File Upload
I am trying to upload file via nginx_upload_module 2.2.0. I have nginx 1.0.4 setup as a reverse proxy with a tornado server at the backend.
Below is my nginx.conf :
#user nobody;
worker_processes 1;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid /var/... | Nginx Tornado File Upload | I am trying to upload file via nginx_upload_module 2.2.0. I have nginx 1.0.4 setup as a reverse proxy with a tornado server at the backend.
Below is my nginx.conf :
#user nobody;
worker_processes 1;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid /var/log/nginx.pid;
events {
... | [
"I have just written a web application with tornado and nginx-upload-module,and it works.\nAccording to the tornado log you've provided, I guess you can try to change your code\nself.get_argument('upfile_path')\n\nto\n self.get_argument('upload_tmp_path')\nnginx did store the file,\nbut \"upload_cleanup 400 404 ... | [
0
] | [] | [] | [
"file_upload",
"nginx",
"python",
"tornado"
] | stackoverflow_0006690143_file_upload_nginx_python_tornado.txt |
Q:
Two dimensional associative array in Python
I have a set() with terms like 'A' 'B' 'C'. I want a 2-d associative array so that i can perform an operation like d['A']['B'] += 1 . What is the pythonic way of doing this, I was thinking a dicts of dicts. Is there a better way.
A:
There are two obvious solutions: On... | Two dimensional associative array in Python | I have a set() with terms like 'A' 'B' 'C'. I want a 2-d associative array so that i can perform an operation like d['A']['B'] += 1 . What is the pythonic way of doing this, I was thinking a dicts of dicts. Is there a better way.
| [
"There are two obvious solutions: One, use defaultdict to nest a dict automatically inside another dict\n>>> d = collections.defaultdict(dict)\n>>> d['a']['b'] = 'abc'\n>>> d\ndefaultdict(<type 'dict'>, {'a': {'b': 'abc'}})\n>>> \n\nThe other is to just use tuples for your dict keys:\n>>> d = {}\n>>> d['a','b'] = ... | [
12,
4,
3
] | [] | [] | [
"associative_array",
"python"
] | stackoverflow_0006696279_associative_array_python.txt |
Q:
Python+Pygame glibc error
I've recently started doing some coding in Python again and I've encountered an error which I simply don't know how to interpret.
Source code:
http://paste.lisp.org/display/123261
Error:
http://paste.lisp.org/display/123270
The problem arises when I call program_loop() and it's probably r... | Python+Pygame glibc error | I've recently started doing some coding in Python again and I've encountered an error which I simply don't know how to interpret.
Source code:
http://paste.lisp.org/display/123261
Error:
http://paste.lisp.org/display/123270
The problem arises when I call program_loop() and it's probably related to the class I've writte... | [
"Well, I didn't closely look at your code, but the error means there was something so f*cked up in Python it crashed through an error in C. It wasn't even able to catch something and handle it, and this should never happen with the interpreter. Please report this bug to pygame.\n"
] | [
2
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006696367_pygame_python.txt |
Q:
Want to use form and styling option together
I'm shifting an application from cgi to web.py. I want to use the web.form. However I've noticed that it creates a table on its own. Is it possible to style the created table (width, height, etc...)??? If yes, how???
A:
The table is the result of form rendering, so na... | Want to use form and styling option together | I'm shifting an application from cgi to web.py. I want to use the web.form. However I've noticed that it creates a table on its own. Is it possible to style the created table (width, height, etc...)??? If yes, how???
| [
"The table is the result of form rendering, so naturally it’s placed within a form element. In my case it looks like this in the login.html template:\n<form name=\"main\" method=\"post\" class=\"login\"> \n$if not form.valid: \n <p class=\"wrong\">Login incorrect.</p>\n$:form.render()\n</form> \n\nIn the browser... | [
2
] | [] | [] | [
"forms",
"python",
"stylesheet",
"web.py"
] | stackoverflow_0006693558_forms_python_stylesheet_web.py.txt |
Q:
Unpickling classes not defined on the receiving end
As stated in the pickle documentation, classes are normally pickled in such a way that they require the exact same class to be present in a module on the receiving end. However, I do note that there's also some __getstate__() and __setstate__() methods for classe... | Unpickling classes not defined on the receiving end | As stated in the pickle documentation, classes are normally pickled in such a way that they require the exact same class to be present in a module on the receiving end. However, I do note that there's also some __getstate__() and __setstate__() methods for classes, which affect how their instances are pickled...
How fe... | [
"The classes have to be somehow present on the receiving end, because methods are not stored with the objects. So, I think that using a specific metaclass unfortunately can't help, here…\n"
] | [
1
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0006696729_pickle_python.txt |
Q:
Not able to access google spreadsheet from app engine: "Moved Temporarily"?
As of a couple of days ago I was able to access my google spreadsheets
from an app (in app engine), but today it is broken.
Namely, I could
name= "name of my spreadsheet"
self.client = gdata.spreadsheet.text_db.DatabaseClient()
self.client... | Not able to access google spreadsheet from app engine: "Moved Temporarily"? | As of a couple of days ago I was able to access my google spreadsheets
from an app (in app engine), but today it is broken.
Namely, I could
name= "name of my spreadsheet"
self.client = gdata.spreadsheet.text_db.DatabaseClient()
self.client.GetDatabases(name=name)
and it worked. In fact, that still works when I run wit... | [
"Docs is redirecting you to the login page. You need to authenticate before attempting to fetch the spreadsheet. I'm not sure why it's not requiring you to authenticate on the dev server, though.\n",
"You probably have to unrestricted access to the spreadsheet. You don't have it shared so everyone can view it.\n... | [
3,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001646073_google_app_engine_python.txt |
Q:
How to deal with a proprietary Python package name conflicting with a public one?
Background
The group I work with has been using and developing a Python package, which for the purposes of this question I'll call foobuilder. We serve updates for Linux systems using private RPM and Deb repositories we provide for o... | How to deal with a proprietary Python package name conflicting with a public one? | Background
The group I work with has been using and developing a Python package, which for the purposes of this question I'll call foobuilder. We serve updates for Linux systems using private RPM and Deb repositories we provide for our users.
Recently, a public package was added to PyPi with the same name. It also got ... | [
"I'd email the new foobuilder package author to discuss the problem. Obviously one of you needs to change package name; due to proprietary nature of your program is may be undesirable to change its name... Asking this question to the new package author may come up with some new solutions. \nThere really is no sane ... | [
3,
1,
1
] | [] | [] | [
"debian",
"naming",
"package",
"python"
] | stackoverflow_0006617895_debian_naming_package_python.txt |
Q:
Are there more search paths than in sys.path?
I thought that the sys.path was a complete list of all search paths for Python modules.
However, on my Ubuntu machine, '/usr/local/lib/python2.6/dist-packages/' is where almost all my modules are and that path is not in sys.path. And I can still import any module on th... | Are there more search paths than in sys.path? | I thought that the sys.path was a complete list of all search paths for Python modules.
However, on my Ubuntu machine, '/usr/local/lib/python2.6/dist-packages/' is where almost all my modules are and that path is not in sys.path. And I can still import any module on that path.
EDIT, NOT TRUE: Even if I set the sys.pat... | [
"Note the mention of an installation-dependent default in the following:\n\n6.1.2. The Module Search Path\nWhen a module named spam is imported, the interpreter searches for a\n file named spam.py in the directory containing the input script and\n then in the list of directories specified by the environment varia... | [
4,
1
] | [] | [] | [
"module_search_path",
"python",
"sys.path"
] | stackoverflow_0006697525_module_search_path_python_sys.path.txt |
Q:
How to allow only selected user login in gae+python application?
I want to upload my application on google app engine
and want to use this by only selected user
so want to know how it possible.
want to use users gmail account.
A:
You basically need to do it in two steps:
Do what systempuntoout's answer said to ... | How to allow only selected user login in gae+python application? | I want to upload my application on google app engine
and want to use this by only selected user
so want to know how it possible.
want to use users gmail account.
| [
"You basically need to do it in two steps:\n\nDo what systempuntoout's answer said to only allow logged-in users to see your site.\nOn each of your routes (URL handlers), the first step should be to get their user object and check if they are on a list you're keeping of users allowed to see your app. For a first ru... | [
2,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006694662_google_app_engine_google_cloud_datastore_python.txt |
Q:
python date.min does not convert back. Why?
Consider this code:
datestring = date.min.strftime("%d-%m-%Y")
date = datetime.strptime(datestring,"%d-%m-%Y")
This raises the following error:
Traceback (most recent call last): File "D:/Dev/foo.py", line 37, in <module>
datestring = date.min.strftime("%d-%m-%Y")... | python date.min does not convert back. Why? | Consider this code:
datestring = date.min.strftime("%d-%m-%Y")
date = datetime.strptime(datestring,"%d-%m-%Y")
This raises the following error:
Traceback (most recent call last): File "D:/Dev/foo.py", line 37, in <module>
datestring = date.min.strftime("%d-%m-%Y") ValueError: year=1 is before 1900; the datetime ... | [
"You could stick the \"ISO 8601 format: YYYY-MM-DD\":\n>>> from datetime import date, datetime\n>>> date_str = date.min.isoformat()\n>>> print date_str\n0001-01-01\n>>> date_obj = datetime.strptime(date_str,\"%Y-%m-%d\")\n>>> print date_obj\n0001-01-01 00:00:00\n\n",
"this is not the problem with date.min or date... | [
4,
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006697362_python_sqlite.txt |
Q:
Python dictionary sum values
I'm using Python 2.7 and I have a large dictionary that looks a little like this
{J: [92704, 238476902378, 32490872394, 234798327, 2390470], M: [32974097, 237407, 3248707, 32847987, 34879], Z: [8237, 328947, 239487, 234, 182673]}
How can I sum these by value to create a new dictionary... | Python dictionary sum values | I'm using Python 2.7 and I have a large dictionary that looks a little like this
{J: [92704, 238476902378, 32490872394, 234798327, 2390470], M: [32974097, 237407, 3248707, 32847987, 34879], Z: [8237, 328947, 239487, 234, 182673]}
How can I sum these by value to create a new dictionary that sums the first values in eac... | [
"In [4]: {'FirstValues': sum(e[0] for e in d.itervalues())}\nOut[4]: {'FirstValues': 33075038}\n\nwhere d is your dictionary.\n",
"print [sum(row) for row in zip(*yourdict.values())]\n\nyourdict.values() gets all the lists, zip(* ) groups the first, second, etc items together and sum sums each group.\n",
"from ... | [
3,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"python",
"sum"
] | stackoverflow_0006697658_dictionary_python_sum.txt |
Q:
How do I add a scale bar to a plot in Mayavi2/VTK?
I would like to add a scale bar (showing how big a micron is for example) to a mayavi plot I create with mlab.
For example, referencing this question: How to display a volume with non-cubic voxels correctly in mayavi
I can set the voxel size of a plot by using
fr... | How do I add a scale bar to a plot in Mayavi2/VTK? | I would like to add a scale bar (showing how big a micron is for example) to a mayavi plot I create with mlab.
For example, referencing this question: How to display a volume with non-cubic voxels correctly in mayavi
I can set the voxel size of a plot by using
from enthought.mayavi import mlab
import numpy as np
s=64... | [
"Try the following:\nmlab.axes()\n\nmlab.outline()\nmlab.colorbar()\n\nThis reference: http://github.enthought.com/mayavi/mayavi/auto/mlab_reference.html would help as would the several examples.\n"
] | [
0
] | [] | [] | [
"mayavi",
"python",
"scipy",
"vtk"
] | stackoverflow_0006696100_mayavi_python_scipy_vtk.txt |
Q:
How to preserve database connection in a python web server
I am looking at the Flask tutorial, and it suggests to create a new database connection for each web request. Is it the right way to do things ? I always thought that the database connection should only once be created once for each thread. Can that be don... | How to preserve database connection in a python web server | I am looking at the Flask tutorial, and it suggests to create a new database connection for each web request. Is it the right way to do things ? I always thought that the database connection should only once be created once for each thread. Can that be done, while maintaining the application as thread-safe, with flask,... | [
"For learning purposes maybe yes. But in a real application running on a production environment that is not an ideal situation at all. \nNormally, you would always want to have a connection pool between your application and the database. No matter what language/database you are using this is a common solution. \nA ... | [
19,
10,
0
] | [] | [] | [
"flask",
"mysql",
"python"
] | stackoverflow_0006688413_flask_mysql_python.txt |
Q:
update file descriptor after os.rename()
What is the best way to handle Bad file descriptor errors after calling os.rename() in the following manner?
f = open('foo.txt', 'rw')
os.rename(f.name, f.name + ".bak")
In the file system there is no longer a foo.txt but instead a foo.txt.bak
However..
f.name
gives foo.t... | update file descriptor after os.rename() | What is the best way to handle Bad file descriptor errors after calling os.rename() in the following manner?
f = open('foo.txt', 'rw')
os.rename(f.name, f.name + ".bak")
In the file system there is no longer a foo.txt but instead a foo.txt.bak
However..
f.name
gives foo.txt instead of foo.txt.bak
But..
f.write("test"... | [
"You can write a function that will rename an open file. Basically, you close, rename, and reopen the file, preserving attributes such as the file position and the mode. Some tweaking of the mode is necessary for the reopen -- if the file's mode is \"w\", reopening it with the same mode will lose everything in it, ... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0006697972_python.txt |
Q:
What does self do?
Possible Duplicate:
Python 'self' keyword
Forgive me if this is an incredibly noobish question, but I never did understand self in Python. What does it do? And when I see things like
def example(self, args):
return self.something
what do they do? I think I've seen args somewhere in a func... | What does self do? |
Possible Duplicate:
Python 'self' keyword
Forgive me if this is an incredibly noobish question, but I never did understand self in Python. What does it do? And when I see things like
def example(self, args):
return self.something
what do they do? I think I've seen args somewhere in a function too. Please explai... | [
"It sounds like you've stumbled onto the object oriented features of Python.\nself is a reference to an object. It's very close to the concept of this in many C-style languages. Check out this code:\nclass Car(object):\n\n def __init__(self, make):\n\n # Set the user-defined 'make' property on the self object... | [
14,
6,
3
] | [] | [] | [
"args",
"python",
"self"
] | stackoverflow_0006698030_args_python_self.txt |
Q:
Python version of JS's x = variable || DEFAULT_VARIABLE?
I'm finding myself using hasattr a lot and would like to write more concisely.
In JS, I use the following pattern often:
var x = variable || DEFAULT_VARIABLE;
What's the equivalent in Python?
Something better than this...
if hasattr(my_obj, 'my_key'):
x =... | Python version of JS's x = variable || DEFAULT_VARIABLE? | I'm finding myself using hasattr a lot and would like to write more concisely.
In JS, I use the following pattern often:
var x = variable || DEFAULT_VARIABLE;
What's the equivalent in Python?
Something better than this...
if hasattr(my_obj, 'my_key'):
x = my_obj.my_key
else:
x = 3
EDIT: Fixed a bug mixing up obje... | [
"x = my_dict.get('my_key', 3)\n\nThat seems clear: http://docs.python.org/library/stdtypes.html#dict.get\nAssuming, of course, that my_dict really is a dictionary. The whole hasattr thing in the question is confusing.\n",
"x=variable if variable else DEFAULT_VARIABLE\n\nDon't remember if this works with all pyth... | [
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006697816_python.txt |
Q:
Python, Pyinstaller creating shortcuts in windows
I am making a python script that creates a shortcut (.lnk) file, using win32com.client module, I am using pyinstaller to convert it to exe. I'm also using Tkinter, so I need --tk support in pyinstaller. Pyinstaller doesn't seem to work with --tk and import win32com... | Python, Pyinstaller creating shortcuts in windows | I am making a python script that creates a shortcut (.lnk) file, using win32com.client module, I am using pyinstaller to convert it to exe. I'm also using Tkinter, so I need --tk support in pyinstaller. Pyinstaller doesn't seem to work with --tk and import win32com.client at the same time (I have no idea why) I need th... | [
"If anyone is interested, I found a way of creating shortcuts using win32com.shell rather than win32.client.\nThis works well with pyinstaller and --tk flag set to ON. \n"
] | [
2
] | [] | [] | [
"pyinstaller",
"python",
"shortcut",
"tkinter",
"win32com"
] | stackoverflow_0006673041_pyinstaller_python_shortcut_tkinter_win32com.txt |
Q:
What's the difference between LP_* pointers and *_p pointers in ctypes? (and weird interaction with structs)
I'm having trouble understanding the difference between LP_* (e.g. LP_c_char) and *_p (e.g. c_char_p) pointers in Python ctypes. Is there documentation distinguishing them?
The little I've read about *_p po... | What's the difference between LP_* pointers and *_p pointers in ctypes? (and weird interaction with structs) | I'm having trouble understanding the difference between LP_* (e.g. LP_c_char) and *_p (e.g. c_char_p) pointers in Python ctypes. Is there documentation distinguishing them?
The little I've read about *_p pointers suggests that they're better (in some unspecified way), but when I try to use them as struct fields, I get ... | [
"http://docs.python.org/library/ctypes.html#ctypes.c_char_p\n\nRepresents the C char * datatype when it points to a zero-terminated string. For a general character pointer that may also point to binary data, POINTER(c_char) must be used.\n\nc_char_p is mapped to Python's str type because it's assuming you're referr... | [
10
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0006697065_ctypes_python.txt |
Q:
Good automated system testing framework in python
I am looking for good End to End testing framework under python, where the tests can be written in python and managed in a comfortable way. I know there are many unit testing frameworks, but I am looking for bigger scope, something like test director with support f... | Good automated system testing framework in python | I am looking for good End to End testing framework under python, where the tests can be written in python and managed in a comfortable way. I know there are many unit testing frameworks, but I am looking for bigger scope, something like test director with support for reports etc,where a whole system is under test.
| [
"You havent given any details so it is very difficult to know what specific product are you looking for. \nMaybe robotframework suits your needs\n",
"I used zope.testing and it was very good for my need, but it's not so different from simple unittest.\nThere is a good comparative here. I guess most of the product... | [
19,
0,
0
] | [] | [] | [
"automated_tests",
"python",
"system_testing",
"testing"
] | stackoverflow_0002826734_automated_tests_python_system_testing_testing.txt |
Q:
Long polling in Django
I'm using a sort of long polling in my Django app to return status messages about a long operation to the client as it progresses. I do this by returning an HttpResponse object in my view function that is initialized with an iterator that returns strings. This all works great, but the iterat... | Long polling in Django | I'm using a sort of long polling in my Django app to return status messages about a long operation to the client as it progresses. I do this by returning an HttpResponse object in my view function that is initialized with an iterator that returns strings. This all works great, but the iterator function is getting prett... | [
"Try:\nimport itertools\n\ndef my_long_operation():\n return itertools.chain(do_something(), do_something_else())\n\n"
] | [
4
] | [] | [] | [
"django",
"long_polling",
"python"
] | stackoverflow_0006698355_django_long_polling_python.txt |
Q:
How to create a variable that will search all text and log files
Can someone tell me why my variable will only return all .txt files or all .log files but not both together. I thought I understood this, as I have used similar cases before with an if statement and qn endswith method of text or log extension. But, w... | How to create a variable that will search all text and log files | Can someone tell me why my variable will only return all .txt files or all .log files but not both together. I thought I understood this, as I have used similar cases before with an if statement and qn endswith method of text or log extension. But, with getting files from a server it's only allowing me to get one or an... | [
"\nHowever, this line searches for .log files only:\n\nNo it doesn't, it searches for .txt files only. :-) The reason is that (('\"*.txt\" ') or ('\"*.log\" ')) evaluates to '\"*.txt\". \nThere's a (somewhat involved) reason for this as well: the or operator takes the logical or of two Boolean (true/false) object... | [
3,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006698495_python.txt |
Q:
Django search in the database
I use MySQL for the production server and SQLite for the testing local server for my django application.
I've a model like this:
class Product(models.Model):
name = models.CharField(max_length = 40)
I've implemented a search feature in my application for searching product.
I use ... | Django search in the database | I use MySQL for the production server and SQLite for the testing local server for my django application.
I've a model like this:
class Product(models.Model):
name = models.CharField(max_length = 40)
I've implemented a search feature in my application for searching product.
I use this command: Product.objects.filte... | [
"https://docs.djangoproject.com/en/1.3/ref/models/querysets/#regex\nhttp://docs.python.org/library/re.html\npattern= r\"\\b%s\\b\" % text\nProduct.objects.filter(name__regex = pattern)\n\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006698661_django_python.txt |
Q:
A list as a key for a dictionary
I have multiple lists of tuples eg
[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]
that I would like to have as keys to a dictionary (so each key in my dictionary would be a list of tuples).
Unfortunately, according to the TypeError I'm getting (unhashable type: list), it seems that python d... | A list as a key for a dictionary | I have multiple lists of tuples eg
[([1, 2, 3, 4], 2), ([5, 6, 7], 3)]
that I would like to have as keys to a dictionary (so each key in my dictionary would be a list of tuples).
Unfortunately, according to the TypeError I'm getting (unhashable type: list), it seems that python doesn't like hashing lists. All of the ... | [
"Use tuples instead.\n>>> dict((tuple(x[0]), x[1]) for x in [([1,2,3,4],2),([5,6,7],3)])\n{(5, 6, 7): 3, (1, 2, 3, 4): 2}\n\n",
">>> def nested_lists_to_tuples(ls):\n return tuple(nested_lists_to_tuples(l) if isinstance(l, (list, tuple)) else l for l in ls)\n\n>>> nested_lists_to_tuples([([1,2,3,4],2),([5,6,7]... | [
4,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006698307_python.txt |
Q:
Django Admin - Bulk editing data?
Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the picture fields of all product models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.
A:
With Django 1.1, you can create admi... | Django Admin - Bulk editing data? | Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the picture fields of all product models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome.
| [
"With Django 1.1, you can create admin actions which can be applied to multiple entries at once. See the documentation on this subject.\n",
"Django \"Mass Change\" Admin Site Extension.\n"
] | [
12,
4
] | [
"You have SQL. You can write SQL UPDATE statements.\nYou have Python for writing batch scripts that interact with the Django ORM. This works really, really well for bulk changes.\n"
] | [
-2
] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0001322425_django_django_admin_django_models_python.txt |
Q:
tornado IOError "Stream is closed" on request finish()
I'm using tornado 2.0 and occassionally when I call self.finish() to end an asynchronous request, I'll get an IOError with the message "Stream is closed". It looks as though this happens when the client ends a request (ie by navigating to another page) prior ... | tornado IOError "Stream is closed" on request finish() | I'm using tornado 2.0 and occassionally when I call self.finish() to end an asynchronous request, I'll get an IOError with the message "Stream is closed". It looks as though this happens when the client ends a request (ie by navigating to another page) prior to the server calling finish(). Is this expected behavior a... | [
"self.finish() is called to end the asynchronous request, and some functions like self.render() will call self.finish().\nIf you call self.finish() after the connection is closed, it will cause the error.\nso you can check if you call some functions that finish the connection before self.finish()\nor you can do lik... | [
0
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0006697322_python_tornado.txt |
Q:
Command to make a Python application open a webpage
What would I have to do to make a Python application I am writing open up a web page in the default browser? It doesn't need to be told what the webpage is or anything, it'll be opening one that I've already chosen.
I found some documentation here but I always ge... | Command to make a Python application open a webpage | What would I have to do to make a Python application I am writing open up a web page in the default browser? It doesn't need to be told what the webpage is or anything, it'll be opening one that I've already chosen.
I found some documentation here but I always get a syntax error from the symbols in the URL. Any help?
| [
"The URL needs to be in a string.\nwebbrowser.open('http://www.google.com/')\n\n",
"Have a look at the webbrowser module.\n"
] | [
6,
1
] | [] | [] | [
"browser",
"python",
"python_2.7",
"syntax_error",
"webpage"
] | stackoverflow_0006699201_browser_python_python_2.7_syntax_error_webpage.txt |
Q:
Redefine or add Methods to class through decorator. Possible?
I have class:
@custom_decorator
class Creature(objects):
def __init__(self):
pass
def rise_hands(self, *args, **kwargs):
print 'hands rised'
I want to define the custom decorator on the top of this class Creature, so that it ... | Redefine or add Methods to class through decorator. Possible? | I have class:
@custom_decorator
class Creature(objects):
def __init__(self):
pass
def rise_hands(self, *args, **kwargs):
print 'hands rised'
I want to define the custom decorator on the top of this class Creature, so that it will redefine the method rise_hands or adds new methods.
By the way... | [
"Don't. Do. This. \nYou have inheritance to do exactly what you're talking about.\nclass FancyCreature( Creature ):\n\n def __init__(self):\n super( FancyCreature, self ).__init___()\n\n def rise_hands(self, *args, **kwargs):\n print 'hands rised'\n super( FancyCreature, self ).rise_hand... | [
1,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0006699162_decorator_python.txt |
Q:
floats inside tuples changing values when accessed
So I have a list of tuples of two floats each. Each tuple represents a range. I am going through another list of floats which represent values to be fit into the ranges. All of these floats are < 1 but positive, so precision matter. One of my tests to determin... | floats inside tuples changing values when accessed | So I have a list of tuples of two floats each. Each tuple represents a range. I am going through another list of floats which represent values to be fit into the ranges. All of these floats are < 1 but positive, so precision matter. One of my tests to determine if a value fits into a range is failing when it should... | [
"In modern day PC's floats aren't that precise. So even if you enter pi as a constant to 100 decimals, it's only getting a few of them accurate. The same is happening to you. This is because in 32-bit floats you only get 24 bits of mantissa, which limits your precision (and in unexpected ways because it's in base2)... | [
3,
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006699313_python.txt |
Q:
How exactly is Python2's sys.path set in Windows?
The Python documentation says that sys.path is "Initialized from the environment variable PYTHONPATH, plus an installation-dependent default."
But what is the "installation-dependent default" exactly for Windows?
(I know this is probably dependent on how python was... | How exactly is Python2's sys.path set in Windows? | The Python documentation says that sys.path is "Initialized from the environment variable PYTHONPATH, plus an installation-dependent default."
But what is the "installation-dependent default" exactly for Windows?
(I know this is probably dependent on how python was compiled, but if all I have is the binary, is there an... | [
"Seems like Praveen Gollakota has good info at Troubleshooting python sys.path (repasted here:)\n\nThe first that is added C:\\WINNT\\system32\\python27.zip (more details in PEP273).\nNext ones that are added are from entries in windows registry. The entries C:\\Python27\\DLLs;C:\\Python27\\lib; C:\\Python27\\lib\\... | [
6,
2,
1
] | [] | [] | [
"path",
"python",
"pythonpath",
"windows"
] | stackoverflow_0006698932_path_python_pythonpath_windows.txt |
Q:
How does one compare a string to the next string in a list?
I'm writing a small NLP algorithm and I need to do the following:
For every string x in the list ["this", "this", "and", "that"], if the string x and the next string are identical, I want to print the string.
A:
s = ["this", "this", "and", "that"]
for... | How does one compare a string to the next string in a list? | I'm writing a small NLP algorithm and I need to do the following:
For every string x in the list ["this", "this", "and", "that"], if the string x and the next string are identical, I want to print the string.
| [
"s = [\"this\", \"this\", \"and\", \"that\"]\nfor i in xrange(1,len(s)):\n if s[i] == s[i-1]:\n print s[i]\n\nEDIT:\nJust as a side note, if you are using python 3.X use range instead of xrange\n",
"strings = ['this', 'this', 'and', 'that']\nfor a, b in zip(strings, strings[1:]):\n if a == b:\n ... | [
6,
5,
2,
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"compare",
"list",
"next",
"python",
"string"
] | stackoverflow_0006697113_compare_list_next_python_string.txt |
Q:
How to pass tuple as parameters of a function
I have a tuple containing tuples.
EVENT_MAPPING = (
(func1, (paramA1, paramA2, paramA3)),
(func2, (paramB1)),
(func3, (paramC1, paramC2)),
)
I iterate over the first tuple. And I want to call the function contained in the first param with args in the seco... | How to pass tuple as parameters of a function | I have a tuple containing tuples.
EVENT_MAPPING = (
(func1, (paramA1, paramA2, paramA3)),
(func2, (paramB1)),
(func3, (paramC1, paramC2)),
)
I iterate over the first tuple. And I want to call the function contained in the first param with args in the second param plus other param. For example, for the fir... | [
"Like this, probably:\nfor func, args in EVENT_MAPPING:\n func(*args)\n\nThe * extracts (expand) the inner tuple and they are passed to the function as arguments.\n",
"for func, args in EVENT_MAPPING:\n func(origin, *args)\n\n",
"If you want to add the origin to the args, something like this should work:\nf... | [
11,
1,
0
] | [] | [] | [
"function",
"function_pointers",
"list",
"python",
"tuples"
] | stackoverflow_0006699592_function_function_pointers_list_python_tuples.txt |
Q:
Why do I see random read errors with Python BaseHTTPServer?
I have Python code that calls external HTTP services. I want to test this code by setting up mock HTTP servers that imitate those external services. I do this by starting a BaseHTTPServer in a separate thread, and then calling that server from the main th... | Why do I see random read errors with Python BaseHTTPServer? | I have Python code that calls external HTTP services. I want to test this code by setting up mock HTTP servers that imitate those external services. I do this by starting a BaseHTTPServer in a separate thread, and then calling that server from the main thread. It looks like this:
import BaseHTTPServer, httplib, threadi... | [
"\"...in a separate thread, and then calling that server from the main thread.\"\nDon't use threads for this kind of thing.\nUse processes. subprocess.Popen (and your operating system's normal features) will do a much, much better job of assuring that this works properly.\n"
] | [
1
] | [] | [] | [
"concurrency",
"http",
"mocking",
"python",
"sockets"
] | stackoverflow_0006697390_concurrency_http_mocking_python_sockets.txt |
Q:
Correct way to code a Python Server
Which way is better?
Creating a while loop and then using the select module OR using ThreadedTCPServer with a custom class.
Im having problems with the Threaded TCP Server, although it could just be my coding.
A:
My personal recommendation is to use Twisted. It's a Python-bas... | Correct way to code a Python Server | Which way is better?
Creating a while loop and then using the select module OR using ThreadedTCPServer with a custom class.
Im having problems with the Threaded TCP Server, although it could just be my coding.
| [
"My personal recommendation is to use Twisted. It's a Python-based framework intended primarily for writing event-driven network software. The documentation has a lot of great examples of how to create various types of servers and clients, as well.\n",
"I am sure there is no such a thing like the \"correct\" wa... | [
5,
1
] | [] | [] | [
"python",
"sockets",
"tcp",
"while_loop"
] | stackoverflow_0006699921_python_sockets_tcp_while_loop.txt |
Q:
How to authenticate to a remote db host with MongoKit?
I am attempting to connect and authenticate to a remote database host (dotcloud, mongolabs, etc) using MongoKit within Flask. Connecting to the server seems to work fine. However I am unable to authenticate to the database. Presumably this should work:
from mo... | How to authenticate to a remote db host with MongoKit? | I am attempting to connect and authenticate to a remote database host (dotcloud, mongolabs, etc) using MongoKit within Flask. Connecting to the server seems to work fine. However I am unable to authenticate to the database. Presumably this should work:
from mongokit import Connection
connection = Connection(my_remote_h... | [
"This is likely due to the current behavior of authenticate() in pymongo. Pymongo doesn't cache authentication credentials between threads, so each thread must authenticate individually. See the note in the pymongo documentation about using authenticate() in a multi-threaded environment.\n"
] | [
4
] | [] | [] | [
"flask",
"mongodb",
"mongokit",
"pymongo",
"python"
] | stackoverflow_0006699947_flask_mongodb_mongokit_pymongo_python.txt |
Q:
Importing modules from more advanced layout
Say this is my package layout
Package
:: core
:: hash
:: hashgen.py
:: validate.py
:: common
:: classes.py
:: tools
:: database_validate.py
:: bot.py
:: config.py
So if I wanted to import databa... | Importing modules from more advanced layout | Say this is my package layout
Package
:: core
:: hash
:: hashgen.py
:: validate.py
:: common
:: classes.py
:: tools
:: database_validate.py
:: bot.py
:: config.py
So if I wanted to import database_validate from tools in bot.py I'd do:
from too... | [
"When building a package - don't forget the __init__.py. This needs to be in every tree you wish to import from. In your example it should look like this..\nPackage\n __init__.py\n :: core\n __init__.py\n :: hash\n __init__.py\n :: hashgen.py\n :: validate.py\n... | [
3,
1,
0
] | [] | [] | [
"bots",
"list",
"python"
] | stackoverflow_0006700071_bots_list_python.txt |
Q:
Can webpy form work well with jinja2?
As the cookbook of webpy and jinja2, I can use webpy's form or jinja2 well independently. However when I try to combining both in a template file like below, it does not work:
Template file:
$def with(form)
{% extends 'layout.html' %}
{% block maincontents %}
<h1>User</h1>
<fo... | Can webpy form work well with jinja2? | As the cookbook of webpy and jinja2, I can use webpy's form or jinja2 well independently. However when I try to combining both in a template file like below, it does not work:
Template file:
$def with(form)
{% extends 'layout.html' %}
{% block maincontents %}
<h1>User</h1>
<form method="post">
$:form.render()
</for... | [
"$:form.render() is the Templetor rendering instruction, taken verbatim from the docs, I presume. \nI believe you should use Jinja2 syntax, something like\n<form method=\"post\">\n {{ form.render() | safe }}\n</form>\n\nDisclaimer: I haven't actually tested the snippet above.\n"
] | [
3
] | [] | [] | [
"jinja2",
"python",
"web.py"
] | stackoverflow_0006543408_jinja2_python_web.py.txt |
Q:
Using Excel to work with large amounts of output data: is an Excel-database interaction the right solution for the problem?
I have a situation where various analysis programs output large amounts of data, but I may only need to manipulate or access certain parts of the data in a particular Excel workbook.
The numb... | Using Excel to work with large amounts of output data: is an Excel-database interaction the right solution for the problem? | I have a situation where various analysis programs output large amounts of data, but I may only need to manipulate or access certain parts of the data in a particular Excel workbook.
The numbers might often change as well as newer analyses are run, and I'd like these changes to be reflected in Excel in as automated a m... | [
"Although you could certainly use a database to do what you're asking, I'm not sure you really want to add that complexity. I don't see much benefit of adding a database to your mix. ...if you were pulling data from a database as well, then it'd make more sense to add some tables for this & use it. \nFrom what I ... | [
0
] | [] | [] | [
"database",
"excel",
"python"
] | stackoverflow_0006699534_database_excel_python.txt |
Q:
Using the socket module in sandboxed Pypy
I'm attempting to allow a subprocess sandboxed with Pypy to communicate, using a limited protocol, with the parent process.
After reviewing the source code of the pypy/pypy/translator/sandbox/sandlib.py included with Pypy, it appears that there is a VirtualizedSocketProc t... | Using the socket module in sandboxed Pypy | I'm attempting to allow a subprocess sandboxed with Pypy to communicate, using a limited protocol, with the parent process.
After reviewing the source code of the pypy/pypy/translator/sandbox/sandlib.py included with Pypy, it appears that there is a VirtualizedSocketProc that allows os.open calls to open sockets. I've ... | [
"I've investigated this further, and it appears that this is a fairly fundamental problem. The socket module, implemented at the library level (inside of the lib directories) is essentially an empty shell for the the _socket library, which is an interpreter-level module defined in the pypy/module directory. For tho... | [
4
] | [] | [] | [
"pypy",
"python",
"sandbox",
"sockets"
] | stackoverflow_0006655258_pypy_python_sandbox_sockets.txt |
Q:
Improper rendering at axes border in Matplotlib
I want to render a rectangle within an axes in matplotlib. The axes is the unit square with the origin at the bottom left corner. For the case where the rectangle is the same size as the axes - I want the rectangle to appear as though it is the border of the axes.
... | Improper rendering at axes border in Matplotlib | I want to render a rectangle within an axes in matplotlib. The axes is the unit square with the origin at the bottom left corner. For the case where the rectangle is the same size as the axes - I want the rectangle to appear as though it is the border of the axes.
The problem is that it appears that the rendering is ... | [
"The exact behavior is backend dependent (Your example works as you'd like it to on my system.)\nHowever, if you turn clipping off for your rectangle, it should behave as you want on any backend.\nIn your example above, just do r.set_clip_on(False).\nimport matplotlib.pyplot as plt\n\nr = plt.Rectangle((0,0), 1, 1,... | [
2
] | [] | [] | [
"matplotlib",
"plot",
"python",
"rendering",
"wxpython"
] | stackoverflow_0006700002_matplotlib_plot_python_rendering_wxpython.txt |
Q:
Calling os.fsync on the stdout/stderr file descriptors kills a subprocess
After spawning a subprocess using the Python subprocess library, I'm using stderr to pass a message from the child process to the parent process containing some serialized data. I then want the parent to return (via stdin) the result of a fu... | Calling os.fsync on the stdout/stderr file descriptors kills a subprocess | After spawning a subprocess using the Python subprocess library, I'm using stderr to pass a message from the child process to the parent process containing some serialized data. I then want the parent to return (via stdin) the result of a function applied to this data.
In essence, I have a function inside the subproces... | [
"I would consider another approach.\nYou may use an indipendent process (multiprocessing.Process) and using two queues to communicate with it (multiprocessing.Queue) one for the input and the other one for the output.\nExample on starting the process:\nimport multiprocessing\n\ndef processWorker(input, result):\n ... | [
2,
1
] | [] | [] | [
"fsync",
"python",
"subprocess"
] | stackoverflow_0006700127_fsync_python_subprocess.txt |
Q:
Python's Socketserver to Telnet errors
I'm writing a tiny server and client kind of for fun and learn how to use sockets, and how to do some simple networking. It uses the Telnet 'protocol' to ask the server for my username, and then I enter my password. The server complains when it gets "NICK" as a username, it ... | Python's Socketserver to Telnet errors | I'm writing a tiny server and client kind of for fun and learn how to use sockets, and how to do some simple networking. It uses the Telnet 'protocol' to ask the server for my username, and then I enter my password. The server complains when it gets "NICK" as a username, it was sent like this: connection.write(byte... | [
"You are using Python3, so \"login: \" is a unicode string, while connection.read_until is expecting something it can interpret as bytes. Try\nconnection.read_until(\"login: \".encode())\n\n"
] | [
0
] | [] | [] | [
"python",
"sockets",
"socketserver",
"telnet"
] | stackoverflow_0006696405_python_sockets_socketserver_telnet.txt |
Q:
Manipulating large amounts of keyword arguments in a Pythonic manner
I have a class who's _init_ function requires quite a few keyword arguments. I'd like to be able to basically rewrite this bit of code so that it's syntactically cleaner (less hard coding). Preferably I'd like to be able to get it so that simply ... | Manipulating large amounts of keyword arguments in a Pythonic manner | I have a class who's _init_ function requires quite a few keyword arguments. I'd like to be able to basically rewrite this bit of code so that it's syntactically cleaner (less hard coding). Preferably I'd like to be able to get it so that simply adding a keyword argument to _init_ would change all the attributes/argume... | [
"This is one thing I love about python. In your __init__\ndef __init__ (self, **kwargs):\n self.__dict__.update(kwargs)\n\nWill append those members defined in a dictionary kwargs as members of the class.\nEDITED - to reflect proper syntax for **kwargs, and update() instead of append()\n",
"Why not accept any ... | [
3,
2
] | [] | [] | [
"dictionary",
"key",
"keyword_argument",
"python"
] | stackoverflow_0006700315_dictionary_key_keyword_argument_python.txt |
Q:
Python widget/cursor detection?
Beginner python learner here. I have a question that I have tried to Google but I just can't come up with the proper way to ask in just a few words (partly because I don't know the right terminology.)
How do I get python to detect other widgets? For example, if I wanted a script to ... | Python widget/cursor detection? | Beginner python learner here. I have a question that I have tried to Google but I just can't come up with the proper way to ask in just a few words (partly because I don't know the right terminology.)
How do I get python to detect other widgets? For example, if I wanted a script to check and see when I click my mouse i... | [
"Do you mean inside your own GUI code, or some other application's/website's?\nSounds like you're looking for a GUI driver, or GUI test/automation driver. There are tons of these, some great, some awful, many abandoned. If you tell us more about what you want that will help narrow down the choices.\nIs this for tes... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006700036_python.txt |
Q:
Is it possible to convert 4:3 pictures to 16:9 using Python (2.7)
I have been searching the net for a while, but to no avail! Is there an image editing library for python that will allow me to convert 4:3 pictures to 16:9?
Any information and/or links are much appreciated!
Thanks!
A:
For naive resizing using on... | Is it possible to convert 4:3 pictures to 16:9 using Python (2.7) | I have been searching the net for a while, but to no avail! Is there an image editing library for python that will allow me to convert 4:3 pictures to 16:9?
Any information and/or links are much appreciated!
Thanks!
| [
"For naive resizing using one of a few various filter types, you can use Image.resize from the PIL:\n\nim.resize(size) => image\nim.resize(size, filter) => image\nReturns a resized copy of an image. The size argument gives the requested size in pixels, as a 2-tuple: (width, height).\nThe filter argument can be one ... | [
2,
0
] | [] | [] | [
"image_editing",
"image_processing",
"python"
] | stackoverflow_0006700451_image_editing_image_processing_python.txt |
Q:
decorator python library hide the kwargs inside args
I got a pretty weird behaviour with the decorator library which is explained in the next code:
from decorator import decorator
@decorator
def wrap(f, a, *args, **kwargs):
print 'Decorator:', a, args, kwargs
return f(a, *args, **kwargs)
def mywrap(f... | decorator python library hide the kwargs inside args | I got a pretty weird behaviour with the decorator library which is explained in the next code:
from decorator import decorator
@decorator
def wrap(f, a, *args, **kwargs):
print 'Decorator:', a, args, kwargs
return f(a, *args, **kwargs)
def mywrap(f):
def new_f(a, *args, **kwargs):
print 'Home ... | [
"Just because you call the function with b=2 does not make b a keyword argument; b is a positional argument in the original function. If there were no argument named b and you specified b=2, then b would become a keyword argument.\ndecorator's behavior is actually the most correct; the wrapper it generates has the ... | [
5
] | [] | [] | [
"decorator",
"keyword_argument",
"python"
] | stackoverflow_0006700432_decorator_keyword_argument_python.txt |
Q:
Java vs Python on Hadoop
I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant perf... | Java vs Python on Hadoop | I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way or ... | [
"With Python you'll probably develop faster and with Java will definitely run faster.\nGoogle \"benchmarksgame\" if you want to see some very accurate speed comparisons between all popular languages, but if I recall correctly you're talking about 3-5x faster.\nThat said, few things are processor bound these days, s... | [
24,
15,
14
] | [] | [] | [
"hadoop",
"java",
"python"
] | stackoverflow_0001482282_hadoop_java_python.txt |
Q:
Editing file header info in Python
I'm pretty new to python, and I'm trying to edit data in a .mobi file from a Python script. I am able to read all the meta data, but I can't figure out how to save the info I need back into the correct place. Every time I try, it just corrupts the file.
This is a snippet of what ... | Editing file header info in Python | I'm pretty new to python, and I'm trying to edit data in a .mobi file from a Python script. I am able to read all the meta data, but I can't figure out how to save the info I need back into the correct place. Every time I try, it just corrupts the file.
This is a snippet of what I'm having problems with:
metadata['... | [
"wb (and w) truncates the file on opening. You want rb+.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006700630_python.txt |
Q:
Help in this content extraction + beautiful soup
I am trying to extract data from a site which is in this format
<div id=storytextp class=storytextp align=center style='padding:10px;'>
<div id=storytext class=storytext>
<div class='a2a_kit a2a_default_style' style='float:right;margin-left:10px;border:none;'>
..... | Help in this content extraction + beautiful soup | I am trying to extract data from a site which is in this format
<div id=storytextp class=storytextp align=center style='padding:10px;'>
<div id=storytext class=storytext>
<div class='a2a_kit a2a_default_style' style='float:right;margin-left:10px;border:none;'>
..... extra stuff
</div> **Main Content**
</div>
</div>... | [
"Just do _divTag.contents[2].\nYour formatting was maybe misleading you - this text does not belong to the innermost div tag (as innerdiv.text, innerdiv.contents or innerdiv.findChildren() will show you).\nIt makes things clearer if you indent your original XML:\n<div id=storytextp class=storytextp align=center sty... | [
2
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006699483_beautifulsoup_python.txt |
Q:
Have I misunderstood how to set up Selenium RC with Python?
I am having difficulty with Selenium RC. When trying to run scripts in Python, I see the message "Cannot import name webdriver".
I'm likely missing something very basic. Let me explain every step I've taken (better to be too granular than too vague...):
... | Have I misunderstood how to set up Selenium RC with Python? | I am having difficulty with Selenium RC. When trying to run scripts in Python, I see the message "Cannot import name webdriver".
I'm likely missing something very basic. Let me explain every step I've taken (better to be too granular than too vague...):
Download and set up Java Development Kit and set Paths. The comma... | [
"WebDriver is part of Selenium 2. You are installing the Selenium 1 bindings and then trying to run WebDriver. That won't work.\nFurthermore, WebDriver API eliminates the need for the Server component (WebDriver is different than Selenium-RC). To use WebDriver, All you need are the Python bindings for Selenium 2... | [
5
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0006700604_python_selenium_selenium_rc.txt |
Q:
SQLAlchemy - Mixin vs MetaClass modification
So say, for example I have two classes:
Base = declarative_base()
class Vendor(Base):
__tablename__ = "vendor"
id = Column(Integer, primary_key=True)
name = Column(String(45))
def __init__(self, name):
self.name = name
def __repr__(self... | SQLAlchemy - Mixin vs MetaClass modification | So say, for example I have two classes:
Base = declarative_base()
class Vendor(Base):
__tablename__ = "vendor"
id = Column(Integer, primary_key=True)
name = Column(String(45))
def __init__(self, name):
self.name = name
def __repr__(self):
return "<Vendor id=%d>" % self.id
class Si... | [
"Custom metaclasses aren't needed with Declarative for simple use cases, and pretty much not at all for hard use cases either. Mixins + custom bases should be able to do pretty much everything.\nDeclare it on the base:\nclass Base(object):\n def get(...):\n # ...\n\nBase = declarative_base(cls=Base)\n\n... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006700735_python_sqlalchemy.txt |
Q:
running python script through shell_plus from command line
I have a python script that I run to populate my database. I usually run the script inside shell_plus because of the dependencies required. Is there a way to load the script into shell_plus and run everything from my linux command line without actually o... | running python script through shell_plus from command line | I have a python script that I run to populate my database. I usually run the script inside shell_plus because of the dependencies required. Is there a way to load the script into shell_plus and run everything from my linux command line without actually opening the shell_plus interface?
| [
"\"Standalone Django scripts\"\n",
"You bet! \nI don't even recommend using shell_plus. I tend to store my utilities scripts in my app utility folder. Then I simply call them from a cron job or manually as needed. Here is framework script I base this off of. (Somewhat simplified)\n#!/usr/bin/env python\n# -*... | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006701261_django_python.txt |
Q:
Can I write a function that carries out symbolic calculations in Python 2.7?
I'm currently transitioning from Java to Python and have taken on the task of trying to create a calculator that can carry out symbolic operations on infix-notated mathematical expressions (without using custom modules like Sympy). Curren... | Can I write a function that carries out symbolic calculations in Python 2.7? | I'm currently transitioning from Java to Python and have taken on the task of trying to create a calculator that can carry out symbolic operations on infix-notated mathematical expressions (without using custom modules like Sympy). Currently, it's built to accept strings that are space delimited and can only carry out ... | [
"You need much more processing before you go into operations on symbols. The form you want to get to is a tree of operations with values in the leaf nodes. First you need to do a lexer run on the string to get elements - although if you always have space-separated elements it might be enough to just split the strin... | [
4,
2
] | [] | [] | [
"algebra",
"parsing",
"python"
] | stackoverflow_0006699338_algebra_parsing_python.txt |
Q:
Python and no obvious way to get a specific element from a dictionary
How come that I can easily do a for-loop in Python to loop through all the elements of a dictionary in the order I appended the elements but there's no obvious way to access a specific element? When I say element I'm talking about a key+value pa... | Python and no obvious way to get a specific element from a dictionary | How come that I can easily do a for-loop in Python to loop through all the elements of a dictionary in the order I appended the elements but there's no obvious way to access a specific element? When I say element I'm talking about a key+value pair.
I've looked through what some basic tutorials on Python says on diction... | [
"You access a specific element in a dictionary by key. That's what a dictionary is. If that behavior isn't what you want, use something other than a dictionary.\n\na dict is supposed to be unordered but then why does the for-loop print them in the order I put them in?\n\nCoincidence: basically, you happened to put ... | [
7,
5,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006701449_dictionary_python.txt |
Q:
Catch & Ignore Signal
I'm trying to write a program that will run a program on a remote machine using ssh and pass it SIGINT signals without killing my ssh connection. If I was running on a terminal, then this would be easy with something like
ssh -t -t host "command to run"
I tried this with the following script... | Catch & Ignore Signal | I'm trying to write a program that will run a program on a remote machine using ssh and pass it SIGINT signals without killing my ssh connection. If I was running on a terminal, then this would be easy with something like
ssh -t -t host "command to run"
I tried this with the following script:
#!/bin/bash
ssh -t -t ho... | [
"os.setpgrp (look at setpgrp manpage) otherwise the signal is propagated to children\n"
] | [
1
] | [] | [] | [
"python",
"signals",
"ssh"
] | stackoverflow_0006340439_python_signals_ssh.txt |
Q:
Numpy - Replace a number with NaN
I am looking to replace a number with NaN in numpy and am looking for a function like numpy.nan_to_num, except in reverse.
The number is likely to change as different arrays are processed because each can have a uniquely define NoDataValue. I have see people using dictionaries, b... | Numpy - Replace a number with NaN | I am looking to replace a number with NaN in numpy and am looking for a function like numpy.nan_to_num, except in reverse.
The number is likely to change as different arrays are processed because each can have a uniquely define NoDataValue. I have see people using dictionaries, but the arrays are large and filled with... | [
"A[A==NDV]=numpy.nan\n\nA==NDV will produce a boolean array that can be used as an index for A\n"
] | [
72
] | [] | [] | [
"arrays",
"gdal",
"nan",
"numpy",
"python"
] | stackoverflow_0006701714_arrays_gdal_nan_numpy_python.txt |
Q:
How do I turn every value in my dictionary to a float? (recursively)
d = { 'scores': 4,
'teams': { 'yellow': 11, 'blue': 4 }
}
How do I take a dictionary, and turn every integer into a float? Recursively, for every value max deep.
A:
def float_dict(d):
new_dict = {}
for k,v in d.iteritems(... | How do I turn every value in my dictionary to a float? (recursively) |
d = { 'scores': 4,
'teams': { 'yellow': 11, 'blue': 4 }
}
How do I take a dictionary, and turn every integer into a float? Recursively, for every value max deep.
| [
"def float_dict(d):\n new_dict = {}\n for k,v in d.iteritems():\n if type(v) == dict:\n new_dict[k] = float_dict(v)\n else:\n new_dict[k] = float(v)\n return new_dict\n\n\n>>> d = { 'scores': 4, 'teams': { 'yellow': 11, 'blue': 4 } }\n>>> print float_dict(d)\n{'scores': ... | [
4,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006701286_dictionary_python.txt |
Q:
How To Transfer data from a python web application to a java desktop applaction
I want some help on a way to transfer data from a python web application to a java desktop application.
What I am doing is having java listen on a port and receive data. But I have no idea how I would send data from python to an open ... | How To Transfer data from a python web application to a java desktop applaction | I want some help on a way to transfer data from a python web application to a java desktop application.
What I am doing is having java listen on a port and receive data. But I have no idea how I would send data from python to an open port on a server.
What my question is how would I send data from a python web app to... | [
"This is a really large question as there are many ways to send data back and forth between server (your java app) and client (your python app).\nYour situation is not quite clear (what exactly is your \"python web application\"?), but you may want to look into XML-RPC. XML-RPC is extremely simple to use and set u... | [
3,
1,
1
] | [] | [] | [
"java",
"port",
"python",
"web_applications"
] | stackoverflow_0006701732_java_port_python_web_applications.txt |
Q:
python & zeroMQ -- Capacity to Handle Messages of Large Size?
I'd like to use python to build an app that is similar to zeroMQ's ventilator / sink scheme
Suppose that we have 10 Workers, all running on the same multi-core server.
Let's say that every 2[sec] or so, each Worker pushes to the Sink a message of size ... | python & zeroMQ -- Capacity to Handle Messages of Large Size? | I'd like to use python to build an app that is similar to zeroMQ's ventilator / sink scheme
Suppose that we have 10 Workers, all running on the same multi-core server.
Let's say that every 2[sec] or so, each Worker pushes to the Sink a message of size 5[MB]. So, the Sink has to handle a total of 50[MB] ( = 10 x 5[MB] ... | [
"Using PUSH/PULL on the same server I've been been able to max out writing to a raid array @ 400MB/sec (bottle-necked by write speed). There are 10GbE benchmark results here. I'd suggest constructing some simple benchmarks, performance is going to be dependent on a lot of factors like message format, size, etc.\nFo... | [
2
] | [] | [] | [
"python",
"zeromq"
] | stackoverflow_0006701819_python_zeromq.txt |
Q:
What web framework to choose
I'm comming from java world (apache wicket) and need to use python for my project.
I've heard about Turbogear2, Pyramid(Pylons) or Django and read some about them.
My first choice will be TurboGears2 built on top of Pylons, with tools already packaged, but
perhaps someone as some ad... | What web framework to choose | I'm comming from java world (apache wicket) and need to use python for my project.
I've heard about Turbogear2, Pyramid(Pylons) or Django and read some about them.
My first choice will be TurboGears2 built on top of Pylons, with tools already packaged, but
perhaps someone as some advice.
I do not need to create a lo... | [
"For myself, mako + sqlalchemy in Pyramid are what seal the deal. If you're into some decent DB work, SqlAlchemy is just the best to work with. I'm also a big fan of the mako templates. The ability to create presentation type functions in mako itself that are reusable vs trying to do things in python modules that y... | [
5,
1,
1,
0
] | [] | [] | [
"django",
"pylons",
"pyramid",
"python",
"turbogears2"
] | stackoverflow_0006692132_django_pylons_pyramid_python_turbogears2.txt |
Q:
What's a good data model for cross-tabulation?
I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that works but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement ... | What's a good data model for cross-tabulation? | I'm implementing a cross-tabulation library in Python as a programming exercise for my new job, and I've got an implementation of the requirements that works but is inelegant and redundant. I'd like a better model for it, something that allows a nice, clean movement of data between the base model, stored as tabular da... | [
"You could use an in-memory sqlite database as a data structure, and define the desired operations as SQL queries.\nimport sqlite3\n\nc = sqlite3.Connection(':memory:')\nc.execute('CREATE TABLE data (a, b, c)')\n\nc.executemany('INSERT INTO data VALUES (?, ?, ?)', [\n (1, None, 1),\n (1, 0, 3),\n ... | [
1,
1,
0
] | [
"Why not store it using HTML Tables? It might not be the best, but you could then, very easily, view it in a browser.\nEdit:\nI just re-read the question and you're asking for data model, not a storage model. To answer that question...\nIt all depends on how you're going to be reporting on the data. For example ... | [
-1
] | [
"algorithm",
"crosstab",
"data_structures",
"python",
"statistics"
] | stackoverflow_0001019643_algorithm_crosstab_data_structures_python_statistics.txt |
Q:
How do I merge dictionaries together, using weights?
d1 = {'weight':1, 'data': { 'apples': 8, 'oranges': 7 } }
d2 = {'weight':3, 'data': { 'apples': 4, 'bananas': 3 } }
all_dictionaries = [d1, d2, ... ]
def mergeDictionariesWithWeight(all_dictionaries)
How do I merge these dictionaries together (if overlap, mult... | How do I merge dictionaries together, using weights? | d1 = {'weight':1, 'data': { 'apples': 8, 'oranges': 7 } }
d2 = {'weight':3, 'data': { 'apples': 4, 'bananas': 3 } }
all_dictionaries = [d1, d2, ... ]
def mergeDictionariesWithWeight(all_dictionaries)
How do I merge these dictionaries together (if overlap, multiple value with the weight)
The function would return:
{ '... | [
">>> from collections import defaultdict\n>>> d=defaultdict(lambda:(0,0))\n>>> for D in all_dictionaries:\n... weight = D['weight']\n... for k,v in D['data'].items():\n... d[k]=d[k][0]+weight*v,d[k][1]+weight\n... \n>>> dict((k,v[0]/v[1]) for k,v in d.items())\n{'apples': 5, 'oranges': 7, 'bananas': 3}\n\nI... | [
7,
1,
1,
1,
0
] | [] | [] | [
"computer_science",
"dictionary",
"python"
] | stackoverflow_0006701358_computer_science_dictionary_python.txt |
Q:
how to use python to produce a group of anagram with a given list
for example :giving a list
['car','bed','stop','pots','arc','tops','z','z','rac','deb']
then with the function: produce
[['arc', 'car', 'rac'], ['bed', 'deb'], ['pots', 'stop', 'tops'], ['z', 'z']]
A:
Seems to be taken from this assigment, ... | how to use python to produce a group of anagram with a given list | for example :giving a list
['car','bed','stop','pots','arc','tops','z','z','rac','deb']
then with the function: produce
[['arc', 'car', 'rac'], ['bed', 'deb'], ['pots', 'stop', 'tops'], ['z', 'z']]
| [
"Seems to be taken from this assigment, but the OP doesn't specify the \"no builtin sort constraint, so...\n>>> from collections import defaultdict\n>>> d=defaultdict(list)\n>>> words = ['car','bed','stop','pots','arc','tops','z','z','rac','deb']\n>>> for w in words:\n... d[''.join(sorted(w)].append(w)\n... \n>>>... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006702370_python.txt |
Q:
Run Python program from shell and keep variables in scope
Python has a nice execfile function inside the interpreter where you can run a program, keep all the variables in scope, and then inspect them at your leisure. However, as far as I know you can't run execfile on a program that takes arguments from the comma... | Run Python program from shell and keep variables in scope | Python has a nice execfile function inside the interpreter where you can run a program, keep all the variables in scope, and then inspect them at your leisure. However, as far as I know you can't run execfile on a program that takes arguments from the command line; if you try to include the arguments, Python throws an ... | [
"You could modify sys.argv directly. The file:\n# foo.py\nimport sys\n\nprint sys.argv\n\nThe other file:\nimport sys\nimport shlex # thanks Matt\n\nold_argv = sys.argv\nsys.argv = shlex.split('foo.py is a happy camper')\n\nexecfile('foo.py')\n\nOutput:\n$ python foo.py is a happy camper\n['foo.py', 'is', 'a', 'h... | [
3
] | [] | [] | [
"interactive",
"python"
] | stackoverflow_0006702387_interactive_python.txt |
Q:
I suspect Popen to timeout without saying
I'm having some difficulties with my scripts. The purpose is to launch one or several OpenVZ container to execute some test. Those test can be very long (about 3 hours usually).
The first script goes this way, after sorting the queue member to launch, it does:
subprocess.P... | I suspect Popen to timeout without saying | I'm having some difficulties with my scripts. The purpose is to launch one or several OpenVZ container to execute some test. Those test can be very long (about 3 hours usually).
The first script goes this way, after sorting the queue member to launch, it does:
subprocess.Popen(QUEUE_EXECUTER % queue['queue_id'], shell=... | [
"Your intent is first to run process_install until it finishes, then run process_wait? (sequentially, not multiprocessing, right?) Which command do you suspect to timeout?\nPlease paste the actual values of queue['cmd_install'], queue['cmd_test']\n(Does either of those commands have a trailing '&' or redirects?)\nH... | [
0
] | [] | [] | [
"openvz",
"python",
"stderr",
"stdout",
"subprocess"
] | stackoverflow_0006505719_openvz_python_stderr_stdout_subprocess.txt |
Q:
Get the most relevant word (spell check) from 'enchant suggest()' in Python
I want to get the most relevant word from enchant suggest(). Is there any better way to do that. I feel my function is not efficient when it comes to checking large set of words in the range of 100k or more.
Problem with enchant suggest()... | Get the most relevant word (spell check) from 'enchant suggest()' in Python | I want to get the most relevant word from enchant suggest(). Is there any better way to do that. I feel my function is not efficient when it comes to checking large set of words in the range of 100k or more.
Problem with enchant suggest():
>>> import enchant
>>> d.suggest("prfomnc")
['prominence', 'performance', 'pre... | [
"No magic bullet, I'm afraid... a few suggestions however.\nI'm guessing that most of the time in the logic is spent in the difflib's SequenceMatcher().ratio() call. This wouldn't be surprising since this method uses a variation on the Rattcliff-Obershelp algorithm which is relatively expensive, CPU-wise (but the... | [
3,
2
] | [] | [] | [
"python",
"spell_checking"
] | stackoverflow_0006702405_python_spell_checking.txt |
Q:
How do you specify the shebang line of a command script created by setuptools
I have created a package that I will be distributing throughout the company that replaces a legacy bash script with the same name. It is referenced many places so it needs to execute like the current script does. This has worked fine unt... | How do you specify the shebang line of a command script created by setuptools | I have created a package that I will be distributing throughout the company that replaces a legacy bash script with the same name. It is referenced many places so it needs to execute like the current script does. This has worked fine until I encountered some servers that do not have a current version of Python as the d... | [
"\nRun the script with /opt/bin/python script.py, or\nedit the first line to read #!/opt/bin/python, or\nput /opt/bin in your path before /usr/bin.\n\n",
"The answer to my question was answered by Keith. Running the setup.py as /opt/bin/python setup.py install produces the results I need without any user interven... | [
1,
1,
0
] | [] | [] | [
"packaging",
"python",
"setuptools"
] | stackoverflow_0006599686_packaging_python_setuptools.txt |
Q:
How to get "first-order optimality" with python script
I curious about how to get "first-order optimality" value using python script.
For optimatization python has many module like scipy.optimize and openopt. But I confused how to use that module to get first-order optimality
This is sample matlab script to get fi... | How to get "first-order optimality" with python script | I curious about how to get "first-order optimality" value using python script.
For optimatization python has many module like scipy.optimize and openopt. But I confused how to use that module to get first-order optimality
This is sample matlab script to get first-order optimality
[x,resnorm,residual,exitflag,output,lam... | [
"Try scipy.linalg.basic.lstsq or scipy.optimize.minpack.curve_fit\nTry to write your own code, refer to the tutorials or else search the web for scipy.linalg.basic.lstsq for code samples (there are some out there). If you encounter any issues, post the code and the issue here.\n"
] | [
1
] | [] | [] | [
"mathematical_optimization",
"numpy",
"optimization",
"python",
"scipy"
] | stackoverflow_0004573788_mathematical_optimization_numpy_optimization_python_scipy.txt |
Q:
SocketServer causing error 10053
Code in question https://github.com/truevision/socketbroker/blob/master/socketbroker/broker.py
Works flawlessly in Linux, on Windows I get
error: [Errno 10053] An established connection was aborted by the software in your host machine
A:
This may be due to a host based IDS and n... | SocketServer causing error 10053 | Code in question https://github.com/truevision/socketbroker/blob/master/socketbroker/broker.py
Works flawlessly in Linux, on Windows I get
error: [Errno 10053] An established connection was aborted by the software in your host machine
| [
"This may be due to a host based IDS and not a firewall. I've ran into the same issue before. Here's how I fixed it..\n"
] | [
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0006693075_python_windows.txt |
Q:
How to use "pycimport" module of Jython?
I want to import a pyc file in Jython, and I was suggested to explore the 'pycimport' module in Jython, but since this is an experimental module , I was not able to get any code examples, I would be very glad if anybody can help me to implement this module in Java.
A:
Why... | How to use "pycimport" module of Jython? | I want to import a pyc file in Jython, and I was suggested to explore the 'pycimport' module in Jython, but since this is an experimental module , I was not able to get any code examples, I would be very glad if anybody can help me to implement this module in Java.
| [
"Why do you want to implement the pycimport module in Java?\nUsing the pycimport module is actually quite simple, you just import the module, and after that you can import modules in pyc-files:\ncole:tmp tobias$ cat mymodule.py\ndef fibonacci(n):\n a,b = 1,0\n for i in range(n):\n a,b = a+b,a\n retu... | [
1,
0
] | [] | [] | [
"jython",
"pyc",
"python"
] | stackoverflow_0006689029_jython_pyc_python.txt |
Q:
how to add http header to a pdf file using python?
Hi is it possible to add a http header to a pdf file like Content-Disposition:attachment;filename=test.pdf in python, for now what i do is i send my pdf files to Amazons S3 by adding
--add-header=Content-Disposition:attachment;filename=test.pdf
but i would like ... | how to add http header to a pdf file using python? | Hi is it possible to add a http header to a pdf file like Content-Disposition:attachment;filename=test.pdf in python, for now what i do is i send my pdf files to Amazons S3 by adding
--add-header=Content-Disposition:attachment;filename=test.pdf
but i would like to set this in python
| [
"Do you mean you want to upload files to S3 using Python and set some extra headers along the way?\nIf so, you could use simples3 library. Or some other similar library. I'll cover using simples3:\nFollow the docs on how to instantiate a S3Bucket object. Once you have that, you can do:\nbucket.put('path/to/your/pdf... | [
1,
0
] | [] | [] | [
"http_headers",
"python"
] | stackoverflow_0006702010_http_headers_python.txt |
Q:
Python script running both FastCGI and traditional CGI?
I have written a Python script that currently is designed to handle traditional CGI requests. Of course, this won't scale well as the overheads for each request are great, which is why I'm looking into implementing FastCGI support.
How can I modify my script ... | Python script running both FastCGI and traditional CGI? | I have written a Python script that currently is designed to handle traditional CGI requests. Of course, this won't scale well as the overheads for each request are great, which is why I'm looking into implementing FastCGI support.
How can I modify my script to work with both CGI and FastCGI? Is there something the scr... | [
"Program to WSGI and use the flup adapters.\n"
] | [
2
] | [] | [] | [
"cgi",
"fastcgi",
"python"
] | stackoverflow_0006703590_cgi_fastcgi_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.