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:
Parameters not getting passed properly
Here's an excerpt of my code:
def listFrom(here):
print "[DBG] here: " + here
def book(here, there, amount):
print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount)
# Code that takes input and stores it into the string input
# Yes, I know thi... | Parameters not getting passed properly | Here's an excerpt of my code:
def listFrom(here):
print "[DBG] here: " + here
def book(here, there, amount):
print "[DBG] here: " + here + "; there: " + there + "; amount: " + str(amount)
# Code that takes input and stores it into the string input
# Yes, I know this is dangerous, but it's part of a
# school ... | [
"This code works without problems in Python 2.6 on Linux/x86-32:\n>>> def listFrom(here):\n... print \"[DBG] here: \" + here\n... \n>>> def book(here, there, amount):\n... print \"[DBG] here: \" + here + \"; there: \" + there + \"; amount: \" + str(amount)\n... \n>>> book('LON', 'MAN', 8)\n[DBG] here: LON; ... | [
0
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0002347266_eval_python.txt |
Q:
Python: passing a function with parameters as parameter
def lite(a,b,c):
#...
def big(func): # func = callable()
#...
#main
big(lite(1,2,3))
how to do this?
in what way to pass function with parameters to another function?
A:
Why not do:
big(lite, (1, 2, 3))
?
Then you can do:
def big(func, args):
... | Python: passing a function with parameters as parameter | def lite(a,b,c):
#...
def big(func): # func = callable()
#...
#main
big(lite(1,2,3))
how to do this?
in what way to pass function with parameters to another function?
| [
"Why not do:\nbig(lite, (1, 2, 3))\n\n?\nThen you can do:\ndef big(func, args):\n func(*args)\n\n",
"import functools\n\n#main\nbig(functools.partial(lite, 1,2,3))\n\n",
"Similar problem is usually solved in two ways:\n\nWith lambda… but then the passed function will expect one argument, so big() needs to be... | [
43,
11,
3,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0002347388_function_python.txt |
Q:
How to consume XML from RESTful web services using Django / Python?
Should I use PyXML or what's in the standard library?
A:
ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation:
# Try to use the C implementation first, falling ... | How to consume XML from RESTful web services using Django / Python? | Should I use PyXML or what's in the standard library?
| [
"ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation:\n# Try to use the C implementation first, falling back to python\ntry:\n from xml.etree import cElementTree as ElementTree\nexcept ImportError, e:\n from xml.etree import ... | [
10,
3,
0
] | [] | [] | [
"django",
"python",
"rest",
"xml"
] | stackoverflow_0000804992_django_python_rest_xml.txt |
Q:
Baby steps to a solution with django and mod-wsgi on os x
I'm running apache / os x and serving up localhost pages to test django on my laptop. I've already verified all the following
• python is working fine and up to date (2.5.1)
• django available to python and up to date (1,1,0, 'final', 0)
• mod_wsgi module... | Baby steps to a solution with django and mod-wsgi on os x | I'm running apache / os x and serving up localhost pages to test django on my laptop. I've already verified all the following
• python is working fine and up to date (2.5.1)
• django available to python and up to date (1,1,0, 'final', 0)
• mod_wsgi module is loaded among apache modules in my apache config - Check!
• ... | [
"Try adding /users/useracct/Sites/ a to your pythonpath in your wsgi file:\nimport os\nimport sys\n.....\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')\n....\n\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"macos",
"mod_wsgi",
"python"
] | stackoverflow_0002336253_apache_django_macos_mod_wsgi_python.txt |
Q:
Coping dictionary within a dictionary(Nested dictionary)
I am having a dictionary like as dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another di... | Coping dictionary within a dictionary(Nested dictionary) | I am having a dictionary like as dict1 = { 0 : 0, 1 : 1, 2 : { 0: 0, 1 : 1}} (which is also having a dictionary as value). I want to keep store these value same for some modification checking purpose. So now I am copy this dictionary content into another dictionary as dict2 = dict1.copy(). Now I am changing the values... | [
"Use copy.deepcopy to perform a deep copy.\n"
] | [
11
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002347854_dictionary_python.txt |
Q:
Dynamic Event Conditions
Consider that we've a class named Foo that fires "ready" event when it's ready.
from observer import SubjectSet
class Foo:
def __init__(self):
self.events = SubjectSet()
self.events.create('ready')
def do_sth(self):
self.events.fire('ready')
As you see, do_sth method mak... | Dynamic Event Conditions | Consider that we've a class named Foo that fires "ready" event when it's ready.
from observer import SubjectSet
class Foo:
def __init__(self):
self.events = SubjectSet()
self.events.create('ready')
def do_sth(self):
self.events.fire('ready')
As you see, do_sth method makes ready instances of the Foo ... | [
"I think you do not actually define very exactly what is the problem you try to solve. However, there's nothing wrong with the solution. It's clearly asynchronous and event-driven. But I think in general the solution should also arrow for error conditions, i.e. what happens if task1 or task2 fails due to any reason... | [
1
] | [] | [] | [
"algorithm",
"asynchronous",
"events",
"python"
] | stackoverflow_0002347958_algorithm_asynchronous_events_python.txt |
Q:
Google Books API - Getting Book Ratings?
I cannot find a way to get a Book's Ratings through the Books API provided by Google.
All I figured out is how to obtain search listings, which do not include ratings and description.
Help would be very much appreciated.
A:
I've never used Google Book API, but its docume... | Google Books API - Getting Book Ratings? | I cannot find a way to get a Book's Ratings through the Books API provided by Google.
All I figured out is how to obtain search listings, which do not include ratings and description.
Help would be very much appreciated.
| [
"I've never used Google Book API, but its documentation claims you can only retrieve an annotation (incl. review) for a specific user.\nAnother proof is some post by Google employee who claims it's not supported (yet).\n"
] | [
2
] | [] | [] | [
"ajax",
"google_books",
"python"
] | stackoverflow_0002284595_ajax_google_books_python.txt |
Q:
webcam motion tracking with Python
Is there a simple way to track the motions of a single entity in a webcam feed? For example, I imagine a "hello world" app with an index finger used as mouse pointer.
I realize there's still a lot of basic research in this area, so it might be too early to expect an easy to use, ... | webcam motion tracking with Python | Is there a simple way to track the motions of a single entity in a webcam feed? For example, I imagine a "hello world" app with an index finger used as mouse pointer.
I realize there's still a lot of basic research in this area, so it might be too early to expect an easy to use, generic abstraction.
For the sake of com... | [
"You might want to take a look at http://opencv.willowgarage.com/wiki/PythonInterface. I'm not sure how hard it would be to do arbitrary motion tracking, but it was fairly simple to implement face tracking.\n"
] | [
4
] | [] | [] | [
"motion_detection",
"python"
] | stackoverflow_0002348151_motion_detection_python.txt |
Q:
Share data between mod_python processes
I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter.
What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something datab... | Share data between mod_python processes | I'm running mod_python under Apache. If I've understood correctly, each Apache process runs its own Python interpreter.
What would be the best way to share a tiny amount of data across all the processes? I'm talking about just a few hundred bytes here, making something database based completely overkill.
| [
"Put it in shared memory.\n",
"The quickest way is to use file IO. One process writes the file and the other reads it. You can use the mmap module to make this a little more seamless. One interesting alternative that I haven't tried (yet) is to use some derivative of multiprocessing.Manager to communicate betw... | [
1,
1
] | [] | [] | [
"apache",
"mod_python",
"python",
"share"
] | stackoverflow_0002348202_apache_mod_python_python_share.txt |
Q:
Python PIL and StringIO
I'm trying to download images from URLs and pass them to PIL.
I would like to use as few resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO.
A:
Unfortunately file-likes from network functions such as urllib2.urlopen()... | Python PIL and StringIO | I'm trying to download images from URLs and pass them to PIL.
I would like to use as few resources as possible, especially RAM. What would the best way of dealing with this? I've had suggestions to use cStringIO.
| [
"Unfortunately file-likes from network functions such as urllib2.urlopen() don't support all the necessary methods, so you'll need to read the data into a StringIO or cStringIO in order to be able to pass them to Image.open().\n"
] | [
4
] | [] | [] | [
"django",
"python",
"python_imaging_library"
] | stackoverflow_0002348443_django_python_python_imaging_library.txt |
Q:
Scraping for a "preview" of a webpage - Python
I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites.
For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content.
But other times there are videos as main content of the pag... | Scraping for a "preview" of a webpage - Python | I'm indexing a list of links, these links update quite often so I'm automating thumbnails for the sites.
For most sites it's easy, as I just grab the biggest image on the page hoping it describes the content.
But other times there are videos as main content of the page.
Does somebody have tips with dealing with this? ... | [
"wkhtmltopdf uses an embedded copy of the WebKit render engine (used in Safari, Chrome etc.) to save a webpage to PDF, including all images (no Flash video though I guess). That could be a starting point for a much more accurate thumbnail.\n",
"There exists (free and paid) services that do exactly what you need. ... | [
3,
3
] | [] | [] | [
"django",
"html",
"python",
"screen_scraping"
] | stackoverflow_0002348401_django_html_python_screen_scraping.txt |
Q:
What's wrong with this string normilizer Python snippet?
It seems that every time I think I mastered encoding, I find something new to puzzle me :-)
I'm trying to get rid of French accents from an UTF-8 string:
>>> import unicodedata
>>> s = u"éèêàùçÇ"
>>> print(unicodedata.normalize('NFKD', s).encode('ascii','i... | What's wrong with this string normilizer Python snippet? | It seems that every time I think I mastered encoding, I find something new to puzzle me :-)
I'm trying to get rid of French accents from an UTF-8 string:
>>> import unicodedata
>>> s = u"éèêàùçÇ"
>>> print(unicodedata.normalize('NFKD', s).encode('ascii','ignore'))
I expected eeeaucC as an output and got instead AA A... | [
"Afters further tests, it works if you use Python 3 or Python 2.6 interpreters instead of iPython.\nMaybe a wrong user setting or a bug.\n",
"python works as it should:\n$ python\nPython 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) \n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for... | [
1,
0
] | [] | [] | [
"encoding",
"normalize",
"python",
"string"
] | stackoverflow_0002347953_encoding_normalize_python_string.txt |
Q:
Why do I need the DJANGO_SETTINGS_MODULE set?
Every time I log on to my server through SSH I need to type the following:
export DJANGO_SETTINGS_MODULE=settings
if I do not any usage of the manage.py module fails
My manage.py has the following added code:
if "notification" in settings.INSTALLED_APPS:
from noti... | Why do I need the DJANGO_SETTINGS_MODULE set? | Every time I log on to my server through SSH I need to type the following:
export DJANGO_SETTINGS_MODULE=settings
if I do not any usage of the manage.py module fails
My manage.py has the following added code:
if "notification" in settings.INSTALLED_APPS:
from notification import models as notification
def cre... | [
"Yourmanage.py is referencing an application (notifications). This forces Django to complain about DJANGO_SETTINGS_MODULE being set because the Django environment hasn't been set up yet.\nIncidentally, you can force the enviroment setup manually, but honestly I wouldn't do this in manage.py. That's not really a go... | [
11,
6,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002102330_django_python.txt |
Q:
Is there any Python wrapper around cron?
I'm looking for a wrapper around cron.
I've stumbled upon PyCron but it's a Python implementation, not a wrapper.
Do you know any good cron Python wrapper ?
If not, did you test PyCron, and what can you tell about it ?
//EDIT (As an answer to comment asking for more details... | Is there any Python wrapper around cron? | I'm looking for a wrapper around cron.
I've stumbled upon PyCron but it's a Python implementation, not a wrapper.
Do you know any good cron Python wrapper ?
If not, did you test PyCron, and what can you tell about it ?
//EDIT (As an answer to comment asking for more details):
I am looking for something to set a cron jo... | [
"python-crontab allows you to read and write user crontabs via python programs.\nfrom crontab import CronTab\n\ntab = CronTab()\ncron = tab.new(command='/foo/bar')\ncron.every_reboot()\ntab.write()\n\n"
] | [
11
] | [] | [] | [
"cron",
"python",
"wrapper"
] | stackoverflow_0002343403_cron_python_wrapper.txt |
Q:
Creating a Persistent Data Object In Django
I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds.
I'd like to create a ... | Creating a Persistent Data Object In Django | I have a Python-based maximum entropy classifier. It's large, stored as a Pickle, and takes about a minute to unserialize. It's also not thread safe. However, it runs fast and can classify a sample (a simple Python dictionary) in a few milliseconds.
I'd like to create a basic Django web app, so users can submit samples... | [
"you could use djangos cache-framework and set the timeout to a extreme value\n",
"Consider running it in another process. You could have your Django application submit samples via a socket that the classifier process listens on, or you could run a queue and have Django submit requests to the queue.\n"
] | [
4,
2
] | [] | [] | [
"django",
"persistence",
"python"
] | stackoverflow_0002345257_django_persistence_python.txt |
Q:
Display value in Charfield for foreign key in django on error
Let's say I've got a model and it has a foreign key to another one.
class ModelA(models.Model):
field = models.CharField(max_length=100)
class ModelB(models.Model):
model_a = models.ForeignKey(ModelA)
Than I've got this form:
class FormB(model... | Display value in Charfield for foreign key in django on error | Let's say I've got a model and it has a foreign key to another one.
class ModelA(models.Model):
field = models.CharField(max_length=100)
class ModelB(models.Model):
model_a = models.ForeignKey(ModelA)
Than I've got this form:
class FormB(models.ModelForm):
model_a = forms.CharField(required=True)
def... | [
"I can think of two options:\n\nMake model_a field on ModelB hidden with editable=false, and add a CharField to ModelB to store the text the user entered. Then show this field in the form, but use its value to populate model_a.\nUse an autocomplete field, for example using django-autocomplete. This allows the user ... | [
0
] | [] | [] | [
"django",
"foreign_keys",
"forms",
"python"
] | stackoverflow_0002348829_django_foreign_keys_forms_python.txt |
Q:
what is the pysvn command equvilent to "svn info file:///path/to/svn/repo"?
I'm looking for a good python library to manipulate subversion repositories. I'm trying out PySvn, but finding that it can't handle something like
pysvn.Client().info("/path/to/svn/repo")
because it's not a working copy. Anyone know of an... | what is the pysvn command equvilent to "svn info file:///path/to/svn/repo"? | I'm looking for a good python library to manipulate subversion repositories. I'm trying out PySvn, but finding that it can't handle something like
pysvn.Client().info("/path/to/svn/repo")
because it's not a working copy. Anyone know of any good libraries that can handle this kind of thing?
Update - I'll try to simplif... | [
"Do you try info2 instead of info? Documentation says it can access URL of repository.\n"
] | [
5
] | [] | [] | [
"python",
"svn"
] | stackoverflow_0002348282_python_svn.txt |
Q:
pysqlite, query for duplicate entries with swapped columns
Currently I have a pysqlite db that I am using to store a list of road conditions. The source this list is generated from however is buggy and sometimes generates duplicates. Some of these duplicates will have the start and end points swapped but everythin... | pysqlite, query for duplicate entries with swapped columns | Currently I have a pysqlite db that I am using to store a list of road conditions. The source this list is generated from however is buggy and sometimes generates duplicates. Some of these duplicates will have the start and end points swapped but everything else the same.
The method i currently have looks like this:
d... | [
"Instead of the first query, you could use\nSELECT DISTINCT * FROM roadCond\n\nwhich will retrieve all the records from the table, removing any duplicates.\nAs for the inner method, this query will return all the records which have \"duplicates\" with start and end swapped. Note that, for each record with \"duplica... | [
0
] | [] | [] | [
"python",
"sql",
"sqlite"
] | stackoverflow_0002344610_python_sql_sqlite.txt |
Q:
Unable to get custom context processor to be invoked
I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following:
Within my settings.py I have
TEMPLATE_CONTEXT_PROCESSOR = (
'django.contrib.auth.context_processors.auth',
'mysite.... | Unable to get custom context processor to be invoked | I am trying to create a custom context processor which will render a list of menu items for a logged in user. I have done the following:
Within my settings.py I have
TEMPLATE_CONTEXT_PROCESSOR = (
'django.contrib.auth.context_processors.auth',
'mysite.accounts.context_processors.user_menu',
)
Under the accou... | [
"The setting name should be TEMPLATE_CONTEXT_PROCESSORS, with an S.\n"
] | [
5
] | [] | [] | [
"django",
"django_context",
"django_templates",
"python"
] | stackoverflow_0002348943_django_django_context_django_templates_python.txt |
Q:
python single configuration file
I am developing a project that requires a single configuration file whose data is used by multiple modules.
My question is: what is the common approach to that? should i read the configuration file from each
of my modules (files) or is there any other way to do it?
I was thinking t... | python single configuration file | I am developing a project that requires a single configuration file whose data is used by multiple modules.
My question is: what is the common approach to that? should i read the configuration file from each
of my modules (files) or is there any other way to do it?
I was thinking to have a module named config.py that r... | [
"I like the approach of a single config.py module whose body (when first imported) parses one or more configuration-data files and sets its own \"global variables\" appropriately -- though I'd favor config.teamdata over the round-about config.data['teamdata'] approach.\nThis assumes configuration settings are read-... | [
10,
4,
3,
1
] | [] | [] | [
"configuration_files",
"python"
] | stackoverflow_0002348927_configuration_files_python.txt |
Q:
Passing multiple arguments from IronPython to .NET method
I have a class in .NET (C#):
public class MyHelper {
public object exec( string script, params object[] arguments ) {
// execute script with passed arguments in some external enviroment
}
}
I'm using IronPython runtime in my code to run pyt... | Passing multiple arguments from IronPython to .NET method | I have a class in .NET (C#):
public class MyHelper {
public object exec( string script, params object[] arguments ) {
// execute script with passed arguments in some external enviroment
}
}
I'm using IronPython runtime in my code to run python scripts, which should in some cases call the "exec" method.... | [
"The problem here is that \"exec\" is a keyword in Python so you can't use that as your function name. You could use \"exec_\" or execute or something like that instead. Alternately you could write:\ngetattr(helper, 'exec')(...)\n",
"According to this FAQ, the MyHelper.exec you've defined should accept both an ... | [
3,
1
] | [] | [] | [
"c#",
"interop",
"ironpython",
"python"
] | stackoverflow_0002347003_c#_interop_ironpython_python.txt |
Q:
What can I do if django runserver seems to be caching my urls.py and settings.py?
I detected this problem when updating the patterns in URLConf and seeing that the new pattern wasn't matched anywhere.
So, with urls.py I don't get anywhere when writing random lines on it, I mean, invalid code, and django doesn't th... | What can I do if django runserver seems to be caching my urls.py and settings.py? | I detected this problem when updating the patterns in URLConf and seeing that the new pattern wasn't matched anywhere.
So, with urls.py I don't get anywhere when writing random lines on it, I mean, invalid code, and django doesn't throw any exception and serves the urls just fine.
So I checked ROOT_URLCONF in settings.... | [
"You're not running what you think you're running. Check your PYTHONPATH.\n"
] | [
2
] | [] | [] | [
"django",
"python",
"url"
] | stackoverflow_0002349302_django_python_url.txt |
Q:
Process for converting python program into threaded application?
I have a code-base that I'm looking to split up and add to by using threading, however I'm relatively new on how to handle it. Please before reading further respect my wish of NOT just re-writing this code and tossing it back at me with the problem ... | Process for converting python program into threaded application? | I have a code-base that I'm looking to split up and add to by using threading, however I'm relatively new on how to handle it. Please before reading further respect my wish of NOT just re-writing this code and tossing it back at me with the problem solved. I would much rather work the problem out by someone pointing ... | [
"As long as you have a single thread (as in the above snippet, where you instantiate Recon just once), it shouldn't matter much what you do where; but of course I imagine the reason you're introducing threading is to eventually move to having multiple threads active.\nIf that's the case, then the first key issue is... | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002349876_multithreading_python.txt |
Q:
How many private variables are too many? Capsulizing classes? Class Practices?
Okay so i am currently working on an inhouse statistics package for python, its mainly geared towards a combination of working with arcgis geoprocessor, for modeling comparasion and tools.
Anyways, so i have a single class, that calcula... | How many private variables are too many? Capsulizing classes? Class Practices? | Okay so i am currently working on an inhouse statistics package for python, its mainly geared towards a combination of working with arcgis geoprocessor, for modeling comparasion and tools.
Anyways, so i have a single class, that calculates statistics. Lets just call it Stats. Now my Stats class, is getting to the point... | [
"I can think of a couple of solutions. One would be to simply store values in an array with an enum like so:\nStatisticType = enum('AveragePerDay','MedianPerDay'...)\n\nAnother would be to use a inheritance like so:\nclass StatisticBase\n....\nclass AveragePerDay ( StatisticBase )\n...\nclass MedianPerDay ( Statist... | [
1,
1,
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002349529_class_python.txt |
Q:
Why am I getting an AttributeError when I have the attribute?
I keep getting the following error:
AttributeError: Caribou instance has no attribute 'on_key_up'
The problem is, I'm pretty sure I do have that attribute...
Here are some excerpts from my code (from caribou.py):
def on_key_up(self, event):
if event... | Why am I getting an AttributeError when I have the attribute? | I keep getting the following error:
AttributeError: Caribou instance has no attribute 'on_key_up'
The problem is, I'm pretty sure I do have that attribute...
Here are some excerpts from my code (from caribou.py):
def on_key_up(self, event):
if event.event_string == "Shift_R":
_r_shift_down = False
elif event.e... | [
"The OP mentions in a comment that dir(caribou) gives him:\n['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']\n\nso it definitely looks at that point that caribou is a module -- nothing else would normally have __builtins__ etc. The error message however clearly mentions a Caribou inst... | [
4,
2,
1
] | [] | [] | [
"attributeerror",
"python"
] | stackoverflow_0002349365_attributeerror_python.txt |
Q:
Emacs: Set/Reset python debug breakpoint
I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py)
Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set_trace();" statements in the ... | Emacs: Set/Reset python debug breakpoint | I use python debugger pdb. I use emacs for python programming. I use python-mode.el. My idea is to make emacs intuitive. So I need the following help for python programs (.py)
Whenever I press 'F9' key, the emacs should put "import pdb; pdb.set_trace();" statements in the current line and move the current line to one ... | [
"to do 1) \n(defun add-py-debug () \n \"add debug code and move line down\" \n (interactive) \n (move-beginning-of-line 1) \n (insert \"import pdb; pdb.set_trace();\\n\")) \n\n(local-set-key (kbd \"<f9>\") 'add-py-debug)\n\nto do 2) you probably have to change the syntax highlighting of the pyth... | [
8,
0
] | [] | [] | [
"customization",
"debugging",
"elisp",
"emacs",
"python"
] | stackoverflow_0002332164_customization_debugging_elisp_emacs_python.txt |
Q:
python csv header error
Trying to read headers for a csv file with:
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
for header in sorted(set(headers)):
It worked on development server, throws this error on production
'NoneType' object is not iterable
Debug shows header... | python csv header error | Trying to read headers for a csv file with:
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
for header in sorted(set(headers)):
It worked on development server, throws this error on production
'NoneType' object is not iterable
Debug shows headers has None value while the cs... | [
"From csvreader.fieldnames documentation:\n\nIf not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.\n\nSo try reading the first row from the file, then reader.fieldnames should contain the data you need. Maybe something ... | [
2,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002350018_csv_python.txt |
Q:
Python: does the set class "leak" when items are removed, like a dict?
I know that Python dicts will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the set class behave the same way? Is it safe to keep a set around, adding and removing stuff fro... | Python: does the set class "leak" when items are removed, like a dict? | I know that Python dicts will "leak" when items are removed (because the item's slot will be overwritten with the magic "removed" value)… But will the set class behave the same way? Is it safe to keep a set around, adding and removing stuff from it over time?
Edit: Alright, I've tried it out, and here's what I found:
... | [
"Yes, set is basically a hash table just like dict -- the differences at the interface don't imply many differences \"below\" it. Once in a while, you should copy the set -- myset = set(myset) -- just like you should for a dict on which many additions and removals are regularly made over time.\n"
] | [
7
] | [
"For questions like these it is often best to run a quick experiment like this one and see what happens:\ns = set()\nfor a in range(1000):\n for b in range(10000000):\n s.add(b)\n for b in range(10000000):\n s.remove(b)\n\nWhat docs and people say and what behaviour actually is are often at odds. If this i... | [
-1
] | [
"dictionary",
"python",
"set"
] | stackoverflow_0002350050_dictionary_python_set.txt |
Q:
How do I print a line following a line containing certain text in a saved file in Python?
I have written a Python program to find the carrier of a cell phone given the number. It downloads the source of http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1 (where 1112223333 is the p... | How do I print a line following a line containing certain text in a saved file in Python? | I have written a Python program to find the carrier of a cell phone given the number. It downloads the source of http://www.whitepages.com/carrier_lookup?carrier=other&number_0=1112223333&response=1 (where 1112223333 is the phone number to lookup) and saves this as carrier.html. In the source, the carrier is in the lin... | [
"What you really want to be doing is parsing the HTML properly. Use the BeautifulSoup library - it's wonderful at doing so.\nSample code:\nimport urllib2, BeautifulSoup\n\nopener = urllib2.build_opener()\nopener.addheaders[0] = ('User-agent', 'Mozilla/5.1')\n\nresponse = opener.open('http://www.whitepages.com/carri... | [
4,
2,
2
] | [] | [] | [
"html",
"parsing",
"python",
"string"
] | stackoverflow_0002350190_html_parsing_python_string.txt |
Q:
Callback, observers, and asynch sockets in Python
I'm still a neophyte Python programmer and I'm trying to do something that is a bit over my head.
What I've done is create a simple IRC bot using asyncore (and asynchronous sockets module). The client runs in a continuous loop, listening to the conversation in the... | Callback, observers, and asynch sockets in Python | I'm still a neophyte Python programmer and I'm trying to do something that is a bit over my head.
What I've done is create a simple IRC bot using asyncore (and asynchronous sockets module). The client runs in a continuous loop, listening to the conversation in the channel. What I would like to do (I think?) is implem... | [
"While Observer is not a particularly popular DP (design pattern) in Python, it's not a totally \"alien\" one either, so if you're familiar with it, go right ahead. However, the normal way to call observe would be with handler=self.log_join, a callback that's actually a callable, not with a string value forcing th... | [
2
] | [] | [] | [
"design_patterns",
"network_programming",
"python",
"sockets"
] | stackoverflow_0002350249_design_patterns_network_programming_python_sockets.txt |
Q:
Python Eval executing environment
I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. Does python create an anonymous module for them, and if that is the case how do the global and local scope d... | Python Eval executing environment | I do not understand what environment a eval or exec statement executes in. You can pass both global and local scopes to them but I don't quite understand what this means. Does python create an anonymous module for them, and if that is the case how do the global and local scope differ?
Does it run it like it was an an... | [
"The \"local\" dictionary is where all names are being set during an exec or eval; the \"global\" one is used for lookup of names not found in the \"local\" one, but names aren't set there unless you're execing code that includes a global statement.\nNo module object is created intrinsically by either eval or exec,... | [
2
] | [] | [] | [
"eval",
"exec",
"python"
] | stackoverflow_0002350390_eval_exec_python.txt |
Q:
Parsing XML in Python using Expat
Background: I'm coming from C#-land, so I'm looking for something like being able to handle nodes and values by selecting via Xpath.
Here's my code, so far:
import urllib
import sys
from xml.parsers import expat
url = 'http://SomeWebService.SomeDomain.com'
u = urllib.urlopen(u... | Parsing XML in Python using Expat | Background: I'm coming from C#-land, so I'm looking for something like being able to handle nodes and values by selecting via Xpath.
Here's my code, so far:
import urllib
import sys
from xml.parsers import expat
url = 'http://SomeWebService.SomeDomain.com'
u = urllib.urlopen(url)
Parser = expat.ParserCreate()
data... | [
"I think you would have more luck if you tried using one of the xml.dom packages, or xml.etree.ElementTree. ElementTree has some limited xpath support, so if that's what you're used to, it might be the best choice.\n"
] | [
1
] | [] | [] | [
"expat_parser",
"python",
"xml",
"xmlnode",
"xpath"
] | stackoverflow_0002350494_expat_parser_python_xml_xmlnode_xpath.txt |
Q:
GraphicsPath doesn't always refresh itself
The simple curve in this application only appears when it's dragged off the screen, or the window is resized. When the application just starts up it doesn't appear, and when the window is maximized or minimized it also disappears. However, all of these times, "Path Drawn"... | GraphicsPath doesn't always refresh itself | The simple curve in this application only appears when it's dragged off the screen, or the window is resized. When the application just starts up it doesn't appear, and when the window is maximized or minimized it also disappears. However, all of these times, "Path Drawn" is printed, so all of the painting functions ar... | [
"Comment out the self.SetDoubleBuffered(True) part and it will work, because due to bug http://trac.wxwidgets.org/ticket/11138 window isn't refreshed correctly if SetDoubleBuffered and GraphicsContext are used together.\nIf you MUST need double buffering implement it yourselves e.g. first draw to a MeomryDC and the... | [
2
] | [] | [] | [
"graphicscontext",
"graphicspath",
"python",
"wxpython"
] | stackoverflow_0002348183_graphicscontext_graphicspath_python_wxpython.txt |
Q:
memory location of dictionary in python 2.6.4 only?
Is it possible to see a memory location/address of data dictionary in python 2.6.4 only??
A:
In CPython use id function.
| memory location of dictionary in python 2.6.4 only? | Is it possible to see a memory location/address of data dictionary in python 2.6.4 only??
| [
"In CPython use id function.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002350719_python.txt |
Q:
literal usage of % in batch
I have a batch file containing a python script using the Output template> %(NAME)s
when I ran it, cmd thinks its a var and igoners the %
so
youtube-dl.py -b -o %(uploader)s-%(title)s-%(id)s.%(ext)s
turns into
youtube-dl.py -b -o (uploader)s-(title)s-(id)s.(ext)s
how do i convin... | literal usage of % in batch | I have a batch file containing a python script using the Output template> %(NAME)s
when I ran it, cmd thinks its a var and igoners the %
so
youtube-dl.py -b -o %(uploader)s-%(title)s-%(id)s.%(ext)s
turns into
youtube-dl.py -b -o (uploader)s-(title)s-(id)s.(ext)s
how do i convince cmd to not process it and pass... | [
"Replace the % with %%:\nyoutube-dl.py -b -o %%(uploader)s-%%(title)s-%%(id)s.%%(ext)s\n\n(Note that, unlike on Unix, double quotes don't do a lot on Windows command lines.)\n",
"If you don't want your % characters interpreted by cmd.exe, you should prefix them with the escape character:\nc:\\> set qwert=55\nc:\... | [
3,
3,
1
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0002350954_cmd_python.txt |
Q:
Putting a pyCurl XML server response into a variable (Python)
I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (http://twitpic.com/api.do). For reference purposes, check out the code (http://pastebin.com/f4c498b6e) and the error I'm getting... | Putting a pyCurl XML server response into a variable (Python) | I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (http://twitpic.com/api.do). For reference purposes, check out the code (http://pastebin.com/f4c498b6e) and the error I'm getting (http://pastebin.com/mff11d31).
Pay special attention to line 27 o... | [
"Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data...\nSomething like this would suffice:\nimport pycurl\nimport cStringIO\n\nresponse = cStringIO.StringIO()\n\nc = pycurl.Curl()\nc.setopt(c.URL, 'http://www.turnkeylinux.org')\nc.setopt(c.WRITEFUN... | [
12,
4
] | [] | [] | [
"pycurl",
"python",
"xml"
] | stackoverflow_0000256564_pycurl_python_xml.txt |
Q:
Can I use wxPython wx.ItemContainer in a derived class?
I'm trying to make a new wx.Choice-like control (actually a replacement for wx.Choice) which uses the wx.ItemContainer to manage the list of items. Here is a minimal example showing the error:
import wx
class c(wx.ItemContainer):
def __init__(my): pass
x... | Can I use wxPython wx.ItemContainer in a derived class? | I'm trying to make a new wx.Choice-like control (actually a replacement for wx.Choice) which uses the wx.ItemContainer to manage the list of items. Here is a minimal example showing the error:
import wx
class c(wx.ItemContainer):
def __init__(my): pass
x = c()
x.Clear()
This fails with:
Traceback (most recent ca... | [
"wx.ItemContainer can't be instantiated directly e.g. try\nx = wx.ItemContainer()\n\nit throws error\nTraceback (most recent call last):\n File \"C:\\<string>\", line 1, in <module>\n File \"D:\\Python25\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\_core.py\", line 11812, in __init__\n def __init__(self): rais... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002335585_python_wxpython.txt |
Q:
Socket shutdown and rebind - How to avoid long wait?
I'm working with socket in python, and being in development stage I need to kill and restart my program frequently.
The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the p... | Socket shutdown and rebind - How to avoid long wait? | I'm working with socket in python, and being in development stage I need to kill and restart my program frequently.
The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the problem:
#!/usr/bin/env python3 ... | [
"I'm not sure how to do it in Python, but you want to set the SO_REUSEADDR socket option.\n"
] | [
4
] | [] | [] | [
"linux",
"python",
"python_3.x",
"sockets"
] | stackoverflow_0002351465_linux_python_python_3.x_sockets.txt |
Q:
python switch by class name?
I am currently doing this, to do different things based on an object's type:
actions = {
SomeClass: lambda: obj.name
AnotherClass: lambda: self.normalize(obj.identifier)
...[5 more of these]...
}
for a in actions.keys():
if isinstance(obj, a... | python switch by class name? | I am currently doing this, to do different things based on an object's type:
actions = {
SomeClass: lambda: obj.name
AnotherClass: lambda: self.normalize(obj.identifier)
...[5 more of these]...
}
for a in actions.keys():
if isinstance(obj, a):
return actions[a]()... | [
"class SomeClass( object ):\n....\n def action( self ):\n return self.name\n\nclass AnotherClass( object ):\n....\n def action( self ):\n return self.normalize( self.identifier )\n\n[5 more classes like the above two]\n\na.action()\n\nSimpler. Clearer. More extensible. Less Magic. No diction... | [
7,
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"switch_statement",
"syntax"
] | stackoverflow_0002351525_python_switch_statement_syntax.txt |
Q:
Why doesn't import prevent NameError in a python script run with execfile()?
I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior.
I want to make a simple game tha... | Why doesn't import prevent NameError in a python script run with execfile()? | I looked at a number of existing questions about NameError exceptions when scripts are run with exec statements or execfile() in Python, but haven't found a good explanation yet of the following behavior.
I want to make a simple game that creates script objects at runtime with execfile(). Below are 4 modules that demo... | [
"From the Python documentation for execfile:\nexecfile(filename[, globals[, locals]])\nIf the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called.\nThere are two optional arguments for execfile... | [
3,
0
] | [] | [] | [
"exec",
"execfile",
"import",
"nameerror",
"python"
] | stackoverflow_0002348630_exec_execfile_import_nameerror_python.txt |
Q:
numpy.matrix manipulations
I have a question about numpy.matrix class. How can I perform such basic manipulations with matrices as adding, deleting and replacing rows and columns?
p.s. I apologize for the lame question..
A:
Perfectly fine question! Try examining this code:
import scipy
X = scipy.rand(3,3)
Y = sc... | numpy.matrix manipulations | I have a question about numpy.matrix class. How can I perform such basic manipulations with matrices as adding, deleting and replacing rows and columns?
p.s. I apologize for the lame question..
| [
"Perfectly fine question! Try examining this code:\nimport scipy\nX = scipy.rand(3,3)\nY = scipy.rand(3,3)\nprint X+Y\nprint scipy.delete(X, 1, 0)\nprint scipy.delete(X, 1, 1)\nX[1,:] = [1,2,3]\nprint X\n\nFor more, see the numpy/scipy docs here: NumPy/SciPy docs\nIf you are fluent in Matlab, this page is useful: N... | [
3
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0002351844_matrix_numpy_python.txt |
Q:
How can I prevent a name error error in python?
When I run my program core.py (http://pastebin.com/kbzbBUYd) it returns:
File "core.py", line 47, in texto
core.mail(numbersendlist, messagetext)
NameError: global name 'core' is not defined
Can anyone tell me what is going on and how I can stop this error?
If it... | How can I prevent a name error error in python? | When I run my program core.py (http://pastebin.com/kbzbBUYd) it returns:
File "core.py", line 47, in texto
core.mail(numbersendlist, messagetext)
NameError: global name 'core' is not defined
Can anyone tell me what is going on and how I can stop this error?
If it helps, the "import carrier" line in core.py refers t... | [
"You're getting NameError Because there's no such name core defined in your code in either local or global scope. Create a Core object first before calling it's methods.\nAlso the indentation of texto() is probably wrong. You won't be able to use this function from rest of the module. If you want to use it from oth... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0002351904_python.txt |
Q:
What's the proper way to describe an associative object by SQLalchemy the declarative way
I'm looking for a way to describe an associative object the declarative way. Beyond storing the foreign keys in the association table, I need to store information like the creation date of the association.
Today, my model loo... | What's the proper way to describe an associative object by SQLalchemy the declarative way | I'm looking for a way to describe an associative object the declarative way. Beyond storing the foreign keys in the association table, I need to store information like the creation date of the association.
Today, my model looks like that :
# Define the User class
class User(Base):
__tablename__ = 'users'
# Def... | [
"What you are using at the moment is just a Many-to-Many-relation. How to work with association objects is described in the docs.\nThere is also an extension called associationproxy which simplifies the relation.\n",
"As you can see in the manual, configuring a one to many relation is really simple:\nclass User(B... | [
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002351927_python_sqlalchemy.txt |
Q:
How can I detect and track people using OpenCV?
I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using OpenCV, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles... | How can I detect and track people using OpenCV? | I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using OpenCV, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles.
I've looked at several of the built-in samples:
No... | [
"The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection. It even comes with a pre-trained detector and a python wrapper. The basic usage is as follows:\nfrom cv import *\n\nstorage = CreateMemStorage(0)\nimg = LoadImage(file) # or read from camera\n\nfound = ... | [
28,
5,
4,
2
] | [] | [] | [
"computer_vision",
"motion_detection",
"opencv",
"python"
] | stackoverflow_0002188646_computer_vision_motion_detection_opencv_python.txt |
Q:
Use Mercurial API to Get Changes to a Repository For a Given Changeset
How can I use the Mercurial API to determine the changes made to a repository for each changeset? I am able to get a list of files relevant to a particular revision, but I cannot figure out how to tell what happened to that file.
How can I answ... | Use Mercurial API to Get Changes to a Repository For a Given Changeset | How can I use the Mercurial API to determine the changes made to a repository for each changeset? I am able to get a list of files relevant to a particular revision, but I cannot figure out how to tell what happened to that file.
How can I answer these questions about each file in a changeset:
Was it added?
Was it del... | [
"localrepo.status() can take contexts as argument (node1 and node2).\nSee http://hg.intevation.org/mercurial/crew/file/6505773080e4/mercurial/localrepo.py#l973\n"
] | [
5
] | [] | [] | [
"changeset",
"dvcs",
"mercurial",
"mercurial_extension",
"python"
] | stackoverflow_0002352129_changeset_dvcs_mercurial_mercurial_extension_python.txt |
Q:
Detect when threads are running in a python application?
How can we detect when threads are running in a python application?
Motivation: We were recently debugging a large Python application that had several customer supplied modules that were supplied without source code. Unbeknowst to us (and our customer!), one... | Detect when threads are running in a python application? | How can we detect when threads are running in a python application?
Motivation: We were recently debugging a large Python application that had several customer supplied modules that were supplied without source code. Unbeknowst to us (and our customer!), one of these modules would launch threads under very specific (an... | [
"Debugger\nUsually a debugger can show you all the threads and what each one is executing. If you tell us which debugger you are using, someone can tell you how to see the thread info. If you aren't using a debugger, I highly suggest you start. Debugging multi-threaded programs without a real debugger is quite erro... | [
6
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002351989_multithreading_python.txt |
Q:
Attempting to insert an integer from a list into datetime object
What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that 'month' type is int...so I'm kind of stuck... | Attempting to insert an integer from a list into datetime object | What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that 'month' type is int...so I'm kind of stuck as to why I can't substitute my month variable. Here is my code:
al... | [
"There are a few things that you need to fix here.\nEDIT: First, be careful with your range, since you are using month+1 to create next_month_begin, you do not want this to be greater than 12 or you will get an error.\nNext, when you are trying to create the date object you are passing the month in as a string when... | [
2,
2,
0,
0
] | [] | [] | [
"datetime",
"python",
"range"
] | stackoverflow_0002349551_datetime_python_range.txt |
Q:
The difference between python dict and tr1::unordered_map in C++
I have a question related to understanding of how python dictionaries work.
I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutabl... | The difference between python dict and tr1::unordered_map in C++ | I have a question related to understanding of how python dictionaries work.
I remember reading somewhere strings in python are immutable to allow hashing, and it is the same reason why one cannot directly use lists as keys, i.e. the lists are mutable (by supporting .append) and hence they cannot be used as dictionary ... | [
"Keys in all C++ map/set containers are const and thus immutable (after added to the container).\nNotice that C++ containers are not specific to string keys, you can use any objects, but the constness will prevent modifications after the key is copied to the container.\n"
] | [
8
] | [] | [] | [
"c++",
"dictionary",
"hashmap",
"python",
"tr1"
] | stackoverflow_0002352342_c++_dictionary_hashmap_python_tr1.txt |
Q:
How to use dicts in Mako templates?
Whenever I pass a complicated data structure to Mako, it's hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something like:
% for item in dict1['dict2']['list']: ... %endfor
I am wondering if Mako has some mechanism that coul... | How to use dicts in Mako templates? | Whenever I pass a complicated data structure to Mako, it's hard to iterate it. For example, I pass a dict of dict of list, and to access it in Mako, I have to do something like:
% for item in dict1['dict2']['list']: ... %endfor
I am wondering if Mako has some mechanism that could replace [] usage to access dictionary e... | [
"Simplification of Łukasz' example:\nclass Bunch:\n def __init__(self, d):\n for k, v in d.items():\n if isinstance(v, dict):\n v = Bunch(v)\n self.__dict__[k] = v\n\nprint Bunch({'a':1, 'b':{'foo':2}}).b.foo\n\nSee also: http://code.activestate.com/recipes/52308-the-... | [
8,
3
] | [] | [] | [
"mako",
"python",
"templates"
] | stackoverflow_0002352252_mako_python_templates.txt |
Q:
What is the proper way to pass errors from classes to rendered html in python
I'm performing all my form validation in a class, and would like to be able to get the errors from the class to the rendered html. One approach I was thinking about was to create a global variable "c" that would store all the errors and... | What is the proper way to pass errors from classes to rendered html in python | I'm performing all my form validation in a class, and would like to be able to get the errors from the class to the rendered html. One approach I was thinking about was to create a global variable "c" that would store all the errors and to set them from within the class, as I still want the individual methods to retur... | [
"I like to use a dictionary to hold the errors and warnings. Then I can either show all errors at the top of the form or inline. I also define error and warning variables so I can easily tell the two apart.\nclass User(object):\n def __init__(self):\n self.messages = {}\n\n def add(self):\n er... | [
1,
1,
1
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0002352201_mako_pylons_python.txt |
Q:
What special method in Python handles AttributeError?
What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases?
For example,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj ... | What special method in Python handles AttributeError? | What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases?
For example,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'... | [
"The example of how to use __getattr__ by Otto Allmendinger overcomplicates its use. You would simply define all the other attributes and—if one is missing—Python will fall back on __getattr__.\nExample:\nclass C(object):\n def __init__(self):\n self.foo = \"hi\"\n self.bar = \"mom\"\n\n def __g... | [
6,
2,
1
] | [] | [] | [
"attributeerror",
"python"
] | stackoverflow_0002352630_attributeerror_python.txt |
Q:
Xerces + Python?
Does anyone know if there's an available python library compatible with Python2.6 that exposes the Xerces functionality and its XML DOM capabilities?
I would define the desired capabilities as: XML DOM select by Xpath & XSLT processor.
A:
pirxx in theory could match your requirements, but it has... | Xerces + Python? | Does anyone know if there's an available python library compatible with Python2.6 that exposes the Xerces functionality and its XML DOM capabilities?
I would define the desired capabilities as: XML DOM select by Xpath & XSLT processor.
| [
"pirxx in theory could match your requirements, but it hasn't been maintained in several years so I'd expect some minor incompatibilities with 2.6 to be likely to show up. However, it might still be worth your while to try it -- perhaps fixing those minor things (if they're indeed minor!) and contributing the fixe... | [
1
] | [] | [] | [
"python",
"xerces",
"xml",
"xpath",
"xslt"
] | stackoverflow_0002352512_python_xerces_xml_xpath_xslt.txt |
Q:
What is a good way to handle database objects in python classes?
Should I access global db object directly from within the methods of each class? Or from each method, should I instantiate an instance of the db object?
One of my database objects changes depending on the id of the info being accessed so it is cre... | What is a good way to handle database objects in python classes? | Should I access global db object directly from within the methods of each class? Or from each method, should I instantiate an instance of the db object?
One of my database objects changes depending on the id of the info being accessed so it is created through a function connectToDatabase(id). Should I make this a g... | [
"In this case, like in many others, I prefer dependency injection: have your class (e.g in its __init__) accept the DB connection as an argument.\nThis makes it easier and cleaner to test, lets you switch strategies as needed (e.g. to move to a \"pool of DB connections\" strategy if you find otherwise you're making... | [
2,
1
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002352661_pylons_python_sqlalchemy.txt |
Q:
Custom data types in numpy arrays
I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it.
class Kernel:
pass
... | Custom data types in numpy arrays | I'm creating a numpy array which is to be filled with objects of a particular class I've made. I'd like to initialize the array such that it will only ever contain objects of that class. For example, here's what I'd like to do, and what happens if I do it.
class Kernel:
pass
>>> L = np.empty(4,dtype=Kernel)
Type... | [
"If your Kernel class has a predictable amount of member data, then you could define a dtype for it instead of a class. e.g. if it's parameterized by 9 floats and an int, you could do\nkerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)])\narr = np.empty(dims, dtype=kerneldt)\n\nYou'll have to... | [
32,
3,
2
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002350072_numpy_python.txt |
Q:
Numpy array memory issue
I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end:
new_data = npy.array([new_x, new_y1, new_y2, new_y3])
private.data = npy.row_stack([private.data, new_data])
where new_x, new_y1, new_y2, new_y3 are floats.
After about 5 hou... | Numpy array memory issue | I believe I am having a memory issue using numpy arrays. The following code is being run for hours on end:
new_data = npy.array([new_x, new_y1, new_y2, new_y3])
private.data = npy.row_stack([private.data, new_data])
where new_x, new_y1, new_y2, new_y3 are floats.
After about 5 hours of recording this data ever... | [
"Use Python lists. Seriously, they grow far more efficiently. This is what they are designed for. They are remarkably efficient in this setting.\nIf you need to create an array out of them at the end (or even occasionally in the midst of this computation), it will be far more efficient to accumulate in a list first... | [
3,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0002345518_arrays_numpy_python.txt |
Q:
How to simplify creating huge data structures in Python
I am writing some and I need to pass a complicated data structure to some function.
The data structure goes like this:
{ 'animals': [ 'cows', 'moose', { 'properties': [ 9, 26 ] } ]
'fruits': {
'land': [ 'strawberries', 'other berries' ],
'space': [ ... | How to simplify creating huge data structures in Python | I am writing some and I need to pass a complicated data structure to some function.
The data structure goes like this:
{ 'animals': [ 'cows', 'moose', { 'properties': [ 9, 26 ] } ]
'fruits': {
'land': [ 'strawberries', 'other berries' ],
'space': [ 'apples', 'cherries' ]
}
}
This structure looks pretty ugl... | [
"Other languages would solve this problem with objects or structs-- so, something like:\nclass whatever:\n animals = AnimalObject()\n fruits = FruitObject()\n\nclass AnimalObject:\n animals = ['cows','moose']\n properties = [9,26]\n\nclass FruitObject:\n land = ['strawberries', 'other berries']\n ... | [
5,
2
] | [] | [] | [
"data_structures",
"python"
] | stackoverflow_0002352793_data_structures_python.txt |
Q:
How to add file extensions based on file type on Linux/Unix?
This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
fd73d0cf8ee68073dce270cf7e770b9... | How to add file extensions based on file type on Linux/Unix? | This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:
I have a directory full of files where the filenames are hash values like this:
fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
These files have different ori... | [
"Here's mimetypes' version:\n#!/usr/bin/env python\n\"\"\"It is a `filename -> filename.ext` filter. \n\n `ext` is mime-based.\n\n\"\"\"\nimport fileinput\nimport mimetypes\nimport os\nimport sys\nfrom subprocess import Popen, PIPE\n\nif len(sys.argv) > 1 and sys.argv[1] == '--rename':\n do_rename = True\n ... | [
18,
12,
7,
2,
0
] | [] | [] | [
"bash",
"linux",
"python",
"shell",
"unix"
] | stackoverflow_0000352837_bash_linux_python_shell_unix.txt |
Q:
Have to Restart Apache When Using Django On Apache with mod_wsgi
I'm creating a web app with Django. Since I'm very familiar with Apache I setup my development environment to have Django run through Apache using mod_wsgi. The only annoyance I have with this is that I have to restart Apache everytime I change my co... | Have to Restart Apache When Using Django On Apache with mod_wsgi | I'm creating a web app with Django. Since I'm very familiar with Apache I setup my development environment to have Django run through Apache using mod_wsgi. The only annoyance I have with this is that I have to restart Apache everytime I change my code. Is there a way around this?
| [
"mod_wsgi is great for production but I think the included server is better for development.\nAnyway you should read this about automatic reloading of source code.\n"
] | [
15
] | [
"I feel like this is really just one of those things most people deal with. It's really not that big of a deal. I made a bash script to make this as easy as possible. I name it 'ra' (reload apache) so it's short and quick. The following works for most apache installs (on UNIX-based systems):\n#!/bin/bash\nsudo /etc... | [
-4
] | [
"apache",
"django",
"mod_wsgi",
"python",
"restart"
] | stackoverflow_0002353012_apache_django_mod_wsgi_python_restart.txt |
Q:
Python 3 object construction: which is the most Pythonic / the accepted way?
Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly".
Trying to accustom myself to a Pythonic wa... | Python 3 object construction: which is the most Pythonic / the accepted way? | Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the constructor really "ugly".
Trying to accustom myself to a Pythonic way of thinking, I'm wondering how I should allow my objects to be constructed.
My i... | [
"The first you describe is very common. Some use the shorter\nclass Foo:\n def __init__(self, foo, bar):\n self.foo, self.bar = foo, bar\n\nYour second approach isn't common, but a similar version is this:\nclass Thing:\n def __init__(self, **kwargs):\n self.something = kwargs['something']\n #... | [
9,
3
] | [] | [] | [
"conventions",
"python",
"python_3.x"
] | stackoverflow_0002353140_conventions_python_python_3.x.txt |
Q:
Django sending e-mail u'' around headers
I wrote a simple contact form for a client in Django. However, whenever it sends e-mail, it wraps the header values in u'' objects. For example, the From: header is
From: (u'my@email.com',)
Here's the code that sends the message:
The form:
class ContactForm(forms.Form):
... | Django sending e-mail u'' around headers | I wrote a simple contact form for a client in Django. However, whenever it sends e-mail, it wraps the header values in u'' objects. For example, the From: header is
From: (u'my@email.com',)
Here's the code that sends the message:
The form:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
sende... | [
"Lose the trailing commas here:\n elif form.is_valid():\n name = form.cleaned_data['name']\n sender = form.cleaned_data['sender']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n\n"
] | [
7
] | [] | [] | [
"django",
"email",
"python"
] | stackoverflow_0002353136_django_email_python.txt |
Q:
Sorting based on the count in a related field in Django
I have two models, Image and Tag. Each Image object can have more than one Tag associated with it, and I want to find my most frequently used tags. How would I go about this? It seems easy enough but I can't seem to figure it out.
A:
Django has (only recent... | Sorting based on the count in a related field in Django | I have two models, Image and Tag. Each Image object can have more than one Tag associated with it, and I want to find my most frequently used tags. How would I go about this? It seems easy enough but I can't seem to figure it out.
| [
"Django has (only recently) acquired Aggregate support, so now you could do something like this:\nfrom django.db.models import Count\nTag.objects.annotate(img_count=Count('image')).order_by('img_count')\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"relational_algebra",
"sql"
] | stackoverflow_0002353205_django_python_relational_algebra_sql.txt |
Q:
GAE python database object design for simple list of values
I'm really new to database object design so please forgive any weirdness in my question. Basically, I am use Google AppEngine (Python) and contructing an object to track user info. One of these pieces of data is 40 Achievement scores. Do I make a list ... | GAE python database object design for simple list of values | I'm really new to database object design so please forgive any weirdness in my question. Basically, I am use Google AppEngine (Python) and contructing an object to track user info. One of these pieces of data is 40 Achievement scores. Do I make a list of ints in the User object for this? Or do I make a separate ent... | [
"I like the simple idea of keeping the list of 40 ints, but you can't force feed it into App Engine's existing User class, whose layout is determined by the GAE API (and doesn't include those 40 ints). So that list will inevitably need to live in a separate entity (i.e., each instance of a separate model).\n"
] | [
2
] | [] | [] | [
"database",
"google_app_engine",
"object",
"python"
] | stackoverflow_0002353135_database_google_app_engine_object_python.txt |
Q:
Anybody know how to toggle caps lock on/off in Python?
I'm trying to toggle caps lock on/off when the two shift buttons are held down for a second. I've tried using the virtkey module, but it's not working. That module does work for other keys though, so I don't think I'm using the module incorrectly.
Does anybody... | Anybody know how to toggle caps lock on/off in Python? | I'm trying to toggle caps lock on/off when the two shift buttons are held down for a second. I've tried using the virtkey module, but it's not working. That module does work for other keys though, so I don't think I'm using the module incorrectly.
Does anybody have a way for doing this?
Just to be clear, I want to actu... | [
"This works for me (turns the led on and off as well as enable/disable caps)\nimport virtkey\n\nv = virtkey.virtkey()\nv.press_keycode(66)\nv.release_keycode(66) # first release doesn't release it\nv.release_keycode(66)\n\nHere are some more examples\nv.press_keycode(66) # turns capslock on\nv.release_keycode(6... | [
4,
0
] | [] | [] | [
"capslock",
"keyboard",
"linux",
"python"
] | stackoverflow_0002353112_capslock_keyboard_linux_python.txt |
Q:
Is there a better Python bundle for textmate than the one in the bundle repository?
At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?
EDIT:
I am fully aware that there are editors and environm... | Is there a better Python bundle for textmate than the one in the bundle repository? | At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?
EDIT:
I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see... | [
"I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best new way to get bundles:\nInstall GetBundles\n"
] | [
9
] | [
"I use Komodo Edit and BBEdit for MacOS development.\n\nThey handle Python whitespace perfectly.\nIt's easy to roll my own snippets and components in either tool.\nThey are really good editors for Python.\n\nBut I don't want to discuss these things.\n"
] | [
-18
] | [
"python",
"textmate",
"textmatebundles"
] | stackoverflow_0000688245_python_textmate_textmatebundles.txt |
Q:
CPython - Internally, what is stored on the stack and heap?
In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc.
I was wondering, does CPython do the same... | CPython - Internally, what is stored on the stack and heap? | In C#, Value Types (eg: int, float, etc) are stored on the stack. Method parameters may also be stored on the stack as well. Most everything else, however, is stored on the heap. This includes Lists, objects, etc.
I was wondering, does CPython do the same thing internally? What does it store on the stack, and what does... | [
"All Python objects in the CPython implementation go on the heap. You can read in detail how Python's memory management works here in the documentation:\n\nMemory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally... | [
20,
13
] | [] | [] | [
"cpython",
"memory_management",
"python",
"python_internals"
] | stackoverflow_0002353552_cpython_memory_management_python_python_internals.txt |
Q:
How can I convert string to "command" in Python?
How can I convert this so it could execute?
Traceback (most recent call last):
File "C:\Users\Shady\Desktop\tet.py", line 14, in <module>
exec test
File "<string>", line 1
print "hello world"
^
IndentationError: unexpected indent
source:
test = ''.jo... | How can I convert string to "command" in Python? | How can I convert this so it could execute?
Traceback (most recent call last):
File "C:\Users\Shady\Desktop\tet.py", line 14, in <module>
exec test
File "<string>", line 1
print "hello world"
^
IndentationError: unexpected indent
source:
test = ''.join(clientIp.split("test6")[1:])
| [
"You might need to use lstrip() on the string to get rid of any leading whitespace before passing it to exec.\n"
] | [
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002353736_python_string.txt |
Q:
How to write modern Python tests?
What is the latest way to write Python tests? What modules/frameworks to use?
And another question: are doctest tests still of any value? Or should all the tests be written in a more modern testing framework?
Thanks, Boda Cydo.
A:
The usual way is to use the builtin unittest mod... | How to write modern Python tests? | What is the latest way to write Python tests? What modules/frameworks to use?
And another question: are doctest tests still of any value? Or should all the tests be written in a more modern testing framework?
Thanks, Boda Cydo.
| [
"The usual way is to use the builtin unittest module for creating unit tests and bundling them together to test suites which can be run independently. unittest is very similar to (and inspired by) jUnit and thus very easy to use.\nIf you're interested in the very latest changes, take a look at the new PyCon talk by... | [
12,
9,
5,
2,
0
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0002352516_python_testing.txt |
Q:
How can I verify and create values on the Windows registry with Python?
How is the simpler way to verify if the value is already created or create Windows registry values ?
A:
Use the standard Python library module _winreg (it's renamed to winreg, no leading _, if you're using Python 3).
You always start with on... | How can I verify and create values on the Windows registry with Python? | How is the simpler way to verify if the value is already created or create Windows registry values ?
| [
"Use the standard Python library module _winreg (it's renamed to winreg, no leading _, if you're using Python 3).\nYou always start with one of the constant keys named _winreg.HKEYsomething; to see them all, do:\n >>> import _winreg\n >>> [k for k in dir(_winreg) if k.startswith('HKEY')]\n\nand repeatedly use (to n... | [
3,
1
] | [] | [] | [
"python",
"registry"
] | stackoverflow_0002353833_python_registry.txt |
Q:
Accessing a ServerFactory from the Service in Twisted
I've been trying to come up with a decent design for multiple factories access each others information. For example, I have the following services: 1 management web service, a VirtualHost instance (multiple domains) and a built in DNS service. Going through the... | Accessing a ServerFactory from the Service in Twisted | I've been trying to come up with a decent design for multiple factories access each others information. For example, I have the following services: 1 management web service, a VirtualHost instance (multiple domains) and a built in DNS service. Going through the finger tutorial was very helpful but it lacks some key poi... | [
"Well, after some help from a friend. I figured it out. If you create a multiservice, you can just pass the multiservice object to all your child services (I pass it in the init). Then you do setName('servicename'). Then from another service you can just get the information like so: x = self.multiService.getService... | [
2
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0002350394_python_twisted.txt |
Q:
Switching mod_python from using python2.4 to python2.5
My goal is to have Apache process a python script and output to the requesting client.
My server has both Python2.4 and Python2.5.5 installed. I have Apache configured to correctly process python scripts and tested with a simple test script. However, the real ... | Switching mod_python from using python2.4 to python2.5 | My goal is to have Apache process a python script and output to the requesting client.
My server has both Python2.4 and Python2.5.5 installed. I have Apache configured to correctly process python scripts and tested with a simple test script. However, the real script I am trying to run requires Python2.5.5. Mod_Python s... | [
"No. Rebuild it against 2.5.5 instead.\n"
] | [
0
] | [] | [] | [
"mod_python",
"python"
] | stackoverflow_0002354043_mod_python_python.txt |
Q:
Remote system event Notification Library
Hi I am looking for some sort of library that will allow:
- multiple remote applications to register with the system on which events it is interested in
- When this event occurs, the system will sent out notification to these remote applications regarding this event
- Objec... | Remote system event Notification Library | Hi I am looking for some sort of library that will allow:
- multiple remote applications to register with the system on which events it is interested in
- When this event occurs, the system will sent out notification to these remote applications regarding this event
- Objects, or hash tables information should be able ... | [
"I think you are looking for a queuing system. Give JMS a try.\n"
] | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0002354064_java_python.txt |
Q:
Controlling distutils from Scons
I have a C++ library that I build using Scons which is eventually linked into (among other things) a Python extension.
Once I have built the library with scons, I have written a standard setup.py script which I call to build and install the extension.
My main problem is that setup.... | Controlling distutils from Scons | I have a C++ library that I build using Scons which is eventually linked into (among other things) a Python extension.
Once I have built the library with scons, I have written a standard setup.py script which I call to build and install the extension.
My main problem is that setup.py does not recognize when the library... | [
"You can do any command line from SCons. See Writing Your Own Builders. Then, you can detect any changes for a given file format by writing a scanner.\n",
"I have successfully created SConstruct to compile extensions for Python written in Pyrex. The main idea is to get appropriate C-compiler flags from distuti... | [
1,
0
] | [] | [] | [
"distutils",
"python",
"scons"
] | stackoverflow_0002351553_distutils_python_scons.txt |
Q:
GoogleAppEngine web proxy
Does anyone know of a simple open source proxy capable of running on google app engine or where to start in making one? (preferably in python, I'm trying to bypass a site blocking system)
A:
You can try Mirrorrr:
http://code.google.com/p/mirrorrr/
Or Masher Nations, Itube Appengine, Toh... | GoogleAppEngine web proxy | Does anyone know of a simple open source proxy capable of running on google app engine or where to start in making one? (preferably in python, I'm trying to bypass a site blocking system)
| [
"You can try Mirrorrr:\nhttp://code.google.com/p/mirrorrr/\nOr Masher Nations, Itube Appengine, Tohr, etc.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"proxy",
"python"
] | stackoverflow_0002354170_google_app_engine_proxy_python.txt |
Q:
How to force Excel VBA to use updated COM server
I'm developing a COM server to be used from Excel VBA. When I update the server (edit code, unregister, re-register) Excel seems to carry on using the original version of the COM server, not the updated version. The only way I have found to get it to use the updat... | How to force Excel VBA to use updated COM server | I'm developing a COM server to be used from Excel VBA. When I update the server (edit code, unregister, re-register) Excel seems to carry on using the original version of the COM server, not the updated version. The only way I have found to get it to use the updated version is to close and re-open Excel, which gets a... | [
"I've found a solution to my problem - the general idea is to set things up so that the main COM server class dynamically loads the rest of the COM server code when it is called. So in Python I've created a COM server class that looks something like:\nimport main_code\n\nclass COMInterface:\n _public_methods_ =... | [
2,
0
] | [] | [] | [
"com",
"excel",
"python",
"vba",
"win32com"
] | stackoverflow_0002339993_com_excel_python_vba_win32com.txt |
Q:
Running Python With STDIN From Bash
I have a bash code (Mybash1.sh) where the result I need to pass
to another bash code (Mybash2.sh) that contain Python
Here are the codes. Mybash1.sh
#! /bin/bash
# Mybash1.sh
cut -f1,3 input_file.txt | sort | ./Mybash2.sh
Mybash2.sh is this:
#! /bin/bash
#Mybash2.sh
python m... | Running Python With STDIN From Bash | I have a bash code (Mybash1.sh) where the result I need to pass
to another bash code (Mybash2.sh) that contain Python
Here are the codes. Mybash1.sh
#! /bin/bash
# Mybash1.sh
cut -f1,3 input_file.txt | sort | ./Mybash2.sh
Mybash2.sh is this:
#! /bin/bash
#Mybash2.sh
python mycode.py foo.txt <("$@") > output.txt
# d... | [
"In python, you want to have file2 = sys.stdin.\nAnd then:\n#! /bin/bash\n#Mybash2.sh\npython mycode.py foo.txt > output.txt\n\nEDIT: I've just seen the fileinput docs and it seems that if you supply '-' to fileinput.input(), it will read stdin, so without any changes in your Python, this should work:\n#! /bin/bash... | [
2,
0
] | [] | [] | [
"bash",
"linux",
"python",
"stdin",
"unix"
] | stackoverflow_0002354724_bash_linux_python_stdin_unix.txt |
Q:
Reading from the serial port from C++ or Python on windows
I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks!
A:
In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux env... | Reading from the serial port from C++ or Python on windows | I need to read the serial port from windows, using either Python or C++. What API/Library should I use? Can you direct me to a tutorial? Thanks!
| [
"In python you've excellent package pyserial that should be cross-platform (I've used only in GNU/Linux environment).\nGive it a look, it's very simple to use but very powerful!\nOf course examples are provided!\nBy the way, if it can be useful here you can find a project of mine which use pyserial, as an extended ... | [
6,
5,
3,
3
] | [] | [] | [
"c++",
"python",
"serial_port",
"windows"
] | stackoverflow_0002354905_c++_python_serial_port_windows.txt |
Q:
Universal construct for STDIN and Fileinput in Python Code
I want my code to be able to accept input from a file AND stdin.
What's the construct to do it?
I mean a unifying construct that implies
file1 = sys.stdin
and
file1 = fileinput.input(sys.argv[1])
A:
import fileinput
for line in fileinput.input():
... | Universal construct for STDIN and Fileinput in Python Code | I want my code to be able to accept input from a file AND stdin.
What's the construct to do it?
I mean a unifying construct that implies
file1 = sys.stdin
and
file1 = fileinput.input(sys.argv[1])
| [
"import fileinput\nfor line in fileinput.input():\n print line\n\n",
"\"Unifying construct\" sounds like you want to be able to access either a file provided as an argument or sys.stdin through one variable, so you can just tell functions to get a line from that thing. Luckily, sys.stdin is just another File o... | [
6,
0
] | [] | [] | [
"linux",
"python",
"unix"
] | stackoverflow_0002355007_linux_python_unix.txt |
Q:
How do I get the URL of an HTTP redirect's target?
I am writing client-side Python unit tests to verify whether the HTTP 302 redirects on my Google App Engine site are pointing to the right pages. So far, I have been calling urllib2.urlopen(my_url).geturl(). However, I have encountered 2 issues:
the URL returned ... | How do I get the URL of an HTTP redirect's target? | I am writing client-side Python unit tests to verify whether the HTTP 302 redirects on my Google App Engine site are pointing to the right pages. So far, I have been calling urllib2.urlopen(my_url).geturl(). However, I have encountered 2 issues:
the URL returned by geturl() does not appear to include URL query strings... | [
"Use httplib (and look at the return status and Location header of the response) to avoid the \"auto-follow redirects\" that's impeding your testing. There's a good example here.\n",
"Supply follow_redirects=False to the fetch function, then retrieve the location of the first redirect from the 'location' header ... | [
5,
5
] | [] | [] | [
"google_app_engine",
"http",
"python",
"redirect"
] | stackoverflow_0002353689_google_app_engine_http_python_redirect.txt |
Q:
python parsing url after string
I want to extract a string from a url (link). That string is in a <h3></h3> tag.
link = http://www.test.com/page.html
Content of link: <h3>Text here</h3>
What would be an elegant way to first get the content/sourcecode of page.html and then exctract the link?
Thanks!
A:
I'd r... | python parsing url after string | I want to extract a string from a url (link). That string is in a <h3></h3> tag.
link = http://www.test.com/page.html
Content of link: <h3>Text here</h3>
What would be an elegant way to first get the content/sourcecode of page.html and then exctract the link?
Thanks!
| [
"I'd recommend Beatiful Soup. That's a nice parser for botched HTML pages (for the most cases you don't have to worry about the page not being well-formed).\n",
"You can use URLLib2 to retrieve the content of the URL:\nhttp://docs.python.org/library/urllib2.html\nYou could then use the HTML parser in the Python l... | [
2,
1,
1
] | [
"Provided the text you want is the only <h3>-wrapped text on the page, try:\nfrom urllib2 import urlopen\nfrom re import search\ntext = search(r'(?<=<h3>).+?(?=</h3>)', urlopen(link).read()).group(0)\nIf there are multiple <h3>-wrapped strings you can either put more details into the pattern or use re.finditer()/re... | [
-1
] | [
"parsing",
"python",
"regex"
] | stackoverflow_0002355177_parsing_python_regex.txt |
Q:
Access module masked by variable name
How do I access a module named x that I masked with a variable named x?
A:
don't name your variable x or use import ... as style.
>>> sys = 2
>>> import sys as s
>>> s
<module 'sys' (built-in)>
>>> sys
2
A:
use sys.modules[module_name] ... and you should avoid masking modu... | Access module masked by variable name | How do I access a module named x that I masked with a variable named x?
| [
"don't name your variable x or use import ... as style.\n>>> sys = 2\n>>> import sys as s\n>>> s\n<module 'sys' (built-in)>\n>>> sys\n2\n\n",
"use sys.modules[module_name] ... and you should avoid masking module names: use wisely the import statement e.g. import XYZ as ABC.\nYou can also rely on using a more comp... | [
3,
1,
0
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0002355310_namespaces_python.txt |
Q:
Python DBAPI time out for connections?
I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled.
This is the code:
def get_connection(self, conn_data):
rtu, hst, prt, usr, pwd, db = conn_data
try:
self.conn = pgdb.connect(ho... | Python DBAPI time out for connections? | I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled.
This is the code:
def get_connection(self, conn_data):
rtu, hst, prt, usr, pwd, db = conn_data
try:
self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, data... | [
"What you are experiencing is the pain of firewalls, and the timeout is the normal TCP timeout.\n",
"You can usually pass timeout argument in connect function. If it doesn't exist you could try with socket.timeout or default timeout:\nimport socket\nsocket.setdefaulttimeout(10) # sets timeout to 10 seconds\n\nThi... | [
0,
0
] | [] | [] | [
"python",
"python_db_api"
] | stackoverflow_0002355401_python_python_db_api.txt |
Q:
Ugly combination of generator expression with for loop
The following appears in my Python 2.6 code:
for src, dst in ([s,d] for s in universe for d in universe if s != d):
Can I do much better? What I particularly don't like is that I'm in effect specifying the same pair twice, once for the for loop and again for ... | Ugly combination of generator expression with for loop | The following appears in my Python 2.6 code:
for src, dst in ([s,d] for s in universe for d in universe if s != d):
Can I do much better? What I particularly don't like is that I'm in effect specifying the same pair twice, once for the for loop and again for the generator expression. I'm uncertain whether I'd prefer:
... | [
"You could use simple nested for-loops:\nfor src in universe:\n for dst in universe:\n if src == dst:\n continue\n ...\n\nI'd say this is the most easy to read syntax in this case.\n",
"I suggest keeping it entirely functional or entirely with comprehensions. Here's an implementation that's en... | [
5,
3,
1
] | [] | [] | [
"for_loop",
"generator",
"python"
] | stackoverflow_0002355542_for_loop_generator_python.txt |
Q:
Group a string into 3s in a loop (python)
I have a nine character string and need to perform operations on groups of three characters in a loop.
How would i achieve this in python?
A:
Maybe something like this?
>>> a = "123456789"
>>> for grp in [a[:3], a[3:6], a[6:]]:
print grp
Of course, if you need to ge... | Group a string into 3s in a loop (python) | I have a nine character string and need to perform operations on groups of three characters in a loop.
How would i achieve this in python?
| [
"Maybe something like this?\n>>> a = \"123456789\"\n>>> for grp in [a[:3], a[3:6], a[6:]]:\n print grp\n\nOf course, if you need to generalize,\n>>> def split3(aString):\n while len(aString) > 0:\n yield aString[:3]\n aString = aString[3:]\n\n\n>>> for c in split3(a):\n ... | [
4,
4,
3
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0002355650_loops_python.txt |
Q:
How can I create my own corpus in the Python Natural Language Toolkit?
I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions?
Ma... | How can I create my own corpus in the Python Natural Language Toolkit? | I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions?
Many thanks,
James.
| [
"As the readme says, the names corpus is not in the public domain -- you should send an email with any changes you make to the corpus author (address is in that file). Apart from that detail of law and courtesy, you can simply replace either or both of those files with your own, they're in perfectly simple format ... | [
4,
1,
0
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0002168793_nlp_nltk_python.txt |
Q:
python ImportError: No module named primes
I'm really new to Python. I'm trying to import a third party module called primes.py. I have placed this module in C:\Python26\Lib (the location where I installed Python). I then have another file which is trying to import this module. The file attempting to import pri... | python ImportError: No module named primes | I'm really new to Python. I'm trying to import a third party module called primes.py. I have placed this module in C:\Python26\Lib (the location where I installed Python). I then have another file which is trying to import this module. The file attempting to import primes is located at C:\Python26.
In my Python file... | [
"The module needs to be on your PYTHONPATH or in the same directory as the script, app, or module that is trying to import the module.\nI'm not a Windows programmer but if you have placed the module in 'C:\\Python26\\Lib' and your path is set to 'C:\\Python26' you need to add '\\Python26\\Lib' to your PYTHONPATH. I... | [
2,
1,
0
] | [] | [] | [
"importerror",
"python"
] | stackoverflow_0002355953_importerror_python.txt |
Q:
Tower of hanoi, python -> scheme, shows error. What am I missing?
The python implementation
import sys
def move(src, dst, tmp, num):
if num == 1: print 'Move from', src, 'to', dst
else:
move(src, tmp, dst, num-1)
move(src, dst, tmp, 1)
move(tmp, dst, src, num-1)
move('left', 'righ... | Tower of hanoi, python -> scheme, shows error. What am I missing? | The python implementation
import sys
def move(src, dst, tmp, num):
if num == 1: print 'Move from', src, 'to', dst
else:
move(src, tmp, dst, num-1)
move(src, dst, tmp, 1)
move(tmp, dst, src, num-1)
move('left', 'right', 'middle', int(sys.argv[1]))
Gives the right solution for tower of ... | [
" ((move src tmp dst (- num 1))\n (move src dst tmp 1)\n (move tmp dst src (- num 1)))\n\nThe above code doesn't do what you think it does :) \nTo execute a series of expressions / statements you need something like this:\n((λ ()\n (move src tmp dst (- num 1))\n (move src dst tmp 1)\n (move tmp dst src (- num... | [
4
] | [] | [] | [
"python",
"scheme",
"towers_of_hanoi"
] | stackoverflow_0002356229_python_scheme_towers_of_hanoi.txt |
Q:
How to post a file via HTTP with cookies using python poster lib
Using Chris Atlee's python poster library is there any way to include cookie handling?
I have python http login code, which works with cookies:
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))... | How to post a file via HTTP with cookies using python poster lib | Using Chris Atlee's python poster library is there any way to include cookie handling?
I have python http login code, which works with cookies:
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
request = urllib2.Request(login_url, params)
result = urlOpener.open(... | [
"I sent an email to Chris AtLee asking whether we could get a basic authentication example. He was very cool about answering my questions and even ran some example code I sent him. \nTo include cookie handling, you do something like this:\nopener = poster.streaminghttp.register_openers()\nopener.add_handler(urllib2... | [
7,
1,
0,
0
] | [] | [] | [
"cookies",
"file_upload",
"http",
"python"
] | stackoverflow_0001690446_cookies_file_upload_http_python.txt |
Q:
Python: Import Data from Open Office calc with lxml
How can I import data for example for the field A1?
When I use etree.parse() I get an error, because I dont have a xml file.
A:
It's a zip file:
import zipfile
from lxml import etree
z = zipfile.ZipFile('mydocument.ods')
data = z.read('content.xml')
data = e... | Python: Import Data from Open Office calc with lxml | How can I import data for example for the field A1?
When I use etree.parse() I get an error, because I dont have a xml file.
| [
"It's a zip file:\nimport zipfile\nfrom lxml import etree\n\nz = zipfile.ZipFile('mydocument.ods')\n\ndata = z.read('content.xml')\ndata = etree.XML(data)\n\netree.dump(data)\n\n"
] | [
1
] | [] | [] | [
"import",
"lxml",
"openoffice_calc",
"python"
] | stackoverflow_0002356451_import_lxml_openoffice_calc_python.txt |
Q:
Reusing module references in Python (Matplotlib)
I think I may have misunderstood something here... But here goes.
I'm using the psd method in matplotlib inside a loop, I'm not making it plot anything, I just want the numerical result, so:
import pylab as pyl
...
psdResults = pyl.psd(inputData, NFFT=512, Fs=sample... | Reusing module references in Python (Matplotlib) | I think I may have misunderstood something here... But here goes.
I'm using the psd method in matplotlib inside a loop, I'm not making it plot anything, I just want the numerical result, so:
import pylab as pyl
...
psdResults = pyl.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman)
But that's being looped 36 tim... | [
"Try this:\nfrom matplotlib import mlab\npsdResults = mlab.psd(inputData, NFFT=512, Fs=sampleRate, window=blackman)\n\nDoes that improve the situation?\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002356695_matplotlib_python.txt |
Q:
Date fields and Django's loaddata
Can a date be loaded into a DateField using Django's loaddata admin feature? I have a JSON file that I'm using to bulk load data into my app. When you dumpdata, date fields are outputted in the format yyyy-mm-dd. However, if you try loading data back in with the same format, th... | Date fields and Django's loaddata | Can a date be loaded into a DateField using Django's loaddata admin feature? I have a JSON file that I'm using to bulk load data into my app. When you dumpdata, date fields are outputted in the format yyyy-mm-dd. However, if you try loading data back in with the same format, the field is treated as a string and the ... | [
"Sounds like something else is broken, lupefiasco. Django has a pretty extensive set of tests to make sure you can dumpdata -> loaddata just fine.\nSounds like it may be a Ticket#5007 [http://code.djangoproject.com/ticket/5007], but it could just as well be one of many others. The error is after all rather vague. A... | [
0
] | [] | [] | [
"bulk_load",
"django",
"python"
] | stackoverflow_0002350557_bulk_load_django_python.txt |
Q:
Modern client/server authentication techniques
I'm building a non-browser client-server (XULRunner-CherryPy) application using HTTP for communication. The area I'm pondering now is user authentication. Since I don't have substantial knowledge in security I would much prefer using tried-and-tested approaches and re... | Modern client/server authentication techniques | I'm building a non-browser client-server (XULRunner-CherryPy) application using HTTP for communication. The area I'm pondering now is user authentication. Since I don't have substantial knowledge in security I would much prefer using tried-and-tested approaches and ready-made libraries over trying to invent and/or buil... | [
"This may not be a complete answer, but I would like to offer some reassuring news about rainbow tables and the web. I wouldn't worry too much about Rainbow Tables with regards to the web for the following reasons: \n(1) Rainbow table cracks work by examining the hashed password. On the web, the hashed password is ... | [
1,
1,
1
] | [] | [] | [
"authentication",
"client_server",
"python",
"xulrunner"
] | stackoverflow_0001975793_authentication_client_server_python_xulrunner.txt |
Q:
Creating a global function, accessible from all classes, with Python + Pylons
Using pylons 0.9.7, I'm trying to make a function that connects to a database on demand. I'd like it to be accessible from all functions within all model classes.
In model/__init__.py, I have:
#Establish an on-demand connection to the ... | Creating a global function, accessible from all classes, with Python + Pylons | Using pylons 0.9.7, I'm trying to make a function that connects to a database on demand. I'd like it to be accessible from all functions within all model classes.
In model/__init__.py, I have:
#Establish an on-demand connection to the central database
def connectCentral():
engine = engine_from_config(config, 'sql... | [
"from model import connectCentral\n\n",
"Have you done import init ? Or rather from init import connectCentral?\nIf you did, that such name should be defined. If not, you can try writing global connectCentral in method's body, but I believe it is only for using global variables.\nAre you sure, this modules is sup... | [
2,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002357419_pylons_python.txt |
Q:
Why does supplying stdin to subprocess.Popen cause what is written to stdout to change?
I'm using Python's subprocess.Popen to perform some FTP using the binary client of the host operating system. I can't use ftplib or any other library for various reasons.
The behavior of the binary seems to change if I attach a... | Why does supplying stdin to subprocess.Popen cause what is written to stdout to change? | I'm using Python's subprocess.Popen to perform some FTP using the binary client of the host operating system. I can't use ftplib or any other library for various reasons.
The behavior of the binary seems to change if I attach a stdin handler to the Popen instance. For example, using XP's ftp client, which accepts a tex... | [
"The program may be using isatty(3) to detect presence of a tty on stdin.\n",
"I think I read somewhere (but can't remember where) that Windows ftp client came from one of the original BSD implementations. In that it would certainly shares some relationship with Mac OS X's ftp implementation. \nFor me, this is no... | [
7,
4
] | [] | [] | [
"popen",
"python",
"stdin",
"stdout",
"subprocess"
] | stackoverflow_0002356391_popen_python_stdin_stdout_subprocess.txt |
Q:
How to get parameters of fail case in Python unittest?
I'm running an assertEqual test case for a list of methods in a particular class. These methods are expanded from string form to something callable using getattr().
How can I get unittest to tell me the particular method which failed? Meaning: how can I get un... | How to get parameters of fail case in Python unittest? | I'm running an assertEqual test case for a list of methods in a particular class. These methods are expanded from string form to something callable using getattr().
How can I get unittest to tell me the particular method which failed? Meaning: how can I get unittest to print to stdout the particular parameters which ca... | [
"You can pass assertEqual a third argument (technically fourth if you count self), which is the error message it will return. So the following should do more or less what you're looking for:\nclass MethodTest(TestCase):\n def test_method(self):\n obj = MyClass()\n for method in \"frob\", \"defrob\... | [
6
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002357921_python_unit_testing.txt |
Q:
Linux/Python: Monitor /proc/acpi files without polling?
Is there any way to monitor /proc files, such as
/proc/acpi/battery/BAT0/state
/proc/acpi/ac_adapter/ADP0/state
in a non-polling fashion, similar to inotify on a normal filesystem?
I want to do this in a PyGTK app, so I tried using PyGObject's gio.FileMonito... | Linux/Python: Monitor /proc/acpi files without polling? | Is there any way to monitor /proc files, such as
/proc/acpi/battery/BAT0/state
/proc/acpi/ac_adapter/ADP0/state
in a non-polling fashion, similar to inotify on a normal filesystem?
I want to do this in a PyGTK app, so I tried using PyGObject's gio.FileMonitor, but no dice. A Python solution that plays well with gtk.ma... | [
"Probably you can get the information you want by listening to the ACPI events. Preferably not directly (/proc/acpi/event), but via acpid or other high-level interface.\nUpdate: the other, higher level interface is the DBus interface provided by DeviceKit-power / UPower.\nFiles in /proc are not regular files, rathe... | [
2
] | [] | [] | [
"inotify",
"linux",
"pygobject",
"pygtk",
"python"
] | stackoverflow_0002357930_inotify_linux_pygobject_pygtk_python.txt |
Q:
Suggestions for first-time sourceforge project contributer?
Hey all. I'm a professional software developer here in Seattle, WA USA. I program for/work in a Windows shop, but I've recently began considering contributing to an Open Source project, specifically one under the Python License (CNRI Python License).
... | Suggestions for first-time sourceforge project contributer? | Hey all. I'm a professional software developer here in Seattle, WA USA. I program for/work in a Windows shop, but I've recently began considering contributing to an Open Source project, specifically one under the Python License (CNRI Python License).
I realize that contacting a human resources representative where ... | [
"Apparently the answer is that there'll be no problem with it. :) Thanks for all the help, you guys!\n"
] | [
0
] | [] | [] | [
"licensing",
"open_source",
"python",
"sourceforge"
] | stackoverflow_0002353868_licensing_open_source_python_sourceforge.txt |
Q:
Serial communication. Sending DTR in the right way?
I'm dealing with a gm29 by Sony Ericsson.
The datasheet says that plugging the power is not sufficient to switch on the modem. It says:
activate the RS232 control line DTR, high for > 0.2s.
I'm writing some tests in python, but:
#!/usr/bin/env python ... | Serial communication. Sending DTR in the right way? | I'm dealing with a gm29 by Sony Ericsson.
The datasheet says that plugging the power is not sufficient to switch on the modem. It says:
activate the RS232 control line DTR, high for > 0.2s.
I'm writing some tests in python, but:
#!/usr/bin/env python ... | [
"There are several things that occur to me here.\n1) the spec says that DTR is active low, so you may need to swap the true and false values to setDTR(), depending on who is confused here.\n2) You are setting DTR to false after you wake the modem. This tells the modem to go offline, and ignore all input till it goe... | [
4
] | [] | [] | [
"modem",
"python",
"serial_port"
] | stackoverflow_0002357610_modem_python_serial_port.txt |
Q:
Making user-made HTML templates safe
I want to allow users to create tiny templates that I then render in Django with a predefined context. I am assuming the Django rendering is safe (I asked a question about this before), but there is still the risk of cross-site-scripting, and I'd like to prevent this. One of th... | Making user-made HTML templates safe | I want to allow users to create tiny templates that I then render in Django with a predefined context. I am assuming the Django rendering is safe (I asked a question about this before), but there is still the risk of cross-site-scripting, and I'd like to prevent this. One of the main requirements of these templates is ... | [
"Seeing Pekka's answer, I tried to quickly Google an HTML Purifier equivalent in Python. Here's what I came up with: Python HTML Sanitizer. At first glance, it looks pretty good to me.\n",
"There's PHP-Based HTML purifier, I have not used it myself yet but heard very good things about it. They promise a lot:\n\n... | [
3,
1,
1,
0
] | [] | [] | [
"html",
"markup",
"python",
"security",
"xss"
] | stackoverflow_0002357750_html_markup_python_security_xss.txt |
Q:
Prevent Windows 7 Shutdown
I know that shutdown -a will abort a Windows shutdown, but I need to know if there is anything any where I can check for to see if a shutdown is in progress.
Ideally, I'd like a small program like this:
import os
while True:
shuttingDown = <shutdown variable to check>
if shutt... | Prevent Windows 7 Shutdown | I know that shutdown -a will abort a Windows shutdown, but I need to know if there is anything any where I can check for to see if a shutdown is in progress.
Ideally, I'd like a small program like this:
import os
while True:
shuttingDown = <shutdown variable to check>
if shuttingDown:
os.system("shu... | [
"For preventing a Windows shutdown when it is happening, you can react to the WM_QUERYENDSESSION message (don't know if you can do that easily with Python's win32 API but it's simple in C). This might not prevent applications from closing because Windows sends WM_ENDSESSION to those that answer TRUE to the query me... | [
1
] | [] | [] | [
"python",
"shutdown",
"windows",
"windows_7"
] | stackoverflow_0002358929_python_shutdown_windows_windows_7.txt |
Q:
How do you make Python wait so that you can read the output?
I've always been a heavy user of Notepad2, as it is fast, feature-rich, and supports syntax highlighting. Recently I've been using it for Python.
My problem: when I finish editing a certain Python source code, and try to launch it, the screen disappear... | How do you make Python wait so that you can read the output? | I've always been a heavy user of Notepad2, as it is fast, feature-rich, and supports syntax highlighting. Recently I've been using it for Python.
My problem: when I finish editing a certain Python source code, and try to launch it, the screen disappears before I can see the output pop up. Is there any way for me to m... | [
"you could start in the command window. e.g.:\nc:\\tmp\\python>main.py\n\nadding raw_input() (or input() in py3k) at the end of your script will let you freeze it for until enter is pressed, but it's not a good thing to do.\n",
"This is a \"problem\" with Notepad2, not Python itself.\nUnless you want to use input... | [
3,
3,
3,
0
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0002356651_ide_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.