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 |
|---|---|---|---|---|---|---|---|---|---|
Bytes in a unicode Python string | 9,845,842 | 24 | 2012-03-23T20:05:54Z | 9,846,354 | 17 | 2012-03-23T20:53:00Z | [
"python",
"unicode",
"utf-8",
"character-encoding"
] | In Python 2, Unicode strings may contain both unicode and bytes:
```
a = u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439 \xd0\xb5\xd0\xba'
```
I understand that this is absolutely **not something one should write** in his own code, but this is a string that I have to deal with.
The bytes in the string above are UTF-8 f... | > In Python 2, Unicode strings may contain both unicode and bytes:
No, they may not. They contain Unicode characters.
Within the original string, `\xd0` is not a byte that's part of a UTF-8 encoding. It is the Unicode character with code point 208. `u'\xd0'` == `u'\u00d0'`. It just happens that the `repr` for Unicode... |
Bytes in a unicode Python string | 9,845,842 | 24 | 2012-03-23T20:05:54Z | 9,847,114 | 10 | 2012-03-23T22:11:14Z | [
"python",
"unicode",
"utf-8",
"character-encoding"
] | In Python 2, Unicode strings may contain both unicode and bytes:
```
a = u'\u0420\u0443\u0441\u0441\u043a\u0438\u0439 \xd0\xb5\xd0\xba'
```
I understand that this is absolutely **not something one should write** in his own code, but this is a string that I have to deal with.
The bytes in the string above are UTF-8 f... | (In response to the comments above): this code converts everything that looks like utf8 and leaves other codepoints as is:
```
a = u'\u0420\u0443\u0441 utf:\xd0\xb5\xd0\xba bytes:bl\xe4\xe4'
def convert(s):
try:
return s.group(0).encode('latin1').decode('utf8')
except:
return s.group(0)
impor... |
Django: Grab a set of objects from ID list (and sort by timestamp) | 9,845,952 | 8 | 2012-03-23T20:14:38Z | 9,845,988 | 7 | 2012-03-23T20:18:15Z | [
"python",
"database",
"django",
"model",
"django-queryset"
] | I have a list of IDs for objects that I need to grab, then I have to sort them by their timestamp. Here's how I was going to do it:
```
For i in object_ids:
instance = Model.objects.get(id = i)
# Append instance to list of instances
#sort the instances list
```
But there are two things that bother me:
* Is the... | Try the following:
```
result = Model.objects.filter(id__in=object_ids)
```
This returns all `Model` objects that have their `id` in the given list of `object_ids`. This way, you also don't need to append additional models to the resulting QuerySet. |
Django: Grab a set of objects from ID list (and sort by timestamp) | 9,845,952 | 8 | 2012-03-23T20:14:38Z | 9,846,003 | 14 | 2012-03-23T20:19:45Z | [
"python",
"database",
"django",
"model",
"django-queryset"
] | I have a list of IDs for objects that I need to grab, then I have to sort them by their timestamp. Here's how I was going to do it:
```
For i in object_ids:
instance = Model.objects.get(id = i)
# Append instance to list of instances
#sort the instances list
```
But there are two things that bother me:
* Is the... | This can be done using such a code:
```
objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp')
```
the `order_by` can be positive or negative `timestamp`, depending how you want it sorted. |
Plotting output of kmeans(PyCluster impl) | 9,847,026 | 8 | 2012-03-23T22:01:02Z | 9,849,186 | 15 | 2012-03-24T04:39:18Z | [
"python",
"cluster-analysis",
"k-means"
] | How does on plot output of kmeans clustering in python?
I am using PyCluster package.
allUserVector is an n by m dimensonal vector , basically n users with m features.
```
import Pycluster as pc
import numpy as np
clusterid,error,nfound = pc.kcluster(allUserVector, nclusters=3, transpose=0,npass=1,method='a',dist='e'... | It's kind of hard to plot `m`-dimensional data. One way to do it is to map into a 2d space through [Principal Component Analysis (PCA)](http://en.wikipedia.org/wiki/Principal_component_analysis). Once we've done that, we can throw them onto a plot with matplotlib (based on [this answer](http://stackoverflow.com/a/51474... |
which day of week given a date python | 9,847,213 | 176 | 2012-03-23T22:21:18Z | 9,847,250 | 18 | 2012-03-23T22:24:44Z | [
"python",
"datetime",
"weekday"
] | I want to find out the following:
given a date (`datetime` object), what is the corresponding day of the week.
For instance Sunday is the first day, Monday: second day.. and so on
And then if the input is something like Today's date.
The output is maybe `6` (since its Friday) | Use `date.weekday()` or `date.isoweekday()`. |
which day of week given a date python | 9,847,213 | 176 | 2012-03-23T22:21:18Z | 9,847,269 | 273 | 2012-03-23T22:26:41Z | [
"python",
"datetime",
"weekday"
] | I want to find out the following:
given a date (`datetime` object), what is the corresponding day of the week.
For instance Sunday is the first day, Monday: second day.. and so on
And then if the input is something like Today's date.
The output is maybe `6` (since its Friday) | Use `weekday()` ([docs](http://docs.python.org/library/datetime.html#datetime.date.weekday)):
```
>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)
>>> datetime.datetime.today().weekday()
4
```
From the documentation:
> Return the day of the week as an integer, wher... |
which day of week given a date python | 9,847,213 | 176 | 2012-03-23T22:21:18Z | 9,847,359 | 10 | 2012-03-23T22:36:21Z | [
"python",
"datetime",
"weekday"
] | I want to find out the following:
given a date (`datetime` object), what is the corresponding day of the week.
For instance Sunday is the first day, Monday: second day.. and so on
And then if the input is something like Today's date.
The output is maybe `6` (since its Friday) | I solved this for a codechef [question](http://www.codechef.com/TCTR2012/problems/NOPC10/).
```
import datetime
dt = '21/03/2012'
day, month, year = (int(x) for x in dt.split('/'))
ans = datetime.date(year, month, day)
print ans.strftime("%A")
``` |
which day of week given a date python | 9,847,213 | 176 | 2012-03-23T22:21:18Z | 17,120,430 | 13 | 2013-06-15T05:18:28Z | [
"python",
"datetime",
"weekday"
] | I want to find out the following:
given a date (`datetime` object), what is the corresponding day of the week.
For instance Sunday is the first day, Monday: second day.. and so on
And then if the input is something like Today's date.
The output is maybe `6` (since its Friday) | A solution whithout imports for dates after 1700/1/1
```
def weekDay(year, month, day):
offset = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
week = ['Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
... |
which day of week given a date python | 9,847,213 | 176 | 2012-03-23T22:21:18Z | 29,519,293 | 64 | 2015-04-08T15:43:58Z | [
"python",
"datetime",
"weekday"
] | I want to find out the following:
given a date (`datetime` object), what is the corresponding day of the week.
For instance Sunday is the first day, Monday: second day.. and so on
And then if the input is something like Today's date.
The output is maybe `6` (since its Friday) | If you'd like to have the date in English:
```
>>> from datetime import date
>>> import calendar
>>> my_date = date.today()
>>> calendar.day_name[my_date.weekday()]
'Wednesday'
``` |
pip search django produces time out error | 9,847,470 | 5 | 2012-03-23T22:50:48Z | 13,813,381 | 11 | 2012-12-11T03:55:17Z | [
"python",
"django",
"pip"
] | coincidentally, I run pip search django command and I got time out error. even specifing a high value of timeout
Below the logs:
```
D:\PERFILES\rmaceissoft\virtualenvs\fancy_budget\Scripts>pip search django --timeout=300
Exception:
Traceback (most recent call last):
File "D:\PERFILES\Marquez\rmaceissoft\Workspace\... | the --timeout option doesn't seem to work properly.
I can install django properly by using either:
```
pip --default-timeout=60 install django
```
or
```
export PIP_DEFAULT_TIMEOUT=60
pip install django
```
Note: using pip version 1.2.1 on RHEL 6.3
Source: [DjangoDay2012-Brescia.pdf, page 11](http://bitbucket.org... |
Removing items from a nested list Python | 9,847,615 | 7 | 2012-03-23T23:10:27Z | 9,847,643 | 9 | 2012-03-23T23:15:17Z | [
"python",
"python-2.7"
] | I am trying to remove items from a nested list in Python. I have a nested list as follows:
```
families = [[0, 1, 2],[0, 1, 2, 3],[0, 1, 2, 3, 4],[1, 2, 3, 4, 5],[2, 3, 4, 5, 6]]
```
I want to remove the entries in each sublist that coorespond to the indexed position of the sublist in the master list. So, for example... | You almost got it right. Just replace `families[i][j]` with `j` and it works:
```
>>> [ [ j for j in families[i] if i !=j ] for i in range(len(families)) ]
[[1, 2], [0, 2, 3], [0, 1, 3, 4], [1, 2, 4, 5], [2, 3, 5, 6]]
```
It can be written a bit cleaner using the `enumerate` function:
```
>>> [[f for f in family if ... |
Is there a function in like re.findall but that returns dictionaries instead of tuples? | 9,848,034 | 3 | 2012-03-24T00:22:20Z | 9,848,091 | 7 | 2012-03-24T00:32:27Z | [
"python",
"regex"
] | Supose I have this string:
```
a= "hello world hella warld"
```
and I want to match all coincidences whit the regex:
```
b='(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)'
```
I can use re.findall(b,a) and get:
```
[('hello', 'world'),('hella','warld')]
```
but I really want to get:
```
[{'hel':'hello','wrl':'world'},{'h... | You can use [`finditer`](http://docs.python.org/library/re.html#re.finditer) instead of `findall` to get an iterator of [`MatchObject`](http://docs.python.org/library/re.html#re.MatchObject)s:
```
>>> regex = re.compile('(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)')
>>> line = "hello world hella warld"
>>> [m.groupdict() fo... |
How to count the number of unique characters in a file? | 9,848,290 | 5 | 2012-03-24T01:13:04Z | 9,848,590 | 8 | 2012-03-24T02:18:28Z | [
"python",
"ruby",
"perl",
"bash"
] | Given a file in UTF-8, containing characters in various languages, how can I obtain a count of the number of unique characters it contains, while excluding a select number of symbols (e.g.: "!", "@", "#", ".") from this count? | Hereâs a bash solution. :)
```
bash$ perl -CSD -ne 'BEGIN { $s{$_}++ for split //, q(!@#.) }
$s{$_}++ || $c++ for split //;
END { print "$c\n" }' *.utf8
``` |
ImportError: No Module named xlwt | 9,848,299 | 8 | 2012-03-24T01:14:25Z | 9,848,348 | 11 | 2012-03-24T01:25:00Z | [
"python",
"importerror",
"python-import"
] | My sytem: Windows, Python 2.7
I downloaded a package and want to include it in my script.
After I unzipped the package, here is my folder structure:
* Work
+ xlwt-0.7.3 (contains a `setup.py`)
- xlwt (contains `__init__.py` among others)
My script runs from the top-level (Work) folder.
Using `import xlwt` in... | First off, try using easy\_install or pip to install it into your pythonpath:
```
easy_install xlwt
```
or
```
pip install xlwt
```
These are python package managers/installers and make the whole process so much easier. But if you have already downloaded it manually, you still need to install it:
```
python setup.... |
Set Popping (Python) | 9,848,693 | 8 | 2012-03-24T02:41:14Z | 9,848,713 | 14 | 2012-03-24T02:43:15Z | [
"python",
"set"
] | Lets say you have a set:
```
foo = {1, 2, 3, 4, 5}
```
In the book I am currently reading, Pro Python, it says that using `foo.pop()`will pop an arbitrary number from that selection. BUT...When I try it out, it `pops 1, then 2, then 3...`Does it do it arbitrarily, or is this just a coincidence? | The reason it says it is arbitrary is because there is no *guarantee* about the ordering it will pop out. Since you just created the set, it may be storing the elements in a "nice" order, and thus `.pop()` happens to return them in that order, but if you were to mutate the set, that might not continue to hold.
Example... |
Set Popping (Python) | 9,848,693 | 8 | 2012-03-24T02:41:14Z | 9,848,763 | 12 | 2012-03-24T02:54:34Z | [
"python",
"set"
] | Lets say you have a set:
```
foo = {1, 2, 3, 4, 5}
```
In the book I am currently reading, Pro Python, it says that using `foo.pop()`will pop an arbitrary number from that selection. BUT...When I try it out, it `pops 1, then 2, then 3...`Does it do it arbitrarily, or is this just a coincidence? | Set and dictionaries are implemented using hash tables. They are unordered collections, meaning that they have no guaranteed order.
The order you're seeing is a non-guaranteed implementation detail. In CPython, the hash value for an integer is the integer itself:
```
>>> [hash(i) for i in range(10)]
[0, 1, 2, 3, 4, 5... |
Sqlite3 - Update table using Python code - syntax error near %s | 9,848,697 | 9 | 2012-03-24T02:41:30Z | 9,848,731 | 16 | 2012-03-24T02:46:37Z | [
"python",
"sql",
"sqlite3"
] | This is my Python code -
```
cursor.execute("""UPDATE tasks SET task_owner=%s,task_remaining_hours=%s, task_impediments=%s,task_notes=%s WHERE task_id=%s""", (new_task_owner,new_task_remaining_hours,new_task_impediments,
new_task_notes,task_id))
```
This... | I believe Python's SQLite implementation uses `?` placeholders, unlike MySQLdb's `%s`. [Review the documentation.](http://docs.python.org/library/sqlite3.html)
```
cursor.execute("""UPDATE tasks SET task_owner = ? ,task_remaining_hours = ?,task_impediments = ?,task_notes = ? WHERE task_id= ? """,
(new_task_owner,new... |
sorting values of python dict using sorted builtin function | 9,849,192 | 6 | 2012-03-24T04:40:04Z | 9,849,223 | 11 | 2012-03-24T04:45:52Z | [
"python",
"sorting"
] | I need to get a sorted representation of a dict ,sorted in the descending order of values (largest value in dict to be shown first).
sample:
```
mydict={u'jon':30,u'den':26,u'rob':42,u'jaime':31}
```
I need to show them like
```
rob=42
jaime=31
jon=30
den=28
```
I tried this
```
from operator import itemgetter
so... | This is an interesting problem because you didn't cause an error like you would have if the keys were of another non-indexable type (say integers), and this is due to a subtle series of things:
1. sorted(mydict, ...) tries to iterate a dictionary using the equivalent of `iter(mydict)` which will call `mydict.__iter__(... |
How to set CFLAGS and LDFLAGS to compile pycrypto | 9,849,257 | 11 | 2012-03-24T04:55:37Z | 13,198,741 | 16 | 2012-11-02T15:53:47Z | [
"python",
"build",
"pip",
"fabric",
"pycrypto"
] | I am trying to install the fabric library to an old machine. There are some legacy libraries in /usr/lib, such as libgmp.
```
(py27)[qrtt1@hcservice app]$ ls /usr/lib|grep gmp
libgmp.a
libgmp.so
libgmp.so.3
libgmp.so.3.3.3
libgmpxx.a
libgmpxx.so
libgmpxx.so.3
libgmpxx.so.3.0.5
```
I have compiled the libgmp 5.x in my... | Please check what you have typed :
CFLAGS=-I/home/qrtt1/app/include LDFLAGS=-L/home/qrtt1/app/lib pip install pycrypto
it should be CFLAGS |
Cygwin Python 2.7 package | 9,850,022 | 11 | 2012-03-24T07:45:22Z | 9,850,189 | 7 | 2012-03-24T08:20:49Z | [
"python",
"cygwin"
] | I'm on Windows trying to run a Python script. The problem I'm facing is that this script requires Python 2.7. Cygwin is currently installed with the Python 2.6 package. I tried searching for a 2.7 package in the installation wizard but couldn't find any. So I'm kinda stuck. Does anybody have a solution? | Install python 2.7 from python.org or EPD, etc. Then put the location of python.exe (default is `C:\Python27\python.exe` ) in your Environment Variables (Right click "Computer" from `start menu -> select "properties" -> Environment Variables` )
and remove python 2.6 from cygwin, before you do all this. |
Cygwin Python 2.7 package | 9,850,022 | 11 | 2012-03-24T07:45:22Z | 14,806,050 | 7 | 2013-02-11T04:49:35Z | [
"python",
"cygwin"
] | I'm on Windows trying to run a Python script. The problem I'm facing is that this script requires Python 2.7. Cygwin is currently installed with the Python 2.6 package. I tried searching for a 2.7 package in the installation wizard but couldn't find any. So I'm kinda stuck. Does anybody have a solution? | 
Running setup.exe for Cygwin will give you the chance to upgrade Python to 2.7.
If you don't see the 2.7 package, go back and select a different mirror, since not all repositories have all versions available. |
how does a python program tell if it's being run within emacs? | 9,850,220 | 4 | 2012-03-24T08:26:50Z | 9,850,306 | 10 | 2012-03-24T08:41:42Z | [
"python",
"emacs"
] | I usually write python in emacs.
I'll often want to re-evaluate my file, which I can do with Ctrl-C Ctrl-C, which causes the interpreter to reload the entire file and then I can carry on playing.
so if I'm writing a program that takes input, I'll usually find myself with two lines:
```
lines = open("/home/jla/inputf... | Shells opened by emacs should have the environment variable `EMACS=t`. At least this works on my emacs, YMMV.
If that doesn't fly for you, here's how to find out what emacs-dependent environment variables python can see. Run from the shell and under emacs, and compare the outputs.
```
import os
for e in os.environ:
... |
bool value of a list in Python | 9,850,245 | 4 | 2012-03-24T08:33:07Z | 9,850,253 | 13 | 2012-03-24T08:34:24Z | [
"python",
"list",
"boolean"
] | what is the best way to turn a list into bool value? I am looking for something like:
```
return eval_bool(my_list)
```
I have a custom container in which I implement the `__nonzero__` method which is supposed to work like this:
```
if self.my_list:
return True
return False
```
But is it pythonic enough? :) Any... | Just use:
```
bool(my_list)
```
Which evaluates it as Python "truthiness" and returns a real Boolean. |
Flipping a function's argument order in Python | 9,850,259 | 5 | 2012-03-24T08:35:23Z | 9,850,282 | 9 | 2012-03-24T08:39:31Z | [
"python",
"functional-programming"
] | Nowadays, I am starting to learn haskell, and while I do it, I try to implement some of the ideas I have learned from it in Python. But, I found this one challenging. You can write a function in Haskell, that takes another function as argument, and returns the same function with it's arguments' order flipped. Can one d... | You can create a closure in Python using nested function definitions. This lets you create a new function that reverses the argument order and then calls the original function:
```
>>> from functools import wraps
>>> def flip(func):
'Create a new function from the original with the arguments reversed'
... |
Django error when installing Graphite - settings.DATABASES is improperly configured. Please supply the ENGINE value | 9,850,581 | 20 | 2012-03-24T09:29:33Z | 9,850,604 | 9 | 2012-03-24T09:33:27Z | [
"python",
"django",
"django-settings"
] | I am trying to install GRAPHITE on ubuntu. I follow the instructions in the blog.
```
http://geek.michaelgrace.org/2011/09/how-to-install-graphite-on-ubuntu/
```
When I get to the part where I run the command..I get the below error. I have zero clue on how to resolve. I am using the lastest version of Django 1.4.
``... | You need to edit `settings.py` and set the contents of the `DATABASES` variable to something other than empty strings. There are comments next to it that tell you which database engines are supported:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', ... |
Django error when installing Graphite - settings.DATABASES is improperly configured. Please supply the ENGINE value | 9,850,581 | 20 | 2012-03-24T09:29:33Z | 12,456,878 | 14 | 2012-09-17T09:53:08Z | [
"python",
"django",
"django-settings"
] | I am trying to install GRAPHITE on ubuntu. I follow the instructions in the blog.
```
http://geek.michaelgrace.org/2011/09/how-to-install-graphite-on-ubuntu/
```
When I get to the part where I run the command..I get the below error. I have zero clue on how to resolve. I am using the lastest version of Django 1.4.
``... | [graphite version 0.9.10 supports Django 1.4](https://bugs.launchpad.net/graphite/+bug/963684)... however they put the sqlite settings in django's `local_settings.py`
```
[mpenning@tsunami graphite]$ cat local_settings.py|grep -v \#
DATABASES = {
'default': {
'NAME': '/opt/graphite/storage/graphite.db',
... |
Django error when installing Graphite - settings.DATABASES is improperly configured. Please supply the ENGINE value | 9,850,581 | 20 | 2012-03-24T09:29:33Z | 17,175,509 | 9 | 2013-06-18T17:44:41Z | [
"python",
"django",
"django-settings"
] | I am trying to install GRAPHITE on ubuntu. I follow the instructions in the blog.
```
http://geek.michaelgrace.org/2011/09/how-to-install-graphite-on-ubuntu/
```
When I get to the part where I run the command..I get the below error. I have zero clue on how to resolve. I am using the lastest version of Django 1.4.
``... | For users landing here with the error message "The SECRET\_KEY setting must not be empty", make sure to set the secret key in /opt/graphite/webapp/graphite/app\_settings.py as well as in your django config. |
Tracking *maximum* memory usage by a Python function | 9,850,995 | 17 | 2012-03-24T10:32:38Z | 10,117,657 | 15 | 2012-04-12T05:05:13Z | [
"python",
"memory",
"profiling"
] | I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage:
[Python memory profiler](http://stackoverflow.com/questions/110259/python-memory-profiler)
[How do I profile memory usage in Python?](http://stackove... | This question seemed rather interesting and it gave me a reason to look into Guppy / Heapy, for that I thank you.
I tried for about 2 hours to get Heapy to do monitor a function call / process without modifying its source with *zero* luck.
I did find a way to accomplish your task using the built in Python library [`r... |
Tracking *maximum* memory usage by a Python function | 9,850,995 | 17 | 2012-03-24T10:32:38Z | 15,682,871 | 7 | 2013-03-28T13:16:07Z | [
"python",
"memory",
"profiling"
] | I want to find out what the maximum amount of RAM allocated during the call to a function is (in Python). There are other questions on SO related to tracking RAM usage:
[Python memory profiler](http://stackoverflow.com/questions/110259/python-memory-profiler)
[How do I profile memory usage in Python?](http://stackove... | It is possible to do this with [memory\_profiler](https://pypi.python.org/pypi/memory_profiler). The function `memory_usage` returns a list of values, these represent the memory usage over time (by default over chunks of .1 second). If you need the maximum, just take the max of that list. Little example:
```
from memo... |
Tokenizing large (>70MB) TXT file using Python NLTK. Concatenation & write data to stream errors | 9,853,227 | 5 | 2012-03-24T16:12:31Z | 9,853,288 | 9 | 2012-03-24T16:20:11Z | [
"python",
"nltk",
"tokenize"
] | First of all, I am new to python/nltk so my apologies if the question is too basic. I have a large file that I am trying to tokenize; I get memory errors.
One solution I've read about is to read the file one line at a time, which makes sense, however, when doing that, I get the error `cannot concatenate 'str' and 'lis... | Problem n°1: You are iterating the file char by char like that. If you want to read every line efficiently simply open the file (don't read it) and iterate over file.readlines() as follows.
Problem n°2: The word\_tokenize function returns a list of tokens, so you were trying to sum a str to a list of tokens. You fir... |
Using Python's max to return two equally large values | 9,853,302 | 7 | 2012-03-24T16:21:26Z | 9,853,368 | 12 | 2012-03-24T16:30:14Z | [
"python",
"dictionary",
"max"
] | I'm using python's [max](http://docs.python.org/library/functions.html#max) function to find the largest integer in a dictionary called count, and the corresponding key (not quite sure if I'm saying it properly; my code probably explains itself better than I'm explaining it). The dictionary "count" is along the lines o... | Idea is to find max value and get all keys corresponding to that value:
```
count = { 'a': 120, 'b': 120, 'c': 100 }
highest = max(count.values())
print [k for k,v in count.items() if v == highest]
``` |
creating a class that behaves like any variable but has callback on change/read | 9,854,003 | 4 | 2012-03-24T17:47:23Z | 9,854,064 | 8 | 2012-03-24T17:53:47Z | [
"python",
"class",
"callback",
"variable-assignment",
"descriptor"
] | I would like to create a class that behaves as a python variable but calls some callback function when the "variable" is changed/read.
In other words, I'd like to be able to use the class as follows:
```
x=myClass(change_callback, read_callback)
```
defines x as an instance of myclass. The constructor (**INIT**) tak... | Objects don't know when they get assigned to a variable. Writing `x = a` adds a dict entry (or locals entry) that points to *a*. The *a* object doesn't get notified (though, in CPython, its reference count gets incremented).
The part that does get notified is the container where the object is assigned. In the case of ... |
Python curses dilemma | 9,854,511 | 8 | 2012-03-24T18:51:20Z | 9,854,532 | 9 | 2012-03-24T18:53:51Z | [
"python",
"ncurses",
"curses"
] | I'm playing around a little with Python and curses.
When I run
```
import time
import curses
def main():
curses.initscr()
curses.cbreak()
for i in range(3):
time.sleep(1)
curses.flash()
pass
print( "Hello World" )
curses.endwin()
if __name__ == '__main__':
main()
```
... | You could do this:
```
def main():
curses.initscr()
try:
curses.cbreak()
for i in range(3):
time.sleep(1)
curses.flash()
pass
print( "Hello World" )
finally:
curses.endwin()
```
Or more nicely, make a context wrapper:
```
class CursesWi... |
Python curses dilemma | 9,854,511 | 8 | 2012-03-24T18:51:20Z | 14,921,704 | 37 | 2013-02-17T13:43:29Z | [
"python",
"ncurses",
"curses"
] | I'm playing around a little with Python and curses.
When I run
```
import time
import curses
def main():
curses.initscr()
curses.cbreak()
for i in range(3):
time.sleep(1)
curses.flash()
pass
print( "Hello World" )
curses.endwin()
if __name__ == '__main__':
main()
```
... | I believe you are looking for curses.wrapper
See <http://docs.python.org/dev/library/curses.html#curses.wrapper>
It will do curses.cbreak(), curses.noecho() and curses\_screen.keypad(1) on init and reverse them on exit, even if the exit was an exception.
Your program goes as a function to the wrapper, example:
```
d... |
How to change text/font color in reportlab.pdfgen | 9,855,445 | 9 | 2012-03-24T20:43:40Z | 10,247,952 | 8 | 2012-04-20T14:12:26Z | [
"python",
"reportlab"
] | I want to use a different color of text in my auto-generated PDF.
According to [the reportlab docs](http://www.reportlab.com/software/opensource/rl-toolkit/faq/#2.1.4) all I need to do is:
```
self.canvas.setFillColorRGB(255,0,0)
self.canvas.drawCentredString(...)
```
But that doesn't do anything. The text is black ... | If you copy and paste the code in User Guide Section 2. You'll get a fancy coloured rectangle with a coloured Text within it. Probably the approach is not that clear in the user guide, I'd spent some time playing with it and I finally know how it works.
You need to imagine yourself drawing a canvas. You need to do all... |
Python GTK3 Treeview buttons | 9,855,671 | 7 | 2012-03-24T21:14:04Z | 9,861,209 | 7 | 2012-03-25T15:10:31Z | [
"python",
"ubuntu",
"gtk"
] | With GTK3 some Treeviews (I presume) have a few buttons at the bottom that appear to be part of it. The System Settings in Ubuntu uses this, as well as the File Selector dialog for GTK3 apps

Is this a part of GTK3 or just a specially made container? | In case anyone else comes here, the buttons are ToolButtons in a Toolbar with the "inline-toolbar" class
```
self.listTools=Gtk.Toolbar()
self.listTools.set_property("icon_size",1)
context=self.listTools.get_style_context()
context.add_class("inline-toolbar")
self.addButton=Gtk.ToolButton()
self.addButton.set_propert... |
using lxml and iterparse() to parse a big (+- 1Gb) XML file | 9,856,163 | 7 | 2012-03-24T22:25:20Z | 9,856,378 | 13 | 2012-03-24T22:53:58Z | [
"python",
"xml",
"parsing",
"lxml",
"iterparse"
] | I have to parse a 1Gb XML file with a structure such as below and extract the text within the tags "Author" and "Content":
```
<Database>
<BlogPost>
<Date>MM/DD/YY</Date>
<Author>Last Name, Name</Author>
<Content>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dictum dictu... | ```
for event, element in etree.iterparse(path_to_file, tag="BlogPost"):
for child in element:
print child.tag, child.text
element.clear()
```
the final clear will stop you from using too much memory.
[update:] to get "everything between ... as a string" i guess you want one of:
```
for event, elemen... |
casting ints to str in Jinja2 | 9,856,576 | 16 | 2012-03-24T23:23:21Z | 9,856,693 | 17 | 2012-03-24T23:43:46Z | [
"python",
"jinja2"
] | I want to cast an int that's passed to the template through the url, but it says that the `str` function isn't defined.
How do I get around this?
Here's my code:
```
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% set year = post.date.year %}
{% set month = post.date.month %}
... | Jinja2 also defines the `~` operator, which automatically converts arguments to string first, as an alternative to the `+` operator.
Example:
```
{% set p = year ~ '/' ~ month ~ '/' ~ day ~ '/' ~ post.slug %}
```
See [Other operators](http://jinja.pocoo.org/docs/templates/#other-operators) or, if you really want to ... |
casting ints to str in Jinja2 | 9,856,576 | 16 | 2012-03-24T23:23:21Z | 19,993,378 | 8 | 2013-11-15T04:09:56Z | [
"python",
"jinja2"
] | I want to cast an int that's passed to the template through the url, but it says that the `str` function isn't defined.
How do I get around this?
Here's my code:
```
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% set year = post.date.year %}
{% set month = post.date.month %}
... | To cast to a string in an expression, you use `x|string()` instead of `str(x)`.
`string()` is an example of a filter, and there are several useful filters that it's worth learning about. |
Using Python's os.path, how do I go up one directory? | 9,856,683 | 97 | 2012-03-24T23:41:31Z | 9,856,725 | 128 | 2012-03-24T23:48:40Z | [
"python",
"django"
] | I recently upgrade Django from v1.3.1 to v1.4.
In my old `settings.py` I have
```
TEMPLATE_DIRS = (
os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.... | ```
os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'templates'))
```
As far as where the templates folder should go, I don't know since Django 1.4 just came out and I haven't looked at it yet. You should probably ask another question on SE to solve that issue.
You can also use `normpath` to clean up ... |
Using Python's os.path, how do I go up one directory? | 9,856,683 | 97 | 2012-03-24T23:41:31Z | 9,856,735 | 34 | 2012-03-24T23:49:49Z | [
"python",
"django"
] | I recently upgrade Django from v1.3.1 to v1.4.
In my old `settings.py` I have
```
TEMPLATE_DIRS = (
os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.... | To get the folder of a file just use :
```
os.path.dirname(path)
```
To get a folder up just use `os.path.dirname` again
```
os.path.dirname(os.path.dirname(path))
```
You might want to check if `__file__` is a symlink :
```
if os.path.islink(__file__): path = os.readlink (__file__)
``` |
Using Python's os.path, how do I go up one directory? | 9,856,683 | 97 | 2012-03-24T23:41:31Z | 12,310,647 | 9 | 2012-09-07T01:36:53Z | [
"python",
"django"
] | I recently upgrade Django from v1.3.1 to v1.4.
In my old `settings.py` I have
```
TEMPLATE_DIRS = (
os.path.join(os.path.dirname( __file__ ), 'templates').replace('\\', '/'),
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.... | You want exactly this:
```
BASE_DIR = os.path.join( os.path.dirname( __file__ ), '..' )
``` |
Encode Decode of strings python | 9,856,990 | 5 | 2012-03-25T00:43:30Z | 9,857,069 | 7 | 2012-03-25T00:58:47Z | [
"python",
"character-encoding",
"decode",
"encode"
] | I have a list of html pages which may contain certain encoded characters. Some examples are as below -
```
<a href="mailto:lad%20at%20maestro%20dot%20com">
<em>ada@graphics.maestro.com</em>
<em>mel@graphics.maestro.com</em>
```
I would like to decode (escape, I'm unsure of the current terminology) these str... | You need to unescape HTML entities, and URL-unquote.
The standard library has [`HTMLParser`](http://docs.python.org/library/htmlparser.html?highlight=htmlparser#HTMLParser) and [`urllib2`](http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2) to help with those tasks.
```
import HTMLParser, urllib2
... |
Assigning multiple lines of a file to multiple variables using .readline() while in a "for line in data" loop | 9,857,104 | 2 | 2012-03-25T01:05:09Z | 9,857,250 | 10 | 2012-03-25T01:41:26Z | [
"python",
"file-io",
"for-loop",
"python-3.x"
] | I'm trying to use a `for line in data:` loop to assign the first 3 lines of a file to 3 different variables (one line to each variable) and have it iterate for every 3 lines, so that if there were 9 lines in the file, each variable would contain 3 different lines throughout the iterations, but I cannot figure it out wh... | You don't actually need to call `readline`, just iterating over the file is enough. You can use the [`zip`](http://docs.python.org/py3k/library/functions.html#zip) function to regroup the lines. Therefore, the generic solution would look like
```
for odd_line,even_line in zip(infile, infile):
# Do something
```
... |
Python 3.2 won't import cookielib | 9,857,677 | 3 | 2012-03-25T03:17:31Z | 9,857,747 | 7 | 2012-03-25T03:37:13Z | [
"python"
] | I have looked everywhere for this and just cannot find the answer. I have checked my python version and it is version 3.2 . When I try to import `cookielib` I receive:
`ImportError: No module named cookielib`
I have seen that in Python 3.0 it was renamed to
`http.cookiejar` and that it would auto import `cookielib`.
... | The *automatic renaming* business only applies if you use [2to3](http://docs.python.org/glossary.html#term-to3). Therefore, you have to `import http.cookiejar`.
The error `EOFError: EOF read where not expected` is only ever thrown by Python marshalling. Most likely, this is caused by a race condition [fixed in Python ... |
Creating a dictionary with list of lists in Python | 9,858,096 | 7 | 2012-03-25T05:20:53Z | 9,858,111 | 10 | 2012-03-25T05:26:59Z | [
"python",
"list",
"dictionary"
] | I have a huge file (with around 200k inputs). The inputs are in the form:
```
A B C D
B E F
C A B D
D
```
I am reading this file and storing it in a list as follows:
```
text = f.read().split('\n')
```
This splits the file whenever it sees a new line. Hence text is like follows:
```
[[A B C D] [B E F] [C A B D] [D... | Try using a slice:
```
inlinkDict[docid] = adoc[1:]
```
This will give you an empty list instead of a 0 for the case where only the key value is on the line. To get a 0 instead you could use conditional assignment:
```
inlinkDict[docid] = adoc[1:] if adoc[1:] else 0
```
---
Easier way with a dict comprehension:
`... |
Creating a dictionary with list of lists in Python | 9,858,096 | 7 | 2012-03-25T05:20:53Z | 9,858,171 | 11 | 2012-03-25T05:43:59Z | [
"python",
"list",
"dictionary"
] | I have a huge file (with around 200k inputs). The inputs are in the form:
```
A B C D
B E F
C A B D
D
```
I am reading this file and storing it in a list as follows:
```
text = f.read().split('\n')
```
This splits the file whenever it sees a new line. Hence text is like follows:
```
[[A B C D] [B E F] [C A B D] [D... | A dictionary comprehension makes short work of this task:
```
>>> s = [['A','B','C','D'], ['B','E','F'], ['C','A','B','D'], ['D']]
>>> {t[0]:t[1:] for t in s}
{'A': ['B', 'C', 'D'], 'C': ['A', 'B', 'D'], 'B': ['E', 'F'], 'D': []}
``` |
Python: Using exception for iteration (beginner) | 9,858,344 | 3 | 2012-03-25T06:31:34Z | 9,858,346 | 7 | 2012-03-25T06:32:30Z | [
"python",
"iteration"
] | I just want to know why this doesn't work
(I am trying to name the ducklings from a book: Jack, Kack, Lack, Mack, Nack, Ouack, Pack, Quack) Note: Quack and Ouack have a U
```
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
if letter != 'O' or 'Q': #I know this doesn't work, need to know alternat... | You likely mean this:
```
if letter != 'O' or letter != 'Q':
```
The result of your original statement,
```
if letter != 'O' or 'Q':
```
compared `letter` to the result of `'O' or 'Q'`, which is a boolean (true to be exact) (so you could see why this comparison would always be true as it was). |
what's the difference between string method and str method in Python? | 9,858,568 | 5 | 2012-03-25T07:29:08Z | 9,858,591 | 7 | 2012-03-25T07:34:42Z | [
"python",
"string",
"methods"
] | String is a module and str is a type.
I found str have methods, and some of str's methods are the same with string.
```
>>>dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__has... | `string` is a deprecated module now. You should use `str` object always.
```
>>> help(str)
Help on class str in module __builtin__:
class str(basestring)
| str(object) -> string
|
| Return a nice string representation of the object.
| If the argument is a string, the return value is the same object.
.
.
>>>h... |
Finding minimum, maximum and average values for nested lists? | 9,858,739 | 5 | 2012-03-25T08:12:22Z | 9,858,781 | 9 | 2012-03-25T08:19:18Z | [
"python",
"list"
] | So I have these lists:
```
Player1 = ["Ryan", 24, 19]
Player2 = ["Jamie", 22, 24]
Player3 = ["Alicia", 17, 15]
Player4 = ["Dominique", 13, 11]
Player5 = ["Michael", 18, 23]
PlayerList = [Player1, Player2, Player3, Player4, Player5]
```
The format is [Player's name, first round score, second round score]
How to writ... | Highest value:
```
max(max(p[1:]) for p in PlayerList)
```
Lowest value:
```
min(min(p[1:]) for p in PlayerList)
```
Averages for each player::
```
[float(p[1] + p[2]) / 2 for p in PlayerList]
```
ETA: Per your comment, the name of the player with the highest score:
```
max(PlayerList, key=lambda p: max(p[1:]))[... |
How to implement normal site registration/login together with social authentication(mainly facebook) in Django? | 9,859,046 | 2 | 2012-03-25T09:14:44Z | 9,860,973 | 7 | 2012-03-25T14:34:11Z | [
"python",
"django",
"authentication"
] | I'm a newbie in Django and I'm trying to port my vanilla php application to Python/Django. In my project, I want to let users authenticate using regular registration/login form or through social authentications like facebook, google and twitter.
I searched on google and stackoverflow for similar questions and came to ... | [`django-social-auth`](https://github.com/omab/django-social-auth) is fantastic, has [a good support community](https://groups.google.com/forum/?fromgroups#!forum/django-social-auth) and is very quick to set up. You can run it easily alongside regular auth and will also work nicely alongside [`django-registration`](htt... |
Maximum value for long integer | 9,860,588 | 43 | 2012-03-25T13:41:55Z | 9,860,611 | 63 | 2012-03-25T13:45:34Z | [
"python"
] | How can I assign the maximum value for a long integer to a variable, similar, for example, to C++'s `LONG_MAX`. | ## Long integers:
There is no explicitly defined limit. The amount of available address space forms a practical limit.
(Taken from [this](http://bytes.com/topic/python/answers/761897-max-long) site). See the docs on [Numeric Types](http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex) ... |
Maximum value for long integer | 9,860,588 | 43 | 2012-03-25T13:41:55Z | 9,860,639 | 7 | 2012-03-25T13:49:18Z | [
"python"
] | How can I assign the maximum value for a long integer to a variable, similar, for example, to C++'s `LONG_MAX`. | `long` type in Python 2.x uses [arbitrary precision arithmetic](http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) and has no such thing as maximum possible value. It is limited by the available memory. Python 3.x has no special type for values that cannot be represented by the native machine integer â ever... |
Maximum value for long integer | 9,860,588 | 43 | 2012-03-25T13:41:55Z | 9,860,722 | 22 | 2012-03-25T14:01:58Z | [
"python"
] | How can I assign the maximum value for a long integer to a variable, similar, for example, to C++'s `LONG_MAX`. | Python `long`s can be arbitrarily large. If you need a value that's greater than any other value, you can use `float('inf')`, since Python has no trouble comparing numeric values of different types. |
Maximum value for long integer | 9,860,588 | 43 | 2012-03-25T13:41:55Z | 9,860,812 | 15 | 2012-03-25T14:14:21Z | [
"python"
] | How can I assign the maximum value for a long integer to a variable, similar, for example, to C++'s `LONG_MAX`. | ### Direct answer to title question:
Integers are unlimited in size and have no maximum value in Python.
### Answer which addresses stated underlying use case:
According to your comment of what you're trying to do, you are currently thinking something along the lines of
```
minval = MAXINT;
for (i = 1; i < num_elem... |
writing robust (color and size invariant) circle detection with opencv (based on Hough transform or other features) | 9,860,667 | 34 | 2012-03-25T13:52:53Z | 9,873,184 | 7 | 2012-03-26T13:37:47Z | [
"c++",
"python",
"c",
"opencv",
"computer-vision"
] | I wrote the following very simple python code to find circles in an image:
```
import cv
import numpy as np
WAITKEY_DELAY_MS = 10
STOP_KEY = 'q'
cv.NamedWindow("image - press 'q' to quit", cv.CV_WINDOW_AUTOSIZE);
cv.NamedWindow("post-process", cv.CV_WINDOW_AUTOSIZE);
key_pressed = False
while key_pressed != STOP_KE... | Looking through your code, I noticed the following:
* Greyscale conversion. I understand why you're doing it, but realize that you're throwing
away information there. As you see in the "post-process" images, your yellow circles are
the same intensity as the background, just in a different color.
* Edge detection a... |
writing robust (color and size invariant) circle detection with opencv (based on Hough transform or other features) | 9,860,667 | 34 | 2012-03-25T13:52:53Z | 10,128,487 | 9 | 2012-04-12T17:14:55Z | [
"c++",
"python",
"c",
"opencv",
"computer-vision"
] | I wrote the following very simple python code to find circles in an image:
```
import cv
import numpy as np
WAITKEY_DELAY_MS = 10
STOP_KEY = 'q'
cv.NamedWindow("image - press 'q' to quit", cv.CV_WINDOW_AUTOSIZE);
cv.NamedWindow("post-process", cv.CV_WINDOW_AUTOSIZE);
key_pressed = False
while key_pressed != STOP_KE... | Ah, yes⦠the old colour/size invariants for circles problem (AKA the Hough transform is too specific and not robust)...
In the past I have relied much more on the [structural and shape analysis](http://opencv.willowgarage.com/documentation/python/structural_analysis_and_shape_descriptors.html) functions of OpenCV in... |
writing robust (color and size invariant) circle detection with opencv (based on Hough transform or other features) | 9,860,667 | 34 | 2012-03-25T13:52:53Z | 10,145,273 | 17 | 2012-04-13T17:12:41Z | [
"c++",
"python",
"c",
"opencv",
"computer-vision"
] | I wrote the following very simple python code to find circles in an image:
```
import cv
import numpy as np
WAITKEY_DELAY_MS = 10
STOP_KEY = 'q'
cv.NamedWindow("image - press 'q' to quit", cv.CV_WINDOW_AUTOSIZE);
cv.NamedWindow("post-process", cv.CV_WINDOW_AUTOSIZE);
key_pressed = False
while key_pressed != STOP_KE... | This is a great modelling problem. I have the following recommendations/ ideas:
1. Split the image to RGB then process.
2. pre-processing.
3. Dynamic parameter search.
4. Add constraints.
5. Be sure about what you are trying to detect.
In more detail:
1: As noted in other answers, converting straight to grayscale di... |
writing robust (color and size invariant) circle detection with opencv (based on Hough transform or other features) | 9,860,667 | 34 | 2012-03-25T13:52:53Z | 10,169,822 | 28 | 2012-04-16T06:54:12Z | [
"c++",
"python",
"c",
"opencv",
"computer-vision"
] | I wrote the following very simple python code to find circles in an image:
```
import cv
import numpy as np
WAITKEY_DELAY_MS = 10
STOP_KEY = 'q'
cv.NamedWindow("image - press 'q' to quit", cv.CV_WINDOW_AUTOSIZE);
cv.NamedWindow("post-process", cv.CV_WINDOW_AUTOSIZE);
key_pressed = False
while key_pressed != STOP_KE... | The following is based on my experience as a vision researcher. From your question you seem to be interested in possible algorithms and methods rather only a working piece of code. First I give a quick and dirty Python script for your sample images and some results are shown to prove it could possibly solve your proble... |
python overwrite previous line | 9,860,680 | 7 | 2012-03-25T13:55:06Z | 9,860,758 | 13 | 2012-03-25T14:06:52Z | [
"python",
"python-2.7",
"printing",
"overwrite",
"pi"
] | how do you overwrite the previous print in python 2.7?
I am making a simple program to calculate pi. here is the code:
```
o = 0
hpi = 1.0
i = 1
print "pi calculator"
acc= int(raw_input("enter accuracy:"))
if(acc>999999):
print "WARNING: this might take a VERY long time. to terminate, press CTRL+Z"
print "prec... | Prefix your output with carriage return symbol `'\r'` and do not end it with line feed symbol `'\n'`. This will place cursor at the beginning of the current line, so output will overwrite previous its content. Pad it with some trailing blank space to guarantee overwrite. E.g.
```
sys.stdout.write('\r' + str(hpi) + ' '... |
How do I make Appstats work using Python 2.7 threadsafe and webapp2? | 9,860,793 | 3 | 2012-03-25T14:12:04Z | 9,862,778 | 7 | 2012-03-25T18:25:57Z | [
"python",
"google-app-engine"
] | My app uses the threadsafe version of python 2.7 and I would like to use Appstats with it.
I currently let the runtime container instantiate my app using `webapp2.WSGIApplication()` and unfortunately none of my modules are picked up in Appstats.
However, if I follow these <http://code.google.com/appengine/docs/python... | I found that if I enabled appstates in app.yaml along with create the appengine\_config.py file it seems to me it works with anything I throw at it.
app.yaml
```
builtins:
- admin_redirect: on
- appstats: on
```
appengine\_config.py:
```
def webapp_add_wsgi_middleware(app):
from google.appengine.ext.appstat... |
play sound file in PyQt | 9,861,592 | 2 | 2012-03-25T16:00:28Z | 9,861,622 | 8 | 2012-03-25T16:03:22Z | [
"python",
"audio",
"pyqt"
] | I've developed a software in PyQt which plays sound.I'm using Phonon Library to play the sound but it has some lag.So how can I play a sound file in PyQt without using Phonon Library.
This is how I am currently using Phonon:
```
def Playnote(self,note_id):
global note
note = note_id
self.PlayThread = ... | *I have rewritten this answer since I think your question has begun to diverge*
**First, addressing your code examples**
In your first PlayThread example, you are starting a new thread every single time you want to play a key, which then has to completely set up a media player, and open the source file, and then play... |
SQLAlchemy: How to order query results (order_by) on a relationship's field? | 9,861,990 | 10 | 2012-03-25T16:45:36Z | 9,862,111 | 20 | 2012-03-25T17:00:47Z | [
"python",
"sqlalchemy",
"sql-order-by",
"field",
"relationship"
] | # Models
```
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import TIMESTAMP
from sqlalchemy.orm import relationship
BaseModel = declarative_base()
class Base(BaseModel):
__tablename__ ... | SQLAlchemy wants you to think in terms of SQL. If you do a query for "Base", that's:
```
SELECT * FROM base
```
easy. So how, in SQL, would you select the rows from "base" and order by the "name" column in a totally different table, that is, "player"? You use a join:
```
SELECT base.* FROM base JOIN player ON base.o... |
Python UDP client/server program, problems | 9,862,762 | 9 | 2012-03-25T18:23:04Z | 9,862,900 | 14 | 2012-03-25T18:40:53Z | [
"python",
"sockets",
"udp"
] | I'm trying to write a basic client/server echo program, to test the usage of timers for retransmission based on select() (though I had to comment out that bit to simplify debugging when it wasn't working as intended). Here are snippets of the relevant code:
Server:
```
from socket import *
import sys
import select
ad... | You have to send to addr instead of address.
```
from socket import *
import sys
import select
address = ('localhost', 6005)
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(address)
while(1):
print "Listening"
recv_data, addr = server_socket.recvfrom(2048)
print recv_data
if recv_data =... |
Vim and PEP 8 -- Style Guide for Python Code | 9,864,543 | 22 | 2012-03-25T22:10:13Z | 9,864,621 | 15 | 2012-03-25T22:20:53Z | [
"python",
"vim",
"coding-style"
] | Could you recommend, how to configure Vim to stick to :
[PEP 8 -- Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)
when editing python2/3 files, and only those (I'd like to leave configuration as it is for all other filetypes). | There's [vim-flake8](https://github.com/nvie/vim-flake8), which is most easily set up using [vim-pathogen](https://github.com/tpope/vim-pathogen) or [Vundle](https://github.com/gmarik/vundle). |
Vim and PEP 8 -- Style Guide for Python Code | 9,864,543 | 22 | 2012-03-25T22:10:13Z | 9,878,565 | 9 | 2012-03-26T19:39:10Z | [
"python",
"vim",
"coding-style"
] | Could you recommend, how to configure Vim to stick to :
[PEP 8 -- Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)
when editing python2/3 files, and only those (I'd like to leave configuration as it is for all other filetypes). | # As of 2014
Using [syntastic](https://github.com/scrooloose/syntastic) plus installing `pip install flake8` gives you the best experience IMHO. `syntastic` is great, because it not only does pep8 checks for Python, but by installing other software it's really easy to add syntax checks and the like for other languages... |
Vim and PEP 8 -- Style Guide for Python Code | 9,864,543 | 22 | 2012-03-25T22:10:13Z | 18,834,661 | 9 | 2013-09-16T18:18:52Z | [
"python",
"vim",
"coding-style"
] | Could you recommend, how to configure Vim to stick to :
[PEP 8 -- Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)
when editing python2/3 files, and only those (I'd like to leave configuration as it is for all other filetypes). | The answers are focusing on checking the style after source code has been written but the question seems to be about making vim stick to the pep8 style during editing *itself*.
The main problem I've had with vim and pep8 is indentation, which can be fixed using this vim script:
EDIT3: Fix the terrible English...
EDI... |
How to tell Condor to dispatch jobs only to machines on the cluster, that have "numpy" installed on them? | 9,864,766 | 11 | 2012-03-25T22:45:32Z | 9,936,104 | 7 | 2012-03-30T02:13:23Z | [
"python",
"cluster-computing",
"job-scheduling",
"condor"
] | I just figured out how to send jobs to be processed on machines on the cluster by using [Condor](http://research.cs.wisc.edu/condor/). Since we have a lot of machines and not each of those machines are configured the same, I was wondering:
**Is it possible to tell condor only to dispatch my jobs (python scripts) to ma... | Like any other machine attribute, you just need to advertise it in the machine classad, and then have your jobs require it.
To advertise it in the machine classad, you can either hard-code it into each machine's condor config file by adding something like this:
```
has_numpy = True
STARTD_EXPRS = $(STARTD_EXPRS) HAS_... |
How to install custom SQL with Django | 9,865,974 | 5 | 2012-03-26T02:39:32Z | 14,493,214 | 8 | 2013-01-24T03:00:13Z | [
"python",
"sql",
"django"
] | What's the best way to deploy custom SQL for views used by unmanaged Django models?
I have a model myapp.models.MyModel using a view myview.sql, specified in the models "db\_table" meta attribute. So, following [the docs](https://docs.djangoproject.com/en/dev/howto/initial-data/#database-backend-specific-sql-data), I ... | `python manage.py sqlcustom` will only output the custom SQL statements that you've defined, but you need to execute them in the database. Of course, you can copy and paste, but if you want to automate the process and have it be less tedious/error-prone, one easy way to do so (at least on a \*nix environment) is to use... |
How to do a DetailView of Users in Django? | 9,867,391 | 7 | 2012-03-26T06:11:01Z | 9,867,610 | 11 | 2012-03-26T06:33:10Z | [
"python",
"django",
"django-templates",
"django-urls"
] | I currently have a `DetailView` for Django's built-in `User`.
```
url(
r'^users/(?P<pk>\d+)/$',
DetailView.as_view(
model = User,
template_name = 'doors/users/detail.html'
),
name = 'users_detail'
)
```
But when I access `user` in the template, it brings up the current *logged in* user... | The django.contrib.auth.context\_processors.auth sets the `{{ user }}` template context variable to either request.user or AnonymousUser. So, it overrides the `{{ user }}` context variable created by your DetailView:
```
def auth(request):
"""
Returns context variables required by apps that use Django's authen... |
pass **kwargs argument to another function with **kwargs | 9,867,562 | 53 | 2012-03-26T06:28:16Z | 9,867,675 | 56 | 2012-03-26T06:38:26Z | [
"python"
] | I do not understand the following example, lets say I have these functions:
```
# python likes
def save(filename, data, **kwargs):
fo = openX(filename, "w", **kwargs) # <- #1
fo.write(data)
fo.close()
# python doesnt like
def save2(filename, data, **kwargs):
fo = openX(filename, "w", kwargs) # <- #2
... | In the second example you provide 3 arguments: filename, mode and a dictionary (`kwargs`). But Python expects: 2 formal arguments plus keyword arguments.
By prefixing the dictionary by '\*\*' you unpack the dictionary `kwargs` to keywords arguments.
A dictionary (type `dict`) is a single variable containing key-value... |
Eclipse how to change default font for python code? | 9,868,711 | 10 | 2012-03-26T08:16:52Z | 9,871,632 | 16 | 2012-03-26T11:56:57Z | [
"python",
"eclipse",
"pydev"
] | In Eclipse, how can I change default font for python code in editor (PyDev plugin)? I navigate to Window - Preference - General - Appearance - Colors & Fonts but don't find which item would affect python code font. | I guess you are using [PyDdev](http://pydev.org/)?
Then you should have a look at Window -> Preferences -> PyDev -> Editor
([PyDev Editor Preferences](http://pydev.org/manual_adv_editor_prefs.html)) |
Find out the unicode script of a character | 9,868,792 | 15 | 2012-03-26T08:25:07Z | 9,871,358 | 13 | 2012-03-26T11:34:37Z | [
"python",
"unicode"
] | Given a unicode character what would be the simplest way to return its [script](http://en.wikipedia.org/wiki/Script_%28Unicode%29) (as "Latin", "Hangul" etc)? [unicodedata](http://docs.python.org/library/unicodedata.html#module-unicodedata) doesn't seem to provide this kind of feature. | I was hoping someone's done it before, but apparently not, so here's what I've ended up with. The module below (I call it `unicodedata2`) extends `unicodedata` and provides `script_cat(chr)` which returns a tuple (Script name, Caterogy) for a unicode char. Example:
```
# coding=utf8
import unicodedata2
print unicodeda... |
Python: Round to next predefined integer in list | 9,869,066 | 5 | 2012-03-26T08:48:34Z | 9,869,148 | 15 | 2012-03-26T08:54:51Z | [
"python"
] | I have a Python list of predefined integers:
```
intvals = [5000, 7500, 10000, 20000, 30000, 40000, 50000]
```
I need to round down and up to the next lower/higher value in the list. So for example, given the number `8000`, the result should be `[7500, 10000]`. For `42000`, it should be `[40000, 50000]`. I am wonderi... | This is perfect for bisect.bisect\_right() and bisect.bisect\_left().
Here is some example code for which you can expand on:
```
import bisect
def get_interval(x):
intvals = [5000, 7500, 10000, 20000, 30000, 40000, 50000]
i = bisect.bisect_right(intvals,x)
return intvals[i-1:i+1]
print get_interval(5500... |
How to convert list of intable strings to int | 9,869,524 | 5 | 2012-03-26T09:20:58Z | 9,869,636 | 8 | 2012-03-26T09:27:57Z | [
"python",
"string",
"list",
"int"
] | In Python, I want to convert a list of strings:
```
l = ['sam','1','dad','21']
```
and convert the integers to integer types like this:
```
t = ['sam',1,'dad',21]
```
I tried:
```
t = [map(int, x) for x in l]
```
but is showing an error.
How could I convert all *intable* strings in a list to int, leaving other e... | I'd use a custom function:
```
def try_int(x):
try:
return int(x)
except ValueError:
return x
```
Example:
```
>>> [try_int(x) for x in ['sam', '1', 'dad', '21']]
['sam', 1, 'dad', 21]
```
---
**Edit:** If you need to apply the above to a list of lists, **why didn't you converted those str... |
is there a built-in feature to say a dict A contains another dict B? | 9,870,221 | 3 | 2012-03-26T10:07:41Z | 9,870,264 | 7 | 2012-03-26T10:11:11Z | [
"python"
] | e.g. dict `a` contains dict `b1` because:
```
a = { 'name': 'mary', 'age': 56, 'gender': 'female' }
b1 = { 'name': 'mary', 'age': 56 }
```
But this is False because the value for the key `name` is different.
```
b2 = { 'name': 'elizabeth', 'age': 56 }
``` | ```
set(b1.iteritems()) <= set(a.iteritems())
```
`<=` implements the subset relation on [`set` objects](http://docs.python.org/library/stdtypes.html#set). This works when both the keys and the values in both dicts are hashable (strings, tuples and ints are, lists are not). |
is there a built-in feature to say a dict A contains another dict B? | 9,870,221 | 3 | 2012-03-26T10:07:41Z | 9,870,318 | 7 | 2012-03-26T10:14:43Z | [
"python"
] | e.g. dict `a` contains dict `b1` because:
```
a = { 'name': 'mary', 'age': 56, 'gender': 'female' }
b1 = { 'name': 'mary', 'age': 56 }
```
But this is False because the value for the key `name` is different.
```
b2 = { 'name': 'elizabeth', 'age': 56 }
``` | This "shortcircuits". When the first item of `b2` is found that isn't in `a`, the `all()` terminates immediately. Also avoids the memory overhead of creating temporary sets
```
>>> a = { 'name': 'mary', 'age': 56, 'gender': 'female' }
>>> b1 = { 'name': 'mary', 'age': 56 }
>>>
>>> all(a[k]==v for k,v in b1.iteritems(... |
getbbox method from python image library (PIL) not working | 9,870,876 | 7 | 2012-03-26T10:58:36Z | 9,874,342 | 16 | 2012-03-26T14:46:10Z | [
"python",
"python-imaging-library",
"crop",
"bounding-box",
"image-editing"
] | I want to crop an image to its smaller size, by cutting the white areas on the borders. I tried the solution suggested in this forum [Crop a PNG image to its minimum size](http://stackoverflow.com/questions/1905421/crop-a-png-image-to-its-minimum-size) but the getbbox() method of pil is returning a bounding box of the ... | Trouble is `getbbox()` crops off the black borders, from the docs: `Calculates the bounding box of the non-zero regions in the image`.

```
import Image
im=Image.open("flowers_whit... |
user authentication via ssl certs in django | 9,871,409 | 8 | 2012-03-26T11:39:05Z | 16,954,726 | 9 | 2013-06-06T06:03:25Z | [
"python",
"django",
"authentication",
"ssl"
] | I'm writing an webaplication for a closed user group. It will be served https only. Server should check if user is allowed to access server by checking user ssl certificate. I would prefer to just have a whitelist (ex field with user cert in userprofile), than signing their keys by my CA. As there would be no user/pass... | I have created a django module for this, the implementation available under MIT license on [github](https://github.com/kimvais/django-ssl-client-auth).
Basically the approach is so that:
1. nginx handles all the SSL & Certificate verification stuff
2. Django authentication backend maps the (validated) certificates dis... |
Python and HTML '% Operator' | 9,872,565 | 5 | 2012-03-26T12:59:16Z | 9,872,602 | 14 | 2012-03-26T13:01:14Z | [
"python",
"html",
"css"
] | I'm trying to get some HTML to work with my python code.
I've got this for one of my CSS codes.
```
#footerBar {
height: 40px;
background: red;
position: fixed;
bottom: 0;
width: 100%;
z-index: -1;
}
```
However, when I try to access the page, I get the following error.
```
File "projv2.py", line 151, in welcome
</f... | If you want to use `%` formatting operator, you need to escape your `%` characters.
So your css should read:
```
#footerBar {
height: 40px;
background: red;
position: fixed;
bottom: 0;
width: 100%%;
z-index: -1;
}
```
instead.
It's preferrable to use the string's [`.format()`](http://docs.python.org/library/string.... |
Calling a Python function with *args,**kwargs and optional / default arguments | 9,872,824 | 29 | 2012-03-26T13:16:27Z | 9,873,280 | 27 | 2012-03-26T13:44:14Z | [
"python",
"syntax",
"python-3.x"
] | In python, I can call a function as follows:
```
def func(kw1=None,kw2=None,**kwargs):
...
```
In this case, i can call func as:
```
func(kw1=3,kw2=4,who_knows_if_this_will_be_used=7,more_kwargs=Ellipsis)
```
I can also define a function as:
```
func(arg1,arg2,*args):
...
```
which can be called as
```
fu... | You *can* do that on Python 3.
```
def func(a,b,*args,kw1=None,**kwargs):
```
The bare `*` is only used when you want to specify keyword only arguments *without* accepting a variable number of positional arguments with `*args`. You don't use two `*`s.
To quote from the grammar, in Python 2, you have
```
parameter_l... |
get PID from paramiko | 9,872,872 | 5 | 2012-03-26T13:18:48Z | 14,158,100 | 8 | 2013-01-04T13:28:28Z | [
"python",
"paramiko"
] | I can't find a simple answer for this: I'm using paramiko to log in and execute a number of processes remotely and I need the PIDs of each process in order to check on them at later times. There doesn't seem to be a function in paramiko to get the PID of an executed command, so I tried using the following:
```
stdin,s... | Here's a way to obtain the remote process ID:
```
def execute(channel, command):
command = 'echo $$; exec ' + command
stdin, stdout, stderr = channel.exec_command(command)
pid = int(stdout.readline())
return pid, stdin, stdout, stderr
``` |
How to automatically add a SQLAlchemy object to the session? | 9,873,251 | 4 | 2012-03-26T13:42:14Z | 9,873,955 | 14 | 2012-03-26T14:23:58Z | [
"python",
"sqlalchemy"
] | I have a SQLAlchemy table class created using the Declarative method:
```
mysqlengine = create_engine(dsn)
session = scoped_session(sessionmaker(bind=mysqlengine))
Base = declarative_base()
Base.metadata.bind = mysqlengine
class MyTable(Base):
__table_args__ = {'autoload' : True}
```
Now, when using this table wit... | Super simple. Use an event:
```
from sqlalchemy import event, Integer, Column, String
from sqlalchemy.orm import scoped_session, sessionmaker, mapper
from sqlalchemy.ext.declarative import declarative_base
Session = scoped_session(sessionmaker())
@event.listens_for(mapper, 'init')
def auto_add(target, args, kwargs):... |
Adding link to django admin page | 9,873,582 | 8 | 2012-03-26T14:03:07Z | 9,873,773 | 10 | 2012-03-26T14:13:33Z | [
"python",
"django",
"django-admin"
] | I have a client that has an app built with django. On every page of
their app is a link to their admin site. They tell me the admin site
is generated entirely by django, and they've never customized it
before. On the very first line of the admin page it says:
```
Django administration Welcome, admin. Change p... | There are many ways to store the last visited non-admin url in request.session. For example, a middleware:
```
import re
class LastSiteUrl(object):
def is_admin_url(self, url):
return re.search('^(http:\/\/.*){0,1}\/admin\/', url) is not None
def process_request(self, request):
if self.is_adm... |
Choose m evenly spaced elements from a sequence of length n | 9,873,626 | 4 | 2012-03-26T14:05:28Z | 9,873,804 | 13 | 2012-03-26T14:15:24Z | [
"python",
"algorithm"
] | I have a vector/array of n elements. I want to choose m elements.
The choices must be fair / deterministic -- equally many from each subsection.
With m=10, n=20 it is easy: just take every second element.
But how to do it in the general case? Do I have to calculate the LCD? | You probably need [Bresenham's line algorithm](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm). Choosing `m` elements uniformly from `n` is equivalent to drawing a line in `m`x`n` discrete pixel grid. Assume `x` coordinate in `0`..`n-1` and `y` coordinate `0`..`m-1`, and proceed like if you were drawing a li... |
How can I pass an array to shared library(.dll) written in c using python | 9,873,678 | 4 | 2012-03-26T14:08:40Z | 9,874,173 | 7 | 2012-03-26T14:36:14Z | [
"python",
"c",
"arrays",
"dll",
"ctypes"
] | the function code of test.dll file:
```
double __cdecl add(int len,double array[]){}
```
(and I have tested it in vc)
python code:
```
import ctypes
from ctypes import *
N=...
arr=(c_double*N)()
...
...
dll=CDLL("test.dll")
sum=dll.add(c_int(N),byref(arr))
print sum
```
but the python code doesn't work,
and the ... | Passing an array in ctypes mirrors passing an array in C, i.e. you do not need to pass a reference to it as the array is already a reference to its first element.
```
from ctypes import *
N = ...
arr=(c_double*N)()
dll=CDLL("test.dll")
sum=dll.add(c_int(N),arr)
print sum
```
An example of this can be seen in the ct... |
Using Python's Multiprocessing module to execute simultaneous and separate SEAWAT/MODFLOW model runs | 9,874,042 | 13 | 2012-03-26T14:29:07Z | 9,874,484 | 15 | 2012-03-26T14:55:34Z | [
"python",
"multiprocessing"
] | I'm trying to complete 100 model runs on my 8-processor 64-bit Windows 7 machine. I'd like to run 7 instances of the model concurrently to decrease my total run time (approx. 9.5 min per model run). I've looked at several threads pertaining to the Multiprocessing module of Python, but am still missing something.
[Usin... | I don't see any computations in the Python code. If you just need to execute several external programs in parallel it is sufficient to use `subprocess` to run the programs and `threading` module to maintain constant number of processes running, but the simplest code is using `multiprocessing.Pool`:
```
#!/usr/bin/env ... |
'admin' is not a registered namespace in Django 1.4 | 9,874,192 | 16 | 2012-03-26T14:37:45Z | 9,889,233 | 8 | 2012-03-27T12:06:52Z | [
"python",
"django",
"django-1.4"
] | I'm attempting to upgrade quite a large Django project to the newly released Django 1.4, and I'm having some issues when running `python manage.py test`.
Lots of the internal tests which passed in Django 1.3 are now failing, with really odd messages that I can't seem to fix. One that appears the most is:
```
NoRevers... | As it turns out, this was due to the order of the `TEMPLATE_LOADERS` key in my settings file.
I had the following:
```
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
'django.template.loaders.filesystem.Loader',
)
```
which, somehow, caused the error when reversing admin URLs. Switchin... |
'admin' is not a registered namespace in Django 1.4 | 9,874,192 | 16 | 2012-03-26T14:37:45Z | 16,651,467 | 12 | 2013-05-20T14:13:00Z | [
"python",
"django",
"django-1.4"
] | I'm attempting to upgrade quite a large Django project to the newly released Django 1.4, and I'm having some issues when running `python manage.py test`.
Lots of the internal tests which passed in Django 1.3 are now failing, with really odd messages that I can't seem to fix. One that appears the most is:
```
NoRevers... | **Short Answer:** You have a copy of Django admin template files copied in on of your app's templates directory from an earlier version of Django, then you upgraded Django but didn't update (re-copy) those local templates.
**Long Answer:** The main cause of this problem is using an older version of Django admin templa... |
Python: converting radians to degrees | 9,875,964 | 11 | 2012-03-26T16:28:54Z | 9,877,360 | 29 | 2012-03-26T18:08:19Z | [
"python",
"math"
] | In the python.org math library, I could only find `math.cos(x)`, with cos/sin/tan/acos/asin/atan. This returns the answer in radians. How can I get the answer in degrees?
Here's my code:
```
import math
x = math.cos(1)
y = x * 180 / math.pi
print y
30.9570417874
```
My calculator, on deg, gives me:
```
cos(1)
0.99... | Python includes two functions in the `math` package; `radians` converts degrees to radians, and `degrees` converts radians to degrees.
To match the output of your calculator you need:
```
>>> math.cos(math.radians(1))
0.9998476951563913
```
Note that all of the trig functions convert between an angle and the ratio o... |
Parsing configure file with same section name in python | 9,876,059 | 6 | 2012-03-26T16:34:53Z | 9,888,814 | 9 | 2012-03-27T11:36:13Z | [
"python",
"python-3.x",
"configparser"
] | I try to parse file like:
```
[account]
User = first
[account]
User = second
```
I use ConfigParser in Python, but when i read file:
```
Config = configparser.ConfigParser()
Config.read(file)
print (Config.sections())
```
I have error:
```
While reading from ... : section 'account' already exists
```
How can i p... | `ConfigParser` stores the sections it reads in a dictionary, so you can't store multiple sections with the same name. However, the `ConfigParser` constructor accepts a `dict_type` argument that allows you to specify a different dictionary-like object. You can use that to support identically named sections. Here's a cru... |
how do i install beautiful soup for python on my mac? see error | 9,876,226 | 5 | 2012-03-26T16:45:17Z | 9,877,397 | 12 | 2012-03-26T18:11:31Z | [
"python",
"osx",
"beautifulsoup"
] | I'm running Mac OS X 10.7.3 on a Macbook Pro. It came with Python 2.7.1 installed. I need the beautiful soup library. So I did the following:
1) went to crummy.com and downloaded beautifulsoup4-4.0.2.tar.gz
2) uncompressed it
3) navigated to uncompressed directory and typed the following
```
python setup.py install... | For BeautifulSoup4 you have to use
```
from bs4 import BeautifulSoup
```
Check the document: [BS4 document](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) |
RabbitMQ consume one message if exists and quit | 9,876,227 | 11 | 2012-03-26T16:45:36Z | 16,727,011 | 10 | 2013-05-24T02:53:54Z | [
"python",
"rabbitmq",
"amqp"
] | I am running code on python to send and receive from RabbitMQ queue from another application where I can't allow threading.
This is very newbie question but, is there a possibility to just check if there is message and if there are no any then just quit listening ? How should I change basic "Hello world" example for su... | Ok, I found following solution:
```
def receive():
parameters = pika.ConnectionParameters(RabbitMQ_server)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.queue_declare(queue='toM')
method_frame, header_frame, body = channel.basic_get(queue = 'toM')
... |
How do I compute derivative using Numpy? | 9,876,290 | 29 | 2012-03-26T16:50:34Z | 9,876,548 | 16 | 2012-03-26T17:09:57Z | [
"python",
"math",
"numpy"
] | How do I calculate the derivative of a function, for example
> y = x2+1
using `numpy`?
Let's say, I want the value of derivative at x = 5... | NumPy does not provide general functionality to compute derivatives. It can handles the simple special case of polynomials however:
```
>>> p = numpy.poly1d([1, 0, 1])
>>> print p
2
1 x + 1
>>> q = p.deriv()
>>> print q
2 x
>>> q(5)
10
```
If you want to compute the derivative numerically, you can get away with us... |
How do I compute derivative using Numpy? | 9,876,290 | 29 | 2012-03-26T16:50:34Z | 9,877,279 | 64 | 2012-03-26T18:02:41Z | [
"python",
"math",
"numpy"
] | How do I calculate the derivative of a function, for example
> y = x2+1
using `numpy`?
Let's say, I want the value of derivative at x = 5... | You have four options
1. You can use [Finite Differences](http://en.wikipedia.org/wiki/Finite_differences)
2. You can use [Automatic Derivatives](http://en.wikipedia.org/wiki/Automatic_differentiation)
3. You can use [Symbolic Differentiation](http://en.wikipedia.org/wiki/Symbolic_differentiation)
4. You can compute d... |
How do I compute derivative using Numpy? | 9,876,290 | 29 | 2012-03-26T16:50:34Z | 26,042,315 | 9 | 2014-09-25T15:25:22Z | [
"python",
"math",
"numpy"
] | How do I calculate the derivative of a function, for example
> y = x2+1
using `numpy`?
Let's say, I want the value of derivative at x = 5... | The most straight-forward way I can think of is using [numpy's gradient function](http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html):
```
x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)
```
This way, dydx will be computed using central differences and will ... |
Which spam corpus I can use in NLTK? | 9,876,616 | 7 | 2012-03-26T17:14:35Z | 9,879,303 | 8 | 2012-03-26T20:27:27Z | [
"python",
"nltk",
"spam-prevention",
"corpus"
] | My question is fairly related to [this one](http://stackoverflow.com/questions/5248100/using-document-length-in-the-naive-bayes-classifier-of-nltk-python), but I decided to open another question thread. I hope it is fine.
I am building a spam filter using the NLTK in Python as well, but I've just started.
I am wonder... | This [presentation](http://www.cs.ucf.edu/courses/cap5636/fall2011/nltk.pdf) uses the [enron-spam dataset](http://www.aueb.gr/users/ion/data/enron-spam/) (200,000+ emails).
> The training and testing sets come from a dataset of 200,000+ Enron
> emails which contain both âspamâ and âhamâ emails |
Scrapy spider not found error | 9,876,793 | 11 | 2012-03-26T17:27:28Z | 9,885,282 | 29 | 2012-03-27T07:42:34Z | [
"python",
"scrapy"
] | This is Windows 7 with python 2.7
I have a scrapy project in a directory called caps (this is where scrapy.cfg is)
My spider is located in caps\caps\spiders\campSpider.py
I cd into the scrapy project and try to run
```
scrapy crawl campSpider -o items.json -t json
```
I get an error that the spider can't be found.... | Make sure you have set the **"name" property** of the spider.
Example:
```
class campSpider(BaseSpider):
name = 'campSpider'
```
Without the name property, the scrapy manager will not be able to find your spider. |
Scrapy spider not found error | 9,876,793 | 11 | 2012-03-26T17:27:28Z | 13,326,067 | 10 | 2012-11-10T21:04:15Z | [
"python",
"scrapy"
] | This is Windows 7 with python 2.7
I have a scrapy project in a directory called caps (this is where scrapy.cfg is)
My spider is located in caps\caps\spiders\campSpider.py
I cd into the scrapy project and try to run
```
scrapy crawl campSpider -o items.json -t json
```
I get an error that the spider can't be found.... | Also make sure that your project is not called `scrapy`! I made that mistake and renaming it fixed the problem. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.