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 |
|---|---|---|---|---|---|---|---|---|---|
Combined list and dict comprehension | 8,929,424 | 6 | 2012-01-19T16:16:35Z | 8,929,598 | 7 | 2012-01-19T16:26:24Z | [
"python"
] | I have some kind of verbose logic that I'd like to compact down with some comprehensions.
Essentially, I have a dict object that I'm reading from which has 16 values in it that I'm concerned with. I'm getting the keys that I want with the following comprehension:
```
["I%d" % (i,) for i in range(16)]
```
The source ... | This is a fully functional solution that can be applied on arbitrary size.
```
d = { "I0": [0,1,5,2], "I1": [1,3,5,2], "I2": [5,9,10,1]}
map(dict, zip(*map(lambda (k, v): map(lambda vv: (k, vv), v), d.iteritems())))
```
to elaborate: (I'm using `ipython` and the underscore `_` means the previous output)
```
In [1]: ... |
Where can I find mad (mean absolute deviation) in scipy? | 8,930,370 | 15 | 2012-01-19T17:18:01Z | 8,933,818 | 10 | 2012-01-19T21:47:04Z | [
"python",
"scipy",
"statsmodels"
] | It seems scipy once provided a function `mad` to calculate the mean absolute deviation for a set of numbers:
<http://projects.scipy.org/scipy/browser/trunk/scipy/stats/models/utils.py?rev=3473>
However, I can not find it anywhere in current versions of scipy. Of course it is possible to just copy the old code from re... | It looks like scipy.stats.models was [removed](https://github.com/scipy/scipy/commit/174e708f823162bb56248c63ee1985f672797503#diff-34) in august 2008 due to insufficient baking. Development has migrated to [`statsmodels`](http://statsmodels.sourceforge.net/). |
Where can I find mad (mean absolute deviation) in scipy? | 8,930,370 | 15 | 2012-01-19T17:18:01Z | 19,472,336 | 14 | 2013-10-19T23:41:30Z | [
"python",
"scipy",
"statsmodels"
] | It seems scipy once provided a function `mad` to calculate the mean absolute deviation for a set of numbers:
<http://projects.scipy.org/scipy/browser/trunk/scipy/stats/models/utils.py?rev=3473>
However, I can not find it anywhere in current versions of scipy. Of course it is possible to just copy the old code from re... | ```
from numpy import mean, absolute
def mad(data, axis=None):
return mean(absolute(data - mean(data, axis)), axis)
``` |
Where can I find mad (mean absolute deviation) in scipy? | 8,930,370 | 15 | 2012-01-19T17:18:01Z | 23,535,934 | 12 | 2014-05-08T07:56:02Z | [
"python",
"scipy",
"statsmodels"
] | It seems scipy once provided a function `mad` to calculate the mean absolute deviation for a set of numbers:
<http://projects.scipy.org/scipy/browser/trunk/scipy/stats/models/utils.py?rev=3473>
However, I can not find it anywhere in current versions of scipy. Of course it is possible to just copy the old code from re... | For what its worth, I use this for MAD:
```
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not u... |
Python append dictionary to dictionary | 8,930,915 | 116 | 2012-01-19T17:55:48Z | 8,930,956 | 8 | 2012-01-19T17:58:00Z | [
"python",
"dictionary"
] | I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:
```
orig = {
'A': 1,
'B': 2,
'C': 3,
}
extra = {
'D': 4,
'E': 5,
}
dest = # something here involving orig... | [`dict.update()`](http://docs.python.org/library/stdtypes.html#dict.update) looks like it will do what you want...
```
>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>>
```
Perhaps, though, you don't want to update your original dictionary, but work on a copy:
```
>>> dest = orig.copy()
>>>... |
Python append dictionary to dictionary | 8,930,915 | 116 | 2012-01-19T17:55:48Z | 8,930,969 | 185 | 2012-01-19T17:58:47Z | [
"python",
"dictionary"
] | I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:
```
orig = {
'A': 1,
'B': 2,
'C': 3,
}
extra = {
'D': 4,
'E': 5,
}
dest = # something here involving orig... | You can do
```
orig.update(extra)
```
or, if you don't want `orig` to be modified, make a copy first:
```
dest = dict(orig) # or orig.copy()
dest.update(extra)
```
Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,
```
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!'... |
Python append dictionary to dictionary | 8,930,915 | 116 | 2012-01-19T17:55:48Z | 8,931,130 | 16 | 2012-01-19T18:13:03Z | [
"python",
"dictionary"
] | I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:
```
orig = {
'A': 1,
'B': 2,
'C': 3,
}
extra = {
'D': 4,
'E': 5,
}
dest = # something here involving orig... | Assuming that you do not want to change `orig`, you can either do a copy and update like the other answers, or you can create a new dictionary in one step by passing all items from both dictionaries into the dict constructor:
```
from itertools import chain
dest = dict(chain(orig.items(), extra.items()))
```
Or witho... |
Quicker to os.walk or glob? | 8,931,099 | 13 | 2012-01-19T18:10:45Z | 8,931,136 | 9 | 2012-01-19T18:13:10Z | [
"python",
"traversal",
"glob",
"os.walk",
"directory-walk"
] | I'm messing around with file lookups in python on a large hard disk. I've been looking at os.walk and glob. I usually use os.walk as I find it much neater and seems to be quicker (for usual size directories).
Has anyone got any experience with them both and could say which is more efficient? As I say, glob seems to be... | If you need to recurse through subdirectories, use `os.walk`. Otherwise, I think it would be easier to use `glob.iglob` or `os.listdir`. |
Quicker to os.walk or glob? | 8,931,099 | 13 | 2012-01-19T18:10:45Z | 8,931,330 | 7 | 2012-01-19T18:29:44Z | [
"python",
"traversal",
"glob",
"os.walk",
"directory-walk"
] | I'm messing around with file lookups in python on a large hard disk. I've been looking at os.walk and glob. I usually use os.walk as I find it much neater and seems to be quicker (for usual size directories).
Has anyone got any experience with them both and could say which is more efficient? As I say, glob seems to be... | Don't waste your time for optimization before measuring/profiling. Focus on making your code simple and easy to maintain.
For example, in your code you precompile RE, which does not give you any speed boost, because re module has internal `re._cache` of precompiled REs.
1. Keep it simple
2. if it's slow, then profile... |
Using Colormaps to set color of line in matplotlib | 8,931,268 | 36 | 2012-01-19T18:24:01Z | 8,931,396 | 53 | 2012-01-19T18:34:10Z | [
"python",
"matplotlib"
] | How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say `jet`)? I tried a couple of different approaches here and I think I'm stumped. `values[]` is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the a... | The error you are receiving is due to how you define `jet`. You are creating the base class `Colormap` with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.
What you've... |
Using Colormaps to set color of line in matplotlib | 8,931,268 | 36 | 2012-01-19T18:24:01Z | 33,905,962 | 14 | 2015-11-24T23:40:29Z | [
"python",
"matplotlib"
] | How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say `jet`)? I tried a couple of different approaches here and I think I'm stumped. `values[]` is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the a... | I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.
```
impo... |
Create MySQLdb database using Python script | 8,932,261 | 11 | 2012-01-19T19:43:27Z | 8,932,471 | 9 | 2012-01-19T19:59:39Z | [
"python",
"mysql-python"
] | I'm having troubles with creating a database and tables. The database needs to be created within a Python script.
```
#connect method has 4 parameters:
#localhost (where mysql db is located),
#database user name,
#account password,
#database name
db1 = MS.connect(host="localhost",user="root",passwd="****",db="t... | Use [`CREATE DATABASE`](http://dev.mysql.com/doc/refman/5.0/en/create-database.html) to create the database:
```
db1 = MS.connect(host="localhost",user="root",passwd="****")
cursor = db1.cursor()
sql = 'CREATE DATABASE mydata'
cursor.execute(sql)
```
Use [`CREATE TABLE`](http://dev.mysql.com/doc/refman/5.1/en/create-... |
Create MySQLdb database using Python script | 8,932,261 | 11 | 2012-01-19T19:43:27Z | 25,621,844 | 7 | 2014-09-02T11:02:14Z | [
"python",
"mysql-python"
] | I'm having troubles with creating a database and tables. The database needs to be created within a Python script.
```
#connect method has 4 parameters:
#localhost (where mysql db is located),
#database user name,
#account password,
#database name
db1 = MS.connect(host="localhost",user="root",passwd="****",db="t... | I think the solution is a lot easier, use "if not":
```
sql = "CREATE DATABASE IF NOT EXISTS test1"
db1.execute(sql)
``` |
How to write integers to a file | 8,932,488 | 4 | 2012-01-19T20:00:47Z | 8,932,508 | 13 | 2012-01-19T20:02:28Z | [
"python"
] | I need to write
```
ranks[a], ranks[b], count
```
to a file, each time on a new line
I am using:
```
file = open("matrix.txt", "w")
for (a, b), count in counts.iteritems():
file.write(ranks[a], ranks[b], count)
file.close()
```
but this is not working and returns
```
TypeError: function takes exactly 1 argum... | As the error says, [`file.write`](http://docs.python.org/library/stdtypes.html#file.write) only takes one arg. Try:
```
file.write("%s %s %s" % (ranks[a], ranks[b], count))
``` |
How do I change directories using Paramiko? | 8,932,862 | 19 | 2012-01-19T20:33:28Z | 11,728,118 | 17 | 2012-07-30T19:18:36Z | [
"python",
"unix",
"paramiko"
] | [Paramiko stderr object won't reset](http://stackoverflow.com/questions/8916650/paramiko-stderr-object-wont-reset)
I posted the above question regarding a persistent error message that I receive using Paramiko. I do not think it is related to my next question, but it might be.
I can successfully connect to my server ... | This guy had it figured out: <http://www.vertigrated.com/blog/2010/02/python-remote-ssh-with-paramiko/>
You just have to send multiple commands with one exec\_command, such as:
```
myssh.exec_command('cd ..; pwd')
```
Then stdout.readlines() will return the directory that you changed to. |
Python imaging library show() on Windows | 8,932,976 | 5 | 2012-01-19T20:42:16Z | 8,933,913 | 7 | 2012-01-19T21:54:26Z | [
"python",
"python-imaging-library"
] | I am working on a script that downloads various image files from the web and then does some processing on them using the PIL. The script uses urlretreive to dump the images to temporary files, and right now I'm just trying to open them in a viewer using the PIL image.show() method. Here is the relevant portion of the c... | `show()` tries to execute the default image viewer with a `start /wait` command on a temporary image file. The `/wait` parameter is supposed to wait until the viewer exits, so that the file can be deleted. Unfortunately the default viewer under Vista and Windows 7 does not respond properly to `/wait` and return even be... |
How to find if directory exists in Python | 8,933,237 | 466 | 2012-01-19T21:03:20Z | 8,933,273 | 22 | 2012-01-19T21:06:12Z | [
"python",
"directory"
] | In the `os` module in Python, is there a way to find if a directory exists, something like:
```
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
``` | Yes, use [`os.path.exists()`](http://docs.python.org/library/os.path.html#os.path.exists). |
How to find if directory exists in Python | 8,933,237 | 466 | 2012-01-19T21:03:20Z | 8,933,290 | 704 | 2012-01-19T21:07:25Z | [
"python",
"directory"
] | In the `os` module in Python, is there a way to find if a directory exists, something like:
```
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
``` | You're looking for [`os.path.isdir`](http://docs.python.org/dev/library/os.path.html#os.path.isdir), or [`os.path.exists`](http://docs.python.org/dev/library/os.path.html#os.path.exists) if you don't care whether it's a file or a directory.
Example:
```
import os
print(os.path.isdir("/home/el"))
print(os.path.exists(... |
How to find if directory exists in Python | 8,933,237 | 466 | 2012-01-19T21:03:20Z | 8,933,302 | 24 | 2012-01-19T21:08:08Z | [
"python",
"directory"
] | In the `os` module in Python, is there a way to find if a directory exists, something like:
```
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
``` | So close! `os.path.isdir` returns `True` if you pass in the name of a directory that currently exists. If it doesn't exist or it's not a directory, then it returns `False`. |
How to find if directory exists in Python | 8,933,237 | 466 | 2012-01-19T21:03:20Z | 8,933,306 | 9 | 2012-01-19T21:08:15Z | [
"python",
"directory"
] | In the `os` module in Python, is there a way to find if a directory exists, something like:
```
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
``` | Yes use [os.path.isdir(path)](http://docs.python.org/library/os.path.html#os.path.isdir) |
How do I wrap a C++ class with Cython? | 8,933,263 | 18 | 2012-01-19T21:05:27Z | 8,933,819 | 12 | 2012-01-19T21:47:10Z | [
"c++",
"python",
"python-2.7",
"cython"
] | I have a C++ class. It's made up of one .ccp file and one .h file. It compiles (I can write a main method that uses it successfully in c++). How do I wrap this class with Cython to make it available in Python?
I've read the docs and don't follow. They talk about generating the cpp file. When I've tried to follow the d... | Even Cython is generally for use with *C*, it can generate *C++* code, too. When compiling, you add the `--cplus` flag.
Now, creating a wrapper for the class is simple and not much different from wrapping a structure. It mainly differs from declaring the `extern`, but that's not much difference at all.
Suppose you ha... |
How to find tags with only certain attributes - BeautifulSoup | 8,933,863 | 21 | 2012-01-19T21:50:05Z | 8,934,124 | 32 | 2012-01-19T22:11:07Z | [
"python",
"beautifulsoup"
] | How would I, using BeautifulSoup, search for tags containing ONLY the attributes I search for?
For example, I want to find all `<td valign="top">` tags.
The following code:
`raw_card_data = soup.fetch('td', {'valign':re.compile('top')})`
gets all of the data I want, but also grabs any `<td>` tag that has the attribu... | As explained on the [BeutifulSoup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20basic%20find%20method%3a%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20%2a%2akwargs%29)
You may use this :
```
soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})... |
How to find tags with only certain attributes - BeautifulSoup | 8,933,863 | 21 | 2012-01-19T21:50:05Z | 23,212,106 | 18 | 2014-04-22T06:33:29Z | [
"python",
"beautifulsoup"
] | How would I, using BeautifulSoup, search for tags containing ONLY the attributes I search for?
For example, I want to find all `<td valign="top">` tags.
The following code:
`raw_card_data = soup.fetch('td', {'valign':re.compile('top')})`
gets all of the data I want, but also grabs any `<td>` tag that has the attribu... | You can use `lambda` functions in `findAll` as explained in [documentation](http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#match-callable). So that in your case to search for `td` tag with only `valign = "top"` use following:
```
td_tag_list = soup.findAll(
lambda tag:tag.name == "... |
sqlalchemy search function on table as classmethod? | 8,933,877 | 4 | 2012-01-19T21:51:33Z | 10,006,573 | 7 | 2012-04-04T07:18:54Z | [
"python",
"oop",
"sqlalchemy"
] | Assuming i have a class that is called Customer that is defined in sqlalchemy to represent the customer table. I want to write a search method so that ...
```
results = Customer.search(query)
```
will return the results based on the method. Do I want to do this as a @classmethod?
```
@classmethod
def search(cls,quer... | To use
```
cls.query
```
you have to assign a `query_property` to your model classes!
You probably want to use this in other model classes as well, so you might want to do that in your model Base class somewhere in your `model/__init__.py`:
```
Base.query = Session.query_property()
```
Then you can simply write:
... |
python zipfile, how do I know an item is a directory? | 8,934,335 | 8 | 2012-01-19T22:29:29Z | 8,934,384 | 10 | 2012-01-19T22:34:53Z | [
"python",
"zip"
] | Doing something like this:
```
from zipfile import ZipFile
#open zip file
zipfile = ZipFile('Photo.zip')
#iterate zip contents
for zipinfo in zipfile.filelist:
#do something
filepath, filename = path.split(zipinfo.filename)
```
**how do I know if `zipinfo` is a file or a directory?**
Thanks for your suppor... | Probably this is the right way:
```
is_dir = lambda zipinfo: zipinfo.filename.endswith('/')
``` |
Making letters uppercase using re.sub in python? | 8,934,477 | 8 | 2012-01-19T22:44:11Z | 8,934,655 | 13 | 2012-01-19T23:02:06Z | [
"python",
"regex"
] | In many programming languages, the following
find `foo([a-z]+)bar` and replace with `GOO\U\1GAR`
will result in the entire match being made uppercase. I can't seem to find the equivalent in python; does it exist? | You can pass a function to [`re.sub()`](http://docs.python.org/library/re.html#re.sub) that will allow you to do this, here is an example:
```
def upper_repl(match):
return 'GOO' + match.group(1).upper() + 'GAR'
```
And an example of using it:
```
>>> re.sub(r'foo([a-z]+)bar', upper_repl, 'foobazbar')
'GOOBA... |
How can I access Amazon DynamoDB via Python? | 8,935,130 | 27 | 2012-01-19T23:59:08Z | 8,935,165 | 20 | 2012-01-20T00:03:47Z | [
"python",
"database",
"nosql",
"amazon-web-services",
"amazon-dynamodb"
] | I'm currently using hbase with my Python apps and wanted to try out Amazon [DynamoDB](http://aws.amazon.com/dynamodb/). Is there a way to use Python to read, write and query data? | You can use boto: <https://github.com/boto/boto>
docs: <https://boto.readthedocs.org/en/latest/dynamodb2_tut.html>
api reference: <https://boto.readthedocs.org/en/latest/ref/dynamodb2.html> |
How can I access Amazon DynamoDB via Python? | 8,935,130 | 27 | 2012-01-19T23:59:08Z | 12,008,089 | 11 | 2012-08-17T14:51:48Z | [
"python",
"database",
"nosql",
"amazon-web-services",
"amazon-dynamodb"
] | I'm currently using hbase with my Python apps and wanted to try out Amazon [DynamoDB](http://aws.amazon.com/dynamodb/). Is there a way to use Python to read, write and query data? | Disclaimer: I'm the current maintainer
You can use [Dynamodb-mapper](http://pypi.python.org/pypi/dynamodb-mapper) Python library. It's a simple/tiny abstraction layer that allows you to **map plain Python object to DynamoDB**. It also features a transaction engine.
For advanced tasks such as table management it is st... |
How can I access Amazon DynamoDB via Python? | 8,935,130 | 27 | 2012-01-19T23:59:08Z | 22,636,410 | 15 | 2014-03-25T13:41:37Z | [
"python",
"database",
"nosql",
"amazon-web-services",
"amazon-dynamodb"
] | I'm currently using hbase with my Python apps and wanted to try out Amazon [DynamoDB](http://aws.amazon.com/dynamodb/). Is there a way to use Python to read, write and query data? | Another alternative is [PynamoDB](http://pynamodb.readthedocs.org/en/latest/). PynamoDB provides an ORM like interface to DynamoDB and supports **both** Python 2 and Python 3. The entire DynamoDB API is supported by PynamoDB - including global and local secondary indexes, batch operations, binary attributes, queries, s... |
Iterate over an object's "public" attributes | 8,935,462 | 10 | 2012-01-20T00:48:00Z | 8,935,494 | 13 | 2012-01-20T00:52:24Z | [
"python"
] | Recently, I find myself writing code like this:
```
for name in dir( object ):
if name.startswith( '__' ) : continue
...
```
Is there a more pythonic way to access the object's "public" namespace? | You could use the [`vars` function](http://docs.python.org/library/functions.html#vars) instead.
For example:
```
>>> class C(object):
... def __init__(self):
... self.__foo = 'foo'
...
>>> c = C()
>>> dir(c)
['_C__foo', '__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__h... |
Iterate over an object's "public" attributes | 8,935,462 | 10 | 2012-01-20T00:48:00Z | 8,935,749 | 13 | 2012-01-20T01:32:23Z | [
"python"
] | Recently, I find myself writing code like this:
```
for name in dir( object ):
if name.startswith( '__' ) : continue
...
```
Is there a more pythonic way to access the object's "public" namespace? | You can prepare list of "public" attributes (as list or as generator) before:
```
>>> public_props = (name for name in dir(object) if not name.startswith('_'))
>>> for name in public_props:
print name
```
But please read a note about `dir()` function in the documentation:
> **Note** Because `dir()` is supplied p... |
Using BeautifulSoup to search html for string | 8,936,030 | 18 | 2012-01-20T02:18:12Z | 8,936,235 | 21 | 2012-01-20T02:57:10Z | [
"python",
"beautifulsoup"
] | I am using BeautifulSoup to look for user entered strings on a specific page.
For example, I want to see if the string 'Python' is located on the page: <http://python.org>
When I used:
`find_string = soup.body.findAll(text='Python')`
find\_string returned `[]`
But when I used:
`find_string = soup.body.findAll(text=re... | The following line is looking for the **exact** NavigableString 'Python':
```
>>> soup.body.findAll(text='Python')
[]
```
Note that the following NavigableString is found:
```
>>> soup.body.findAll(text='Python Jobs')
[u'Python Jobs']
```
Note this behaviour:
```
>>> import re
>>> soup.body.findAll(text=re.compil... |
python import path: packages with the same name in different folders | 8,936,884 | 14 | 2012-01-20T04:52:46Z | 9,003,220 | 11 | 2012-01-25T13:06:46Z | [
"python",
"path",
"python-import"
] | I am developing several Python projects for several customers at the same time. A simplified version of my project folder structure looks something like this:
```
/path/
to/
projects/
cust1/
proj1/
pack1/
__init__.py
mod1.py
proj2/
pack2/
... | [This](http://stackoverflow.com/questions/1675734/how-do-i-create-a-namespace-package-in-python) is the solution to my problem, albeit it might not be obvious at first.
In my projects, I have now introduced a convention of one namespace per customer. In every customer folder (`cust1`, `cust2`, etc.), there is an `__in... |
how to pip uninstall with virtualenv on heroku cedar stack? | 8,937,905 | 21 | 2012-01-20T07:08:20Z | 9,463,068 | 10 | 2012-02-27T09:58:13Z | [
"python",
"heroku",
"virtualenv",
"pip"
] | I tried to uninstall a module on heroku with:
heroku run bin/python bin/pip uninstall whatever
Pip shows the module in the /app tree then claims to have uinstalled the module, but running the same command again shows it installed in the same location in the /app tree.
Is there a way to get pip uinstall to succeed?
... | By default **virtualenv** is cached between deploys.
To avoid caching of packages you can run:
```
heroku config:add BUILDPACK_URL=git@github.com:heroku/heroku-buildpack-python.git#purge
```
That way everything will be built from scratch after you push some changes. To enable the caching just remove the BUILDPACK\_U... |
how to pip uninstall with virtualenv on heroku cedar stack? | 8,937,905 | 21 | 2012-01-20T07:08:20Z | 11,055,852 | 31 | 2012-06-15T17:56:13Z | [
"python",
"heroku",
"virtualenv",
"pip"
] | I tried to uninstall a module on heroku with:
heroku run bin/python bin/pip uninstall whatever
Pip shows the module in the /app tree then claims to have uinstalled the module, but running the same command again shows it installed in the same location in the /app tree.
Is there a way to get pip uinstall to succeed?
... | **Updated 2013-09-30:** the current way to clear the virtualenv seems to specify a different python runtime version in `runtime.txt` [as stated on Github](https://github.com/heroku/heroku-buildpack-python/issues/72) and in the [Heroku's devcenter reference](https://devcenter.heroku.com/articles/python-runtimes#changing... |
how to pip uninstall with virtualenv on heroku cedar stack? | 8,937,905 | 21 | 2012-01-20T07:08:20Z | 15,087,542 | 21 | 2013-02-26T11:09:18Z | [
"python",
"heroku",
"virtualenv",
"pip"
] | I tried to uninstall a module on heroku with:
heroku run bin/python bin/pip uninstall whatever
Pip shows the module in the /app tree then claims to have uinstalled the module, but running the same command again shows it installed in the same location in the /app tree.
Is there a way to get pip uinstall to succeed?
... | There is now a simpler way to clear the pip cache. Just change the runtime environment, for example from 'python-2.7.3' to 'python-2.7.2', or vice versa.
To do this add a file called runtime.txt to the root of your repository that contains just the runtime string (as show above) in it.
For this to work you need to ha... |
How to extract data from matplotlib plot | 8,938,449 | 8 | 2012-01-20T08:15:42Z | 8,939,010 | 12 | 2012-01-20T09:12:36Z | [
"python",
"matplotlib"
] | I have a `wxPython` program which reads from different datasets, performs various types of simple on-the-fly analysis on the data and plots various combinations of the datasets to `matplotlib` canvas. I would like to have the opportunity to dump currently plotted data to file for more sophisticated analysis later on.
... | Jakub is right about modifying the Python script to write out the data directly from the source from which it was sent into the plot; that's the way I'd prefer to do this. But for reference, if you do need to get data out of a plot, I think this should do it
```
gca().get_lines()[n].get_xydata()
```
Alternatively you... |
Execute a default .py file in PyDev | 8,939,592 | 8 | 2012-01-20T09:59:39Z | 8,940,016 | 12 | 2012-01-20T10:32:39Z | [
"python",
"eclipse",
"pydev"
] | I'm doing a Python project in Eclipse with PyDev. I have a "main" file and some "class" files. I primarily work in the classes, but I need to execute the code via the main file.
At the moment I need to either switch to the main file, or use the drop down menu of the run/debug-button to execute the main file. Pressing ... | Surely (relaunching the last launch was actually the default in in Eclipse 3.2, never understood why they changed that)...
You can have that back in the preferences at: **window > preferences > Run/Debug > Launching** and set the Launch Operation to **Always launch the previously launched application**.
So, **`Ctrl`+... |
PyDev adding tabs to block indentation | 8,939,838 | 5 | 2012-01-20T10:18:49Z | 9,004,046 | 8 | 2012-01-25T14:10:11Z | [
"python",
"eclipse",
"whitespace",
"pydev"
] | I am using Eclipse Ingigo with Pydev 2.3.0.2011121518, it has been working great, but has suddenly starting doing this weird thing with tabs.
I have got the "Replace tabs with spaces when typing" option set for PyDev --> Editor in Eclipse preferences, and that works fine, when I press tab, I get 4 spaces. However for ... | I have just solved this - I had the option ."Assume tab spacing when file contain tabs" checked in Eclipse Preferences --> PyDev --> Editor. When I unchecked this option the automatic indentation worked properly and it added spaces and not tabs. It seems that in one of my docstrings I had some tabs (possibly copied in ... |
GraphViz library Rectangle style edges instead of curves | 8,939,973 | 7 | 2012-01-20T10:29:07Z | 9,055,243 | 15 | 2012-01-29T17:41:44Z | [
"python",
"graphviz",
"edge"
] | I have generated Graphviz images with dot language using pydot python library.
[Generated Graphviz Graph](http://www.flickr.com/photos/yatinkumbhare/6746999075/in/photostream)
But the edges are getting draw in curves.
and I need this kind: [Expected Graphviz](http://www.flickr.com/photos/yatinkumbhare/6746999155/in/p... | This feature is called "[orthogonal](http://en.wikipedia.org/wiki/Orthogonality) edge routing" and is available in Graphviz versions from September 28, 2010 and newer. Use "graph [splines=ortho]"; see the [Graphviz documentation](http://www.graphviz.org/content/attrs#dsplines).
```
digraph Orthogonal {
graph [label=... |
How would you group/cluster these three areas in arrays in python? | 8,940,049 | 12 | 2012-01-20T10:35:17Z | 8,941,175 | 10 | 2012-01-20T12:04:43Z | [
"python",
"cluster-analysis",
"data-mining",
"pattern-recognition"
] | So you have an array
```
1
2
3
60
70
80
100
220
230
250
```
For a better understanding:

How would you group/cluster the three areas in arrays in python(v2.6), so you get three arrays in this case containing
> [1 2 3] [60 70 80 100] [220 230 250]
**Ba... | This is a simple algorithm implemented in python that **check whether or not a value is too far (in terms of standard deviation) from the mean of a cluster**:
```
from math import sqrt
def stat(lst):
"""Calculate mean and std deviation from the input list."""
n = float(len(lst))
mean = sum(lst) / n
st... |
How would you group/cluster these three areas in arrays in python? | 8,940,049 | 12 | 2012-01-20T10:35:17Z | 8,941,578 | 11 | 2012-01-20T12:36:10Z | [
"python",
"cluster-analysis",
"data-mining",
"pattern-recognition"
] | So you have an array
```
1
2
3
60
70
80
100
220
230
250
```
For a better understanding:

How would you group/cluster the three areas in arrays in python(v2.6), so you get three arrays in this case containing
> [1 2 3] [60 70 80 100] [220 230 250]
**Ba... | Observe that your data points are actually one-dimensional if `x` just represents an index. You can cluster your points using Scipy's `cluster.vq` module, which implements the *k*-means algorithm.
```
>>> import numpy as np
>>> from scipy.cluster.vq import kmeans, vq
>>> y = np.array([1,2,3,60,70,80,100,220,230,250])
... |
Connect to two databases | 8,940,368 | 3 | 2012-01-20T11:00:09Z | 8,940,753 | 10 | 2012-01-20T11:31:41Z | [
"python",
"mysql"
] | I want to connect to two databases using Python and, later on, use tables from both of the databases. How can I do this? Is the following code correct?
```
con = mdb.connect(host=MY_HOST, user=MY_USER, passwd=MY_PASS, db1=MY_DB1, db2=MY_DB2)
``` | If you don't specify the database in your `connect` call, you can write queries against multiple databases at once. The [documentation](https://mysqlclient.readthedocs.org/en/latest/user_guide.html#some-mysql-examples) says that `db` is not required.
```
db = _mysql.connect('localhost', 'user', 'passwd')
```
then
``... |
Cycle through list starting at a certain element | 8,940,737 | 12 | 2012-01-20T11:30:06Z | 8,940,984 | 16 | 2012-01-20T11:50:03Z | [
"python",
"list",
"cycle"
] | Say I have a list:
```
l = [1, 2, 3, 4]
```
And I want to cycle through it. Normally, it would do something like this,
```
1, 2, 3, 4, 1, 2, 3, 4, 1, 2...
```
I want to be able to start at a certain point in the cycle, not necessarily an index, but perhaps matching an element. Say I wanted to start at whatever elem... | Look at [itertools](http://docs.python.org/library/itertools.html) module. It provides all the necessary functionality.
```
from itertools import cycle, islice, dropwhile
L = [1, 2, 3, 4]
cycled = cycle(L) # cycle thorugh the list 'L'
skipped = dropwhile(lambda x: x != 4, cycled) # drop the values until x==4
slice... |
Pysvn installer fails to detect Python installation | 8,941,706 | 7 | 2012-01-20T12:47:52Z | 8,975,498 | 8 | 2012-01-23T17:01:00Z | [
"python",
"windows-installer",
"pysvn"
] | I have Python 2.7.2 installed in the default location, C:\Python27.
I've downloaded pysvn 2.7 from <http://pysvn.tigris.org/project_downloads.html> > Windows installation kits. Pysvn Windows installer aborts on
> pysvn requires Python 2.7 to be installed.
>
> Quitting installation
I've tried both installer files, py2... | Did u perhaps install the 64-bit version of Python? If yes: Try the 32-bit installer.
Background: It seems like the 64-bit installer doesn't properly set the correct values in the windows registry (which is the place where PySVN tries to find Python). |
Django admin List Display + ForeignKey = Empty Change List | 8,941,857 | 6 | 2012-01-20T13:02:56Z | 8,959,614 | 7 | 2012-01-22T07:12:11Z | [
"python",
"mysql",
"django",
"django-admin"
] | I've got a weird problem in django admin `list_display`. Whenever I add a foreign key to a `list_display` the whole change list view goes blank showing only the total no of entries.
**models.py:**
```
class Organization(models.Model):
org_id = models.AutoField(primary_key=True)
org_name = models.CharField(max... | I second **Stefano** on the fact that `null=True, blank=True` is to be added. But, I think you only need to add it to the `org_name` field of the `Organization` model. That should make your way through. It has to be done because you have run `inspectdb` to create models from your legacy DB. And probably the `organizati... |
Ordering query result by numeric strings in django (postgres backend) | 8,941,962 | 6 | 2012-01-20T13:12:19Z | 8,942,115 | 10 | 2012-01-20T13:26:59Z | [
"python",
"django",
"postgresql",
"orm"
] | I have a table with a name (varchar) field that only holds numeric string and I want to order my queries by this field. But name fields are being ordered by alphabetically but I want them to be ordered numerically.
For instance if I get 1 2 200 100 as name fields values, It is being ordered like 1 100 2 200
but I need ... | I'd ask first of all why you have a varchar column that needs to be treated as numeric, but never mind.
You can use the `extra` queryset method to convert your string:
```
MyTable.objects.extra(select={'int_name': 'CAST(t.name AS INTEGER)'},
order_by=['int_name'])
``` |
Cannot import module | 8,943,421 | 6 | 2012-01-20T15:04:06Z | 8,943,998 | 8 | 2012-01-20T15:46:00Z | [
"python",
"apache",
"wsgi"
] | I have created a python web app with this directory structure:
```
# cd /usr/local/www/myapp
modules
layout
__init__.py
layout.py
packages
public
myapp.wsgi
```
I have set my PYTHONPATH to:
```
/usr/local/www/myapp/modules:/usr/local/www/myapp/packages
```
In myapp.wsgi I try to do:
```
import... | First try:
```
python /usr/local/www/myapp/myapp.wsgi
```
Does it load correctly?
If yes, then probably you have some environment (in `~/.bashrc` or such) which is needed for your app. Try::
```
# to wipe-out extra env
env -i bash
# try again
python /usr/local/www/myapp/myapp.wsgi
```
Verify you use same python in... |
How does the name of an immutable object rebind to the result of an augmented assignment? | 8,943,613 | 4 | 2012-01-20T15:18:39Z | 8,943,660 | 10 | 2012-01-20T15:21:24Z | [
"python",
"binding",
"namespaces",
"variable-assignment"
] | How does the name of an immutable object rebind to the result of an augmented assignment?
For mutable objects, example, if `x = [1, 2, 3]`, and y = [4, 5], then when we do x += y, it is executed as `x.__iadd__(y)` which modifies `x` *in place* and does the name `x` rebind to it again?
And how does it work when `x` is... | A line like
```
x += y
```
is actually translated to the equivalent of
```
x = x.__iadd__(y)
```
The rebinding always happens, even if `x` is mutable. If `__iadd__()` is implemented in a way that performs an in-place operation, it needs to return `self`, and the name is rebound to the object it pointed to anyway. I... |
Can python do a gaussian fitting and extrapolation? | 8,944,045 | 2 | 2012-01-20T15:48:48Z | 8,944,318 | 15 | 2012-01-20T16:07:03Z | [
"python",
"numpy"
] | I think numpy or scipy will do it, but didn't find. Thanks! | ```
import numpy as np
import scipy.stats as stats
np.random.seed(0)
gaussian = stats.norm
```
Generating some random, normal data:
```
data = gaussian.rvs(loc = 5, scale = 22, size = 1000)
```
Computing descriptive statistics:
```
print(data.mean())
# 4.00435243522
print(data.std())
# 21.7147294907
```
Fitting t... |
Why are form field __init__ methods being called on Django startup? | 8,944,403 | 2 | 2012-01-20T16:12:59Z | 8,944,547 | 8 | 2012-01-20T16:22:42Z | [
"python",
"django"
] | I have a Django app with custom form fields, some of which have slow operations in their constructors. I was surprised recently to find out that those constructors were getting called when Django itself was starting up, even before a user does something that requires that form in a view.
Why are they getting instantia... | Because you instantiate the fields in the form definition, which is presumably being imported by one of your views.
The field init is the wrong place to do this sort of dynamic initialization, for this exact reason. You want something that is called when the form is initialized: ie, the form's `__init__`.
That said, ... |
gnuplot linecolor variable in matplotlib? | 8,945,699 | 5 | 2012-01-20T17:51:57Z | 18,516,488 | 12 | 2013-08-29T16:37:43Z | [
"python",
"plot",
"matplotlib",
"gnuplot"
] | I have an array of y-values that form a line. Additionally, I have an array with the same number of elements as the y-array of values ranging from 0 to 1. We'll call this array 'z'. I want to plot the array of y-values so that the color of each point corresponds with the z-value.
In gnuplot, you can do this using the ... | I had the same problem: wanted to plot line(s) with non-uniform color, which I wanted to be dependent on a third variable (z).
But I definitelly wanted to use a line, not markers (as in @joaquin's answer).
I found a solution in a [matplotlib gallery example](http://matplotlib.org/examples/pylab_examples/multicolored_l... |
Invoking shell-command from function in interactive IPython shell | 8,946,221 | 3 | 2012-01-20T18:37:45Z | 8,946,403 | 7 | 2012-01-20T18:52:22Z | [
"python",
"function",
"shell",
"ipython"
] | I have just been playing around with IPython. Currently I am wondering how it would be possible to run a shell-command with a python variable within a function. For example:
```
def x(go):
return !ls -la {go}
x("*.rar")
```
This gives me "sh: 1: Syntax error: end of file unexpected". Could anybody please give me... | If you look at the `history` command output, you'll see that to call external programs ipython uses `_ip.system` method.
Hence, this should work for you:
```
def x(go):
return _ip.system("ls -la {0}".format(go))
```
However, please note that outside ipython you should probably use `subprocess.Popen`. |
Is there an equivalent to the MATLAB function bsxfun in python? | 8,946,810 | 15 | 2012-01-20T19:27:15Z | 8,947,777 | 8 | 2012-01-20T20:58:10Z | [
"python",
"c",
"matlab",
"bsxfun"
] | I'm trying to port some of my code from matlab to python, and some of it uses the bsxfun() function for virtual replication followed by multiplication or division (I also use it for logical operations). I'd like to be able to do this without actually replicating the vector (either with a function or with some kind of d... | To explicitly answer the question: use [numpy](http://numpy.scipy.org/) and look at [the tutorial](http://wiki.scipy.org/EricsBroadcastingDoc) suggested by DSM. |
Is there a Pythonic way to close over a loop variable? | 8,946,868 | 14 | 2012-01-20T19:32:49Z | 8,946,952 | 21 | 2012-01-20T19:39:07Z | [
"python",
"for-loop",
"closures"
] | I just ran across Eric Lippert's [Closing over the loop variable considered harmful](http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx) via SO, and, after experimenting, realized that the same problem exists (and is even harder to get around) in Python.
```
>... | One way is to use a parameter with default value:
```
l = []
for r in range(10):
def foo(r = r):
return r
l.append(foo)
for f in l:
print(f())
```
yields
```
0
1
2
3
4
5
6
7
8
9
```
This works because it defines an `r` in `foo`'s local scope, and binds the default value to it at the time `foo` ... |
How to append dictionary to a list in loop | 8,947,327 | 3 | 2012-01-20T20:15:08Z | 8,947,376 | 9 | 2012-01-20T20:19:42Z | [
"python",
"dictionary"
] | I have at my disposal huge amount of data, in the form of a list of tuples. Each tuple has a specified format like `(a, b, c, d, e)`. The list of tuples looks like:
```
tupleList = [('a1', 'b1', 'c1', 'd1', 'e1'),
('a2', 'b2', 'c2', 'd2', 'e2'),
...
('a10000', 'b10000', 'c10000',... | We're going to mix three important concepts to make this code really small and beautiful. First, a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions), then, the [zip](http://docs.python.org/library/functions.html#zip) method, and finally, the [dict](http://docs.python.org/libr... |
python sqlalchemy get column names dynamically? | 8,947,616 | 8 | 2012-01-20T20:42:47Z | 8,947,913 | 11 | 2012-01-20T21:12:12Z | [
"python",
"sqlalchemy",
"associative"
] | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
connection = create_engine('mysql://user:passwd@localhost:3306/db').connect()
result = connection.execute("select * from table")
for v in result:
print v['id']
print v['name']
connection.close()
```
how i can get ... | You can either find the columns by calling `result.keys()` or you can access them through calling `v.keys()` inside the `for` loop.
Here's an example using `items()`:
```
for v in result:
for column, value in v.items():
print('{0}: {1}'.format(column, value))
``` |
Call a python subprocess as daemon and exit | 8,947,711 | 8 | 2012-01-20T20:51:46Z | 8,947,742 | 8 | 2012-01-20T20:54:24Z | [
"python",
"daemon",
"python-2.x"
] | I'm using a pair of python programs, one of which should call the second.
But this should be done in a way that the first program makes the second one a daemon (or running in the background process), then exits, without waiting for the second program to end.
Is this possible in Python?
I've been looking at os.fork, ... | You can use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html#popen-constructor) for this:
```
import subprocess
cmd = ['/usr/bin/python', '/path/to/my/second/pythonscript.py']
subprocess.Popen(cmd)
```
You might want to redirect `stdout` and `stderr` somewhere, you can do that by passing `stdout=<... |
Mock patch is not working with class in __init__.py | 8,947,817 | 11 | 2012-01-20T21:01:56Z | 8,948,043 | 11 | 2012-01-20T21:25:18Z | [
"python",
"unit-testing",
"mocking",
"twilio"
] | I'm trying to use patch to return the a Mock from within a method. The basic structure is as follows:
```
MyCode.py
class MyClass:
def __init__(self, first_name, last_name):
self.first = first_name
self.last = last_name
def get_greeting(self):
return 'Hello {f} {l}'.format(f=self.fir... | I figured it out. It had nothing to do with `__init__.py` file. It was (as usual) my fault! :)
Just for anyone that is every trying to use Mock and patch with Twilio and SMS in the future, here is the solution:
I was Mocking the class twilio.rest.TwilioRestClient But, things are chained together and I needed to call ... |
read slave , read-write master setup | 8,947,918 | 19 | 2012-01-20T21:13:02Z | 8,981,058 | 24 | 2012-01-24T01:36:21Z | [
"python",
"mysql",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | I have a Flask,SQLAlchemy webapp which uses a single mysql server. I want to expand the database setup to have a read-only slave server such that I can spread the reads between both master and slave while continuing to write to the master db server.
I have looked at few of options and I believe I can't do this with pl... | I have an example of how to do this on my blog at <http://techspot.zzzeek.org/2012/01/11/django-style-database-routers-in-sqlalchemy/> . Basically you can enhance the Session so that it chooses from master or slave on a query-by-query basis. One potential glitch with that approach is that if you have one transaction th... |
Proper NoSQL data schema for web photo gallery | 8,948,767 | 20 | 2012-01-20T22:36:50Z | 9,152,557 | 11 | 2012-02-05T20:07:44Z | [
"python",
"sql",
"nosql",
"amazon-dynamodb"
] | I'm looking to build an appropriate data structure for NoSQL storage of a photo gallery. In my web application, a photo can be part of 1 or more albums. I have experience with MySQL, but almost none with key-value storage.
With MySQL, I would have set up (3) tables as follows:
```
photos (photo_id, title, date_upload... | Using mongodb lingo, your collections could look like this:
```
photos = [
{
_id: ObjectId(...),
title: "...",
date_uploaded: Date(...),
albums: [
ObjectId(...),
...
]
},
...
]
albums = [
{
_id: ObjectId(...),
title: "..."... |
Create an object without calling a class | 8,948,777 | 4 | 2012-01-20T22:38:51Z | 8,948,833 | 11 | 2012-01-20T22:47:27Z | [
"python",
"matlab"
] | In matlab, I can create a structure array (struct) by doing the following.
```
person.name = 'Mike';
person.age = 25;
person.gender = 'male';
```
wherein person is not defined prior to creating the struct. When I try to do it in python, it gives me an error
```
name 'person' is not defined
```
Is there a similar wa... | In Python you can add members dynamically to an existing class, but that name must be known to be of the type of some class. To do so you may create an empty class:
```
class Empty:
pass # empty statement otherwise the class declaration cannot succeed
```
construct your variable as an instance of it
```
p... |
Python string slicing | 8,948,867 | 2 | 2012-01-20T22:52:30Z | 8,948,881 | 13 | 2012-01-20T22:54:35Z | [
"python",
"list",
"indexing"
] | The code:
```
count = 0
oldcount = 0
for char in inwords:
if char == " ":
anagramlist.append(inwords[oldcount, count])
oldcount = count
count = 0
else:
count += 1
```
the error:
```
Traceback (most recent call last):
File "C:/Users/Knowhaw/Desktop/Python Programs/Anagram sol... | You're trying to use `(oldcount, count)` as an index to the list. This is a tuple, not an int.
Do you perhaps mean:
```
anagramlist.append(inwords[oldcount:count])
```
? |
Filter Django database for field containing any value in an array | 8,949,145 | 4 | 2012-01-20T23:24:58Z | 8,949,234 | 16 | 2012-01-20T23:36:13Z | [
"python",
"django",
"django-models"
] | I have a django model and a field representing a users full name. My client wants me to set up a filter to search for a user based on an array of strings where all of them have to be case insensitive contained within the full name.
For example
If a users full\_name = "Keith, Thomson S.".
And I have a list ['keith','... | Make successive calls to `filter`, like so:
```
queryset = Profile.objects.all()
strings = ['keith', 's', 'thompson']
for string in strings:
queryset = queryset.filter(full_name__icontains=string)
```
Alternatively you can `&` together a bunch of `Q` objects:
```
condition = Q(full_name__icontains=s[0])
for stri... |
Python: Attribute Error - 'NoneType' object has no attribute 'something' | 8,949,252 | 90 | 2012-01-20T23:38:00Z | 8,949,265 | 94 | 2012-01-20T23:40:07Z | [
"python",
"object",
"attributeerror"
] | I keep getting an error that says
```
AttributeError: 'NoneType' object has no attribute 'something'
```
The code I have is too long to post here, but I was wondering if someone could give a gist of what general scenarios would be cause this 'AttributeError', and what **'NoneType'** is supposed to mean? (Usually you ... | NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got `None`. That usually means that an assignment or function call up above failed or returned an unexpected result. |
Python: Attribute Error - 'NoneType' object has no attribute 'something' | 8,949,252 | 90 | 2012-01-20T23:38:00Z | 8,949,272 | 47 | 2012-01-20T23:40:51Z | [
"python",
"object",
"attributeerror"
] | I keep getting an error that says
```
AttributeError: 'NoneType' object has no attribute 'something'
```
The code I have is too long to post here, but I was wondering if someone could give a gist of what general scenarios would be cause this 'AttributeError', and what **'NoneType'** is supposed to mean? (Usually you ... | You have a variable that is equal to None and you're attempting to access an attribute of it called 'something'.
```
foo = None
foo.something = 1
```
or
```
foo = None
print foo.something
```
Both will yield an `AttributeError: 'NoneType'` |
Python: Attribute Error - 'NoneType' object has no attribute 'something' | 8,949,252 | 90 | 2012-01-20T23:38:00Z | 8,949,280 | 8 | 2012-01-20T23:41:57Z | [
"python",
"object",
"attributeerror"
] | I keep getting an error that says
```
AttributeError: 'NoneType' object has no attribute 'something'
```
The code I have is too long to post here, but I was wondering if someone could give a gist of what general scenarios would be cause this 'AttributeError', and what **'NoneType'** is supposed to mean? (Usually you ... | The `NoneType` is the type of the value `None`. In this case, the variable `lifetime` has a value of `None`.
A common way to have this happen is to call a function missing a `return`.
There are an infinite number of other ways to set a variable to None, however. |
Python: Attribute Error - 'NoneType' object has no attribute 'something' | 8,949,252 | 90 | 2012-01-20T23:38:00Z | 8,949,588 | 23 | 2012-01-21T00:20:36Z | [
"python",
"object",
"attributeerror"
] | I keep getting an error that says
```
AttributeError: 'NoneType' object has no attribute 'something'
```
The code I have is too long to post here, but I was wondering if someone could give a gist of what general scenarios would be cause this 'AttributeError', and what **'NoneType'** is supposed to mean? (Usually you ... | Others have explained what `NoneType` is and a common way of ending up with it (i.e., failure to return a value from a function).
Another common reason you have `None` where you don't expect it is assignment of an in-place operation on a mutable object. For example:
```
mylist = mylist.sort()
```
The `sort()` method... |
Django - How do I Iterate through a list of dictionaries to concatenate values from a same element | 8,949,834 | 4 | 2012-01-21T01:00:25Z | 8,949,851 | 12 | 2012-01-21T01:04:44Z | [
"python",
"django"
] | I have a list of dictionaries as follows:
```
listDict = [{'product':'sandwich','price':'5200'}, {'product':'hamburger','price':'3000'}]
```
to iterate through the elements i do:
```
{%for element in listDict%}
{% for key,value in element.items %}
<input type="checkbox" name = "bar" value = "{{ value }}"... | You can just do this:
```
{%for element in listDict%}
{{ element.product }} - {{ element.price }}
{% endfor %}
``` |
Django Model Auto Increment Primary Key Based on Foreign Key | 8,950,010 | 8 | 2012-01-21T01:43:55Z | 8,951,832 | 8 | 2012-01-21T09:05:57Z | [
"python",
"mysql",
"django",
"model"
] | I'm trying to figure out how to lay out two of my Django models so that when a new model is saved to the database, its primary key is incremented such that it is the next highest value for all records with the same foreign key.
It's much like [this question asked](http://stackoverflow.com/questions/3605085/mysql-auto-... | Dirk, you have to make some changes to model (if permissible) as **Ignacio** has said. So, `ModelA` should now look something like the following.
```
class ModelA(models.Model):
key = models.PositiveIntegerField()
fk = models.ForeignKey(ModelB)
def Meta(self):
unique_together = ("key", "fk")
... |
Debugging a Flask app running in Gunicorn | 8,950,674 | 43 | 2012-01-21T04:33:09Z | 8,959,107 | 37 | 2012-01-22T05:03:23Z | [
"python",
"flask",
"gunicorn"
] | I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my log... | The Flask config is entirely separate from gunicorn's. Following [the Flask documentation on config files](http://flask.pocoo.org/docs/config/#configuring-from-files), a good solution would be change my source to this:
```
app = Flask(__name__)
app.config.from_pyfile('config.py')
```
And in config.py:
```
DEBUG = Tr... |
Debugging a Flask app running in Gunicorn | 8,950,674 | 43 | 2012-01-21T04:33:09Z | 13,946,679 | 60 | 2012-12-19T06:26:04Z | [
"python",
"flask",
"gunicorn"
] | I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my log... | The acception solution doesn't work for me.
Gunicorn is a pre-forking environment and apparently [the Flask debugger doesn't work in a forking environment](http://flask.pocoo.org/docs/quickstart/#debug-mode).
> ### Attention
>
> Even though the interactive debugger does not work in
> forking environments (which makes... |
Debugging a Flask app running in Gunicorn | 8,950,674 | 43 | 2012-01-21T04:33:09Z | 18,413,210 | 22 | 2013-08-23T23:15:00Z | [
"python",
"flask",
"gunicorn"
] | I've been working on a new dev platform using nginx/gunicorn and Flask for my application.
Ops-wise, everything works fine - the issue I'm having is with debugging the Flask layer. When there's an error in my code, I just get a straight 500 error returned to the browser and nothing shows up on the console or in my log... | **For Heroku users**, there is a simpler solution than creating a bin/web script like suggested by Nick.
Instead of `foreman start`, just use `foreman run python app.py` if you want to debug your application in development. |
Pythonic Circular List | 8,951,020 | 10 | 2012-01-21T05:52:44Z | 8,951,047 | 22 | 2012-01-21T05:58:48Z | [
"python",
"list"
] | Say I have a list,
```
l = [1, 2, 3, 4, 5, 6, 7, 8]
```
I want to grab the index of an arbitrary element and the values of its neighbors. For example,
```
i = l.index(n)
j = l[i-1]
k = l[i+1]
```
However, for the edge case when `i == len(l) - 1` this fails. So I thought I'd just wrap it around,
```
if i == len(l) ... | You could use the modulo operator!
```
i = len(l) - 1
jIndex = (i - 1) % len(l)
kIndex = (i + 1) % len(l)
j = l[jIndex]
k = l[kIndex]
```
Or, to be less verbose:
```
k = l[(i + 1) % len(l)]
``` |
Pythonic Circular List | 8,951,020 | 10 | 2012-01-21T05:52:44Z | 8,951,224 | 13 | 2012-01-21T06:40:51Z | [
"python",
"list"
] | Say I have a list,
```
l = [1, 2, 3, 4, 5, 6, 7, 8]
```
I want to grab the index of an arbitrary element and the values of its neighbors. For example,
```
i = l.index(n)
j = l[i-1]
k = l[i+1]
```
However, for the edge case when `i == len(l) - 1` this fails. So I thought I'd just wrap it around,
```
if i == len(l) ... | The easiest way to wrap around a fixed length list is with the % (modulo) operator
```
list_element = my_list[idx % len(my_list)]
```
but anyway look at
<http://docs.python.org/library/itertools.html>
```
from itertools import cycle
for p in cycle([1,2,3]):
print "endless cycle:", p
``` |
Django objects being "non subscriptable" leads me to write redundant code | 8,951,024 | 2 | 2012-01-21T05:53:21Z | 8,951,035 | 7 | 2012-01-21T05:56:18Z | [
"python",
"django",
"object",
"models"
] | Django objects aren't "subscriptable" meaning if you have `user.name` you can't define it with `user['name']` meaning you can't dynamically load up an object with info.
```
info = {'first_name': 'Artur', 'last_name': 'Sapek'}
me = User()
for i in info:
me[i] = info[i]
```
brings up `TypeError: 'User' object is n... | [setattr](http://docs.python.org/library/functions.html#setattr) is what you're looking for.
In your case you could do something like this:
```
for attr, value in info.items():
setattr(me, attr, value)
``` |
Django objects being "non subscriptable" leads me to write redundant code | 8,951,024 | 2 | 2012-01-21T05:53:21Z | 8,951,175 | 7 | 2012-01-21T06:31:19Z | [
"python",
"django",
"object",
"models"
] | Django objects aren't "subscriptable" meaning if you have `user.name` you can't define it with `user['name']` meaning you can't dynamically load up an object with info.
```
info = {'first_name': 'Artur', 'last_name': 'Sapek'}
me = User()
for i in info:
me[i] = info[i]
```
brings up `TypeError: 'User' object is n... | Why not do the following:
```
info = {'first_name': 'Artur', 'last_name': 'Sapek'}
user = User(**info)
```
Of course if you are using `contrib.auth`'s `User` model you'll need to provide the required fields. |
Import Script from a Parent Directory | 8,951,255 | 20 | 2012-01-21T06:48:17Z | 8,951,269 | 9 | 2012-01-21T06:50:53Z | [
"python",
"import"
] | How do I import a module(python file) that resides in the parent directory?
Both directories have a **init**.py file in them but I still cannot import a file from the parent directory?
In this folder layout, Script B is attempting to import Script A:
```
Folder A:
__init__.py
Script A:
Folder B:
__init... | From the [docs](http://docs.python.org/tutorial/modules.html#intra-package-references):
```
from .. import scriptA
```
You can do this in packages, but not in scripts you run directly. From the link above:
> Note that both explicit and implicit relative imports are based on the
> name of the current module. Since th... |
Import Script from a Parent Directory | 8,951,255 | 20 | 2012-01-21T06:48:17Z | 8,951,563 | 16 | 2012-01-21T08:04:11Z | [
"python",
"import"
] | How do I import a module(python file) that resides in the parent directory?
Both directories have a **init**.py file in them but I still cannot import a file from the parent directory?
In this folder layout, Script B is attempting to import Script A:
```
Folder A:
__init__.py
Script A:
Folder B:
__init... | You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
```
toplevel_package/
âââ __init__.py
âââ moduleA.py
âââ... |
Defining Python decorators for a complete module | 8,951,787 | 9 | 2012-01-21T08:57:52Z | 8,951,874 | 9 | 2012-01-21T09:12:55Z | [
"python",
"decorator"
] | I have a module which contains a lot of functions (more than 25). I want to add a common decorator function to each of these functions. The normal way to do is to add a @decorator line above each function, but I was wondering if there is a better way to do it? Probably I can declare a global decorator at the top of the... | If your decorator is called `my_decorator`
```
### Decorate all the above functions
import types
for k,v in globals().items():
if isinstance(v, types.FunctionType):
globals()[k] = my_decorator(v)
```
You could also apply this to the module after importing it
```
import othermodule
import types
for k,v in... |
Best way to count char occurences in a string | 8,952,101 | 4 | 2012-01-21T09:55:53Z | 8,952,140 | 7 | 2012-01-21T10:03:03Z | [
"python",
"string",
"optimization",
"performancecounter"
] | Hello I am trying to write these python lines in a single line but getting some errors due to the dictionary modifications the code is doing.
```
for i in range(len(string)):
if string[i] in dict:
dict[string[i]] += 1
```
the general syntax I believe is
```
abc = [i for i in len(x) if x[i] in array]
```
... | What you're trying to do can be done with **`dict`**, a **generator expression** and [**`str.count()`**](http://docs.python.org/library/stdtypes.html#str.count):
```
abc = dict((c, string.count(c)) for c in string)
```
**Alternative** using `set(string)` *(from a comment down below by `soulcheck`)*:
```
abc = dict((... |
Best way to count char occurences in a string | 8,952,101 | 4 | 2012-01-21T09:55:53Z | 8,952,201 | 7 | 2012-01-21T10:15:25Z | [
"python",
"string",
"optimization",
"performancecounter"
] | Hello I am trying to write these python lines in a single line but getting some errors due to the dictionary modifications the code is doing.
```
for i in range(len(string)):
if string[i] in dict:
dict[string[i]] += 1
```
the general syntax I believe is
```
abc = [i for i in len(x) if x[i] in array]
```
... | Alternative for Python 2.7+:
```
from collections import Counter
abc = Counter('asdfdffa')
print abc
print abc['a']
```
Output:
```
Counter({'f': 3, 'a': 2, 'd': 2, 's': 1})
2
``` |
How to portably parse the (Unicode) degree symbol with regular expressions? | 8,952,430 | 10 | 2012-01-21T10:56:26Z | 8,952,528 | 8 | 2012-01-21T11:14:09Z | [
"python",
"regex",
"unicode",
"portability"
] | I'm writing a simple regular expression parser for the output of the `sensors` utility on Ubuntu. Here's an example of a line of text I'm parsing:
```
temp1: +31.0°C (crit = +107.0°C)
```
And here's the regex I'm using to match that (in Python):
```
temp_re = re.compile(r'(temp1:)\s+(\+|-)(\d+\.\d+)\W\WC\s... | Possible portable solution:
Convert input data to unicode, and use `re.UNICODE` flag in regular expressions.
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
data = u'temp1: +31.0°C (crit = +107.0°C)'
temp_re = re.compile(ur'(temp1:)\s+(\+|-)(\d+\.\d+)°C\s+'
ur'\(crit\s+=... |
Python: waiting for external launched process finish | 8,953,119 | 6 | 2012-01-21T12:57:43Z | 8,953,132 | 8 | 2012-01-21T13:00:52Z | [
"python",
"system-calls"
] | The question already in title - how can one make the python script wait until some process launched with os.system() call is completed ? For example a code like
```
for i in range( 0, n ):
os.system( 'someprog.exe %d' % i )
```
This launches the requested process n times simultaneously, which may make my p... | Use `subprocess` instead:
```
import subprocess
for i in xrange(n):
p = subprocess.Popen(('someprog.exe', str(i))
p.wait()
```
Read more here: <http://docs.python.org/library/subprocess.html> |
Python dictionary.keys() error | 8,953,627 | 34 | 2012-01-21T14:12:12Z | 8,953,658 | 71 | 2012-01-21T14:18:06Z | [
"python",
"python-3.x",
"dictionary",
"python-3.2"
] | I am trying to use the `.keys()` and instead of getting a list of the keys like
always have in the past. However I get this.
```
b = { 'video':0, 'music':23 }
k = b.keys()
print( k[0] )
>>>TypeError: 'dict_keys' object does not support indexing
print( k )
dict_keys(['music', 'video'])
```
it should just print ['mus... | Python 3 changed the behavior of `dict.keys` such that it now returns a `dict_keys` object, which is iterable but not indexable (it's like the old `dict.iterkeys`, which is gone now). You can get the Python 2 result back with an explicit call to `list`:
```
>>> b = { 'video':0, 'music':23 }
>>> k = list(b.keys())
>>> ... |
Python dictionary.keys() error | 8,953,627 | 34 | 2012-01-21T14:12:12Z | 8,953,660 | 8 | 2012-01-21T14:18:19Z | [
"python",
"python-3.x",
"dictionary",
"python-3.2"
] | I am trying to use the `.keys()` and instead of getting a list of the keys like
always have in the past. However I get this.
```
b = { 'video':0, 'music':23 }
k = b.keys()
print( k[0] )
>>>TypeError: 'dict_keys' object does not support indexing
print( k )
dict_keys(['music', 'video'])
```
it should just print ['mus... | If you assigned `k` like so:
```
k = list(b.keys())
```
your code will work.
As the error says, the `dict_keys` type does not support indexing. |
Import module from subfolder | 8,953,844 | 34 | 2012-01-21T14:44:22Z | 8,954,533 | 53 | 2012-01-21T16:18:01Z | [
"python",
"import",
"module",
"subfolder"
] | I want to import subfolders as modules. Therefore every subfolder contains a `__init__.py`. My folder structure is like this:
```
src\
main.py
dirFoo\
__init__.py
foofactory.py
dirFoo1\
__init__.py
foo1.py
dirFoo2\
__init__.py
foo2.py
```
In my main script I import
```
fro... | There's no need to mess with your `PYTHONPATH` or `sys.path` here.
To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:
```
from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2
```
Or you can use [relative imports](http://docs.python.org/tutorial... |
ValueError: Too many values to unpack Django | 8,954,270 | 24 | 2012-01-21T15:41:31Z | 8,954,475 | 11 | 2012-01-21T16:10:31Z | [
"python",
"django"
] | So I just got my first django app deployed.
I did a `syncdb` and created my superuser account for the site.
Now when I access the page and press the login button I get this error. I think it has something to do with the password but I'm not sure.
```
ValueError at /accounts/login/
too many values to unpack
```
I'm ... | Yes, there is a problem in the password.
The error is in the way the password has been encrypted and stored in the DB. It can be clearly seen from the statement `algo, salt, hsh = enc_password.split('$')` in the traceback. The encrypted password splitting returns more than 3 values.
So, please have look at the passwo... |
ValueError: Too many values to unpack Django | 8,954,270 | 24 | 2012-01-21T15:41:31Z | 9,510,591 | 33 | 2012-03-01T04:24:19Z | [
"python",
"django"
] | So I just got my first django app deployed.
I did a `syncdb` and created my superuser account for the site.
Now when I access the page and press the login button I get this error. I think it has something to do with the password but I'm not sure.
```
ValueError at /accounts/login/
too many values to unpack
```
I'm ... | Just had the same problem.
It seem that in my case, the site was running with Django 1.4 when the password was created (due to a PYTHONPATH mix-up).
When I tried to login running the site with 1.3.1 I got this error. Then I noticed the Django version, switched to 1.4 and the login started working again.
It seems the... |
ValueError: Too many values to unpack Django | 8,954,270 | 24 | 2012-01-21T15:41:31Z | 11,507,743 | 12 | 2012-07-16T15:42:59Z | [
"python",
"django"
] | So I just got my first django app deployed.
I did a `syncdb` and created my superuser account for the site.
Now when I access the page and press the login button I get this error. I think it has something to do with the password but I'm not sure.
```
ValueError at /accounts/login/
too many values to unpack
```
I'm ... | You can reset the password in the shell.
```
from django.contrib.auth.models import User
u = User.objects.get(username="myuser")
u.set_password("mypassword")
u.save()
```
This happens when we downgrade from 1.4.X to test old deployments as detailed by @h3. |
ValueError: Too many values to unpack Django | 8,954,270 | 24 | 2012-01-21T15:41:31Z | 11,657,227 | 18 | 2012-07-25T19:33:57Z | [
"python",
"django"
] | So I just got my first django app deployed.
I did a `syncdb` and created my superuser account for the site.
Now when I access the page and press the login button I get this error. I think it has something to do with the password but I'm not sure.
```
ValueError at /accounts/login/
too many values to unpack
```
I'm ... | The easiest fix is to reset your password from the command line.
```
./manage.py changepassword <user>
``` |
Why Python for loop doesn't work like C for loop? | 8,954,400 | 6 | 2012-01-21T16:01:30Z | 8,954,415 | 24 | 2012-01-21T16:04:15Z | [
"python",
"c",
"for-loop"
] | C:
```
# include <stdio.h>
main()
{
int i;
for (i=0; i<10; i++)
{
if (i>5)
{
i=i-1;
printf("%d",i);
}
}
}
```
Python:
```
for i in range(10):
if i>5: i=i-1
print i,
```
When we compile C code, it goes into a infinite loop, where... | In Python, the loop does not increment `i`, instead it assigns it values from the iterable object (in this case, list). Therefore, changing `i` inside the for loop does not "confuse" the loop, since in the next iteration `i` will simply be assigned the next value.
In the code you provided, when `i` is 6, it is then de... |
Python arguments as a dictionary | 8,954,746 | 26 | 2012-01-21T16:48:05Z | 8,954,761 | 40 | 2012-01-21T16:50:19Z | [
"python",
"dictionary",
"arguments"
] | How can I get argument names and their values passed to a method as a dictionary?
I want to specify the optional and required parameters for a GET request as part of a HTTP API in order to build the URL. I'm not sure of the best way to make this pythonic. | Use a single argument prefixed with `**`.
```
>>> def foo(**args):
... print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}
``` |
Python arguments as a dictionary | 8,954,746 | 26 | 2012-01-21T16:48:05Z | 8,954,974 | 23 | 2012-01-21T17:19:17Z | [
"python",
"dictionary",
"arguments"
] | How can I get argument names and their values passed to a method as a dictionary?
I want to specify the optional and required parameters for a GET request as part of a HTTP API in order to build the URL. I'm not sure of the best way to make this pythonic. | For *non-keyworded* arguments, use a single `*`, and for *keyworded* arguments, use a `**`.
For example:
```
def test(*args, **kwargs):
print args
print kwargs
>>test(1, 2, a=3, b=4)
(1, 2)
{'a': 3, 'b': 4}
```
Non-keyworded arguments would be unpacked to a tuple and keyworded arguments would be unpacked to... |
Save / load scipy sparse csr_matrix in portable data format | 8,955,448 | 27 | 2012-01-21T18:20:42Z | 8,956,767 | 8 | 2012-01-21T21:17:10Z | [
"python",
"numpy",
"scipy"
] | How do you save/load a scipy sparse `csr_matrix` in a portable format? The scipy sparse matrix is created on Python 3 (Windows 64-bit) to run on Python 2 (Linux 64-bit). Initially, I used pickle (with protocol=2 and fix\_imports=True) but this didn't work going from Python 3.2.2 (Windows 64-bit) to Python 2.7.2 (Window... | Assuming you have scipy on both machines, you can just use `pickle`.
However, be sure to specify a binary protocol when pickling numpy arrays. Otherwise you'll wind up with a huge file.
At any rate, you should be able to do this:
```
import cPickle as pickle
import numpy as np
import scipy.sparse
# Just for testing... |
Save / load scipy sparse csr_matrix in portable data format | 8,955,448 | 27 | 2012-01-21T18:20:42Z | 8,980,156 | 42 | 2012-01-23T23:33:09Z | [
"python",
"numpy",
"scipy"
] | How do you save/load a scipy sparse `csr_matrix` in a portable format? The scipy sparse matrix is created on Python 3 (Windows 64-bit) to run on Python 2 (Linux 64-bit). Initially, I used pickle (with protocol=2 and fix\_imports=True) but this didn't work going from Python 3.2.2 (Windows 64-bit) to Python 2.7.2 (Window... | Got an answer from the Scipy user group:
> A csr\_matrix has 3 data attributes that matter: `.data`, `.indices`, and `.indptr`. All are simple ndarrays, so `numpy.save` will work on them. Save the three arrays with `numpy.save` or `numpy.savez`, load them back with `numpy.load`, and then recreate the sparse matrix obj... |
Save / load scipy sparse csr_matrix in portable data format | 8,955,448 | 27 | 2012-01-21T18:20:42Z | 28,998,152 | 16 | 2015-03-11T21:55:28Z | [
"python",
"numpy",
"scipy"
] | How do you save/load a scipy sparse `csr_matrix` in a portable format? The scipy sparse matrix is created on Python 3 (Windows 64-bit) to run on Python 2 (Linux 64-bit). Initially, I used pickle (with protocol=2 and fix\_imports=True) but this didn't work going from Python 3.2.2 (Windows 64-bit) to Python 2.7.2 (Window... | Though you write, `scipy.io.mmwrite` and `scipy.io.mmread` don't work for you, I just want to add how they work. This question is the no. 1 Google hit, so I myself started with `np.savez` and `pickle.dump` before switching to the simple and obvious scipy-functions. They work for me and shouldn't be overseen by those wh... |
Can I define a __repr__ for a class rather than an instance? | 8,955,754 | 8 | 2012-01-21T18:58:46Z | 8,955,878 | 16 | 2012-01-21T19:12:05Z | [
"python",
"metaprogramming",
"metaclass"
] | Can I define a `__repr__` for a class rather than an instance? For example, I'm trying to do this
```
class A(object):
@classmethod
def __repr__(cls):
return 'My class %s' % cls
```
What I get is
```
In [58]: a=A()
In [59]: a
Out[59]: My class <class '__main__.A'>
In [60]: A
Out[60]: __main__.A
```... | You need to define `__repr__` on the metaclass.
```
class Meta(type):
def __repr__(cls):
return 'My class %s' % cls.__name__
class A(object):
__metaclass__ = Meta
```
`__repr__` returns a representation of an instance of an object. So by defining `__repr__` on `A`, you're specifying what you want `re... |
Accessing matched substrings when substituting using regular expressions in Python | 8,955,816 | 4 | 2012-01-21T19:05:12Z | 8,955,853 | 8 | 2012-01-21T19:09:23Z | [
"python",
"regex"
] | I want to match two regular expressions A and B where A and B appear as 'AB'. I want to then insert a space between A and B so that it becomes 'A B'.
For example, if A = [0-9] and B = !+, I want to do something like the following.
```
match = re.sub('[0-9]!+', '[0-9] !+', input_string)
```
But, this obviously does n... | Use the groups!
```
match = re.sub('([0-9])(!+)', r'\1 \2', input_string);
```
`\1` and `\2` indicate the first and second parenthesised fragment. The prefix `r` is used to keep the `\` character intact. |
why is plotting with Matplotlib so slow? | 8,955,869 | 49 | 2012-01-21T19:11:13Z | 8,956,211 | 71 | 2012-01-21T20:01:59Z | [
"python",
"matplotlib"
] | I'm currently evaluating different python plotting libraries. Right now I'm trying matplotlib and I'm quite disappointed with the performance. The following example is modified from <http://www.scipy.org/Cookbook/Matplotlib/Animations> and gives me only ~ 8 frames per second!
Am I doing something wrong, or why is the ... | First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
```
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.