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 do I use a dictionary to update fields in Django models? | 5,503,925 | 38 | 2011-03-31T17:35:38Z | 7,535,133 | 27 | 2011-09-23T21:36:44Z | [
"python",
"database",
"django"
] | Suppose I have a model like this:
```
class Book(models.Model):
num_pages = ...
author = ...
date = ...
```
Can I create a dictionary, and then insert or update the model using it?
```
d = {"num_pages":40, author:"Jack", date:"3324"}
``` | If you know you want to create it:
```
Book.objects.create(**d)
```
Assuming you need to check for an existing instance, you can find it with get or create:
```
instance, created = Book.objects.get_or_create(slug=slug, defaults=d)
if not created:
for attr, value in d.iteritems():
setattr(instance, attr,... |
What is the easiest way to get a list of whole factor pairs of a given integer? | 5,504,848 | 3 | 2011-03-31T18:56:17Z | 5,505,024 | 7 | 2011-03-31T19:11:44Z | [
"python",
"math"
] | What is the easiest way to get a list of whole factor pairs of a given integer?
For example: `f(20)` would return `[(1,20), (2,10), (4,5)]`. | ```
def f(value):
factors = []
for i in range(1, int(value**0.5)+1):
if value % i == 0:
factors.append((i, value / i))
return factors
```
Or the same thing using a list comprehension:
```
def f(val):
return [(i, val / i) for i in range(1, int(val**0.5)+1) if val % i == 0]
``` |
django render_to_response is not defined error | 5,505,530 | 8 | 2011-03-31T19:52:39Z | 5,505,555 | 36 | 2011-03-31T19:54:56Z | [
"python",
"django-cms",
"render-to-response"
] | Hi I am getting this error, while I tried make a simple app.
```
NameError at /first/
global name 'render_to_response' is not defined
Request Method: GET
Request URL: http://localhost:8000/first/?preview
Django Version: 1.3
Exception Type: NameError
Exception Value:
global name 'render_to_respons... | Did you try import render\_to\_response as `from django.shortcuts import render_to_response`? |
Is it possible to install another version of Python to Virtualenv? | 5,506,110 | 97 | 2011-03-31T20:46:22Z | 5,506,336 | 18 | 2011-03-31T21:05:26Z | [
"python",
"virtualenv"
] | I have a shared account in a web-hosting that has Python 2.4 installed, but my code is not compatible with 2.4. Is it possible to install Python 2.6 directly to Virtualenv?
Note: I don´t have permission to install it in the shared server. | Pre-requisites:
1. `sudo easy_install virtualenv`
2. `sudo pip install virtualenvwrapper`
Installing virtualenv with Python2.6:
1. You could manually download, build and install another version of Python to `/usr/local` or another location.
2. If it's another location other than `/usr/local`, add it to your PATH.
3.... |
Is it possible to install another version of Python to Virtualenv? | 5,506,110 | 97 | 2011-03-31T20:46:22Z | 5,507,373 | 177 | 2011-03-31T22:58:37Z | [
"python",
"virtualenv"
] | I have a shared account in a web-hosting that has Python 2.4 installed, but my code is not compatible with 2.4. Is it possible to install Python 2.6 directly to Virtualenv?
Note: I don´t have permission to install it in the shared server. | **Here are the options for virtualenv**
```
$ virtualenv
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR
Options:
--version show program's version number and exit.
-h, --help show this help message and exit.
-v, --verbose Increase verbosity.
-q, --quiet ... |
Python Multiprocessing queue | 5,506,227 | 5 | 2011-03-31T20:55:17Z | 5,506,274 | 13 | 2011-03-31T20:59:51Z | [
"python",
"multiprocessing"
] | I am populating a queue with a set of jobs that I want to run in parallel and using python's multiprocessing module for doing that. Code snippet below:
```
import multiprocessing
from multiprocessing import Queue
queue = Queue()
jobs = [['a', 'b'], ['c', 'd']]
for job in jobs:
queue.put(job)
```
When I do queue.g... | The queue is actually geting populated. You need to call queue.get() for each time you put an object to the queue. So you just need to call queue.get() one more time.
```
>>> import multiprocessing
>>> from multiprocessing import Queue
>>> queue = Queue()
>>> jobs = [['a', 'b'], ['c', 'd']]
>>> for job in jobs:
qu... |
Python Multiprocessing queue | 5,506,227 | 5 | 2011-03-31T20:55:17Z | 5,506,280 | 12 | 2011-03-31T21:00:09Z | [
"python",
"multiprocessing"
] | I am populating a queue with a set of jobs that I want to run in parallel and using python's multiprocessing module for doing that. Code snippet below:
```
import multiprocessing
from multiprocessing import Queue
queue = Queue()
jobs = [['a', 'b'], ['c', 'd']]
for job in jobs:
queue.put(job)
```
When I do queue.g... | The queue is getting populated with all your jobs. [queue.get()](http://docs.python.org/library/queue.html#Queue.Queue.get) will
> Remove and return **an item** from the
> queue.
An item is singular. If you want to drain the queue, then just put your `.get()` in a loop, but be sure to catch the [Empty](http://docs.py... |
Python: converting list of lists to tuples of tuples | 5,506,511 | 10 | 2011-03-31T21:22:15Z | 5,506,527 | 36 | 2011-03-31T21:23:35Z | [
"python",
"list",
"function",
"tuples"
] | A Python newbie! I need help converting a list of lists tuples of tuples.
I want to call the append\_as\_tuples function, but every time I return it, it says
it can only concatenate lists (not tuples) to lists
Here is what I have so far:
```
def append_as_tuple(t, l):
''' Convert list l to a tuple and append i... | To convert `list_of_lists` to a tuple of tuples, use
```
tuple_of_tuples = tuple(tuple(x) for x in list_of_lists)
``` |
Browser and wget load JPEG differently? | 5,507,761 | 9 | 2011-03-31T23:51:01Z | 5,507,921 | 13 | 2011-04-01T00:18:59Z | [
"python",
"image",
"facebook",
"cdn"
] | I'm stumped on this one. Try loading this image in your browser, and then save it to your hard disk.
<http://profile.ak.fbcdn.net/hprofile-ak-snc4/41674_660962816_995_n.jpg>
It's a valid JPEG file at 11377 bytes.
Now try to download it with `wget` or `curl`. Only 11252 bytes show up, and the bottom right part of the... | Here goesâ¦
Taking a packet dump, I see that Facebook returns *the same* Content-Length to Safari as it does to curl, and that content-length is the *incorrect* 11252:
```
GET /hprofile-ak-snc4/41674_660962816_995_n.jpg HTTP/1.1
User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/... |
How can I insert NULL data into MySQL database with Python? | 5,507,948 | 13 | 2011-04-01T00:24:28Z | 14,370,784 | 41 | 2013-01-17T01:23:15Z | [
"python",
"mysql"
] | I'm getting a weird error when inserting some data from a Python script to MySQL. It's basically related to a variable being blank that I am inserting. I take it that MySQL does not like blank variables but is there something else I can change it to so it works with my insert statement?
I can successfully use an `IF` ... | When using mysqldb and `cursor.execute()`, pass the value None, not "NULL":
```
value = None
cursor.execute("INSERT INTO table (`column1`) VALUES (%s)", (value,))
```
Found the answer [here](http://bytes.com/topic/python/answers/166025-python-mysql-insert-null) |
How do I check if a string is valid JSON in Python? | 5,508,509 | 59 | 2011-04-01T02:16:38Z | 5,508,552 | 94 | 2011-04-01T02:25:34Z | [
"python",
"json"
] | In Python, is there a way to check if a string is valid JSON before trying to parse it?
For example working with things like the Facebook Graph API, sometimes it returns JSON, sometimes it could return an image file. | You can try to do `json.loads()`, which will throw a `ValueError` if the string you pass can't be decoded as JSON.
In general, the "[Pythonic](https://docs.python.org/2/glossary.html#term-pythonic)" philosophy for this kind of situation is called [EAFP](https://docs.python.org/2/glossary.html#term-eafp), for *easier t... |
How do I check if a string is valid JSON in Python? | 5,508,509 | 59 | 2011-04-01T02:16:38Z | 20,725,965 | 40 | 2013-12-22T03:30:50Z | [
"python",
"json"
] | In Python, is there a way to check if a string is valid JSON before trying to parse it?
For example working with things like the Facebook Graph API, sometimes it returns JSON, sometimes it could return an image file. | **Example Python script returns a boolean if a string is valid json:**
```
import json
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
```
Which prints:
```
print is_json("{}") #prints True
print is_json("{asdf}") ... |
Add and Compare Datetime in Python | 5,508,588 | 4 | 2011-04-01T02:33:45Z | 5,508,605 | 13 | 2011-04-01T02:37:30Z | [
"python",
"datetime",
"compare",
"add"
] | How do I write this pseudocode in Python? With 'created\_date' being a datetime object.
```
if (created_date + 30days) < now:
print 'valid'
else:
print 'expired'
``` | ```
import datetime as DT
if (created_date + DT.timedelta(days=30)) < DT.datetime.now():
print('valid')
else:
print('expired')
``` |
matching query does not exist Error in Django | 5,508,888 | 34 | 2011-04-01T03:38:08Z | 5,508,924 | 95 | 2011-04-01T03:47:44Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] | I have implemented a password recovery functionality in django. With my method the new password will be sent to his email id entered. And its working fine when i give the correct email (e-mail id which exists in the database). But when i give an email id which is not in the database, it gives me this error 'DoesNotExis... | ```
try:
user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
user = None
```
I also see you're storing your passwords in plaintext (a big security no-no!). Why don't you use the built-in auth system? |
C-extension in Python - return Py_BuildValue() memory leak problem | 5,508,904 | 7 | 2011-04-01T03:42:00Z | 5,509,985 | 10 | 2011-04-01T06:43:18Z | [
"python",
"c",
"memory",
"extension-methods",
"memory-leaks"
] | I have a huge memory leak problem involving a C-extension I'm developing. In C, I have an array of doubles called `A` and an int variable called `AnotherIntVariable`that I want to pass to Python. Well, in my C-extension module I do the following:
```
int i;
PyObject *lst = PyList_New(len_A);
PyObject *num;
if(!l... | If you look at the documentation for `Py_BuildValue` (http://docs.python.org/c-api/arg.html#Py\_BuildValue) you can see that under the `O` typecode, it says that the reference count of the passed in object is incremented by one.
So, after the call to `Py_BuildValue`, the refcount for your list is `2`, but you only wan... |
What's the best way of skip N values of the iteration variable in Python? | 5,509,302 | 23 | 2011-04-01T04:54:33Z | 5,509,311 | 17 | 2011-04-01T04:55:41Z | [
"python",
"iterator"
] | In many languages we can do something like:
```
for (int i = 0; i < value; i++)
{
if (condition)
{
i += 10;
}
}
```
**How can I do the same in Python?** The following (of course) does not work:
```
for i in xrange(value):
if condition:
i += 10
```
I could do something like this:
```... | Use `continue`.
```
for i in xrange(value):
if condition:
continue
```
If you want to force your iterable to skip forwards, you must call `.next()`.
```
>>> iterable = iter(xrange(100))
>>> for i in iterable:
... if i % 10 == 0:
... [iterable.next() for x in range(10)]
...
[1, 2, 3, 4, 5, 6,... |
What's the best way of skip N values of the iteration variable in Python? | 5,509,302 | 23 | 2011-04-01T04:54:33Z | 5,509,448 | 11 | 2011-04-01T05:21:08Z | [
"python",
"iterator"
] | In many languages we can do something like:
```
for (int i = 0; i < value; i++)
{
if (condition)
{
i += 10;
}
}
```
**How can I do the same in Python?** The following (of course) does not work:
```
for i in xrange(value):
if condition:
i += 10
```
I could do something like this:
```... | Create the iterable before the loop.
Skip one by using next on the iterator
```
it = iter(xrange(value))
for i in it:
if condition:
i = next(it)
```
Skip many by using itertools or recipes based on ideas from itertools.
[itertools.dropwhile()](http://docs.python.org/library/itertools.html#itertools.isli... |
Using cyclone or tornado in python, how do i make a simple handler that responds with json? | 5,509,373 | 3 | 2011-04-01T05:07:36Z | 5,510,118 | 7 | 2011-04-01T07:01:47Z | [
"python",
"json",
"tornado"
] | Do i do it like this?
```
import cyclone
class MyHandler(cyclone.web.RequestHandler):
def get(self, command):
details = {'status':'success'}
json = json_encode(details)
self.write(json)
```
Or is there more to it than that? | It's even less than that: You can simply use `self.write(details)` if it you write a dict, it will be automatically converted to JSON. |
Python append multiple files in given order to one big file | 5,509,872 | 6 | 2011-04-01T06:26:13Z | 5,509,894 | 15 | 2011-04-01T06:29:52Z | [
"python",
"file",
"append"
] | I have up to 8 seperate Python processes creating temp files in a shared folder. Then I'd like the controlling process to append all the temp files in a certain order into one big file. What's the quickest way of doing this at an os agnostic shell level? | Just using simple file IO:
```
# tempfiles is a list of file handles to your temp files. Order them however you like
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
f.write(tempfile.read())
```
That's about as OS agnostic as it gets. It's also fairly simple, and the performance ought to be about as good a... |
What is -s flag in python | 5,510,273 | 3 | 2011-04-01T07:19:14Z | 5,510,293 | 9 | 2011-04-01T07:21:17Z | [
"python"
] | From Python Cookbook
```
python timeit.py -s"import random" -s"x=range(100000); random.shuffle(x)" "sorted(x)"
10 loops, best of 3: 152 msec per loop
```
What does the `-s` flag do?
Searched online, python help and SO. But did not find a good explanation. Thanks. | From Python's built-in `help()`
```
>>>import timeit
>>>help(timeit)
....
Command line usage:
python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [--] [statement]
Options:
-n/--number N: how many times to execute 'statement' (default: see below)
-r/--repeat N: how many times to repeat the timer (default 3)
... |
Django : Syncdb incorrectly warns that many-to-many field is stale | 5,510,843 | 12 | 2011-04-01T08:28:47Z | 5,511,221 | 20 | 2011-04-01T09:00:44Z | [
"python",
"django",
"django-models",
"django-admin",
"django-authentication"
] | I have a django application where one application has many-to-many relationship with a UserProfile. But whenever I do a syncdb, it warns me that app\_users is stale field
```
The following content types are stale and need to be deleted:
Apps | app_users
#settings.py
AUTH_PROFILE_MODULE = 'kprofile.UserProfile'
... | Pay attention to the message. It's not claiming that your field is stale - it's talking about an entry in the [Content Types](http://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/) model.
In the shell, do this:
```
from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get(app_la... |
how to make a variable immutable in python | 5,511,128 | 4 | 2011-04-01T08:53:40Z | 5,511,371 | 21 | 2011-04-01T09:15:04Z | [
"python",
"list"
] | My python script:
```
N = 2 # 2*2 matrix
a = N * [0]
b = a
print(b) # prints [0, 0]
for i in range(N):
a[i] = N * [0]
for i in range(N):
for j in range(N):
a[i][j] = 0
print(a) # prints [[0, 0], [0, 0]]
print(b) # prints [[0, 0], [0, 0]]
```
Why does my second `print(b)` change? How to make ... | Your understanding of "objects" in Python and variable assignments is flawed.
In a language like C, when you define a variable (say `int a`), a tiny area of memory is allocated and reserved for this variable and `a` is now something that refers to this area of memory. You can poke into this area, change it and find th... |
Removing punctuation/numbers from text problem | 5,512,765 | 5 | 2011-04-01T11:32:37Z | 5,512,810 | 7 | 2011-04-01T11:37:05Z | [
"python",
"nltk"
] | I had some code that worked fine removing punctuation/numbers using regular expressions in python, I had to change the code a bit so that a stop list worked, not particularly important. Anyway, now the punctuation isn't being removed and quite frankly i'm stumped as to why.
```
import re
import nltk
# Quran subset
fi... | Change
```
for word in word_list:
word = punctuation.sub("", word)
```
to
```
word_list = [punctuation.sub("", word) for word in word_list]
```
Assignment to `word` in the `for-loop` above, simply changes the value referenced by this temporary variable. It does not alter `word_list`. |
Python httplib2, AttributeError: 'set' object has no attribute 'items' | 5,512,993 | 5 | 2011-04-01T11:55:31Z | 5,513,024 | 15 | 2011-04-01T11:58:09Z | [
"python",
"httplib2"
] | I'm playing with the Python library [httplib2](http://code.google.com/p/httplib2/). The following is my code.
```
import urllib.parse
import httplib2
httplib2.debuglevel = 1
http = httplib2.Http()
url = "http://login.sina.com.cn/hd/signin.php"
body = {"act": "1",
"entry": "vblog",
"password": "P@$sW... | `headers` should be a dictionary, not a set:
```
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
...}
```
Note the colon instead of the comma. |
python mechanize find_link find the final matching link | 5,513,059 | 2 | 2011-04-01T12:00:43Z | 5,513,414 | 7 | 2011-04-01T12:33:34Z | [
"python",
"mechanize"
] | I've got a page with >=1 links with "Display charges" in the text.
I can find the first such link with
```
firstLink = br.find_link(text_regex=re.compile("Display charges"),nr=0)
```
I'd love to be able to find the final link. I hoped this would work
```
lastLink = br.find_link(text_regex=re.compile("Display charges... | You could use `br.links()` to generate all such links, then use `list(...)[-1]` to pick off the last one:
```
lastLink = list(br.links(text_regex=re.compile("Display charges")))[-1]
```
For example:
```
In [29]: import mechanize
In [30]: import re
In [31]: br=mechanize.Browser()
In [32]: br.open('http://www.examp... |
Add 'decimal-mark' thousands separators to a number | 5,513,615 | 37 | 2011-04-01T12:50:40Z | 5,513,684 | 15 | 2011-04-01T12:56:58Z | [
"python",
"format",
"locale",
"number-formatting",
"digit-separator"
] | How do I format `1000000` to `1.000.000` in Python? where the '.' is the decimal-mark thousands separator. | I didn't really understand it; but here is what I understand:
You want to convert 1123000 to 1,123,000. You can do that by using format:
<http://docs.python.org/release/3.1.3/whatsnew/3.1.html#pep-378-format-specifier-for-thousands-separator>
Example:
```
>>> format(1123000,',d')
'1,123,000'
``` |
Add 'decimal-mark' thousands separators to a number | 5,513,615 | 37 | 2011-04-01T12:50:40Z | 5,513,747 | 77 | 2011-04-01T13:02:09Z | [
"python",
"format",
"locale",
"number-formatting",
"digit-separator"
] | How do I format `1000000` to `1.000.000` in Python? where the '.' is the decimal-mark thousands separator. | If you want to add a thousands separator, you can write:
```
>>> '{0:,}'.format(1000000)
'1,000,000'
```
But it only works in Python 2.7 and higher.
See [format string syntax](http://docs.python.org/library/string.html#format-string-syntax).
In older versions, you can use [locale.format()](http://docs.python.org/li... |
How to write a web server using twisted? | 5,514,162 | 3 | 2011-04-01T13:37:15Z | 5,514,320 | 9 | 2011-04-01T13:50:18Z | [
"python",
"twisted"
] | How do i write a simple http web server using twisted framework?
I want a web server that can receive http request and return a response to the client.
Am going through the twisted documentation and am kinda confused (maybe am just lazy), but it does not look very direct on how to do this, especially how does the twi... | Your questions should mostly be answered at <http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html> |
Python error: TypeError: 'module' object is not callable for HeadFirst Python code | 5,514,573 | 10 | 2011-04-01T14:11:36Z | 5,514,612 | 43 | 2011-04-01T14:14:33Z | [
"python",
"module"
] | I'm new to Python. I'm following the tutorial from the HeadFirst Python book, and on chapter 7 I get the below error message when trying to run the next code:
Athlete class:
```
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_times=[]):
list.__init__([])
self.name = a_name
... | Your module and your class `AthleteList` have the same name. The line
```
import AthleteList
```
imports the module and creates a name `AthleteList` in your current scope that points to the module object. If you want to access the actual class, use
```
AthleteList.AthleteList
```
In particular, in the line
```
ret... |
Python error: TypeError: 'module' object is not callable for HeadFirst Python code | 5,514,573 | 10 | 2011-04-01T14:11:36Z | 14,916,862 | 7 | 2013-02-17T00:46:09Z | [
"python",
"module"
] | I'm new to Python. I'm following the tutorial from the HeadFirst Python book, and on chapter 7 I get the below error message when trying to run the next code:
Athlete class:
```
class AthleteList(list):
def __init__(self, a_name, a_dob=None, a_times=[]):
list.__init__([])
self.name = a_name
... | You module and class `AthleteList` have the same name. Change:
```
import AthleteList
```
to:
```
from AthleteList import AthleteList
```
This now means that you are importing the module object and will not be able to access any module methods you have in `AthleteList` |
Is there a shorthand for querying a dictionary in python? | 5,514,906 | 4 | 2011-04-01T14:42:01Z | 5,515,067 | 10 | 2011-04-01T14:54:25Z | [
"python",
"syntactic-sugar"
] | Here's the type of query I want to execute, written in pseudocode:
```
select blob from blobs where blob['color'] == 'red' having maximum(blob['size'])
```
Obviously, I could write that like this in python:
```
redBlobs = [];
for blob in blobs:
if blob['color'] == 'red':
redBlobs.append('blob')
largest... | The folowing give the largest blob
**EDIT**: catch exception when there is no red blob
```
import operator
try:
largestBlob = max((blob for blob in blobs if blob['color'] == 'red'),key=operator.itemgetter('size'))
except ValueError:
largestBlob = None
``` |
Compute a compounded return series in Python | 5,515,021 | 8 | 2011-04-01T14:50:44Z | 5,516,153 | 7 | 2011-04-01T16:26:40Z | [
"python",
"list-comprehension",
"time-series",
"pandas"
] | Greetings all, I have two series of data: daily raw stock price returns (positive or negative floats) and trade signals (buy=1, sell=-1, no trade=0).
The raw price returns are simply the log of today's price divided by yesterday's price:
```
log(p_today / p_yesterday)
```
An example:
```
raw_return_series = [ 0.006... | There is a fantastic module called [pandas](http://pandas.sf.net/) that was written by a guy at AQR (a hedge fund) that excels at calculations like this... what you need is a way to handle "missing data"... as someone mentioned above, the basics are using the nan (not a number) capabilities of scipy or numpy; however, ... |
How to iterate over columns of a matrix? | 5,515,181 | 23 | 2011-04-01T15:02:45Z | 5,515,198 | 37 | 2011-04-01T15:04:38Z | [
"python",
"numpy"
] | In python if a define:
```
a = arange(9).reshape(3,3)
```
as a 3x3 matrix and iterate:
```
for i in a:
```
It'll iterate over the matrix's rows. Is there any way to iterate over columns? | How about
```
for i in a.transpose():
```
or, shorter:
```
for i in a.T:
```
This may look expensive but is in fact very cheap (it returns a view onto the same data, but with the shape and stride attributes permuted). |
How to match non-printable characters in a python regular expression? | 5,515,226 | 5 | 2011-04-01T15:06:35Z | 5,515,245 | 7 | 2011-04-01T15:08:36Z | [
"python",
"regex",
"non-printing-characters"
] | How do you match non-printable characters in a python regular expression? In my case I have a string that has a combination of printable and non-printable characters.
```
Example String: "Det 3 @ NYY 5 ?7" where the ? is either 0x7f or 0x80.
```
In the above example I need to match 0x7f or 0x80. How do I specify this... | Use a character range.
```
'[\x7f\x80]'
``` |
Plot matplotlib on the Web | 5,515,278 | 10 | 2011-04-01T15:11:27Z | 5,515,994 | 18 | 2011-04-01T16:09:53Z | [
"python",
"matplotlib"
] | The following code will of course create a PNG named test and save it on the server:
```
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
fig = Figure(figsize=[4,4])
ax = fig.add_axes([.1,.1,.8,.8]) ... | First you need a page to load a url from the webserver controller which generates the image:
```
<img src="/matplot/makegraph?arg1=foo" />
```
Then, embed the matplotlib code into the `makegraph` controller. You just need to capture the canvas rendered PNG in a memory buffer, then create an HTTP response and write th... |
Python Implementation of OPTICS (Clustering) Algorithm | 5,515,675 | 24 | 2011-04-01T15:43:28Z | 9,198,708 | 9 | 2012-02-08T17:49:49Z | [
"python",
"machine-learning",
"cluster-analysis",
"data-mining",
"optics-algorithm"
] | I'm looking for a decent implementation of the [OPTICS](http://en.wikipedia.org/wiki/OPTICS_algorithm) algorithm in Python. I will use it to form density-based clusters of points ((x,y) pairs).
I'm looking for something that takes in (x,y) pairs and outputs a list of clusters, where each cluster in the list contains a... | I'm not aware of a *complete* and exact python implementation of OPTICS. The links posted here seem just rough approximations of the OPTICS idea. They also do not use an index for acceleration, so they will run in `O(n^2)` or more likely even `O(n^3)`.
OPTICS has a number of tricky things besides the obvious idea. In ... |
Python Smooth Time Series Data | 5,515,720 | 10 | 2011-04-01T15:47:54Z | 5,515,773 | 8 | 2011-04-01T15:52:24Z | [
"python",
"time-series"
] | I have some data in python that is unixtime, value:
```
[(1301672429, 274), (1301672430, 302), (1301672431, 288)...]
```
Time constantly steps by one second. How might I reduce this data so the timestamp is every second, but the value is the average of the surrounding 10 values?
Fancier rolling averages would be goo... | If you have access to `numpy`, you could try this recipe:
<http://www.scipy.org/Cookbook/SignalSmooth> |
Python Smooth Time Series Data | 5,515,720 | 10 | 2011-04-01T15:47:54Z | 5,516,430 | 11 | 2011-04-01T16:54:06Z | [
"python",
"time-series"
] | I have some data in python that is unixtime, value:
```
[(1301672429, 274), (1301672430, 302), (1301672431, 288)...]
```
Time constantly steps by one second. How might I reduce this data so the timestamp is every second, but the value is the average of the surrounding 10 values?
Fancier rolling averages would be goo... | Using <http://www.scipy.org/Cookbook/SignalSmooth>:
```
import numpy
def smooth(x,window_len=11,window='hanning'):
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than ... |
ValueError: need more than 2 values to unpack in Python 2.6.6 | 5,515,859 | 9 | 2011-04-01T15:58:33Z | 5,515,980 | 13 | 2011-04-01T16:08:54Z | [
"python"
] | i am getting error: ValueError: need more than 2 values to unpack
when i run the unit test now, so 2 failures and one skip
now as far as i have read about
```
lambda i: get_error_count(self._error_lookup, i))
```
line 142 of source is the method
```
for test, err, capt in errors:
```
which has the line of code:
``... | Instead of unpacking in your assignment:
```
a, b, c = do_something()
```
Try assigning the result to a single variable and testing its length:
```
t = do_something()
# t is now a tuple (or list, or whatever was returned) of results
if len(t) > 2:
# Can use the third result!
c = t[2]
``` |
How do I start and stop a Linux program using the subprocess module in Python? | 5,516,511 | 15 | 2011-04-01T17:02:23Z | 5,517,927 | 7 | 2011-04-01T19:28:16Z | [
"python",
"linux",
"selenium",
"subprocess",
"xvfb"
] | Iâm writing a web app that uses Selenium to screen-scrape another website. This screen-scraping only happens once a day, so Iâd rather not leave Selenium and Xvfb running all the time.
Iâm trying to figure out how to start Xvfb and Selenium from Python, and then stop them once the screen-scrapingâs done.
If I... | I don't know why you want to run Xvfb as root. Your usual X server only needs to run as root (on many but not all unices) only so that it can access the video hardware; that's not an issue for Xvfb by definition.
```
tempdir = tempfile.mkdtemp()
xvfb = subprocess.Popen(['Xvfb', ':99', '-nolisten', 'tcp', '-fbdir', tem... |
How to reload python module imported using "from module import *" | 5,516,783 | 29 | 2011-04-01T17:30:38Z | 5,516,896 | 9 | 2011-04-01T17:42:29Z | [
"python"
] | I saw in this useful q&a how to reload a module imported using "import whatever\_module":
[How do I unload (reload) a Python module?](http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module)
I saw that one can use reload(whatever\_module) or, in Python 3, imp.reload(whatever\_module).
My que... | Never use `import *`; it destroys readability.
Also, be aware that reloading modules is almost never useful. You can't predict what state your program will end up in after reloading a module, so it's a great way to get incomprehensible, unreproduceable bugs. |
How to reload python module imported using "from module import *" | 5,516,783 | 29 | 2011-04-01T17:30:38Z | 11,724,550 | 31 | 2012-07-30T15:27:58Z | [
"python"
] | I saw in this useful q&a how to reload a module imported using "import whatever\_module":
[How do I unload (reload) a Python module?](http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module)
I saw that one can use reload(whatever\_module) or, in Python 3, imp.reload(whatever\_module).
My que... | I agree with the *"don't do this generally"* consensus, but...
The correct answer is:
```
import X
reload( X )
from X import Y # or * for that matter
``` |
Is there any trick to "overload the dot operator"? | 5,517,241 | 7 | 2011-04-01T18:20:36Z | 5,517,322 | 14 | 2011-04-01T18:27:24Z | [
"python",
"json"
] | I know the question is a little weirdly stated, but I can't think of any other way of saying it. I have an application that deals with large json objects, and I want to be able to just say:
```
object1.value.size.whatever.attributexyz
```
instead of
```
object1.get('value').get('size').get('whatever').get('attribute... | In `object1`'s class definition,
```
def __getattr__(self, key):
return self.get(key)
```
Any attempt to resolve a property, method, or field name that doesn't actually exist on the object itself will be passed to [`__getattr__`](http://docs.python.org/reference/datamodel.html#object.__getattr__).
If you don't h... |
Dangerous Python Keywords? | 5,517,582 | 24 | 2011-04-01T18:51:59Z | 5,518,062 | 24 | 2011-04-01T19:41:50Z | [
"python"
] | I am about to get a bunch of python scripts from an untrusted source.
I'd like to be sure that no part of the code can hurt my system, meaning:
`(1) the code is not allowed to import ANY MODULE`
`(2) the code is not allowed to read or write any data, connect to the network etc`
(the purpose of each script is to loo... | This point hasn't been made yet, and should be:
> **You are not going to be able to secure arbitrary Python code.**
A VM is the way to go unless you want security issues up the wazoo. |
Dangerous Python Keywords? | 5,517,582 | 24 | 2011-04-01T18:51:59Z | 5,764,421 | 9 | 2011-04-23T13:27:19Z | [
"python"
] | I am about to get a bunch of python scripts from an untrusted source.
I'd like to be sure that no part of the code can hurt my system, meaning:
`(1) the code is not allowed to import ANY MODULE`
`(2) the code is not allowed to read or write any data, connect to the network etc`
(the purpose of each script is to loo... | You can still obfuscate `import` without using `eval`:
```
s = '__imp'
s += 'ort__'
f = globals()['__builtins__'].__dict__[s]
** BOOM **
``` |
How to import python script files in folders on Google App Engine? | 5,517,625 | 5 | 2011-04-01T18:57:03Z | 5,517,634 | 10 | 2011-04-01T18:57:58Z | [
"python",
"google-app-engine"
] | I'm fairly new to both Python and Google App Engine. I want to organize my script files by creating a folder structure. However when I do that I can no longer figure out how to import them.
For example:
```
main.py
/eggs/spam.py
```
How do I import spam.py in main.py? | Make eggs a package by adding an `__init__.py` file in the folder. It can be empty, as long as it's there. Then, import spam like this:
`import eggs.spam`
[More information on packages](http://docs.python.org/tutorial/modules.html#packages). |
pip install PyQt IOError | 5,517,924 | 27 | 2011-04-01T19:28:04Z | 5,518,386 | 9 | 2011-04-01T20:19:05Z | [
"python",
"pyqt",
"pip",
"ioerror",
"setup.py"
] | I'm trying to install PyQt package with pip, but I get this error:
```
~$ pip install PyQt
Downloading/unpacking PyQt
Downloading PyQt-x11-gpl-4.8.3.tar.gz
(9.8Mb): 9.8Mb downloaded Running
setup.py egg_info for package PyQt
Traceback (most recent call last):
File "<string>", line 14, in <module>
IO... | That's because that file has a `configure.py` not a `setup.py`. configure.py generate a make file that you use to build pyqt against the qt lib you choose by passing --qmake option to configure.py, it has different options too. I suggest filing a bug with the pip maintainer. |
pip install PyQt IOError | 5,517,924 | 27 | 2011-04-01T19:28:04Z | 13,583,779 | 8 | 2012-11-27T11:58:48Z | [
"python",
"pyqt",
"pip",
"ioerror",
"setup.py"
] | I'm trying to install PyQt package with pip, but I get this error:
```
~$ pip install PyQt
Downloading/unpacking PyQt
Downloading PyQt-x11-gpl-4.8.3.tar.gz
(9.8Mb): 9.8Mb downloaded Running
setup.py egg_info for package PyQt
Traceback (most recent call last):
File "<string>", line 14, in <module>
IO... | If you're on Mac, you can use [homebrew](http://mxcl.github.com/homebrew/):
```
brew install pyqt
``` |
Python: fastest way to create a list of n lists | 5,518,435 | 52 | 2011-04-01T20:23:59Z | 5,518,513 | 52 | 2011-04-01T20:31:29Z | [
"python"
] | So I was wondering how to best create a list of blank lists:
```
[[],[],[]...]
```
Because of how Python works with lists in memory, this doesn't work:
```
[[]]*n
```
This does create `[[],[],...]` but each element is the same list:
```
d = [[]]*n
d[0].append(1)
#[[1],[1],...]
```
Something like a list comprehens... | The probably only way which is marginally faster than
```
d = [[] for x in xrange(n)]
```
is
```
from itertools import repeat
d = [[] for i in repeat(None, n)]
```
It does not have to create a new `int` object in every iteration and is about 5 % faster on my machine.
**Edit**: Using NumPy, you can avoid the Python... |
Python: fastest way to create a list of n lists | 5,518,435 | 52 | 2011-04-01T20:23:59Z | 5,518,522 | 10 | 2011-04-01T20:32:07Z | [
"python"
] | So I was wondering how to best create a list of blank lists:
```
[[],[],[]...]
```
Because of how Python works with lists in memory, this doesn't work:
```
[[]]*n
```
This does create `[[],[],...]` but each element is the same list:
```
d = [[]]*n
d[0].append(1)
#[[1],[1],...]
```
Something like a list comprehens... | The list comprehensions actually are implemented more efficiently than explicit looping (see [the `dis` output for example functions](http://codepad.org/PChAeNB5)) and the `map` way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.
Regardless, `[[] for _dummy in ... |
How to have a nested inline formset within a form in Django? | 5,518,826 | 14 | 2011-04-01T21:02:58Z | 5,518,841 | 13 | 2011-04-01T21:05:19Z | [
"python",
"django",
"django-templates",
"django-forms"
] | I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects.
For example, I have a Contact model
`class Contact(models.Model):
...`
And a Communication model
`class Communi... | Of course it's possible - how do you think the admin does it?
Take a look at the [inline formsets documentation](http://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#inline-formsets).
**Edited after comment** Of course, you need to instantiate and render both the parent form and the nested formset. Something... |
'module' object is not callable - Bio.IUPAC | 5,519,081 | 4 | 2011-04-01T21:28:06Z | 5,519,263 | 8 | 2011-04-01T21:51:57Z | [
"python",
"biopython"
] | When I try,
```
from Bio.Alphabet import IUPAC
from Bio import Seq
my_prot = Seq("AGTACACTGGT", IUPAC.protein)
```
Why do I encounter the following error:
```
TypeError: 'module' object is not callable
```
PS: this is an Example from the BioPython's Cookbook | In the BioPython source code the "Seq" class is located in the file "[Seq.py](http://biopython.open-bio.org/SRC/biopython/Bio/Seq.py)" in the path "/Seq/Seq.py"
Meaning... You need to import Seq (a file) which means its a "Module" and then call the class "Seq" within the 'Module' 'Seq'
So try this:
```
from Bio.Alph... |
Erlang-like concurrency for Python? | 5,519,513 | 9 | 2011-04-01T22:25:28Z | 5,520,059 | 7 | 2011-04-01T23:54:15Z | [
"python",
"concurrency",
"erlang",
"python-stackless",
"greenlets"
] | Is there anything for Python that has concurrency like Erlang does, particulary transparent actors over networks? I've looked at things like [greenlet](http://pypi.python.org/pypi/greenlet) and [stackless](http://www.stackless.com/), but they don't seem to have network transparency for actors.
I still can't quite jump... | Instead of trying to make Python more like Erlang, how about making Erlang more like Python?
[Efene](http://www.marianoguerra.com.ar/efene/) and [Elixir](http://elixir-lang.org/) are language compilers that produce BEAM files which can take advantage of all the features of the Erlang BEAM emulator including network-tr... |
WTForms: How to select options in SelectMultipleField? | 5,519,729 | 12 | 2011-04-01T22:57:25Z | 5,519,971 | 12 | 2011-04-01T23:38:24Z | [
"python",
"html",
"select",
"wtforms"
] | Choices can be set using `form.myfield.choices=[("1","Choice1"), ("2","Choice2")]`
What is the way to set the selected option? | You can use the `choices` and `default` keyword arguments when creating the field, like this:
```
my_choices = [('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')]
SelectMultipleField(choices = my_choices, default = ['1', '3'])
```
This will mark choices 1 and 3 as selected.
---
**Edit:** Default values are appa... |
WTForms: How to select options in SelectMultipleField? | 5,519,729 | 12 | 2011-04-01T22:57:25Z | 10,356,115 | 14 | 2012-04-27T18:43:21Z | [
"python",
"html",
"select",
"wtforms"
] | Choices can be set using `form.myfield.choices=[("1","Choice1"), ("2","Choice2")]`
What is the way to set the selected option? | This is what worked for me on a `SelectField`:
```
form.myfield.default = '1'
form.process()
```
I'm guessing you can just assign a list to `form.myfield.default` for a `SelectMultipleField`. The key, though, seems to be calling the `process` method on the form after you assign to default. |
Slicing lists and strings to negative zero | 5,519,914 | 2 | 2011-04-01T23:26:46Z | 5,519,933 | 7 | 2011-04-01T23:30:30Z | [
"python"
] | I've read the [Python informal tutorial](http://docs.python.org/tutorial/introduction.html#strings) on slicing, which all makes sense to me except for one edge case. It seems like
```
'help'[:-0]
```
should evaluate to `'help'`, but it really evaluates to `''`. What's a good way to think about negative index slicing ... | `'help'[:-0]` is actually equal to `'help'[:0]`, in which case it makes sense that it evaluates to `''`. In fact, as you can see from the interactive python interpreter, `-0` is the same as `0`:
```
>>> -0
0
``` |
How do I parse subjectAltName extension data using pyasn1? | 5,519,958 | 12 | 2011-04-01T23:36:09Z | 5,529,933 | 14 | 2011-04-03T13:44:12Z | [
"python",
"ssl",
"x509",
"asn.1"
] | I have some data that pyOpenSSL gave me, `'0\r\x82\x0bexample.com'`. This should be the value of a subjectAltName X509 extension. I tried to encode the necessary parts of the ASN1 specification for this extension using pyasn1 (and based on one of the pyasn1 examples):
```
from pyasn1.type import univ, constraint, char... | I posted this question on the pyasn1-users list and Ilya Etingof (the author of pyasn1) pointed out my mistake. In brief, each `NamedType` in `GeneralName.componentType` needs to be given tag information. This is done with the `subtype` method. For example, instead of:
```
namedtype.NamedType('rfc822Name', char.IA5Str... |
join two lists by interleaving | 5,520,310 | 4 | 2011-04-02T00:45:26Z | 5,520,324 | 7 | 2011-04-02T00:48:46Z | [
"python"
] | I have a list that I create by parsing some text.
Let's say the list looks like
```
charlist = ['a', 'b', 'c']
```
I would like to take the following list
```
numlist = [3, 2, 1]
```
and join it together so that my combined list looks like
```
[['a', 3], ['b', 2], ['c', 1]]
```
is there a simple method for this? | The [zip](http://docs.python.org/library/functions.html#zip) builtin function should do the trick.
Example from the docs:
```
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
``` |
join two lists by interleaving | 5,520,310 | 4 | 2011-04-02T00:45:26Z | 5,520,455 | 9 | 2011-04-02T01:17:04Z | [
"python"
] | I have a list that I create by parsing some text.
Let's say the list looks like
```
charlist = ['a', 'b', 'c']
```
I would like to take the following list
```
numlist = [3, 2, 1]
```
and join it together so that my combined list looks like
```
[['a', 3], ['b', 2], ['c', 1]]
```
is there a simple method for this? | If you want a list of lists rather than a list of tuples you could use:
```
map(list,zip(charlist,numlist))
``` |
None Type issues in Python 2.6 | 5,520,454 | 2 | 2011-04-02T01:16:59Z | 5,520,471 | 9 | 2011-04-02T01:21:14Z | [
"python"
] | I'm doing a script where I get some values from a Database but sometimes this value can be None, but when I assign it to a variable and try to compare it I get this error:
```
TypeError: 'NoneType' object is unsubscriptable
```
I've already tried this:
```
if sgSlate[ 'sg_client_2' ][ 'name' ] != None:
self.ui.b... | The unsubscriptable error arises when you try to perform a `[]` operation on a `None` variable. So in this case, it is most likely the `sgSlate['sg_client_2']` value that is `None`, not the `sgSlate['sg_client_2']['name']` itself. |
Python: No module named contextlib? | 5,520,515 | 2 | 2011-04-02T01:34:10Z | 5,520,844 | 7 | 2011-04-02T03:04:43Z | [
"python"
] | Does anyone know where i can find this python module 'contextlib'?
```
root@overo:~# python
Python 2.6.6 (r266:84292, Mar 9 2011, 10:05:36)
[GCC 4.3.3] on linux2
Type ... | As others have noted, that module *should* be in the standard library, but if it's an embedded device, it may have been dropped to save space (if true, a foolish choice IMO, since leaving out `contextlib.contextmanager` robs the `with` statement of much of its power and convenience)
If you can name the specific device... |
How do you get all classes defined in a module but not imported? | 5,520,580 | 30 | 2011-04-02T01:51:14Z | 5,520,589 | 23 | 2011-04-02T01:54:38Z | [
"python",
"introspection",
"python-2.7"
] | I've already seen the following question but it doesn't quite get me where I want: [Python: Get list of all classes within current module](http://stackoverflow.com/questions/1796180/python-get-list-of-all-classes-within-current-module)
In particular, I do not want classes that are imported, e.g. if I had the following... | Inspect the `__module__` attribute of the class to find out which module it was defined in. |
How do you get all classes defined in a module but not imported? | 5,520,580 | 30 | 2011-04-02T01:51:14Z | 5,520,871 | 7 | 2011-04-02T03:14:06Z | [
"python",
"introspection",
"python-2.7"
] | I've already seen the following question but it doesn't quite get me where I want: [Python: Get list of all classes within current module](http://stackoverflow.com/questions/1796180/python-get-list-of-all-classes-within-current-module)
In particular, I do not want classes that are imported, e.g. if I had the following... | You may also want to consider using the "Python class browser" module in the standard library:
<http://docs.python.org/library/pyclbr.html>
Since it doesn't actually execute the module in question (it does naive source inspection instead) there are some specific techniques it doesn't quite understand correctly, but fo... |
How do you get all classes defined in a module but not imported? | 5,520,580 | 30 | 2011-04-02T01:51:14Z | 21,563,930 | 10 | 2014-02-04T21:33:07Z | [
"python",
"introspection",
"python-2.7"
] | I've already seen the following question but it doesn't quite get me where I want: [Python: Get list of all classes within current module](http://stackoverflow.com/questions/1796180/python-get-list-of-all-classes-within-current-module)
In particular, I do not want classes that are imported, e.g. if I had the following... | I apologize for answering such an old question, but I didn't feel comfortable using the inspect module for this solution. I read somewhere that is wasn't safe to use in production.
[Initialize all the classes in a module into nameless objects in a list](http://stackoverflow.com/questions/18316820/initialize-all-the-cl... |
Python crashing while calculating SHA-1 hashs for large files in Windows OS | 5,520,585 | 6 | 2011-04-02T01:54:15Z | 5,520,593 | 9 | 2011-04-02T01:55:52Z | [
"python",
"hash",
"large-files",
"sha1"
] | I am wondering if I could have some fresh eyes on this python script. It works fine with small and medium size files but with large ones (4-8GB or so) it inexplicable crashes after running for a couple of minutes.
[Zipped script here](http://dl.dropbox.com/u/3150177/Programming/Python/Source%20code/SHA-1/SHA-1HashGen.... | Stop reading the file in one go; you're consuming all the memory on the system. Read in 16MB or so chunks instead.
```
data = File.read(16 * 1024 * 1024)
``` |
Python crashing while calculating SHA-1 hashs for large files in Windows OS | 5,520,585 | 6 | 2011-04-02T01:54:15Z | 5,520,671 | 8 | 2011-04-02T02:14:32Z | [
"python",
"hash",
"large-files",
"sha1"
] | I am wondering if I could have some fresh eyes on this python script. It works fine with small and medium size files but with large ones (4-8GB or so) it inexplicable crashes after running for a couple of minutes.
[Zipped script here](http://dl.dropbox.com/u/3150177/Programming/Python/Source%20code/SHA-1/SHA-1HashGen.... | (In response to Peter's comment that 2 GB are left.)
I suspect Ignacio is right nonetheless. Try replacing the read/update line with this:
```
while True:
buf = File.read(0x100000)
if not buf:
break
SHA1Hash.update(buf)
``` |
Convert TimeDiff to total seconds | 5,522,031 | 48 | 2011-04-02T08:11:24Z | 5,522,070 | 101 | 2011-04-02T08:20:11Z | [
"python",
"datetime"
] | I have a time difference
```
time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
...
time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
diff = time2 - time1
```
Now, how do I find the total number of seconds that passed? `diff.seconds` doesn't count days. I could do:
```
diff.seconds... | Use [`timedelta.total_seconds()`](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds). |
Automatically build Sphinx documentation when a source file changes | 5,522,326 | 10 | 2011-04-02T09:21:14Z | 20,484,362 | 7 | 2013-12-10T01:28:58Z | [
"python",
"python-sphinx"
] | I'm using [Sphinx](http://sphinx.pocoo.org/) to document one of my projects, and I like to preview my changes in my browser. I want to be able to save some changes to an `.rst` file, and be able to immediately refresh my browser and see the changes.
Essentially I want to automatically execute a `make html` whenever on... | Jacob Kaplan-Moss [has a good solution](http://jacobian.org/writing/auto-building-sphinx/):
```
pip install watchdog
watchmedo shell-command \
--patterns="*.rst" \
--ignore-pattern='_build/*' \
--recursive \
--command='make html'
```
Note, change the pattern to match your suffi... |
Automatically build Sphinx documentation when a source file changes | 5,522,326 | 10 | 2011-04-02T09:21:14Z | 21,389,615 | 13 | 2014-01-27T19:15:26Z | [
"python",
"python-sphinx"
] | I'm using [Sphinx](http://sphinx.pocoo.org/) to document one of my projects, and I like to preview my changes in my browser. I want to be able to save some changes to an `.rst` file, and be able to immediately refresh my browser and see the changes.
Essentially I want to automatically execute a `make html` whenever on... | You can use [sphinx-autobuild](https://pypi.python.org/pypi/sphinx-autobuild).
It is easy to use, for example:
```
sphinx-autobuild docs docs/_build/html
```
or, if you have a separate build dir,
```
sphinx-autobuild source build/html
```
It will also automatically initiate a page refresh in the browser. |
How to optimize this Python code (from ThinkPython, Exercise 10.10) | 5,523,058 | 8 | 2011-04-02T12:10:43Z | 5,523,071 | 13 | 2011-04-02T12:14:56Z | [
"python"
] | I'm working through Allen Downey's *How To Think Like A Computer Scientist*, and I've written what I believe to be a functionally correct solution to Exercise 10.10. But it took just over 10 hours (!) to run, so I'm wondering if I'm missing some really obvious and helpful optimization.
Here's the Exercise:
"Two words... | Do it the other way around: Iterate through all words and split them into two words by taking the odd and even letters. Then look up those two words in the dictionary.
As a side node, the two words that interlock must not necessarily have the same length -- the lengths might also differ by 1.
Some (untested) code:
`... |
Semantics of SUID (Set-User-ID) | 5,523,279 | 6 | 2011-04-02T12:56:31Z | 5,523,325 | 8 | 2011-04-02T13:02:54Z | [
"python",
"permissions",
"semantics",
"suid"
] | it seems that I have some trouble understanding the semantics of the SUID bit, perhaps someone can help me clarify the situation.
My understanding of the semantic of the SUID bit are as follows:
When I set the SUID bit with a file, then the file will be executed as the owner of the file and not as the caller of the fi... | Setting the SUID bit on a \*.py file does not help in any way here since the script is executed by the Python interpreter which must be set SUID in this case. Using 'sudo' is your better friend here. |
How do I get the Application ID at runtime | 5,523,281 | 7 | 2011-04-02T12:57:04Z | 7,135,973 | 13 | 2011-08-21T02:40:29Z | [
"python",
"google-app-engine"
] | I need the Application ID to construct the correct `<applicationid>.appspotmail.com` address, and I'm having a hard time finding out how to retrieve it at runtime. | The recommended approach now is to use `app_identity.get_application_id()`:
<http://code.google.com/appengine/docs/python/appidentity/functions.html#get_application_id>
See the warning box here for details:
<http://code.google.com/appengine/docs/python/runtime.html#Requests_and_Domains> |
Why do these two implementations produce different results? | 5,523,296 | 2 | 2011-04-02T12:58:29Z | 5,523,314 | 10 | 2011-04-02T13:00:52Z | [
"python"
] | I asked [this question](http://stackoverflow.com/q/5523058/115543) and got an excellent answer (thanks!). Part of the problem to be solved involved taking a word and de-interlacing it, so that you get two words, one containing the even-indexed characters of the original word, the other containing the odd-indexed charac... | Because `index(c)` asks the index of the *first* occurrance of the letter in the word â so you are creating a single âbucketâ for each letter. So if the first `'a'` is odd, then *all* of the `'a'` letters also get stuffed into the "odd" string. To fix this, you should just use `enumerate()` to count:
```
for i, ... |
Python: How to move a file with unicode filename to a unicode folder | 5,523,373 | 7 | 2011-04-02T13:14:53Z | 5,523,385 | 15 | 2011-04-02T13:18:27Z | [
"python",
"unicode",
"file-manipulation"
] | I'm having hell with moving a unicode named file between unicode named folders in a Python script under Windows...
What syntax would you use to find all files of type \*.ext in a folder and move them to a relative location?
Assume files and folders are unicode. | The basic problem is the unconverted mix between Unicode and byte strings. The solutions can be converting to a single format or avoiding the problems using some trickery. All of my solutions include the `glob` and `shutil` standard library.
For the sake of example, I have some Unicode filenames ending with `ods`, and... |
Equivalent of template context in Pyramid (pylons user) | 5,523,546 | 13 | 2011-04-02T13:51:46Z | 5,637,690 | 11 | 2011-04-12T15:25:59Z | [
"python",
"pylons",
"pyramid"
] | What is the equivalent of template context in Pyramid?
Does the IBeforeRender event in pyramid have anything to with this? I've gone through the official documentation but diffcult to understand what the IBeforeRender event is exactly. | Pyramid already provides a `tmpl_context` on its Request object, so pretty simply you just have to subscribe a `BeforeRender` event to add it to the renderer globals:
```
def add_renderer_globals(event):
event['c'] = request.tmpl_context
event['tmpl_context'] = request.tmpl_context
config.add_subscriber(add_r... |
Equivalent of Python's dir in Javascript | 5,523,747 | 24 | 2011-04-02T14:33:24Z | 6,166,711 | 11 | 2011-05-29T08:30:52Z | [
"javascript",
"python",
"namespaces",
"interactive",
"dir"
] | when I write Python code from the interpreter I can type `dir()` to have a list of names defined in the current scope. How can achieve to have the same information, programmatically, when I develop Javascript code from a browser using an interactive console like firebug, chrome console, etc? | This may work for you, if you need a simple solution:
```
function dir(object) {
stuff = [];
for (s in object) {
stuff.push(s);
}
stuff.sort();
return stuff;
}
``` |
Equivalent of Python's dir in Javascript | 5,523,747 | 24 | 2011-04-02T14:33:24Z | 11,088,041 | 15 | 2012-06-18T17:33:37Z | [
"javascript",
"python",
"namespaces",
"interactive",
"dir"
] | when I write Python code from the interpreter I can type `dir()` to have a list of names defined in the current scope. How can achieve to have the same information, programmatically, when I develop Javascript code from a browser using an interactive console like firebug, chrome console, etc? | There is "keys" method in Object, for example:
```
Object.keys(object)
```
But this return object's own properties and methods only.
To list all properties and methods of an object I know 2 possibilities:
1. console.dir(object) method in firebug console for Firefox and
2. dir(object) method in Google Chrome dev... |
How can I convert an RFC 822 timestamp into a human readable format in Python? | 5,523,751 | 2 | 2011-04-02T14:33:59Z | 5,523,799 | 8 | 2011-04-02T14:43:08Z | [
"python",
"rfc822"
] | Does anyone know of a Python module that will convert an RFC 822 timestamp into a human readable format (like Twitter does) in Python?
I found [parsedatetime](https://code.google.com/p/parsedatetime/), which seems to do the reverse. | In python, you can use rfc822 module. This module provides the [parsedate](http://docs.python.org/library/rfc822.html#rfc822.parsedate) method.
> Attempts to parse a date according to the rules in RFC 2822.
However, this module is **deprecated**.
> Deprecated since version 2.3: The email package should be used in pr... |
How to detect motion between two PIL images? (wxPython webcam integration example included) | 5,524,179 | 7 | 2011-04-02T15:53:23Z | 5,524,652 | 8 | 2011-04-02T17:20:49Z | [
"python",
"wxpython",
"webcam",
"python-imaging-library",
"video-capture"
] | Does anyone have any suggestions as to how I might do image comparison in python to detect changes within an image? I'm currently working on an app that will monitor my area with my webcam, I would like to figure out how to compare the images taken each frame to see if any motion has been detected. In the long run I wo... | This might be a naive approach, but it's a simple place to begin. I'm sure you will be influenced by camera noise and you may want to distinguish changes in lighting from changes in image composition. But here's what came to my mind:
You can use PIL [ImageChops](http://www.pythonware.com/library/pil/handbook/imagechop... |
matplotlib show() doesn't work twice | 5,524,858 | 11 | 2011-04-02T17:54:22Z | 5,531,274 | 7 | 2011-04-03T17:40:49Z | [
"python",
"numpy",
"pyqt",
"matplotlib"
] | I have a strange problem, with matplotlib. If I run this program, I'm able to open and close several time the same figure.
```
import numpy
from pylab import figure, show
X = numpy.random.rand(100, 1000)
xs = numpy.mean(X, axis=1)
ys = numpy.std(X, axis=1)
fig = figure()
ax = fig.add_subplot(111)
ax.set_title('clic... | I have new information about this that a google search turned up
This is from the writer of matplotlib. This came from <http://old.nabble.com/calling-show%28%29-twice-in-a-row-td24276907.html>
> Hi Ondrej,
>
> I'm not sure where to find a good
> explanation of that, but let me give
> you some hints. It is intended to... |
Put docstrings on special methods? | 5,525,501 | 5 | 2011-04-02T19:55:45Z | 5,525,511 | 9 | 2011-04-02T19:58:27Z | [
"python",
"docstring"
] | I'm trying to decide what information to put in the class docstring and what to put in the `__init__` method docstring. Up until now I've been putting an overview of the class and how to work with it in the class docstring, while stuff directly related to initialization (argument details etc.) I put in the `__init__` d... | Straight from [PEP 257](http://www.python.org/dev/peps/pep-0257/):
> Public methods (including the `__init__` constructor) should also have docstrings.
[...]
> The class constructor should be documented in the docstring for its `__init__` method. |
is there ever a reason to use "is"? | 5,525,676 | 2 | 2011-04-02T20:31:31Z | 5,525,722 | 7 | 2011-04-02T20:40:31Z | [
"python",
"syntax",
"operators",
"comparison-operators"
] | Instead of "=="? I know what "is" is, it is comparing the identity of the variable. But when would you ever want to do that? All it has ever done for me is cause problems. After using it for a while (because I felt it made my code more readable), I am not declaring war on "is".
Does anyone use it for something that "=... | Yes, there is a reason.
When you want to compare *object-identity* ("same object") and not *object-equality* ("same value"). In almost all cases `==` (*object-equality*) is the correct operator to use. (As pointed out in the comments, the trivial case I skipped entirely is the `x is None` idiom -- `None` is the sole i... |
Google appengine Send local gif as an email attachment | 5,526,272 | 3 | 2011-04-02T22:18:29Z | 5,526,293 | 8 | 2011-04-02T22:23:06Z | [
"python",
"image",
"google-app-engine",
"gif",
"email-attachments"
] | I'm trying to send a local gif as an email attachment on Google appengine. The email will send but without an attachment.
```
message = mail.EmailMessage(sender="My image <whomever@gmail.com>",
subject="image")
message.to = "Jim <whomever@gmail.com>"
message.body = my_body_text
message.html = my_body_html
image = ... | You forgot to set the `attachments` field on your `message`, and made a local variable you didn't use instead. Simply change
```
attachments=[(image.name, image.read())]
```
to
```
message.attachments=[(image.name, image.read())]
``` |
How to get all objects in a module in python? | 5,527,415 | 8 | 2011-04-03T03:38:39Z | 5,528,445 | 11 | 2011-04-03T08:19:21Z | [
"python",
"module"
] | I need to get a list of all the objects within a module -- not a list of just their names. So, for instance, I have:
```
class myClass:
def __init__(self):
(code)
class thing1(myClass):
def __init__(self):
self.x = 1
class thing2(myClass):
def __init__(self):
self.x = 2
... | If you have the name of an attribute in a string, you should use `getattr` to fetch it out.
Given a module X, you can get a list of all it's attributes and (for example) their types with something like this.
```
for i in dir(X):
print i," ",type(getattr(X,i))
``` |
Is there a standard Python data structure that keeps thing in sorted order? | 5,527,630 | 13 | 2011-04-03T04:45:19Z | 5,528,318 | 9 | 2011-04-03T07:50:34Z | [
"python",
"data-structures"
] | I have a set of ranges that might look something like this:
```
[(0, 100), (150, 220), (500, 1000)]
```
I would then add a range, say `(250, 400)` and the list would look like this:
```
[(0, 100), (150, 220), (250, 400), (500, 1000)]
```
I would then try to add the range `(399, 450)`, and it would error out because... | It looks like you want something like [bisect's](http://docs.python.org/release/2.7.1/library/bisect.html) insort\_right/insort\_left. The bisect module works with lists and tuples.
```
import bisect
l = [(0, 100), (150, 300), (500, 1000)]
bisect.insort_right(l, (250, 400))
print l # [(0, 100), (150, 300), (250, 400)... |
Can you create an Mac OS X Service with Python? How? | 5,527,899 | 12 | 2011-04-03T06:04:37Z | 5,527,943 | 11 | 2011-04-03T06:17:39Z | [
"python",
"cocoa",
"osx",
"service"
] | Can you create an Mac OS X Service with Python? How ?
What I want to do is to know hook my Python-fu to the service system provided by Mac OS X.
Anyone knows how? If yes any working code snippet? Will work only on text or also on a given mimetype - defined object?
 | * Open Automator.app and create a new service.
* Select "Utilities" from the left-hand actions list, then drag the "Run Shell Script" action into the workflow.
* Choose `/usr/bin/python` as your shell.
* Type some python. For example:
:
```
import sys
for f in sys.stdin:
print "Hello World: " + f,
```
* Save t... |
Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | 5,529,625 | 72 | 2011-04-03T12:39:33Z | 5,531,148 | 14 | 2011-04-03T17:17:02Z | [
"python",
"machine-learning",
"cluster-analysis",
"k-means",
"scikit-learn"
] | Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | Unfortunately no: scikit-learn current implementation of k-means only uses Euclidean distances. |
Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | 5,529,625 | 72 | 2011-04-03T12:39:33Z | 5,551,499 | 47 | 2011-04-05T12:05:28Z | [
"python",
"machine-learning",
"cluster-analysis",
"k-means",
"scikit-learn"
] | Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | Here's a small kmeans that uses any of the 20-odd distances in
[scipy.spatial.distance](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist), or a user function.
Comments would be welcome (this has had only one user so far, not enough);
in particular, wha... |
Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | 5,529,625 | 72 | 2011-04-03T12:39:33Z | 9,875,395 | 7 | 2012-03-26T15:52:44Z | [
"python",
"machine-learning",
"cluster-analysis",
"k-means",
"scikit-learn"
] | Is it possible to specify your own distance function using scikit-learn K-Means Clustering? | Yes you can use a difference metric function; however, by definition, the k-means clustering algorithm relies on the eucldiean distance from the mean of each cluster.
You could use a different metric, so even though you are still calculating the mean you could use something like the mahalnobis distance. |
sqlite3.OperationalError: database is locked | 5,529,820 | 6 | 2011-04-03T13:20:27Z | 5,529,826 | 7 | 2011-04-03T13:22:34Z | [
"python",
"sqlite3"
] | I'm trying to insert all values of a list to my sqlite3 database. When I simulate this query by using the python interactive interpreter, I am able to insert the single value to DB properly. But my code fails while using an iteration:
```
...
connection=lite.connect(db_name)
cursor=connection.cursor()
for name in matc... | Do you have another connection elsewhere in your code that you use to begin a transaction that is still active (not committed) when you try to commit the operation that fails? |
How to make Facebook Login possible in Django app ? | 5,530,277 | 38 | 2011-04-03T14:48:02Z | 5,530,609 | 69 | 2011-04-03T15:45:28Z | [
"python",
"django",
"facebook",
"oauth",
"facebook-oauth"
] | I have created a Django application. The app has a login functionality.
Can somebody help to find a way to make it possible to login using Facebook credential or point me some tutorials to implement it ? | ## Summary;
* <https://github.com/mlavin/django-all-access>
* <https://github.com/pennersr/django-allauth>
* <https://github.com/omab/django-social-auth>
* <https://github.com/uswaretech/Django-Socialauth>
* <https://github.com/hiidef/oauth2app>
* <https://github.com/timetric/django-oauth>
* <https://github.com/daaku/... |
How to make Facebook Login possible in Django app ? | 5,530,277 | 38 | 2011-04-03T14:48:02Z | 5,531,653 | 17 | 2011-04-03T18:42:50Z | [
"python",
"django",
"facebook",
"oauth",
"facebook-oauth"
] | I have created a Django application. The app has a login functionality.
Can somebody help to find a way to make it possible to login using Facebook credential or point me some tutorials to implement it ? | I highly recommend using [django-social-auth](https://github.com/omab/django-social-auth). The README is very complete, and it also includes information for authenticating against other OAuth sources such as twitter, and against OpenID sources like Google and Yahoo. Of course, if you just wanted Facebook authentication... |
No hosts found: Fabric | 5,530,646 | 10 | 2011-04-03T15:53:03Z | 6,126,495 | 10 | 2011-05-25T14:57:17Z | [
"python",
"fabric"
] | when I run my python code it is asking for host.
> No hosts found. Please specify (single) host string for connection:
I have the following code:
```
from fabric.api import *
from fabric.contrib.console import confirm
env.hosts = [ 'ipaddress' ]
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname... | If it's only one host, you can use `env.host_string = 'somehost or ipaddress'`.
You also donât need the `;` at the end of your `remoteRun`.
```
from __future__ import with_statement
from fabric.api import *
from fabric.contrib.console import confirm
from fabric.api import env, run
env.host_string = 'ipaddress'
de... |
No hosts found: Fabric | 5,530,646 | 10 | 2011-04-03T15:53:03Z | 12,025,143 | 9 | 2012-08-19T08:09:33Z | [
"python",
"fabric"
] | when I run my python code it is asking for host.
> No hosts found. Please specify (single) host string for connection:
I have the following code:
```
from fabric.api import *
from fabric.contrib.console import confirm
env.hosts = [ 'ipaddress' ]
def remoteRun():
print "ENV %s" %(env.hosts)
out = run('uname... | In order to get hosts to work in a script outside of the fab command-line tool and fabfile.py, [you'll have to use execute()](http://docs.fabfile.org/en/1.10/api/core/tasks.html#fabric.tasks.execute):
```
from fabric.tasks import execute
def mytask():
run('uname -a')
results = execute(mytask)
``` |
Can I redirect unicode output from the console directly into a file? | 5,530,708 | 20 | 2011-04-03T16:02:31Z | 5,530,880 | 20 | 2011-04-03T16:32:12Z | [
"python",
"unicode",
"console"
] | I've got a python script that outputs unicode to the console, and I'd like to redirect it to a file. Apparently, the redirect process in python involves converting the output to a string, so I get errors about inability to decode unicode characters.
So then, is there any way to perform a redirect into a file encoded i... | When printing to the console, Python looks at `sys.stdout.encoding` to determine the encoding to use to encode unicode objects before printing.
When redirecting output to a file, `sys.stdout.encoding` is None, so Python2 defaults to the `ascii` encoding. (In contrast, Python3 defaults to `utf-8`.) This often leads to ... |
Can I redirect unicode output from the console directly into a file? | 5,530,708 | 20 | 2011-04-03T16:02:31Z | 5,531,730 | 10 | 2011-04-03T18:58:04Z | [
"python",
"unicode",
"console"
] | I've got a python script that outputs unicode to the console, and I'd like to redirect it to a file. Apparently, the redirect process in python involves converting the output to a string, so I get errors about inability to decode unicode characters.
So then, is there any way to perform a redirect into a file encoded i... | Set the environment variable `PYTHONIOENCODING` to the encoding you want before redirecting a python script to a file. Then you won't have to modify the original script. Make sure to write *Unicode* strings as well, otherwise `PYTHONIOENCODING` will have no effect. If you write byte strings, the bytes are sent as-is to... |
Parse XML file into Python object | 5,530,857 | 11 | 2011-04-03T16:29:19Z | 5,531,714 | 7 | 2011-04-03T18:53:41Z | [
"python",
"xml",
"regex",
"xml-parsing"
] | I have an XML file which looks like this:
```
<encspot>
<file>
<Name>some filename.mp3</Name>
<Encoder>Gogo (after 3.0)</Encoder>
<Bitrate>131</Bitrate>
<Mode>joint stereo</Mode>
<Length>00:02:43</Length>
<Size>5,236,644</Size>
<Frame>no</Frame>
<Quality>good</Quality>
<Freq.>44100</Freq.>... | Use [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html). You don't need/want to muck about with a parse-only gadget like `pyexpat` ... you'd only end up re-inventing ElementTree partially and poorly.
Another possibility is [lxml](http://lxml.de/) which is a third-party package which implements the... |
Parse XML file into Python object | 5,530,857 | 11 | 2011-04-03T16:29:19Z | 5,533,742 | 23 | 2011-04-04T01:27:13Z | [
"python",
"xml",
"regex",
"xml-parsing"
] | I have an XML file which looks like this:
```
<encspot>
<file>
<Name>some filename.mp3</Name>
<Encoder>Gogo (after 3.0)</Encoder>
<Bitrate>131</Bitrate>
<Mode>joint stereo</Mode>
<Length>00:02:43</Length>
<Size>5,236,644</Size>
<Frame>no</Frame>
<Quality>good</Quality>
<Freq.>44100</Freq.>... | My beloved SD Chargers hat is off to you if you think a regex is easier than this:
```
#!/usr/bin/env python
import xml.etree.cElementTree as et
sxml="""
<encspot>
<file>
<Name>some filename.mp3</Name>
<Encoder>Gogo (after 3.0)</Encoder>
<Bitrate>131</Bitrate>
</file>
<file>
<Name>another filename.m... |
How to convert time format into milliseconds and back in Python? | 5,531,249 | 4 | 2011-04-03T17:34:48Z | 5,531,351 | 10 | 2011-04-03T17:54:02Z | [
"python",
"datetime"
] | The reason is because I'm making a script to work with ffmpeg and I need to be able to add/subtract time in the format 00:00:00[.000]
The last 3 digits are optional and they mean milliseconds. A time string could look like any of the following
```
4:34.234
5.000
2:99:34
4:14
```
This would be easier if a lot of the ... | From string to milliseconds:
```
s = "4:34.234"
hours, minutes, seconds = (["0", "0"] + s.split(":"))[-3:]
hours = int(hours)
minutes = int(minutes)
seconds = float(seconds)
miliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds)
```
From milliseonds to string:
```
hours, milliseconds = divmod(miliseco... |
Installing MySQLdb on Mac OS X | 5,531,958 | 9 | 2011-04-03T19:37:48Z | 5,532,113 | 8 | 2011-04-03T20:01:46Z | [
"python",
"mysql",
"osx",
"mysql-python"
] | I've spent several hours trying to install MySQLdb (the Python library) on Mac OS X Snow Leopard. I'm using [these instructions](http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x) from SO. I keep getting an error, so I've tried using MacPorts (as one of th... | Ack. I feel your pain. I spent a really long time also trying to get MySQL working with Python 2.6 on Snow Leopard using a Macbook Air and had lots of architecture problems. What ended up solving it for me, was making sure both my Python and MySQL installations were using a 32 bit architecture like my Snow Leopard was.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.