title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How can I introspect properties and model fields in Django? | 4,930,414 | 7 | 2011-02-08T07:00:00Z | 4,933,425 | 8 | 2011-02-08T13:10:52Z | [
"python",
"django",
"models"
] | I am trying to get a list of all existing model fields and properties for a given object. Is there a clean way to instrospect an object so that I can get a dict of fields and properties.
```
class MyModel(Model)
url = models.TextField()
def _get_location(self):
return "%s/jobs/%d"%(url, self.id)
... | If you strictly want just the model fields and properties (those declared using property) then:
```
def get_fields_and_properties(model, instance):
field_names = [f.name for f in model._meta.fields]
property_names = [name for name in dir(model) if isinstance(getattr(model, name), property)]
return dict((na... |
How can I set the 'backend' in matplotlib in Python? | 4,930,524 | 41 | 2011-02-08T07:17:14Z | 4,930,867 | 44 | 2011-02-08T08:15:25Z | [
"python",
"linux",
"graphics",
"matplotlib"
] | I am new user of matplotlib, my platform is Ubuntu 10.04 Python 2.6.5
This is my code
```
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
```
The error is:
```
/usr/local/lib/python2.6/dist-packages/matplotlib/backends/__init__.py:41: UserWarning:
Your currently selected ... | > Your currently selected backend, 'agg' does not support show().
`AGG` backend is for writing to file, not for rendering in a window. See the [backend FAQ](http://matplotlib.sourceforge.net/faq/usage_faq.html#what-is-a-backend) at the matplotlib web site.
> ImportError: No module named \_backend\_gdk
For the second... |
How to specify rows and columns of a <textarea > tag using wtforms | 4,930,747 | 11 | 2011-02-08T07:53:54Z | 5,116,661 | 10 | 2011-02-25T11:27:31Z | [
"python",
"wtforms"
] | Constructing a wtforms' TextAreaField is something like this:
```
content = wtf.TextAreaField('Content', id="content-area", validators=[validators.Required()])
```
How can I specify the number of rows and columns associated with this textarea? | You are not supposed to do it in the place where you declare the widget. You have do it in the template. For eg:
```
{{form.content(rows='50',cols='100')}}
```
Need to ensure the rows and cols are specified as a string. |
Python doctest: result with multiple lines | 4,931,247 | 4 | 2011-02-08T09:11:26Z | 4,931,302 | 10 | 2011-02-08T09:19:17Z | [
"python",
"multiline",
"doctest"
] | I can't get a `doctest` to work with a result which contains multiple lines and may contain empty lines at the beginning. This is probably caused by indentation and parsing issues. I've figured out some solutions:
* Write the desired result to a file, and `doctest` the comparison between the result and the file conten... | Put `<BLANKLINE>` in the expected output just like it shows in the error message. Then the test should work just fine. The expected input terminates at the first whitespace only line which is why you have to mark it specially:
```
>>> data_lists=[ {"Average execution" : [1, 2, 3, 2, 3]},
... ... |
How to import python module with same filename that is already imported? | 4,931,487 | 4 | 2011-02-08T09:43:42Z | 4,931,577 | 8 | 2011-02-08T09:53:41Z | [
"python",
"django",
"module",
"import"
] | I have a problem with python module import.
I installed django (this can be any other module). I use this module:
```
from django.template import Context
# other imports
# use Context
```
I have a folder in my application named "utilities". In this folder I created a file "django.py" - this file contains some functio... | You will have to enable [absolute imports](http://www.python.org/dev/peps/pep-0328/) at the top of the file:
```
from __future__ import absolute_import
```
You will then have to convert the imports in the module into absolute or relative imports as appropriate. |
How to create a custom string representation for a class object? | 4,932,438 | 84 | 2011-02-08T11:27:11Z | 4,932,466 | 7 | 2011-02-08T11:30:27Z | [
"python",
"class"
] | Consider this class:
```
class foo(object):
pass
```
The default string representation looks something like this:
```
>>> str(foo)
"<class '__main__.foo'>"
```
How can I make this display a custom string? | ```
class foo(object):
def __str__(self):
return "representation"
def __unicode__(self):
return u"representation"
``` |
How to create a custom string representation for a class object? | 4,932,438 | 84 | 2011-02-08T11:27:11Z | 4,932,473 | 123 | 2011-02-08T11:30:44Z | [
"python",
"class"
] | Consider this class:
```
class foo(object):
pass
```
The default string representation looks something like this:
```
>>> str(foo)
"<class '__main__.foo'>"
```
How can I make this display a custom string? | Implement `__str__()` or `__repr__()` in the class's metaclass.
```
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print C
```
Use `__str__` if you mean a readable stringification, use `__repr__` for unambiguous representations. |
How to install a python library manually | 4,933,224 | 12 | 2011-02-08T12:50:08Z | 4,934,928 | 8 | 2011-02-08T15:27:02Z | [
"python",
"package",
"quickfix"
] | I built quickfix engine (http://www.quickfixengine.org/) for one of my tasks and also built in python support for it. Unfortunately this is a multi user env and I dont have access to the oython installation path. Thus the make install command tries to copy over the files and fails. I managed to comment out the two line... | I'm going to assume compiling the QuickFix package does not produce a `setup.py` file, but rather only compiles the Python bindings and relies on `make install` to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicate... |
Using Python 2.6 how do I get the day of the month as an integer? | 4,934,783 | 6 | 2011-02-08T15:12:47Z | 4,934,820 | 23 | 2011-02-08T15:15:53Z | [
"python",
"date"
] | I need to write a method that returns the day of the month as an integer. For example, if it's Feb 8th 2011, I want to have method like this:
```
>>> day = get_day_of_month()
```
where day would be given the integer value 8 | ```
>>>import datetime
>>>datetime.datetime.today().day
``` |
Can 64-bit python create 32-bit Windows executables | 4,935,502 | 18 | 2011-02-08T16:20:56Z | 4,935,537 | 20 | 2011-02-08T16:24:08Z | [
"python",
"32bit-64bit",
"py2exe"
] | I have a new 64-bit Windows machine and use python for various things and so would prefer to install 64-bit python.
However, one of my python projects creates a Windows executable that is then run on a 32-bit Windows machine (created using py2exe).
How do I use 64-bit python and py2exe to create a 32-bit executable?
... | You can install both 32 and 64 bit Python on the machine and use the py2exe associated with each installation.
However, unless you actually need the extra address space of 64 bit, then you may as well just stick to 32 bit Python for compatibility. You may well find that 3rd party modules will have better availability ... |
Discover what window is active on Gnome/Linux/Ubuntu from Python? | 4,935,863 | 4 | 2011-02-08T16:53:46Z | 4,935,941 | 8 | 2011-02-08T17:00:12Z | [
"python",
"linux",
"gnome",
"window-managers",
"metacity"
] | Is there any way to get a list of all windows that are open at present and see what window is at the top (i.e. active?) from Python?
This is using Gnome on Ubuntu Linux.
wnck looks like it might do this, but it's very lacking in documentation. | ```
import wnck
screen = wnck.screen_get_default()
window_list = screen.get_windows()
active_window = screen.get_active_window()
```
See also [Get active window title in X](http://stackoverflow.com/questions/3983946/get-active-window-title-in-x), and WnckScreen in the documentation. Other [questions containing wnck](h... |
Discover what window is active on Gnome/Linux/Ubuntu from Python? | 4,935,863 | 4 | 2011-02-08T16:53:46Z | 16,703,115 | 9 | 2013-05-22T23:18:54Z | [
"python",
"linux",
"gnome",
"window-managers",
"metacity"
] | Is there any way to get a list of all windows that are open at present and see what window is at the top (i.e. active?) from Python?
This is using Gnome on Ubuntu Linux.
wnck looks like it might do this, but it's very lacking in documentation. | Here's the same code using the modern GObject Introspection libraries instead of the now deprecated PyGTK method Josh Lee posted:
```
from gi.repository import Gtk, Wnck
Gtk.init([]) # necessary if not using a Gtk.main() loop
screen = Wnck.Screen.get_default()
screen.force_update() # recommended per Wnck documentat... |
Fibonacci numbers, with an one-liner in Python 3? | 4,935,957 | 27 | 2011-02-08T17:01:34Z | 4,935,997 | 24 | 2011-02-08T17:05:52Z | [
"python",
"fibonacci"
] | I know there is nothing wrong with writing with proper function structure, but I would like to know how can I find nth fibonacci number with most Pythonic way with a one-line.
I wrote that code, but It didn't seem to me best way:
```
>>> fib=lambda n:reduce(lambda x,y:(x[0]+x[1],x[0]),[(1,1)]*(n-2))[0]
>>> fib(8)
13
... | A rarely seen trick is that a lambda function can refer to itself recursively:
```
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
```
By the way, it's rarely seen because it's confusing, and in this case it is also inefficient. It's much better to write it on multiple lines:
```
def fibs():
a = 0
b = 1
... |
Fibonacci numbers, with an one-liner in Python 3? | 4,935,957 | 27 | 2011-02-08T17:01:34Z | 4,936,099 | 30 | 2011-02-08T17:15:39Z | [
"python",
"fibonacci"
] | I know there is nothing wrong with writing with proper function structure, but I would like to know how can I find nth fibonacci number with most Pythonic way with a one-line.
I wrote that code, but It didn't seem to me best way:
```
>>> fib=lambda n:reduce(lambda x,y:(x[0]+x[1],x[0]),[(1,1)]*(n-2))[0]
>>> fib(8)
13
... | ```
fib = lambda n:reduce(lambda x,n:[x[1],x[0]+x[1]], range(n),[0,1])[0]
```
(this maintains a tuple mapped from [a,b] to [b,a+b], initialized to [0,1], iterated N times, then takes the first tuple element)
```
>>> fib(1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051
89040387984... |
Fibonacci numbers, with an one-liner in Python 3? | 4,935,957 | 27 | 2011-02-08T17:01:34Z | 15,393,094 | 9 | 2013-03-13T18:05:30Z | [
"python",
"fibonacci"
] | I know there is nothing wrong with writing with proper function structure, but I would like to know how can I find nth fibonacci number with most Pythonic way with a one-line.
I wrote that code, but It didn't seem to me best way:
```
>>> fib=lambda n:reduce(lambda x,y:(x[0]+x[1],x[0]),[(1,1)]*(n-2))[0]
>>> fib(8)
13
... | I recently learned about using matrix multiplication to generate Fibonacci numbers, which was pretty cool. You take a base matrix:
```
[1, 1]
[1, 0]
```
and multiply it by itself N times to get:
```
[F(N+1), F(N)]
[F(N), F(N-1)]
```
This morning, doodling in the steam on the shower wall, I realized that you could c... |
How do I write a logging middleware for pyramid/pylons 2? | 4,936,507 | 4 | 2011-02-08T17:54:01Z | 4,941,976 | 8 | 2011-02-09T06:34:35Z | [
"python",
"logging",
"mongodb",
"pyramid"
] | I want to use either mongodb or redis to keep logs for users in pyramid/pylons, but cant find the doc on creating a middeware. How do I go about it? | Standart middleware
```
class LoggerMiddleware(object):
'''WSGI middleware'''
def __init__(self, application):
self.app = application
def __call__(self, environ, start_response):
# write logs
try:
return self.app(environ, start_response)
except Exception, e:... |
Using strides for an efficient moving average filter | 4,936,620 | 20 | 2011-02-08T18:05:38Z | 4,946,883 | 7 | 2011-02-09T15:27:17Z | [
"python",
"image-processing",
"filter",
"numpy"
] | I recently learned about [strides](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html) in the [answer to this post](http://stackoverflow.com/questions/4923617/efficient-numpy-2d-array-construction-from-1d-array), and was wondering how I could use them to compute a moving average filter more ... | I'm not familiar enough with Python to write out code for that, but the two best ways to speed up convolutions is to either separate the filter or to use the Fourier transform.
*Separated filter* : Convolution is O(M\*N), where M and N are number of pixels in the image and the filter, respectively. Since average filte... |
Using strides for an efficient moving average filter | 4,936,620 | 20 | 2011-02-08T18:05:38Z | 4,947,453 | 18 | 2011-02-09T16:12:10Z | [
"python",
"image-processing",
"filter",
"numpy"
] | I recently learned about [strides](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html) in the [answer to this post](http://stackoverflow.com/questions/4923617/efficient-numpy-2d-array-construction-from-1d-array), and was wondering how I could use them to compute a moving average filter more ... | For what it's worth, here's how you'd do it using "fancy" striding tricks. I was going to post this yesterday, but got distracted by actual work! :)
@Paul & @eat both have nice implementations using various other ways of doing this. Just to continue things from the earlier question, I figured I'd post the N-dimensiona... |
Grouping a series in Python | 4,937,163 | 6 | 2011-02-08T19:03:58Z | 4,937,182 | 8 | 2011-02-08T19:06:56Z | [
"python",
"matplotlib"
] | Title edit: capitalization fixed and 'for python' added.
Is there a better or more standard way to do what I'm describing?
I want input like this:
`[1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2]`
to be transformed to this:
`[0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0]`
or,... | To get the labels you can use itertools [`groupby`](http://docs.python.org/library/itertools.html#itertools.groupby):
```
>>> import itertools
>>> numbers = [1, 1, 1, 0, 2, 2, 0, 2, 2, 0, 0, 3, 3, 0, 1, 1, 1, 1, 1, 2, 2, 2]
>>> list(k for k, g in itertools.groupby(numbers))
[1, 0, 2, 0, 2, 0, 3, 0, 1, 2]
```
And to r... |
Matrix Transpose in Python | 4,937,491 | 87 | 2011-02-08T19:38:48Z | 4,937,526 | 197 | 2011-02-08T19:41:39Z | [
"python",
"list",
"multidimensional-array"
] | I am trying to create a matrix transpose function for python but I can't seem to make it work.
Say I have
```
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
```
and I want my function to come up with
```
newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]
```
So in other words, if I were to print this ... | ```
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
``` |
Matrix Transpose in Python | 4,937,491 | 87 | 2011-02-08T19:38:48Z | 4,938,130 | 32 | 2011-02-08T20:38:07Z | [
"python",
"list",
"multidimensional-array"
] | I am trying to create a matrix transpose function for python but I can't seem to make it work.
Say I have
```
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
```
and I want my function to come up with
```
newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]
```
So in other words, if I were to print this ... | If your rows are not equal you can also use `map`:
```
>>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
>>> map(None,*uneven)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
```
Edit: In Python 3 the functionality of `map` changed, `itertools.zip_longest` can be used instead:
Source: [Whatâs New In Pytho... |
Matrix Transpose in Python | 4,937,491 | 87 | 2011-02-08T19:38:48Z | 11,387,441 | 43 | 2012-07-08T23:05:21Z | [
"python",
"list",
"multidimensional-array"
] | I am trying to create a matrix transpose function for python but I can't seem to make it work.
Say I have
```
theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
```
and I want my function to come up with
```
newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]
```
So in other words, if I were to print this ... | ```
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> [list(i) for i in zip(*theArray)]
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
```
the list generator creates a new 2d array with list items instead of tuples. |
Python: Name resolution; order of function def's | 4,937,532 | 10 | 2011-02-08T19:42:05Z | 4,937,565 | 18 | 2011-02-08T19:45:25Z | [
"python",
"function",
"namespaces"
] | I have a very simple example:
```
#!/usr/bin/env python
#a() # 1: NameError: name 'a' is not defined
#b() # 1: NameError: name 'b' is not defined
#c() # 1: NameError: name 'c' is not defined
def a():
c() # note the forward use here...
#a() #2: NameError: global name 'c' is not defined
#b() #2: NameError... | The order of definitions is simply "everything has to be defined before you call it". That's pretty much it.
**edit** (to include answer in comments, elucidated):
The reason something like
```
def call_a():
a()
def a():
pass
call_a()
```
works when you've got `a()` in `call_a()` before `a` is even defined... |
In Python, how to compare two lists and get all indices of matches? | 4,937,634 | 7 | 2011-02-08T19:51:35Z | 4,937,707 | 7 | 2011-02-08T19:57:55Z | [
"python"
] | This is probably a simple question that I am just missing but I have two lists containing strings and I want to "bounce" one, element by element, against the other returning the index of the matches. I expect there to be multiple matches and want all of the indices. I know that list.index() gets the first and you can e... | Personally I'd start with:
`matches = [item for item in list1 if item in list2]` |
How to properly make custom filter in django framework? | 4,938,303 | 3 | 2011-02-08T20:54:15Z | 4,938,777 | 21 | 2011-02-08T21:37:32Z | [
"python",
"django",
"django-template-filters"
] | ```
# -*- coding: utf-8 -*-
from django import template
register = template.Library()
@register.inclusion_tag('menu/create_minimenu.html', takes_context = True)
def minimenu(context):
....
....
@register.inclusion_tag('menu/create_topmenu.html', takes_context = True)
def topmenu(context):
....
....
@register.filter(n... | 1. Did you put the file with the filters inside a `templatetags` module in your app? I.e., you should have a structure like:
```
project/
my_app/
templatetags/
__init__.py # Important! It makes templatetags a module. You can put your filters here, or in another file.
apptags.py # Or just put t... |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 4,938,665 | 95 | 2011-02-08T21:27:00Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | You need to create your own admin base\_site.html template to do this. The easiest way is to create the file:
```
/<projectdir>/templates/admin/base_site.html
```
This should be a copy of <https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/base_site.html> - except putting in your custom... |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 9,285,188 | 9 | 2012-02-14T22:29:32Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | As you can see in the [templates](http://code.djangoproject.com/svn/django/branches/releases/1.3.X/django/contrib/admin/templates/admin/base_site.html), the text is delivered via the localization framework (note the use of the `trans` template tag). You can make changes to the translation files to override the text wit... |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 24,983,231 | 171 | 2014-07-27T16:53:38Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | As of Django 1.7 you don't need to override templates. You can now implement [site\_header](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite.site_header), [`site_title`](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.AdminSite.site_title), and [`inde... |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 26,011,790 | 90 | 2014-09-24T08:11:30Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | There is an easy way to set admin site header - assign it to current admin instance in `urls.py` like this
```
admin.site.site_header = 'My admin'
```
Or one can implement some header-building magic in separate method
```
admin.site.site_header = get_admin_header()
```
Thus, in simple cases there's no need to subcl... |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 31,718,696 | 22 | 2015-07-30T08:25:50Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | A simple complete solution in Django 1.8.3 based on answers in this question.
In `settings.py` add:
```
ADMIN_SITE_HEADER = "My shiny new administration"
```
In `urls.py` add:
```
from django.conf import settings
admin.site.site_header = settings.ADMIN_SITE_HEADER
``` |
Django Admin - change header 'Django administration' text | 4,938,491 | 95 | 2011-02-08T21:10:16Z | 36,251,770 | 7 | 2016-03-27T19:39:54Z | [
"python",
"django",
"django-admin"
] | How does one change the 'Django administration' text in the django admin header?
It doesn't seem to be covered in the "Customizing the admin" documentation. | In urls.py you can override the 3 most important variables:
```
admin.site.site_header = _('My project')
admin.site.index_title = _('Features area')
admin.site.site_title = _('HTML title from adminsitration')
``` |
What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)? | 4,938,723 | 48 | 2011-02-08T21:33:12Z | 4,939,113 | 29 | 2011-02-08T22:12:22Z | [
"python",
"linux",
"qt",
"pyqt",
"signals"
] | What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)?
Currently (I have done nothing special to handle unix signals), my PyQt application ignores SIGINT (Ctrl+C). I want it to behave nicely and quit when it is killed. How should I do that? | > [17.4. signal â Set handlers for asynchronous events](http://docs.python.org/library/signal.html)
>
> Although Python signal handlers are called asynchronously as far as the Python user is concerned, they can only occur between the âatomicâ instructions of the Python interpreter. This means that signals arrivin... |
What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)? | 4,938,723 | 48 | 2011-02-08T21:33:12Z | 6,072,360 | 29 | 2011-05-20T13:08:45Z | [
"python",
"linux",
"qt",
"pyqt",
"signals"
] | What is the correct way to make my PyQt application quit when killed from the console (Ctrl-C)?
Currently (I have done nothing special to handle unix signals), my PyQt application ignores SIGINT (Ctrl+C). I want it to behave nicely and quit when it is killed. How should I do that? | If you simply wish to have ctrl-c close the application - without being "nice"/graceful about it - then from <http://www.mail->[archive.com/pyqt@riverbankcomputing.com/msg13758.html](http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg13758.html), you can use this:
```
import signal
signal.signal(signal.SIGINT,... |
How to document a Python project? | 4,939,411 | 7 | 2011-02-08T22:47:40Z | 4,939,429 | 10 | 2011-02-08T22:49:16Z | [
"python",
"documentation"
] | I am programming a new Python library, that needs a good documentation. What are good ways to document such a library? I would favor a method which generates a complete documentation in html. | Using docstrings everywhere is the first step. Then you can use any of a number of python documentation generation tools to generate quality documentation. It's what python.org does, using [Sphinx](http://sphinx.pocoo.org/).
But using docstrings also has the extra benefit of being useful for programmers right in the i... |
Automatic image scaling on resize with (Py)GTK | 4,939,734 | 5 | 2011-02-08T23:32:30Z | 4,941,301 | 7 | 2011-02-09T04:27:02Z | [
"python",
"gtk",
"pygtk"
] | I have a `GtkImage` widget in a resizable window and a reference `GdkPixBuf` storing the image I want to fill the `GtkImage` with.
I can scale the `GdkPixBuf` to fill the `GtkImage` widget using this method:
```
def update_image(self, widget=None, data=None):
# Get the size of the source pixmap
src_width, src... | I believe you could use [expose-event](http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#signal-gtkwidget--expose-event) signal of the widget for image scaling. Also adding image into scrollable container should fix the problem with window resize. Please check if an example below would work for you.
```
import gtk
... |
Search for string in txt file Python | 4,940,032 | 61 | 2011-02-09T00:09:48Z | 4,940,041 | 7 | 2011-02-09T00:10:52Z | [
"python"
] | I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns `True` for some reason. Can anyone see what is wrong?
```
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
... | ```
if True:
print "true"
```
This always happens because True is always True.
You want something like this:
```
if check():
print "true"
else:
print "false"
```
Good luck! |
Search for string in txt file Python | 4,940,032 | 61 | 2011-02-09T00:09:48Z | 4,940,068 | 17 | 2011-02-09T00:14:53Z | [
"python"
] | I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns `True` for some reason. Can anyone see what is wrong?
```
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
... | As Jeffrey Said, you are not checking the value of `check()`. In addition, your `check()` function is not returning anything. Note the difference:
```
def check():
datafile = file('example.txt')
found = False #this isn't really necessary
for line in datafile:
if blabla in line:
... |
Search for string in txt file Python | 4,940,032 | 61 | 2011-02-09T00:09:48Z | 4,944,929 | 153 | 2011-02-09T12:39:29Z | [
"python"
] | I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns `True` for some reason. Can anyone see what is wrong?
```
def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
... | The reason why you always got `True` has already been given, so I'll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
```
if 'blabla' in open('example.txt').read():
print "true"
```
An... |
Is it possible to deploy a Python application on the Mac App Store? | 4,940,273 | 48 | 2011-02-09T00:45:27Z | 4,993,464 | 8 | 2011-02-14T14:40:41Z | [
"python",
"osx",
"app-store",
"py2app"
] | Does Apple accept Python applications for distribution on the new Mac App Store?
If so, how should the application be packaged? Is py2app sufficient? Something else? | I know it's possible because I know of at least one Python-based app that is in the app store ("Pennywise", which is based on my own app, moneyGuru, which uses Python + PyObjc + py2app). I didn't do it myself, so I'm not sure of the details. |
Is it possible to deploy a Python application on the Mac App Store? | 4,940,273 | 48 | 2011-02-09T00:45:27Z | 5,016,342 | 55 | 2011-02-16T12:20:31Z | [
"python",
"osx",
"app-store",
"py2app"
] | Does Apple accept Python applications for distribution on the new Mac App Store?
If so, how should the application be packaged? Is py2app sufficient? Something else? | I packaged Pennywise, which is available on the Mac App Store. It's based on Virgil's moneyGuru, which uses Python, PyObjC, and py2app.
You will have to follow [Apple's process for preparing an application for submission to the Mac App Store](http://developer.apple.com/devcenter/mac/documents/submitting.html). Most im... |
How do I update the python lib boto? | 4,940,449 | 7 | 2011-02-09T01:21:14Z | 4,940,485 | 16 | 2011-02-09T01:27:22Z | [
"python",
"boto"
] | I am using python's boto script, and I haven't touched in a long time and sort of forgot basic python stuff.
How do I update the script? I'm not even sure how I installed it so please guide me to figure out what I have to do. | If you have `pip` available: `pip install -U boto`
If you have `easy_install` available: `easy_install -U boto`
Otherwise... install `pip`. |
pymysql fetchall() results as dictionary? | 4,940,670 | 16 | 2011-02-09T02:14:58Z | 8,539,552 | 36 | 2011-12-16T20:08:59Z | [
"python",
"mysql"
] | Is there any way to get the results from a fetchall() as a dictionary using pymysql? | PyMySQL includes a `DictCursor`. It does what I think you want. Here's how to use it:
```
import pymysql
connection = pymysql.connect(db="test")
cursor = connection.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT ...")
```
<https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/tests/test_DictCursor.py> |
Sqlalchemy type for very long text for articles | 4,940,742 | 4 | 2011-02-09T02:30:11Z | 4,941,062 | 8 | 2011-02-09T03:36:03Z | [
"python",
"mysql",
"sqlalchemy"
] | What type should I define in my sqlalchemy definition for text for a article or blog entry? I'm using MySQL.
```
Column('article_text', ???)
``` | ```
Column('article_text', sqlalchemy.UnicodeText())
```
That should work on any supported database, not just mysql. |
Django: How to set DateField to only accept Today & Future dates | 4,941,974 | 10 | 2011-02-09T06:34:22Z | 4,942,284 | 17 | 2011-02-09T07:20:04Z | [
"python",
"django",
"django-forms",
"datefield"
] | I have been looking for ways to set my Django form to only accept dates that are today or days in the future. I currently have a jQuery datepicker on the frontend, but here is the form field to a modelform.
Thanks for the help, much appreciated.
```
date = forms.DateField(
label=_("What day?"),
widget=forms.T... | You could add a `clean()` method in your form to ensure that the date is not in the past.
```
import datetime
class MyForm(forms.Form):
date = forms.DateField(...)
def clean_date(self):
date = self.cleaned_data['date']
if date < datetime.date.today():
raise forms.ValidationError("... |
Python: string.uppercase vs. string.ascii_uppercase | 4,942,239 | 3 | 2011-02-09T07:13:03Z | 4,942,256 | 13 | 2011-02-09T07:15:39Z | [
"python"
] | This might be a stupid question but I don't understand what's the difference between string.uppercase and string.ascii\_uppercase in the string module. Printing the docstring of both the function prints same thing. Even the output of `print string.uppercase` and `print string.ascii_uppercase` is same.
Thanks. | See: <http://docs.python.org/library/string.html>
string.ascii\_uppercase:
* The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. This value is not locale-dependent and will not change.
string.uppercase:
* A string containing all the characters that are considered uppercase letters. On most systems this is the strin... |
Why don't scripting languages output Unicode to the Windows console? | 4,942,305 | 18 | 2011-02-09T07:23:36Z | 4,943,333 | 7 | 2011-02-09T10:04:23Z | [
"python",
"windows",
"perl",
"unicode",
"console"
] | The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" w... | I have to unask many of your questions.
Did you know that
* Windows uses UTF-16 for its APIs, but still defaults to the various "fun" legacy encodings (e.g. Windows-1252, Windows-1251) in userspace, including file names, differently for the many localisations of Windows?
* you need to encode output, and picking the a... |
Why don't scripting languages output Unicode to the Windows console? | 4,942,305 | 18 | 2011-02-09T07:23:36Z | 4,943,709 | 19 | 2011-02-09T10:39:23Z | [
"python",
"windows",
"perl",
"unicode",
"console"
] | The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" w... | The main problem seems to be that it is not possible to use Unicode on Windows using only the standard C library and no platform-dependent or third-party extensions. The languages you mentioned originate from Unix platforms, whose method of implementing Unicode blends well with C (they use normal `char*` strings, the C... |
Why don't scripting languages output Unicode to the Windows console? | 4,942,305 | 18 | 2011-02-09T07:23:36Z | 4,943,927 | 9 | 2011-02-09T10:59:09Z | [
"python",
"windows",
"perl",
"unicode",
"console"
] | The Windows console has been Unicode aware for at least a decade and perhaps as far back as Windows NT. However for some reason the major cross-platform scripting languages including Perl and Python only ever output various 8-bit encodings, requiring much trouble to work around. Perl gives a "wide character in print" w... | Small contribution to the discussion - I am running Czech localized Windows XP, which almost everywhere uses CP1250 code page. Funny thing with console is though that it still uses legacy DOS 852 code page.
I was able to make very simple perl script that prints utf8 encoded data to console using:
```
binmode STDOUT, ... |
Is there a library for Python that gives the script name for a given unicode character or string? | 4,944,377 | 2 | 2011-02-09T11:43:03Z | 4,944,471 | 7 | 2011-02-09T11:50:22Z | [
"python",
"unicode"
] | Is there a library that tells what script a particular unicode character belongs to?
For example for the input "u'á'" it should return Ethiopic or similar. | Maybe the data in the [`unicodedata`](http://docs.python.org/library/unicodedata.html) module is what you are looking for:
```
print unicodedata.name(u"á")
```
prints
```
ETHIOPIC SYLLABLE HHE
```
The printed name can be used to look up the corresponding character:
```
unicodedata.lookup("ETHIOPIC SYLLABLE HHE")... |
How to clone a Python generator object? | 4,945,155 | 30 | 2011-02-09T12:58:24Z | 4,945,175 | 46 | 2011-02-09T13:00:03Z | [
"python",
"object",
"clone",
"generator"
] | Consider this scenario:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
walk = os.walk('/home')
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathname)
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathna... | You can use [`itertools.tee()`](http://docs.python.org/library/itertools.html#itertools.tee):
```
walk, walk2 = itertools.tee(walk)
```
Note that this might "need significant extra storage", as the documentation points out. |
How to clone a Python generator object? | 4,945,155 | 30 | 2011-02-09T12:58:24Z | 4,945,294 | 12 | 2011-02-09T13:11:04Z | [
"python",
"object",
"clone",
"generator"
] | Consider this scenario:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
walk = os.walk('/home')
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathname)
for root, dirs, files in walk:
for pathname in dirs+files:
print os.path.join(root, pathna... | If you know you are going to iterate through the whole generator for every usage, you will probably get the best performance by unrolling the generator to a list and using the list multiple times.
`walk = list(os.walk('/home'))` |
Remove the first character of a string | 4,945,548 | 43 | 2011-02-09T13:33:29Z | 4,945,558 | 84 | 2011-02-09T13:34:21Z | [
"python",
"string"
] | I want to remove the first character of a string.
For example, my string starts with a ":" and I want to remove that only, there are a lot of ":" in the string which shouldn't be removed.
I am writing my code in Python | ```
s = ":dfa:sif:e"
print s[1:]
```
prints
```
dfa:sif:e
``` |
Remove the first character of a string | 4,945,548 | 43 | 2011-02-09T13:33:29Z | 4,945,578 | 7 | 2011-02-09T13:36:00Z | [
"python",
"string"
] | I want to remove the first character of a string.
For example, my string starts with a ":" and I want to remove that only, there are a lot of ":" in the string which shouldn't be removed.
I am writing my code in Python | Depending on the structure of the string, you can use [`lstrip`](http://docs.python.org/library/stdtypes.html#str.lstrip):
```
str = str.lstrip(':')
```
But this would remove all colons at the beginning, i.e. if you have `::foo`, the result would be `foo`. But this function is helpful if you also have strings that do... |
Remove the first character of a string | 4,945,548 | 43 | 2011-02-09T13:33:29Z | 4,945,800 | 19 | 2011-02-09T13:55:53Z | [
"python",
"string"
] | I want to remove the first character of a string.
For example, my string starts with a ":" and I want to remove that only, there are a lot of ":" in the string which shouldn't be removed.
I am writing my code in Python | Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.
If you only need to remove the first character you would do:
```
s = ":dfa:sif:e"
fixed = s[1:]
```
If you want to remove a character at a particular position, you... |
Why "decimal.Decimal('0') < 1.0" yields False in Python 2.6.5 | 4,945,683 | 5 | 2011-02-09T13:46:24Z | 4,945,803 | 13 | 2011-02-09T13:56:12Z | [
"python",
"floating-point",
"decimal"
] | In Python 2.6.5 the following expression yields False:
```
>>> import decimal
>>> decimal.Decimal('0') < 1.0
False
```
Is there a rationale explaining why comparison of Decimal against float should behave like this? | From the [documentation of the decimal module](http://docs.python.org/library/decimal.html):
> Changed in version 2.7: A comparison
> between a float instance x and a
> Decimal instance y now returns a
> result based on the values of x and y.
> In earlier versions x < y returned the
> same (arbitrary) result for any
>... |
How can I disable a model field in a django form | 4,945,802 | 8 | 2011-02-09T13:56:03Z | 4,945,913 | 28 | 2011-02-09T14:07:02Z | [
"python",
"django",
"django-forms"
] | I have a model like this:
```
class MyModel(models.Model):
REGULAR = 1
PREMIUM = 2
STATUS_CHOICES = ((REGULAR, "regular"), (PREMIUM, "premium"))
name = models.CharField(max_length=30)
status = models.IntegerField(choices = STATUS_CHOICES, default = REGULAR)
class MyForm(forms.ModelForm):
class... | Use the HTML readonly attribute:
<http://www.w3schools.com/tags/att_input_readonly.asp>
Or disabled
<http://www.w3.org/TR/html401/interact/forms.html#adef-disabled>
You can inject arbitrary HTML key value pairs via the widget attrs property:
```
myform.fields['status'].widget.attrs['readonly'] = True # text inpu... |
Python : Why use "list[:]" when "list" refers to same thing? | 4,947,762 | 12 | 2011-02-09T16:37:09Z | 4,947,776 | 35 | 2011-02-09T16:38:04Z | [
"python",
"slice"
] | Consider a list `>>> l=[1,2,3]`.
What is the benefit of using `>>> l[:]` when `>>> l` prints the same thing as former does?
Thanks. | It creates a (shallow) copy.
```
>>> l = [1,2,3]
>>> m = l[:]
>>> n = l
>>> l.append(4)
>>> m
[1, 2, 3]
>>> n
[1, 2, 3, 4]
>>> n is l
True
>>> m is l
False
``` |
Python : Why use "list[:]" when "list" refers to same thing? | 4,947,762 | 12 | 2011-02-09T16:37:09Z | 4,947,793 | 12 | 2011-02-09T16:39:32Z | [
"python",
"slice"
] | Consider a list `>>> l=[1,2,3]`.
What is the benefit of using `>>> l[:]` when `>>> l` prints the same thing as former does?
Thanks. | `l[:]` is called slice notation. It can be used to extract only some of the elements in the list, but in this case the bounds are omitted so the entire list is returned, but because of the slice, this will actually be a reference to a different list than `l` that contains the same elements. This technique is often used... |
Visiting nodes in a syntax tree with Python ast module | 4,947,783 | 8 | 2011-02-09T16:38:47Z | 4,948,131 | 7 | 2011-02-09T17:11:14Z | [
"python",
"parsing",
"abstract-syntax-tree"
] | I'm playing with python ast (abstract syntax tree).
I wrote the following and it visited all nodes of the AST.
```
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self,... | Since your visit\_Assign method does not explicitly process the child nodes of the Assign node, traversal of the syntax tree stops there.
If you have a look at the NodeVisitor.generic\_visit method in the implementation of ast.py, you'll see that it loops through the children of the current node. So, you can explicitl... |
pcap python library? | 4,948,043 | 15 | 2011-02-09T17:02:04Z | 4,948,251 | 10 | 2011-02-09T17:24:20Z | [
"python",
"tcp",
"pcap"
] | I'd like to ask for recommendation of a pcap library for python. I'm doing project on .pcap file parsing. I searched google and found pylibpcap. Is there anything else out there? Which lib do you prefer and why?
thank you. | I tried that and then tried pcapy. I choose pcapy because my use was similar to an example which I found googling.
<http://snipplr.com/view/3579/live-packet-capture-in-python-with-pcapy/> (or see the same code copied below)
```
import pcapy
from impacket.ImpactDecoder import *
# list all the network devices
pcapy.fi... |
pcap python library? | 4,948,043 | 15 | 2011-02-09T17:02:04Z | 4,948,316 | 11 | 2011-02-09T17:29:40Z | [
"python",
"tcp",
"pcap"
] | I'd like to ask for recommendation of a pcap library for python. I'm doing project on .pcap file parsing. I searched google and found pylibpcap. Is there anything else out there? Which lib do you prefer and why?
thank you. | Try [scapy](http://www.secdev.org/projects/scapy/). It is a very powerful program for packet inspection, manipulation and creation.
You can use it to [build your own tools](http://www.secdev.org/projects/scapy/build_your_own_tools.html). |
Python Slice Assignment Memory Usage | 4,948,293 | 17 | 2011-02-09T17:28:06Z | 4,948,508 | 36 | 2011-02-09T17:46:50Z | [
"python",
"memory-management",
"performance",
"benchmarking"
] | I read in a comment here on Stack Overflow that it is more memory efficient to do slice assignment when changing lists. For example,
```
a[:] = [i + 6 for i in a]
```
should be more memory efficient than
```
a = [i + 6 for i in a]
```
because the former replaces elements in the existing list, while the latter creat... | The line
```
a[:] = [i + 6 for i in a]
```
would not save any memory. Python does evaluate the right hand side first, as stated in the [language documentation](http://docs.python.org/reference/simple_stmts.html#assignment-statements):
> An assignment statement evaluates the expression list (remember that this can be... |
Removing duplicated lines from a txt file | 4,948,509 | 5 | 2011-02-09T17:46:50Z | 4,948,636 | 12 | 2011-02-09T17:59:46Z | [
"python",
"linux",
"awk"
] | I am processing large text files (~20MB) containing data delimited by line.
Most data entries are duplicated and I want to remove these duplications to only keep one copy.
Also, to make the problem slightly more complicated, some entries are repeated with an extra bit of info appended. In this case I need to keep the ... | How about the following (in Python):
```
prev = None
for line in sorted(open('file')):
line = line.strip()
if prev is not None and not line.startswith(prev):
print prev
prev = line
if prev is not None:
print prev
```
If you find memory usage an issue, you can do the sort as a pre-processing step using Uni... |
Python 2.6 GC appears to cleanup objects, but memory is not released | 4,949,335 | 3 | 2011-02-09T19:09:54Z | 4,949,459 | 8 | 2011-02-09T19:22:59Z | [
"python",
"memory",
"memory-leaks"
] | I have a program written in python 2.6 that creates a large number of short lived instances (it is a classic producer-consumer problem). I noticed that the memory usage as reported by top and pmap seems to increase when these instances are created and never goes back down. I was concerned that some python module I was ... | Python will release the objects, but it will not release the memory back to the operating system immediately. Instead, it will re-use the same segments for future allocations within the same interpreter.
Here's a blog post about the issue: <http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-l... |
Joining: string and absolute path with os.path | 4,949,827 | 5 | 2011-02-09T20:02:04Z | 4,949,867 | 8 | 2011-02-09T20:06:52Z | [
"python",
"string",
"path"
] | Why is this not working, what am I doing wrong?
```
>>> p1 = r'\foo\bar.txt'
>>> os.path.join('foo1', 'foo2', os.path.normpath(p1))
'\\foo\\bar.txt'
```
I expected this:
```
'foo1\\foo2\\foo\\bar.txt'
```
Edit:
# A Solution
```
>>> p1 = r'\foo\bar.txt'
>>> p1 = p1.strip('\\') # Strip '\\' so the path would not be... | When `os.path.join` encounters an absolute path, it throws away what it has accumulated to far. An absolute string is one that starts with a slash (ans on windows, with an *optional* drive letter). `normpath` won't touch that slash as it has the same notion of absolute paths. You have to strip that slash.
And if I may... |
File Parsing on the fly in Flask | 4,949,849 | 3 | 2011-02-09T20:05:04Z | 4,954,630 | 10 | 2011-02-10T07:55:13Z | [
"python",
"parsing",
"file",
"flask"
] | I recently received some advice on a question regarding an easy to use web-framework to use for a simple project that I am helping a friend with and was suggested to use *Flask*.
Everything has been working out so far - however I am trying to figure out how to (or if it is possible) to read a file on the fly, and pass... | The documentation on the flask site (<http://flask.pocoo.org/docs/patterns/fileuploads/>) demonstrates how to properly and safely handle file uploads, I would start there. If you wish to parse the file before/instead of saving it, you should be able to use the [stream](http://werkzeug.pocoo.org/docs/datastructures/#wer... |
simple inter-process communication | 4,950,120 | 17 | 2011-02-09T20:32:34Z | 4,950,283 | 18 | 2011-02-09T20:49:43Z | [
"python",
"perl",
"ipc"
] | I'm looking for a *simple* way to pass messages from one process (Perl script, short-lived) to another (Python script, long-running) - both processes local to the same machine.
I've done some research, but what I've found was either over my head or seemed unnecessarily complex - leaving me a bit lost and confused.
I i... | It turns out that interprocess communication is, while on the surface straightforward, actually fraught with complications. Whatever anyone tells you here in terms of a simplified answer, always keep in mind that there is probably a lot of caveats that are being left unsaid.
Now with that disclaimer out of the way, I ... |
simple inter-process communication | 4,950,120 | 17 | 2011-02-09T20:32:34Z | 4,950,784 | 8 | 2011-02-09T21:37:11Z | [
"python",
"perl",
"ipc"
] | I'm looking for a *simple* way to pass messages from one process (Perl script, short-lived) to another (Python script, long-running) - both processes local to the same machine.
I've done some research, but what I've found was either over my head or seemed unnecessarily complex - leaving me a bit lost and confused.
I i... | And for powered-up communications in the same style as socket, consider looking at 0MQ. It can make use of different communication technologies depending where your two apps are located, and even for local processes it's very easy to use and solves the problems for you.
<http://zeromq.org> |
objects as keys in python dictionaries | 4,950,155 | 8 | 2011-02-09T20:34:40Z | 4,950,215 | 16 | 2011-02-09T20:41:52Z | [
"python",
"dictionary"
] | I'm trying to use an object as a key in a python dictionary, but it's behaving in a way that I can't quite understand.
First I create a dictionary with my object as the key:
```
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
ContentType("application", "zip") : "two"
... | From the python documentation:
> A dictionaryâs keys are almost
> arbitrary values. Values that are not
> hashable, that is, values containing
> lists, dictionaries or other mutable
> types (that are compared by value
> rather than by object identity) may
> not be used as keys.
[Hashable](http://docs.python.org/glo... |
objects as keys in python dictionaries | 4,950,155 | 8 | 2011-02-09T20:34:40Z | 4,950,220 | 11 | 2011-02-09T20:42:39Z | [
"python",
"dictionary"
] | I'm trying to use an object as a key in a python dictionary, but it's behaving in a way that I can't quite understand.
First I create a dictionary with my object as the key:
```
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
ContentType("application", "zip") : "two"
... | Since dicts are hash tables under the hood, you need to define both `__eq__` and `__hash__` for that to work.
The basic rule of thumb is:
* For objects that `__eq__` compares equal, `__hash__` must return the same hash.
From your description, something like
```
def __hash__(self):
return hash(str(self))
```
sh... |
Explanation of Python namespaces | 4,950,402 | 18 | 2011-02-09T21:01:37Z | 4,950,420 | 7 | 2011-02-09T21:04:09Z | [
"python",
"namespaces"
] | I am looking for a good introduction to Python namespaces. I found [this tutorial](http://bytebaker.com/2008/07/30/python-namespaces/) to be good, but I'm sure there is more to the story than that.
The Python reference contains information but it's quite hard to read.
Please explain python namespaces. In your explana... | They're really not all that complex. The import mechanisms can be somewhat complex and with relative imports now it can get even a bit more tricky, but as far as actual namespaces and how they're resolved in code, that tutorial seems to be pretty comprehensive.
The [language reference](http://docs.python.org/reference... |
setting breakpoints with nosetests --pdb option | 4,950,637 | 53 | 2011-02-09T21:24:46Z | 4,950,690 | 74 | 2011-02-09T21:28:45Z | [
"python",
"testing",
"nosetests",
"pdb"
] | Nosetests --pdb let's me halt upon error or failure, but this is too late for my needs. Stepping through code during execution helps me debug where the problem is.
However, nosetests are helpful as they allow tests that rely on relative imports (i.e. tests in a package).
How can I set breakpoints before the tests are... | You can add
```
import pdb; pdb.set_trace()
```
anywhere in your source that you want to stop in the debugger.
Make sure you pass `-s` to nose so that it does not capture `stdout`. |
setting breakpoints with nosetests --pdb option | 4,950,637 | 53 | 2011-02-09T21:24:46Z | 7,493,906 | 98 | 2011-09-21T02:26:18Z | [
"python",
"testing",
"nosetests",
"pdb"
] | Nosetests --pdb let's me halt upon error or failure, but this is too late for my needs. Stepping through code during execution helps me debug where the problem is.
However, nosetests are helpful as they allow tests that rely on relative imports (i.e. tests in a package).
How can I set breakpoints before the tests are... | Even better than remembering to use `-s` is to use the `set_trace` variant that comes with Nose. Add
```
from nose.tools import set_trace; set_trace()
```
wherever you'd like to break in to the debugger. The stdin/out redirection will be taken care of for you. The only strange side effect I've run into is the inabili... |
Getting progress message from a subprocess | 4,951,099 | 13 | 2011-02-09T22:07:06Z | 4,951,175 | 13 | 2011-02-09T22:16:07Z | [
"python",
"subprocess"
] | I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The problem is that I cannot find a way to read out its output during its run.
The only function I found to read out the output of a program is `Pope... | Simplest is to call Popen with the keyword argument `stdout=subprocess.PIPE`.
```
p = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
if not line:
break
print line
```
---
To see this in action, here are two sample scripts. Make them both in the same direct... |
What are the default URLs for Django's User Authentication system? | 4,951,203 | 9 | 2011-02-09T22:18:45Z | 4,951,394 | 17 | 2011-02-09T22:38:21Z | [
"python",
"django"
] | Django's User Authentication system ( <http://docs.djangoproject.com/en/dev/topics/auth/> ) is incredibly helpful in working with users. However, the documentation talks about password reset forms and makes it seem like it takes care of it the same way it does user login/logout.
The default URL for login and logout is... | If you look at [`django.contrib.auth.urls`](https://github.com/django/django/blob/master/django/contrib/auth/urls.py) you can see the default views that are defined. That would be `login`, `logout`, `password_change` and `password_reset`.
> These URLs are normally mapped to /admin/urls.py. This URLs file is
> provided... |
Creating a new corpus with NLTK | 4,951,751 | 47 | 2011-02-09T23:19:48Z | 4,952,238 | 27 | 2011-02-10T00:42:42Z | [
"python",
"nlp",
"nltk",
"corpus"
] | I reckoned that often the answer to my title is to go and read the documentations, but I ran through the [NLTK book](http://www.nltk.org/book) but it doesn't give the answer. I'm kind of new to python.
I have a bunch of `.txt` files and I want to be able to use the corpus functions that NLTK provides for the corpus `n... | I think the `PlaintextCorpusReader` already segments the input with a punkt tokenizer, at least if your input language is english.
[Documentation of PlainTextCorpusReader's `__init__`](http://nltk.googlecode.com/svn/trunk/doc/api/nltk.corpus.reader.plaintext.PlaintextCorpusReader-class.html#__init__)
```
__init__(
... |
Creating a new corpus with NLTK | 4,951,751 | 47 | 2011-02-09T23:19:48Z | 5,113,509 | 7 | 2011-02-25T04:11:22Z | [
"python",
"nlp",
"nltk",
"corpus"
] | I reckoned that often the answer to my title is to go and read the documentations, but I ran through the [NLTK book](http://www.nltk.org/book) but it doesn't give the answer. I'm kind of new to python.
I have a bunch of `.txt` files and I want to be able to use the corpus functions that NLTK provides for the corpus `n... | ```
>>> import nltk
>>> from nltk.corpus import PlaintextCorpusReader
>>> corpus_root = './'
>>> newcorpus = PlaintextCorpusReader(corpus_root, '.*')
"""
if the ./ dir contains the file my_corpus.txt, then you
can view say all the words it by doing this
"""
>>> newcorpus.words('my_corpus.txt')
``` |
Creating a new corpus with NLTK | 4,951,751 | 47 | 2011-02-09T23:19:48Z | 20,922,201 | 33 | 2014-01-04T14:29:11Z | [
"python",
"nlp",
"nltk",
"corpus"
] | I reckoned that often the answer to my title is to go and read the documentations, but I ran through the [NLTK book](http://www.nltk.org/book) but it doesn't give the answer. I'm kind of new to python.
I have a bunch of `.txt` files and I want to be able to use the corpus functions that NLTK provides for the corpus `n... | After some years of figuring out how it works, here's the updated tutorial of
**How to create an NLTK corpus with a directory of textfiles?**
The main idea is to make use of the [**nltk.corpus.reader**](http://nltk.org/api/nltk.corpus.html) package. In the case that you have a directory of textfiles in **English**, i... |
try: except: not working | 4,952,134 | 9 | 2011-02-10T00:28:15Z | 4,952,261 | 8 | 2011-02-10T00:46:47Z | [
"python",
"exception",
"exception-handling"
] | So I'm running into a problem where the try: except: mechanism doesn't seem to be working correctly in python.
Here are the contents of my two files.
## pytest1.py
```
import pytest2
class MyError( Exception ):
def __init__( self, value ):
self.value = value
def __str__( self ):
return repr... | The main python program is always imported as the module `__main__`.
When you import `pytest2`, it doesn't reuse the existing module because the originally imported module has the name `__main__` not `pytest2`. The result is that `pytest1` is run multiple times generating multiple exception classes. `__main__.MyError`... |
interrupted system call with processing queue | 4,952,247 | 5 | 2011-02-10T00:44:48Z | 5,395,277 | 7 | 2011-03-22T17:21:25Z | [
"python",
"queue",
"multiprocessing"
] | We suddenly started see "Interrupted system call" on Queue operations like this:
```
Exception in thread Thread-2:
Traceback (most recent call last):
[ . . . ]
result = self.pager.results.get(True, self.WAIT_SECONDS)
File "/usr/lib/python2.5/site-packages/processing-0.52-py2.5-linux-x86_64.egg/processing/queue.py"... | Based on [this thread](http://groups.google.com/group/comp.lang.python/browse_thread/thread/ae3cf5d475c4f1ba) on comp.lang.python and [this reply](http://code.activestate.com/lists/python-list/595310/) from Dan Stromberg I wrote a RetryQueue which is a drop-in replacement for Queue and which does the job for us:
```
f... |
how to estimate the (power of a signal at a given frequency) vs. time in python | 4,953,250 | 2 | 2011-02-10T04:06:55Z | 4,953,341 | 7 | 2011-02-10T04:21:23Z | [
"python",
"matplotlib",
"signal-processing",
"scientific-computing"
] | I'm looking for a good way to estimate the power of a signal (regularly sampled say at 10 kHz) vs. time at just one frequency (say 50 Hz). I could calculate the spectrogram, and then take a slice of it at the target frequency. This seems inefficient though, since I only care about the power at one frequency vs. time. I... | There's a ton of ways of doing this. One crude but effective way is to apply a bandpass filter (at 50Hz), thereby eliminating all other signals, and then calculate the RMS power of the last N samples.
Another is you can do a windowed FFT, but not actually FFT - just calculate the bin you want. The window can be whatev... |
How to match exact "multiple" strings in Python | 4,953,272 | 7 | 2011-02-10T04:09:48Z | 4,953,289 | 11 | 2011-02-10T04:11:24Z | [
"python",
"regex"
] | I've got a list of exact patterns that I want to search in a given string. Currently I've got a real bad solution for such a problem.
```
pat1 = re.compile('foo.tralingString')
mat1 = pat1.match(mystring)
pat2 = re.compile('bar.trailingString')
mat2 = pat2.match(mystring)
if mat1 or mat2:
# Do whatever
pat = re... | You could do a trivial regex that combines those two:
```
pat = re.compile('foo|bar')
if pat.match(mystring):
# Do whatever
```
You could then expand the regex to do whatever you need to, using the `|` separator (which means *or* in regex syntax)
**Edit:** Based upon your recent edit, this should do it for you:
... |
Does Python 2.6 have a built in URL parameters parser? | 4,953,819 | 3 | 2011-02-10T05:48:32Z | 4,953,829 | 7 | 2011-02-10T05:49:24Z | [
"python"
] | Given a URl, how can I get a dictionary of parameters back? | <http://docs.python.org/library/urlparse.html>
edit: It returns a tuple of the url parameters. If you absolutely need to have it be in a dictionnary looks like you will have to implement it yourself. (get the tuple then assign it to dict)
```
string = "addressing scheme network location path query fragment_identifier... |
Create Board Game-like Grid in Python | 4,954,395 | 2 | 2011-02-10T07:18:33Z | 4,959,995 | 10 | 2011-02-10T16:43:26Z | [
"python"
] | I am thinking of creating a board game in Python, one which will have a grid of spaces, each with different properties, and which may or may not have pieces resting on them. These pieces should be able to move between spaces, though subject to various rules. (Chess or checkers would be good examples of what I'm thinkin... | Drawing a chessboard is pretty trivial with Tkinter. Here's a really simple example:
```
import Tkinter as tk
class GameBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=32, color1="white", color2="blue"):
'''size is the size of a square, in pixels'''
self.rows = rows
sel... |
How come my template tag in Django doesn't work? | 4,955,296 | 2 | 2011-02-10T09:26:52Z | 4,955,430 | 8 | 2011-02-10T09:42:46Z | [
"python",
"html",
"django",
"templates"
] | ```
{% gen_aws "hello" %}
```
In my file, I do this:
```
#I want to add "goodbye" to every word passed to this tag.
@register.tag(name="gen_aws")
def gen_aws(s):
return s + "goodbye"
```
The .py file is fine...I'm including everything fine. I have other template "filters" in there that work fine. But then I adde... | Your description of "doesn't work" is not very accurate (to be exact it doesn't exist). But I guess you get an error because the tag is not found.
The [documentation](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) clearly states that you need a "templatetags" module in your app, with a submodule lik... |
Deleting specific control characters(\n \r \t) from a string | 4,955,452 | 3 | 2011-02-10T09:44:17Z | 4,955,517 | 18 | 2011-02-10T09:50:33Z | [
"python",
"string"
] | I have quite large amount of text which include control charachters like \n \t and \r.
I need to replace them with a simple space--> " ". What is the fastest way to do this?
Thanks | I think the fastest way is to use `str.translate()`:
```
import string
s = "a\nb\rc\td"
print s.translate(string.maketrans("\n\t\r", " "))
```
prints
```
a b c d
```
**EDIT**: As this once again turned into a discussion about performance, here some numbers. For long strings, `translate()` is *way* faster than usi... |
Wave Simulation with Python | 4,956,331 | 7 | 2011-02-10T11:11:30Z | 4,956,611 | 9 | 2011-02-10T11:39:28Z | [
"python",
"numpy",
"simulation",
"physics",
"wave"
] | I want to simulate a propagating wave with absorption and reflection on some bodies in three dimensional space. I want to do it with python. Should I use numpy? Are there some special libraries I should use?
How can I simulate the wave? Can I use the wave equation? But what if I have a reflection?
Is there a better me... | If you do any computationally intensive numerical simulation in Python, you should *definitely* use NumPy.
The most general algorithm to simulate an electromagnetic wave in arbitrarily-shaped materials is the [finite-difference time domain method](http://en.wikipedia.org/wiki/FDTD) (FDTD). It solves the wave equation,... |
How do you split a csv file into evenly sized chunks in Python? | 4,956,984 | 12 | 2011-02-10T12:20:19Z | 4,957,046 | 16 | 2011-02-10T12:26:11Z | [
"python",
"list",
"csv",
"chunks"
] | In a basic I had the next process.
```
import csv
reader = csv.reader(open('huge_file.csv', 'rb'))
for line in reader:
process_line(line)
```
See this related [question](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python). I want to send the process line every 10... | Just make your `reader` subscriptable by wrapping it into a `list`. Obviously this will break on really large files (see alternatives in the *Updates* below):
```
>>> reader = csv.reader(open('big.csv', 'rb'))
>>> lines = list(reader)
>>> print lines[:100]
...
```
Further reading: [How do you split a list into evenly... |
More Pythonic (or perhaps functional) way of creating this list? | 4,957,030 | 4 | 2011-02-10T12:24:39Z | 4,957,204 | 8 | 2011-02-10T12:41:13Z | [
"python",
"functional-programming"
] | I'm returning a list of lists, but the following seems far more convoluted than it should be:
```
new_list = []
for key, value in group.items():
new_list.extend([['%s%s%s%s%s' % (
ncode, vendor, extra, value['suffix'], tariff),
value['latest_cost'], value['rrp'], value['rb']] for tariff in value['trf']])
... | That's not particularly convoluted. You have two "levels", the items in the group which you are expanding into one level. For doing that it's not very convoluted.
A more *functional* way would be to merge it all into one nested list expression, I think that could be possible. But it sure wouldn't be more readable, and... |
How to compare Debian package versions | 4,957,514 | 18 | 2011-02-10T13:14:31Z | 4,957,741 | 27 | 2011-02-10T13:37:22Z | [
"python",
"debian",
"apt"
] | I looked at python-apt and python-debian, and they don't seem to have functionality to compare package versions. Do I have to write my own, or is there something I can use?
Ideally, it would look something like:
```
>>> v1 = apt.version("1:1.3.10-0.3")
>>> v2 = apt.version("1.3.4-1")
>>> v1 > v2
True
``` | You could use [apt\_pkg.version\_compare](http://apt.alioth.debian.org/python-apt-doc/library/apt_pkg.html#apt_pkg.version_compare):
```
import apt_pkg
apt_pkg.init_system()
a = '1:1.3.10-0.3'
b = '1.3.4-1'
vc = apt_pkg.version_compare(a,b)
if vc > 0:
print('version a > version b')
elif vc == 0:
print('versio... |
How to compare Debian package versions | 4,957,514 | 18 | 2011-02-10T13:14:31Z | 18,408,532 | 31 | 2013-08-23T17:27:34Z | [
"python",
"debian",
"apt"
] | I looked at python-apt and python-debian, and they don't seem to have functionality to compare package versions. Do I have to write my own, or is there something I can use?
Ideally, it would look something like:
```
>>> v1 = apt.version("1:1.3.10-0.3")
>>> v2 = apt.version("1.3.4-1")
>>> v1 > v2
True
``` | Perhaps because the title doesn't mention Python (though the tags do), Google brought me here when asking the same question but hoping for a bash answer. That seems to be:
```
$ dpkg --compare-versions 11a lt 100a && echo true
true
$ dpkg --compare-versions 11a gt 100a && echo true
$
```
To install a version of rubyg... |
South django table already exists | 4,958,136 | 5 | 2011-02-10T14:12:35Z | 4,958,296 | 8 | 2011-02-10T14:26:31Z | [
"python",
"django-models",
"data-migration",
"django-south"
] | I'm experiencing the same problem as with: [django - "manage.py test" fails "table already exists"](http://stackoverflow.com/questions/4882377/django-manage-py-test-fails-table-already-exists)
The schemamigration / migration worked fine (although did have some problems that required me to --fake, but all subsequent mi... | No, it doesn't mean that. Don't forget that Django already knows what your tables should look like if you create them from scratch *now* - it just uses the model definitions. South is useful because it allows you to easily transform your table structure when you change your models, but when you're running tests you don... |
Python 2.7 getting user input and manipulating as string without quotations | 4,960,208 | 62 | 2011-02-10T17:00:34Z | 4,960,216 | 117 | 2011-02-10T17:01:33Z | [
"python",
"string"
] | I want to get a string from a user, and then to manipulate it.
```
testVar = input("Ask user for something.")
```
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is... | Use `raw_input()` instead of `input()`:
```
testVar = raw_input("Ask user for something.")
```
`input()` actually evaluates the input as Python code. I suggest to never use it. `raw_input()` returns the verbatim string entered by the user. |
Python: Using a dictionary as switch not working | 4,960,332 | 5 | 2011-02-10T17:12:21Z | 4,960,352 | 14 | 2011-02-10T17:14:26Z | [
"python",
"data-structures",
"switch-statement"
] | I'm a 'python neophyte' and trying to grasp the inner workings of the dictionary datatype. Last night I was attempting to use one as a control structure (i.e. switch statement) for keyboard input on an openGL program.
The *problem* was that for some reason the dictionary kept evaluating ALL cases (two in this instance... | You shouldn't call the functions. Just store the function objects itself in the dictionary, not their return values:
```
def keyboard(key):
values = {
110: discoMode,
27: exit
}
values.get(key, default)()
```
`f()` is a call to the function `f` and evaluates to the return value of this call. `... |
how to safely remove elements from a list in Python | 4,960,968 | 4 | 2011-02-10T18:12:08Z | 4,960,990 | 9 | 2011-02-10T18:14:25Z | [
"python",
"list",
"iterator"
] | I loop through a list and remove the elements that satisfy my condition. But why doesn't this work, as noted below? Thank you.
```
>>> a=[ i for i in range(4)]
>>> a
[0, 1, 2, 3]
>>> for e in a:
... if (e > 1) and (e < 4):
... a.remove(e)
...
>>> a
[0, 1, 3]
>>> a=[ i for i in range(4)]
>>> for e in a:
..... | You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (e.g. sets and dicts).
Instead, iterate over a copy (`for e in a[:]: ...`) or, instead of modifying an existing list, filter it to get a... |
Clojure style function "threading" in Python | 4,961,017 | 9 | 2011-02-10T18:17:53Z | 4,961,063 | 12 | 2011-02-10T18:23:28Z | [
"python",
"functional-programming",
"clojure"
] | Clojure has a "->" macro which inserts each expression recursively as the first argument of the next expression.
This means that I could write:
```
(-> arg f1 f2 f3)
```
and it behaves like (shell piping):
```
f3(f2(f1(arg)))
```
I would like to do this in Python; however, searching seems to be a nightmare! I coul... | You can easily implement something like this yourself.
```
def compose(current_value, *args):
for func in args:
current_value = func(current_value)
return current_value
def double(n):
return 2*n
print compose(5, double, double) # prints 20
``` |
Clojure style function "threading" in Python | 4,961,017 | 9 | 2011-02-10T18:17:53Z | 4,961,120 | 12 | 2011-02-10T18:29:29Z | [
"python",
"functional-programming",
"clojure"
] | Clojure has a "->" macro which inserts each expression recursively as the first argument of the next expression.
This means that I could write:
```
(-> arg f1 f2 f3)
```
and it behaves like (shell piping):
```
f3(f2(f1(arg)))
```
I would like to do this in Python; however, searching seems to be a nightmare! I coul... | Or possibly use the reduce function in the following way:
```
reduce(lambda x,f : f(x), [f1,f2,f3], arg)
``` |
Clojure style function "threading" in Python | 4,961,017 | 9 | 2011-02-10T18:17:53Z | 4,961,462 | 7 | 2011-02-10T19:05:36Z | [
"python",
"functional-programming",
"clojure"
] | Clojure has a "->" macro which inserts each expression recursively as the first argument of the next expression.
This means that I could write:
```
(-> arg f1 f2 f3)
```
and it behaves like (shell piping):
```
f3(f2(f1(arg)))
```
I would like to do this in Python; however, searching seems to be a nightmare! I coul... | Building on Howard's solution:
```
def T(*args):
return reduce(lambda l, r: r(l), args)
def dbl(n):
return 2*n
T(5,dbl,dbl)
#=> 20
T(5,dbl,dbl,lambda x: 3*x)
#=> 60
``` |
Speed up writing to files | 4,961,589 | 17 | 2011-02-10T19:20:17Z | 4,961,701 | 25 | 2011-02-10T19:31:27Z | [
"python",
"performance",
"file-io"
] | I've profiled some legacy code I've inherited with cProfile. There were a bunch of changes I've already made that have helped (like using simplejson's C extensions!).
Basically this script is exporting data from one system to an ASCII fixed-width file. Each row is a record, and it has many values. Each line is 7158 ch... | Actually, your problem is not that `file.write()` takes 20% of your time. Its that 80% of the time you aren't in `file.write()`!
Writing to the disk is slow. There is really nothing you can do about it. It simply takes a very large amount of time to write stuff out to disk. There is almost nothing you can do to speed ... |
Speed up writing to files | 4,961,589 | 17 | 2011-02-10T19:20:17Z | 4,985,439 | 12 | 2011-02-13T16:45:39Z | [
"python",
"performance",
"file-io"
] | I've profiled some legacy code I've inherited with cProfile. There were a bunch of changes I've already made that have helped (like using simplejson's C extensions!).
Basically this script is exporting data from one system to an ASCII fixed-width file. Each row is a record, and it has many values. Each line is 7158 ch... | Batching the writes into groups of 500 did indeed speed up the writes significantly. For this test case the writing rows individually took 21.051 seconds in I/O, while writing in batches of 117 took 5.685 seconds to write the same number of rows. Batches of 500 took a total of only 0.266 seconds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.