title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How do I get all bars in a matplotlib bar chart? | 22,688,915 | 4 | 2014-03-27T13:19:23Z | 22,689,127 | 8 | 2014-03-27T13:28:47Z | [
"python",
"matplotlib"
] | It is easy to retrieve all lines in a line chart by calling the `get_lines()` function. I cannot seem to find an equivalent function for a barchart, that is retrieving all Rectangle instances in the `AxesSubplot`. Suggestions? | If you want all bars, just capture the output from the plotting method. Its a list containing the bars:
```
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = np.arange(5)
y = np.random.rand(5)
bars = ax.bar(x, y, color='grey')
bars[3].set_color('g')
```
![enter image description h... |
Is it pythonic to use generators to write header and body of a file? | 22,689,476 | 11 | 2014-03-27T13:43:16Z | 22,689,573 | 10 | 2014-03-27T13:47:08Z | [
"python",
"python-3.x",
"file-io",
"generator",
"send"
] | If I was to write a file with this content:
```
#You have been defeated!
#It's merely a flesh wound!
We are the knights who say Ni!
We are the knights who say Ni!
We are the knights who say Ni!
```
Would it then be very non-pythonic to do it with a generator using send? I have never seen generators used like this els... | I like the creativity of your solution, but my subjective opinion would be that using [contextlib.ExitStack()](http://docs.python.org/dev/library/contextlib.html#contextlib.ExitStack) will look cleaner, be more readable, than using the generator since each generator would need to be primed with `generator.send(None)` a... |
Why is one class variable not defined in list comprehension but another is? | 22,692,227 | 13 | 2014-03-27T15:30:26Z | 22,692,274 | 14 | 2014-03-27T15:32:48Z | [
"python",
"scope",
"list-comprehension",
"python-internals",
"python-3.4"
] | I just read the answer to this question: [Accessing class variables from a list comprehension in the class definition](http://stackoverflow.com/q/13905741/1175080)
It helps me to understand why the following code results in `NameError: name 'x' is not defined`:
```
class A:
x = 1
data = [0, 1, 2, 3]
new_d... | `data` is the *source* of the list comprehension; it is the one parameter that is passed to the nested scope created.
Everything in the list comprehension is run in a separate scope (as a function, basically), except for the iterable used for the left-most `for` loop. You can see this in the byte code:
```
>>> def fo... |
Multiple assignment of variables in coffee | 22,692,291 | 6 | 2014-03-27T15:33:31Z | 22,692,398 | 13 | 2014-03-27T15:37:16Z | [
"javascript",
"python",
"coffeescript"
] | Can I assign multiple variables in `coffee` like in `python`:
`a, b, c = 'this', 'is', 'variables'`
`print c` >>>variables | Try with `[a, b, c] = ['this', 'is', 'variables']`. |
How to restart a python script after it finishes | 22,696,168 | 3 | 2014-03-27T18:27:30Z | 22,696,249 | 7 | 2014-03-27T18:31:59Z | [
"python",
"cron"
] | I have a python script that will be running that basically collects data and inserts it into a database based on the last time the database was updated. Basically, i want this script to keep running and never stop, and to start up again after it finishes. What would be the best way to do this?
I considered using a cro... | You could wrap your script in a
```
while True:
...
```
block, or with a bash script:
```
while true ; do
yourpythonscript.py
done
``` |
"'cc' failed with exit status 1" error when install python library | 22,697,440 | 23 | 2014-03-27T19:33:10Z | 22,697,917 | 63 | 2014-03-27T19:57:12Z | [
"python",
"clang",
"osx-mavericks",
"xcode5.1"
] | Like many others, I'm having issues installing a python library (downloaded as a tar, then extracted).
```
rodolphe-mbp:python-Levenshtein-0.11.2 Rodolphe$ sudo python setup.py install
running install
running bdist_egg
running egg_info
writing requirements to python_Levenshtein.egg-info/requires.txt
writing python_Lev... | Run these two lines in your shell before you build:
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
```
Those exports tell the compiler to ignore unused arguments rather than complaining about them.
---
The reason seems to be that Python is compiling modules using the options that it was bui... |
how to check the dtype of a column in python pandas | 22,697,773 | 11 | 2014-03-27T19:49:31Z | 22,697,903 | 19 | 2014-03-27T19:56:32Z | [
"python",
"pandas"
] | i need to use different functions to treat numeric columns and string columns. what I am doing now is really dumb:
```
allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns)
for y in allc:
treat_numeric(agg[y])
allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).c... | You can access a dtype of a column with `agg[y].dtype`:
```
for y in agg.columns:
if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
treat_numeric(agg[y])
else:
treat_str(agg[y])
``` |
How to merge two json string in Python? | 22,698,244 | 2 | 2014-03-27T20:13:04Z | 22,698,556 | 10 | 2014-03-27T20:30:36Z | [
"python",
"json",
"string",
"kazoo"
] | I recently started working with Python and I am trying to concatenate one of my JSON String with existing JSON String. I am also working with Zookeeper so I get the existing json string from zookeeper node as I am using Python kazoo library.
```
# gets the data from zookeeper
data, stat = zk.get(some_znode_path)
jsonS... | Assuming a and b are the dictionaries you want to merge:
```
c = {key: value for (key, value) in (a.items() + b.items())}
```
To convert your string to python dictionary you use the following:
```
import json
my_dict = json.loads(json_str)
```
---
**Update: full code using *strings*:**
```
# test cases for jsonSt... |
What is the difference between the declarative_base() and db.Model? | 22,698,478 | 17 | 2014-03-27T20:25:54Z | 22,700,629 | 15 | 2014-03-27T22:31:31Z | [
"python",
"sqlalchemy",
"flask",
"bottle",
"flask-sqlalchemy"
] | The [quickstart tutorial](http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html) for the Flask-SQLAlchemy plugin instructs users to create table models inheriting the `db.Model` class, e.g.
```
app = Flask(__main__)
db = SQLAlchemy(app)
class Users(db.Model):
__tablename__ = 'users'
...
```
However, the [S... | Looking in the Flask-SQLAlchemy source code the `db.Model` class is initialized as follows:
```
self.Model = self.make_declarative_base()
```
And here is the `make_declarative_base()` method:
```
def make_declarative_base(self):
"""Creates the declarative base."""
base = declarative_base(cls=Model, name='Mod... |
Python mysql (using pymysql) auto reconnect | 22,699,807 | 6 | 2014-03-27T21:40:58Z | 22,714,501 | 8 | 2014-03-28T13:40:05Z | [
"python",
"mysql",
"database-connection",
"connection-pooling",
"pymysql"
] | I'm not sure if this is possible, but I'm looking for a way to reconnect to mysql database when the connection is lost. All the connections are held in a gevent queue but that shouldn't matter I think. I'm sure if I put some time in, I can come up with a way to reconnect to the database. However I was glancing pymysql ... | Finally got a working solution, might help someone.
```
from gevent import monkey
monkey.patch_socket()
import logging
import gevent
from gevent.queue import Queue
import pymysql as db
logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger("connection_pool")
class ConnectionPool:
def __init__(self... |
Sort Python Dictionary by first four characters in Key | 22,700,457 | 2 | 2014-03-27T22:20:35Z | 22,700,510 | 10 | 2014-03-27T22:23:35Z | [
"python",
"sorting",
"dictionary"
] | I have a python dictionary that looks like the following:
```
{'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '3000 -> 3332': 9753, '6333 -> 6665': 7966, '0 -> 332': 877}
```
The keys are obviously all strings, but each key depicts a range of numbers. What ... | Use a sorting key:
```
sorted(yourdict, key=lambda k: int(k.split()[0]))
```
This returns a list of *keys*, sorted numerically on the first part of the key (split on whitespace).
Demo:
```
>>> yourdict = {'666 -> 999': 4388, '4000 -> 4332': 4383, '1333 -> 1665': 7998, '5666 -> 5999': 4495, '3666 -> 3999': 6267, '30... |
How would I cross-reference a function generated by autodoc in Sphinx? | 22,700,606 | 9 | 2014-03-27T22:29:48Z | 22,714,510 | 13 | 2014-03-28T13:40:35Z | [
"python",
"methods",
"hyperlink",
"python-sphinx",
"restructuredtext"
] | I am using the *Sphinx* `autodoc` feature to generate documentation based on the docstrings of my Python library.
The syntax for cross referencing is found [here](http://sphinx-doc.org/markup/inline.html#ref-role)
A label must precede the section in order to allow that section to be referenced from other areas of the... | You don't need to add labels. In order to refer to a Python class, method, or other documented object, use the markup provided by the [Python domain](http://sphinx-doc.org/domains.html#python-roles).
For example, the following defines a cross-reference to the `mymethod` method:
```
:py:meth:`mymodule.MyClass.mymethod... |
Pandas Dataframe Find Rows Where all Columns Equal | 22,701,799 | 8 | 2014-03-28T00:11:41Z | 22,701,944 | 11 | 2014-03-28T00:25:31Z | [
"python",
"pandas"
] | I have a dataframe that has characters in it - I want a boolean result by row that tells me if all columns for that row have the same value.
For example, I have
```
df = [ a b c d
0 'C' 'C' 'C' 'C'
1 'C' 'C' 'A' 'A'
2 'A' 'A' 'A' 'A' ]
```
and I want the result to be
```
0 True
1 ... | I think the cleanest way is to check all columns against the first column using eq:
```
In [11]: df
Out[11]:
a b c d
0 C C C C
1 C C A A
2 A A A A
In [12]: df.iloc[:, 0]
Out[12]:
0 C
1 C
2 A
Name: a, dtype: object
In [13]: df.eq(df.iloc[:, 0], axis=0)
Out[13]:
a b c ... |
how to multiply multiple columns by a column in Pandas | 22,702,760 | 11 | 2014-03-28T01:56:23Z | 22,702,814 | 15 | 2014-03-28T02:01:40Z | [
"python",
"pandas"
] | I would like to have:
```
df[['income_1', 'income_2']] * df['mtaz_proportion']
```
return those columns multiplied by `df['mtaz_proportion']`
so that I can set
```
df[['mtaz_income_1', 'mtaz_income_2']] =
df[['income_1', 'income_2']] * df['mtaz_proportion']
```
but instead I get:
```
income_1 income_2 0 ... | use `multiply` method and set `axis="index"`:
```
df[["A", "B"]].multiply(df["C"], axis="index")
``` |
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] | 22,703,393 | 12 | 2014-03-28T03:02:59Z | 22,704,271 | 23 | 2014-03-28T04:33:24Z | [
"python",
"scrapy",
"pip",
"x11",
"xcode5.1"
] | I get the following error trying to install Scrapy in a Mavericks OS.
I have command line tools and X11 installed I don't really know whats going on and I haven`t found the same error browsing through the Web. I think it might be related to some change in Xcode 5.1
Thanks for the answers!
this is part of the command... | It is due to a change in `clang` defaults in `Xcode 5.1` and Apple not noticing that it would break extension module builds using the system Python. One workaround is to define the following environment variables first:
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
```
UPDATE [2014-05-16]: A... |
clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future] | 22,703,393 | 12 | 2014-03-28T03:02:59Z | 22,885,038 | 8 | 2014-04-05T18:34:01Z | [
"python",
"scrapy",
"pip",
"x11",
"xcode5.1"
] | I get the following error trying to install Scrapy in a Mavericks OS.
I have command line tools and X11 installed I don't really know whats going on and I haven`t found the same error browsing through the Web. I think it might be related to some change in Xcode 5.1
Thanks for the answers!
this is part of the command... | The latest version of clang **raised to the level of error** what used to be a warning. To switch back you can **remove this behavior inline** right before running your install command:
```
ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install <your package>
```
This should work, but just... |
Flask-SQLAlchemy and Flask-Restless not fetching grandchildren | 22,707,223 | 4 | 2014-03-28T08:02:12Z | 26,248,306 | 8 | 2014-10-08T02:28:57Z | [
"python",
"sqlalchemy",
"flask",
"flask-sqlalchemy",
"flask-restless"
] | ## Problem
I am building an app on Flask, Flask-SQLAlchemy, and Flask-Restless. I have used restless to generate an API for a parent-child-grandchild relationship\*. A GET on my child will correctly fetch the grandchild, but a GET on the parent will not fetch the grandchild for each child.
\*In fact, the parent-child... | [postprocessors](http://flask-restless.readthedocs.org/en/latest/customizing.html#request-preprocessors-and-postprocessors) can be used to fetch grandchild.
```
def parent_post_get_many(result=None, search_params=None, **kw):
for object in result['objects']:
for child in object['children']:
grandchil... |
Flask - ImportError: No module named app | 22,711,087 | 5 | 2014-03-28T11:05:31Z | 22,711,701 | 9 | 2014-03-28T11:33:26Z | [
"python",
"python-import"
] | First I created `__init__.py`
```
from flask import Flask
app = Flask(__name__)
```
Then in a separate file, in the same directory, `run.py`
```
from app import app
app.run(
debug = True
)
```
When I try to run `run.py`, I get the error
```
Traceback (most recent call last):
File "run.py", line 1, in <mod... | `__init__.py` is imported using a directory. if you want to import it as `app` you should put `__init__.py` file in directory named `app`
a better option is just to rename `__init__.py` to `app.py` |
How to use `numpy.savez` in a loop for save more than one array? | 22,712,292 | 5 | 2014-03-28T12:02:36Z | 22,712,918 | 7 | 2014-03-28T12:29:37Z | [
"python",
"arrays",
"numpy"
] | From a loop I'm getting an array. I want to save this arrays in a `tempfile`.
The problem is that `np.savez` only saves the last array from the loop. I think I understand why this happens, but dont know how to do it better.
To solve my problem I had the idea to open the tempfile in `mode=a+b` with the goal to append t... | You can use the `*args` arguments to save many arrays in only one temp file.
```
np.savez(tmp, *getarray[:10])
```
or:
```
np.savez(tmp, *[getarray[0], getarray[1], getarray[8]])
``` |
Recursively searching for files with specific extensions in a directory | 22,714,013 | 2 | 2014-03-28T13:19:06Z | 22,714,118 | 7 | 2014-03-28T13:23:00Z | [
"python"
] | For some reason this returns me an empty list, and I have no idea why.
```
import os, fnmatch
vidext = ['.avi', '.mkv', '.wmv', '.mp4', '.mpg', '.mpeg', '.mov', '.m4v']
def findExt(folder):
matches = []
for root, dirnames, filenames in os.walk(folder):
for extension in vidext:
for filenam... | You'd need to add a wildcard to each extension for `fnmatch.filter()` to match:
```
fnmatch.filter(filenames, '*' + extension)
```
but there is no need to use `fnmatch` here at all. Just use `str.endswith()`:
```
for root, dirnames, filenames in os.walk(folder):
for filename in filenames:
if filename.end... |
Scheduling Python Script to run every hour accurately | 22,715,086 | 17 | 2014-03-28T14:05:37Z | 22,715,345 | 18 | 2014-03-28T14:16:04Z | [
"python",
"python-3.x",
"cron",
"scheduled-tasks",
"cron-task"
] | Before I ask, **Cron Jobs and Task Scheduler** will be my last options, this script will be used across Windows and Linux and I'd prefer to have a coded out method of doing this than leaving this to the end user to complete.
Is there a library for Python that I can use to schedule tasks? I will need to run a function ... | Maybe this can help: [Advanced Python Scheduler](http://apscheduler.readthedocs.io/)
Here's a small piece of code from their documentation:
```
from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "Decorated job"
scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interva... |
Plot topics with bokeh or matplotlib | 22,715,696 | 11 | 2014-03-28T14:31:14Z | 22,729,291 | 13 | 2014-03-29T09:28:56Z | [
"python",
"matplotlib",
"data-visualization",
"bokeh"
] | I'm trying to plot topic visualization from a model.
I want to do something like bokeh covariance [implementation](http://bokeh.pydata.org/docs/gallery/les_mis.html).
My data is:
```
data 1: index, topics.
data 2: index, topics, weights(use it for color).
```
where topic is just set of ... | **UPDATE**: The answer below is still correct in all major points, but the API has changed slightly to be more explicit as of Bokeh 0.7. In general, things like:
```
rect(...)
```
should be replaced with
```
p = figure(...)
p.rect(...)
```
---
Here are the relevant lines from the Les Mis examples, simplified to yo... |
How can one modify the outline color of a node In networkx? | 22,716,161 | 7 | 2014-03-28T14:51:10Z | 22,717,772 | 7 | 2014-03-28T16:03:32Z | [
"python",
"matplotlib",
"attributes",
"nodes",
"networkx"
] | I am relatively new to networkx and plotting using matplotlib.pyplot and would like to know how to modify the color (or other attributes such as weight) of a node's outline. By "outline" I don't mean an arc or edge between two nodes; I mean the thin black line around the circle that is by default used to represent a no... | Ok, this is kind of hacky, but it works. Here's what I came up with.
**The Problem**
`networkx.draw()` calls `networkx.draw_networkx_nodes()`, which then calls `pyplot.scatter()` to draw the nodes. The problem is that the keyword args accepted by `draw_networkx_nodes()` aren't passed on to `scatter()`. ([source here]... |
Pandas Left Outer Join results in table larger than left table | 22,720,739 | 10 | 2014-03-28T18:39:48Z | 22,720,823 | 14 | 2014-03-28T18:44:48Z | [
"python",
"pandas"
] | From what I understand about a left outer join, the resulting table should never have more rows than the left table...Please let me know if this is wrong...
My left table is 192572 rows and 8 columns.
My right table is 42160 rows and 5 columns.
My Left table has a field called 'id' which matches with a column in my ... | You can expect this to increase if keys match more than one row in the other DataFrame:
```
In [11]: df = pd.DataFrame([[1, 3], [2, 4]], columns=['A', 'B'])
In [12]: df2 = pd.DataFrame([[1, 5], [1, 6]], columns=['A', 'C'])
In [13]: df.merge(df2, how='left') # merges on columns A
Out[13]:
A B C
0 1 3 5
1 ... |
Sorting a nested OrderedDict by key, recursively | 22,721,579 | 3 | 2014-03-28T19:29:35Z | 22,721,724 | 8 | 2014-03-28T19:36:37Z | [
"python",
"sorting",
"recursion",
"ordereddictionary"
] | Say `orig` is an `OrderedDict` which contains normal string:string key value pairs, but sometimes the value could be another, nested `OrderedDict`.
I want to sort `orig` by key, alphabetically (ascending), and do it *recursively*.
Rules:
* Assume key strings are unpredictable
* Assume nesting can take place infinite... | something like:
```
def sortOD(od):
res = OrderedDict()
for k, v in sorted(od.items()):
if isinstance(v, dict):
res[k] = sortOD(v)
else:
res[k] = v
return res
``` |
Import order coding standard | 22,722,976 | 41 | 2014-03-28T20:51:49Z | 22,771,367 | 41 | 2014-03-31T20:17:38Z | [
"python",
"python-import",
"static-analysis",
"pep8"
] | [PEP8](http://www.python.org/dev/peps/pep-0008/#id16) suggests that:
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
>
> You should put a blank line between each group of imports.
Is there a way to che... | Found it! (accidentally, while reading "Hacker's guide to python")
*OpenStack Hacking Style Checks* project named [hacking](https://github.com/openstack-dev/hacking) introduces several unique [`flake8`](https://pypi.python.org/pypi/flake8) extensions. There is [hacking\_import\_groups](https://github.com/openstack-dev... |
Import order coding standard | 22,722,976 | 41 | 2014-03-28T20:51:49Z | 22,789,161 | 17 | 2014-04-01T14:39:37Z | [
"python",
"python-import",
"static-analysis",
"pep8"
] | [PEP8](http://www.python.org/dev/peps/pep-0008/#id16) suggests that:
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
>
> You should put a blank line between each group of imports.
Is there a way to che... | Have a look at <https://pypi.python.org/pypi/isort> or <https://github.com/timothycrosley/isort>
> isort parses specified files for global level import lines (imports outside of try / excepts blocks, functions, etc..) and puts them all at the top of the file grouped together by the type of import:
>
> * Future
> * Pyt... |
Import order coding standard | 22,722,976 | 41 | 2014-03-28T20:51:49Z | 35,213,338 | 7 | 2016-02-04T23:00:48Z | [
"python",
"python-import",
"static-analysis",
"pep8"
] | [PEP8](http://www.python.org/dev/peps/pep-0008/#id16) suggests that:
> Imports should be grouped in the following order:
>
> 1. standard library imports
> 2. related third party imports
> 3. local application/library specific imports
>
> You should put a blank line between each group of imports.
Is there a way to che... | The current version of pylint now does this, and reports it as error class C0411. |
TypeError with ufunc bitwise_xor | 22,725,421 | 6 | 2014-03-29T00:24:53Z | 22,725,500 | 11 | 2014-03-29T00:36:37Z | [
"python",
"if-statement",
"numpy",
"typeerror"
] | In my program which traces out the path of a particle, I get the following error:
```
Traceback (most recent call last):
File "C:\Users\Felix\Google Drive\Research\particles.py", line 154, in <module>
bfield += b_X(r_p(r,pos[2]))*(r_p(r,pos[2])/r)
*((r-r_p(r,pos[2]))**2+pos[2]**2)^(-1/2)*np.array
([(1-r... | In the offending line you are using a `^` when you want a `**` to raise a value to a power. Python interprets this as an xor:
```
bfield += b_X(r_p(r,pos[2]))*(r_p(r,pos[2])/r)*((r-r_p(r,pos[2]))**2+
pos[2]**2)^(-1/2)*np.array([(1-r_p(r,pos[2])/r)*pos[0],
(1-r_p(r,pos[2])/r)*pos[1],pos[2]])
```
See:
... |
Django test coverage vs code coverage | 22,726,449 | 14 | 2014-03-29T03:00:54Z | 22,852,442 | 14 | 2014-04-04T02:29:50Z | [
"python",
"django",
"unit-testing",
"code-coverage",
"django-nose"
] | I've successfully installed and configured [`django-nose`](https://github.com/django-nose/django-nose) with [`coverage`](https://pypi.python.org/pypi/coverage/3.7.1)
Problem is that if I just run coverage for `./manage.py shell` and exit out of that shell - it shows me 37% code coverage. I fully understand that execut... | since you use django-nose you have two options on how to run coverage. The first was already pointed out by DaveB:
```
coverage run ./manage.py test myapp
```
The above actually runs coverage which then monitors all code executed by the test command.
But then, there is also a nose coverage plugin included by default... |
Repeatedly failing to install scrapy and lxml | 22,727,782 | 12 | 2014-03-29T06:16:34Z | 23,239,568 | 44 | 2014-04-23T09:02:48Z | [
"python",
"ubuntu",
"scrapy",
"lxml"
] | I'd previously used Anaconda to handle python, but I'm and start working with virtual environments.
I set up virtualenv and virtualenvwrapper, and have been trying to add modules, specifically scrapy and lxml, for a project I want to try.
Each time I pip install, I hit an error.
For scrapy:
```
File "/home/philip/E... | I had the same problem in Ubuntu 14.04. I've solved it with the instructions of the page linked by @jdigital and the openssl-dev library pointed by @user3115915. Just to help others:
```
sudo apt-get install libxslt1-dev libxslt1.1 libxml2-dev libxml2 libssl-dev
sudo pip install scrapy
``` |
Django CMS - Placeholder for edit mode | 22,731,507 | 3 | 2014-03-29T13:09:34Z | 22,745,484 | 9 | 2014-03-30T14:57:30Z | [
"python",
"django",
"django-cms"
] | Is there a placeholder that indicates if the page is in edit mode or not? Something like
`{% is_edit_mode %}`?
I couldn't find anything in [djangocms documentation](http://django-cms.readthedocs.org/en/2.4.3/index.html). | in 3.0: {{ request.toolbar.edit\_mode }} |
Concatenating empty array in Numpy | 22,732,589 | 9 | 2014-03-29T14:52:17Z | 22,732,845 | 8 | 2014-03-29T15:14:21Z | [
"python",
"arrays",
"matlab",
"numpy"
] | in Matlab I do this:
```
>> E = [];
>> A = [1 2 3 4 5; 10 20 30 40 50];
>> E = [E ; A]
E =
1 2 3 4 5
10 20 30 40 50
```
Now I want the same thing in Numpy but I have problems, look at this:
```
>>> E = array([],dtype=int)
>>> E
array([], dtype=int64)
>>> A = array([[1,2,3,4,5],... | if you know the number of columns before hand:
```
>>> xs = np.array([[1,2,3,4,5],[10,20,30,40,50]])
>>> ys = np.array([], dtype=np.int64).reshape(0,5)
>>> ys
array([], shape=(0, 5), dtype=int64)
>>> np.vstack([ys, xs])
array([[ 1., 2., 3., 4., 5.],
[ 10., 20., 30., 40., 50.]])
```
if not:
```
>>... |
how to write a unicode csv in Python 2.7 | 22,733,642 | 5 | 2014-03-29T16:25:33Z | 22,734,072 | 7 | 2014-03-29T17:06:30Z | [
"python",
"python-2.7",
"csv",
"unicode"
] | I want to write data to files where a row from a CSV should look like this list (directly from the Python console):
```
row = ['\xef\xbb\xbft_11651497', 'http://kozbeszerzes.ceu.hu/entity/t/11651497.xml', "Szabolcs Mag '98 Kft.", 'ny\xc3\xadregyh\xc3\xa1za', 'ny\xc3\xadregyh\xc3\xa1za', '4400', 't\xc3\xbcnde utca 20.'... | You are passing bytestrings containing non-ASCII data in, and these are being decoded to Unicode using the default codec at this line:
```
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
```
`unicode(bytestring)` with data that cannot be decoded as ASCII fails:
```
>>> unicode('\xef\xbb\xbft_11651497... |
"ImportError: No module named httplib2" even after installation | 22,735,496 | 12 | 2014-03-29T19:01:12Z | 30,040,291 | 11 | 2015-05-04T21:27:53Z | [
"python",
"python-2.7",
"pip",
"httplib2"
] | I'm having a hard time understanding why I get `ImportError: No module named httplib2` after making sure httplib2 *is* installed. See below:
```
$ which -a python
/usr/bin/python
/usr/local/bin/python
$ pip -V
pip 1.4.1 from /usr/local/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg (python 2.7
$ pip list
google-ap... | If there are multiple Python instances (2 & 3), try different `pip`, for example:
Python 2:
```
pip2 install httplib2 --upgrade
```
Python 3:
```
pip3 install httplib2 --upgrade
```
To check what's installed and where, try:
```
pip list
pip2 list
pip3 list
```
Then make sure you're using the right Python instanc... |
backports/lzma/_lzmamodule.c:115:18: fatal error: lzma.h: No such file or directory | 22,738,077 | 6 | 2014-03-29T23:05:03Z | 22,764,178 | 11 | 2014-03-31T14:24:52Z | [
"python",
"pip",
"docker"
] | I'm trying to install docker-registry. I got stuck after this:
```
$ apt-get install python-pip python-dev
$ pip install -r requirements.txt
[...]
backports/lzma/_lzmamodule.c:115:18: fatal error: lzma.h: No such file or directory
```
The docker-registry I downloaded is v0.6.7 | ```
$ apt-get install -y liblzma-dev
``` |
A suitable 'do nothing' lambda expression in python? | 22,738,412 | 10 | 2014-03-29T23:46:10Z | 22,738,458 | 20 | 2014-03-29T23:52:35Z | [
"python",
"lambda"
] | I sometimes find myself wanting to make placeholder 'do nothing' lambda expressions, similar to saying:
```
def do_nothing(*args):
pass
```
But the following syntax is illegal since lambda expressions attempt to return whatever is after the colon, and you can't return `pass`.
```
do_nothing = lambda *args: pass
... | This:
```
def do_nothing(*args):
pass
```
is equivalent to:
```
lambda *args: None
```
With some minor differences in that one is a `lambda` and one isn't. (For example, `__name__` will be `do_nothing` on the function, and `<lambda>` on the lambda.) Don't forget about `**kwargs`, if it matters to you. Functions... |
PyCharm Unresolved reference 'print' | 22,738,455 | 21 | 2014-03-29T23:52:21Z | 23,043,824 | 33 | 2014-04-13T14:16:01Z | [
"python",
"pycharm"
] | I started to learn python language, and decided to try out PyCharm IDE, which looks really nice. But, whenever I write print it says "Unresolved reference 'print'". I can run the program, but this red-underline is really annoying. How can I fix this? | I have had the same problem as you, even though I configured Python 3.4.0 as the project's interpreter and all `print`'s in the code were Python 3 compliant function calls.
I got it sorted out by doing this in PyCharm:
> File -> Invalidate Caches / Restart... -> Invalidate and Restart |
Convert date from mm/dd/yyyy to another format in Python | 22,739,015 | 5 | 2014-03-30T01:02:41Z | 22,739,059 | 14 | 2014-03-30T01:08:04Z | [
"python",
"datetime",
"python-3.x"
] | I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays Janu... | Don't reinvent the wheel and use a combination of `strptime()` and `strftime()` from `datetime` module which is a part of python standard library ([docs](http://docs.python.org/3.3/library/datetime.html#strftime-strptime-behavior)):
```
>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy)... |
Mavericks Python 3.4 pip install error | 22,739,475 | 2 | 2014-03-30T02:14:44Z | 22,739,769 | 8 | 2014-03-30T03:03:21Z | [
"python",
"osx",
"pip"
] | Trying to install pip and I get this error
following <https://github.com/Homebrew/homebrew/wiki/Homebrew-and-Python>
```
Sumners-MacBook-Pro:Downloads Sumner$ python get-pip.py
Downloading/unpacking pip
Downloading pip-1.5.4-py2.py3-none-any.whl (1.2MB): 1.2MB downloaded
Installing collected packages: pip
Cleaning u... | As I cannot comment due to my lack of 50 reputation, I will 'comment' in an answer.
Although you may be admin, you still have to type `sudo` before you do anything...
To check if your account has admin privileges, type `sudo bash` in your terminal, and if it says `myusername is not in the sudoers file. This incident w... |
How to get html with javascript rendered sourcecode by using selenium | 22,739,514 | 9 | 2014-03-30T02:19:21Z | 22,739,613 | 12 | 2014-03-30T02:35:51Z | [
"javascript",
"python",
"selenium"
] | I run a query in one web page, then I get result url. If I right click see html source, I can see the html code generated by JS. If I simply use urllib, python cannot get the JS code. So I see some solution using selenium. Here's my code:
```
from selenium import webdriver
url = 'http://www.archives.com/member/Default... | You will need to get get the document via `javascript` you can use seleniums `execute_script` function
```
from time import sleep # this should go at the top of the file
sleep(5)
html = driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
print html
```
That will get everything inside o... |
How to share single SQLite connection in multi-threaded Python application | 22,739,590 | 7 | 2014-03-30T02:31:57Z | 22,739,924 | 10 | 2014-03-30T03:29:32Z | [
"python",
"multithreading",
"sqlite3"
] | I am trying to write a multi-threaded Python application in which a single SQlite connection is shared among threads. I am unable to get this to work. The real application is a cherrypy web server, but the following simple code demonstrates my problem.
What change or changes to I need to make to run the sample code, b... | It's not safe to share a connection between threads; at the very least you need to use a lock to serialize access. Do also read <http://docs.python.org/2/library/sqlite3.html#multithreading> as older SQLite versions have more issues still.
The `check_same_thread` option appears deliberately under-documented in that re... |
Django, save ModelForm | 22,739,701 | 9 | 2014-03-30T02:51:33Z | 22,749,879 | 17 | 2014-03-30T21:06:50Z | [
"python",
"django",
"django-forms"
] | I have created a model **Student** which extends from the **Django User** and is a foreign key to another model while it has an integer field called year. What i'm trying to do is to save a form, which has 2 fields. The one is the **course id** and the another one is the the integer field **year**. When I'm clicking su... | You dont need to redefine fields in the `ModelForm` if you've already mentioned them in the `fields` attribute. So your form should look like this -
```
class SelectCourseYear(forms.ModelForm):
class Meta:
model = Student
fields = ['course', 'year'] # removing user. we'll handle that in view
```
A... |
How to update Django HttpRequest body in Middleware | 22,740,310 | 4 | 2014-03-30T04:38:09Z | 22,745,559 | 7 | 2014-03-30T15:03:20Z | [
"python",
"django",
"httprequest",
"middleware"
] | I have a PUT request and I want to update the values of few of the params in my middleware. I know there is no way to directly access the PUT params, so I'm accessing them via `request.body`.
Once these values have been updated, I need to pass this `request` onto the view. However, if I try to do:
```
request.body = ... | [`request.body`](https://github.com/django/django/blob/master/django/http/request.py#L204) is defined as a `property` in [`HttpRequest`](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest) class.
This is code how `body` property looks like:
```
@property
def body(self):
if not has... |
How do I remove identical items from a list and sort it in Python? | 22,741,068 | 6 | 2014-03-30T06:37:56Z | 22,741,069 | 15 | 2014-03-30T06:37:56Z | [
"python",
"performance",
"list",
"sorting",
"set"
] | How can I most optimally remove identical items from a list and sort it in Python?
Say I have a list:
```
my_list = ['a', 'a', 'b', 'c', 'd', 'a', 'e', 'd', 'f', 'e']
```
I could iterate over a copy of the list (since you should not mutate the list while iterating over it), item for item, and remove all of the item ... | The best way to remove redundant elements from a list is to cast it as a set, and since sorted accepts any iterable and returns a list, this is far more efficient than doing this piecewise.
```
my_list = ['a', 'a', 'b', 'c', 'd', 'a', 'e', 'd', 'f', 'e']
def sorted_set(a_list):
return sorted(set(a_list))
new_lis... |
Python Selenium Webdriver - Try except loop | 22,741,591 | 4 | 2014-03-30T07:50:00Z | 22,741,689 | 11 | 2014-03-30T08:05:29Z | [
"python",
"selenium",
"try-except"
] | I'm trying to automate processes on a webpage that loads frame by frame. I'm trying to set up a `try-except` loop which executes only after an element is confirmed present. This is the code I've set up:
```
from selenium.common.exceptions import NoSuchElementException
while True:
try:
link = driver.find_e... | The answer on your specific question is:
```
from selenium.common.exceptions import NoSuchElementException
link = None
while not link:
try:
link = driver.find_element_by_xpath(linkAddress)
except NoSuchElementException:
time.sleep(2)
```
However, there is a better way to wait until element ap... |
Python : Finding an item in a list where a function return a minimum value? | 22,744,237 | 2 | 2014-03-30T12:53:57Z | 22,744,252 | 8 | 2014-03-30T12:55:33Z | [
"python",
"list-comprehension"
] | I've a list of point with coordinates and another point.
A sample from the list :
```
(45.1531912,5.7184742),(45.1531912,5.7184742),(45.1531113,5.7184544),(45.1525337,5.718298),(45.1525337,5.718298),
```
A point :
```
(45.1533837,5.7185242)
```
A function :
```
def dist(point1,point2)
....
return aDistance
... | The [`min()` function](http://docs.python.org/2/library/functions.html#min) takes a `key` argument already, no need for a list comprehension.
Let's say you wanted to find the closest point in the list to the origin:
```
min(list_of_points, key=lambda p: distance(p, (0, 0)))
```
would find it (given a `distance()` fu... |
Using 'if in' with a dictionary | 22,744,903 | 4 | 2014-03-30T14:02:56Z | 22,744,932 | 8 | 2014-03-30T14:05:40Z | [
"python",
"dictionary"
] | I can't believe it, but I've been stumped by what should be a very simple task.
I need to check if a value is in a dictionary as ***either*** key or value. I can find keys using `if 'A' in dictionary`, however I can't seem to get this to work for `values`. I realise I could use a for loop to do this and I may resort t... | You can use `in` operator and `any` function like this
```
value in dictionary or any(value in dictionary[key] for key in dictionary)
```
Here, `value in dictionary` makes sure that the expression is evaluated to be Truthy if the `value` is one of the keys of `dictionary`
```
any(value in dictionary[key] for key in ... |
Runtime error:App registry isn't ready yet | 22,744,949 | 9 | 2014-03-30T14:07:12Z | 23,241,093 | 11 | 2014-04-23T10:05:58Z | [
"python",
"django",
"runtime-error",
"django-1.7"
] | I am trying to create a script that populates a database with test users. I am new to Django and Python. I keep on getting:
```
Runtime error: App registry isn't ready yet.
```
Here is the output and error:
```
starting population script
Traceback (most recent call last):
File "populate.py", line 32, in <module>
pop... | # [django 1.7] The Standalone script you wish to run, import django and settings like below
```
import os
import django
[...]
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
``` |
Python print unicode list | 22,745,876 | 4 | 2014-03-30T15:29:17Z | 22,746,048 | 9 | 2014-03-30T15:44:28Z | [
"python",
"string",
"python-2.7",
"python-unicode"
] | With the following code
```
lst = [u'\u5de5', u'\u5de5']
msg = repr(lst).decode('unicode-escape')
print msg
```
I got
```
[u'å·¥', u'å·¥']
```
How can I remove the leading `u` so that the content of `msg` is:
```
['å·¥', 'å·¥']
``` | ```
>>> import sys
>>> lst = [u'\u5de5', u'\u5de5']
>>> msg = repr([x.encode(sys.stdout.encoding) for x in lst]).decode('string-escape')
>>> print msg
['å·¥', 'å·¥']
``` |
Split Python list of strings into seperate lists based on character | 22,747,722 | 2 | 2014-03-30T18:05:16Z | 22,747,921 | 7 | 2014-03-30T18:20:22Z | [
"python",
"algorithm",
"list"
] | I'm trying to figure out how to split the following list into separate lists based on a character in the list.
```
list = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']
```
I want to create a list after every "@" symbol is introduced. For example, I would want... | You could use `itertools.groupby`:
```
import itertools as IT
import operator
seq = ['@', '2014', '00:03:01', 'Matt', '"login"', '0.01', '@', '2014', '02:06:12', 'Mary', '"login"', '0.01']
groups = (list(g) for k,g in IT.groupby(seq, lambda item: item=='@'))
print(list(IT.starmap(operator.add, IT.izip(*[groups]*2)))... |
How to get the length of words in a sentence? | 22,749,706 | 5 | 2014-03-30T20:51:37Z | 22,749,723 | 9 | 2014-03-30T20:53:21Z | [
"python"
] | I am trying to get the length of each word in a sentence. I know you can use the "len" function, I just don't know how to get the length of each word.
Instead of this
```
>>> s = "python is pretty fun to use"
>>> len(s)
27
>>>
```
I'd like to get this
```
6, 2, 6, 3, 2, 3
```
which is the actual length of every wo... | Try this, using [`map()`](http://docs.python.org/2.7/library/functions.html#map) for applying [`len()`](http://docs.python.org/2.7/library/functions.html#len) over each word in the sentence, understanding that [`split()`](https://docs.python.org/2/library/string.html#string.split) creates a list with each word in the s... |
How to get the length of words in a sentence? | 22,749,706 | 5 | 2014-03-30T20:51:37Z | 22,749,725 | 8 | 2014-03-30T20:53:30Z | [
"python"
] | I am trying to get the length of each word in a sentence. I know you can use the "len" function, I just don't know how to get the length of each word.
Instead of this
```
>>> s = "python is pretty fun to use"
>>> len(s)
27
>>>
```
I'd like to get this
```
6, 2, 6, 3, 2, 3
```
which is the actual length of every wo... | Use [`map`](http://docs.python.org/2/library/functions.html#map)1 and [`str.split`](http://docs.python.org/2/library/stdtypes.html#str.split):
```
>>> s = "python is pretty fun to use"
>>> map(len, s.split())
[6, 2, 6, 3, 2, 3]
>>>
```
---
1*Note*: `map` returns an iterator in Python 3. If you are using that version... |
ImportError: cannot import name inplace_column_scale | 22,750,247 | 21 | 2014-03-30T21:41:59Z | 22,871,433 | 29 | 2014-04-04T19:24:07Z | [
"python",
"scikit-learn"
] | Using Python 2.7 with scikit-learn 0.14 package. It runs well on some examples from the user guild expect the Linear Models.
```
Traceback (most recent call last):
File "E:\P\plot_ols.py", line 28, in <module>
from sklearn import datasets, linear_model
File "C:\Python27\lib\site-packages\sklearn\linear_model\__init__.... | I was able to fix this by going to my python folder and deleting the file:
```
python27\Lib\site-packages\sklearn\utils\sparsefuncs.pyd
```
My guess is that the problem was:
1. An older version of scikit-learn implemented sparsefuncs as a windows DLL
2. The current version implements it as a python file
3. If you in... |
ImportError: cannot import name inplace_column_scale | 22,750,247 | 21 | 2014-03-30T21:41:59Z | 23,130,198 | 18 | 2014-04-17T10:06:14Z | [
"python",
"scikit-learn"
] | Using Python 2.7 with scikit-learn 0.14 package. It runs well on some examples from the user guild expect the Linear Models.
```
Traceback (most recent call last):
File "E:\P\plot_ols.py", line 28, in <module>
from sklearn import datasets, linear_model
File "C:\Python27\lib\site-packages\sklearn\linear_model\__init__.... | I encountered the same issue in Mac Os.
I solved it by deleting the file manually:
> rm /usr/local/lib/python2.7/site-packages/sklearn/utils/sparsefuncs.so |
Split large text file(around 50GB) into multiple files | 22,751,000 | 3 | 2014-03-30T22:55:41Z | 22,752,317 | 10 | 2014-03-31T01:35:54Z | [
"python",
"unix",
"python-2.7",
"split"
] | I would like to split a large text file around size of 50GB into multiple files.
Data in the files are like this-[x= any integer between 0-9]
```
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx
...............
...............
```
There might be few billions of lines in the file and i would like write ... | This working solution uses `split` command available in shell. Since the author has already accepted a possibility of a non-python solution, please do not downvote.
First, I created a test file with 1000M entries (15 GB) with
```
awk 'BEGIN{for (i = 0; i < 1000000000; i++) {print "123.123.123.123"} }' > t.txt
```
Th... |
sqlite3.OperationalError: Could not decode to UTF-8 column | 22,751,363 | 3 | 2014-03-30T23:38:50Z | 22,751,440 | 13 | 2014-03-30T23:48:04Z | [
"python",
"sqlite",
"sqlite3"
] | I have a sqlite database with this row of information, the ù should really be a '-'
```
sqlite> select * from t_question where rowid=193;
193|SAT1000|having a pointed, sharp qualityùoften used to describe smells|pungent|lethargic|enigmatic|resolute|grievous
```
When I read that row from python I get this error, wha... | Set `text_factory` to `str`:
```
conn = sqlite3.connect('sat1000.db')
conn.text_factory = str
```
This will [cause `cur` to return `str`s](https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.text_factory) instead of automatically trying to decode the `str` with the `UTF-8` codec.
I wasn't able to find ... |
DLL load failed with scipy.optimize? | 22,753,695 | 6 | 2014-03-31T04:32:54Z | 31,504,138 | 11 | 2015-07-19T17:49:32Z | [
"python",
"matplotlib",
"scipy"
] | I'm trying to upload the curve\_fit from scipy.optimize to fit an exponential function to some data I have generated. My code looks like:
```
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
```
When I run the code, I get the following error:
> ImportError: DLL load failed: The... | I encountered the error
```
from ._ufuncs import *
ImportError: DLL load failed: The specified module could not be found.
```
when using [cgoehlke's "Unofficial Windows Binaries for Python Extension Packages" for SciPy](http://www.lfd.uci.edu/~gohlke/pythonlibs/) with a pip3-installed NumPy, overlooking this note... |
Parallel I/O - why does it work? | 22,755,218 | 6 | 2014-03-31T06:53:11Z | 22,755,533 | 7 | 2014-03-31T07:11:52Z | [
"python",
"io",
"parallel-processing"
] | I have a python function which reads a line from a text file and writes it to another text file. It repeats this for every line in the file. Essentially:
```
Read line 1 -> Write line 1 -> Read line 2 -> Write line 2...
```
And so on.
I can parallelise this process, using a queue to pass data, so it is more like:
`... | In short: IO buffering. Two levels of it, even.
First, Python itself has IO buffers. So, when you write all those lines to the file, Python doesn't necessarily invoke the `write` syscall immediately - it does that when it flushes its buffers, which could be anytime from when you call write until you close the file. Th... |
How to avoid e-05 in python | 22,756,324 | 2 | 2014-03-31T07:56:30Z | 22,756,459 | 7 | 2014-03-31T08:04:22Z | [
"python",
"int",
"decimal"
] | I have a Python program where i calculate some probabilities, but in some of the answers I get f.ex. 8208e-06, but I want my numbers to come out on the regular form 0.000008... How do I do this? | You can use the `f` format specifier and specify the number of decimal digits:
```
>>> '{:.10f}'.format(1e-10)
'0.0000000001'
```
Precision defaults to `6`, so:
```
>>> '{:f}'.format(1e-6)
'0.000001'
>>> '{:f}'.format(1e-7)
'0.000000'
```
---
If you want to remove trailing zeros just [`rstrip`](https://docs.python... |
Compact way to assign values by slicing list in Python | 22,756,632 | 44 | 2014-03-31T08:15:21Z | 22,756,643 | 86 | 2014-03-31T08:16:26Z | [
"python",
"list",
"slice"
] | I have the following list
```
bar = ['a','b','c','x','y','z']
```
What I want to do is to assign 1st, 4th and 5th values of `bar` into `v1,v2,v3`,
is there a more compact way to do than this:
```
v1, v2, v3 = [bar[0], bar[3], bar[4]]
```
Because in Perl you can do something like this:
```
my($v1, $v2, $v3) = @bar[... | You can use [`operator.itemgetter`](https://docs.python.org/2/library/operator.html#operator.itemgetter):
```
>>> from operator import itemgetter
>>> bar = ['a','b','c','x','y','z']
>>> itemgetter(0, 3, 4)(bar)
('a', 'x', 'y')
```
So for your example you would do the following:
```
>>> v1, v2, v3 = itemgetter(0, 3, ... |
Compact way to assign values by slicing list in Python | 22,756,632 | 44 | 2014-03-31T08:15:21Z | 22,756,672 | 35 | 2014-03-31T08:18:23Z | [
"python",
"list",
"slice"
] | I have the following list
```
bar = ['a','b','c','x','y','z']
```
What I want to do is to assign 1st, 4th and 5th values of `bar` into `v1,v2,v3`,
is there a more compact way to do than this:
```
v1, v2, v3 = [bar[0], bar[3], bar[4]]
```
Because in Perl you can do something like this:
```
my($v1, $v2, $v3) = @bar[... | Since you want compactness, you can do it something as follows:
```
indices = (0,3,4)
v1, v2, v3 = [bar[i] for i in indices]
>>> print v1,v2,v3 #or print(v1,v2,v3) for python 3.x
a x y
``` |
Compact way to assign values by slicing list in Python | 22,756,632 | 44 | 2014-03-31T08:15:21Z | 22,756,712 | 21 | 2014-03-31T08:20:44Z | [
"python",
"list",
"slice"
] | I have the following list
```
bar = ['a','b','c','x','y','z']
```
What I want to do is to assign 1st, 4th and 5th values of `bar` into `v1,v2,v3`,
is there a more compact way to do than this:
```
v1, v2, v3 = [bar[0], bar[3], bar[4]]
```
Because in Perl you can do something like this:
```
my($v1, $v2, $v3) = @bar[... | In `numpy`, you can index an array [with another array](http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays) that contains indices. This allows for very compact syntax, exactly as you want:
```
In [1]: import numpy as np
In [2]: bar = np.array(['a','b','c','x','y','z'])
In [3]: v1, v2, v3 = bar[[0, ... |
Compact way to assign values by slicing list in Python | 22,756,632 | 44 | 2014-03-31T08:15:21Z | 22,761,913 | 43 | 2014-03-31T12:46:16Z | [
"python",
"list",
"slice"
] | I have the following list
```
bar = ['a','b','c','x','y','z']
```
What I want to do is to assign 1st, 4th and 5th values of `bar` into `v1,v2,v3`,
is there a more compact way to do than this:
```
v1, v2, v3 = [bar[0], bar[3], bar[4]]
```
Because in Perl you can do something like this:
```
my($v1, $v2, $v3) = @bar[... | Assuming that your indices are neither dynamic nor too large, I'd go with
```
bar = ['a','b','c','x','y','z']
v1, _, _, v2, v3, _ = bar
``` |
Compact way to assign values by slicing list in Python | 22,756,632 | 44 | 2014-03-31T08:15:21Z | 22,762,192 | 7 | 2014-03-31T12:59:28Z | [
"python",
"list",
"slice"
] | I have the following list
```
bar = ['a','b','c','x','y','z']
```
What I want to do is to assign 1st, 4th and 5th values of `bar` into `v1,v2,v3`,
is there a more compact way to do than this:
```
v1, v2, v3 = [bar[0], bar[3], bar[4]]
```
Because in Perl you can do something like this:
```
my($v1, $v2, $v3) = @bar[... | Yet another method:
```
from itertools import compress
bar = ['a','b','c','x','y','z']
v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1, 0))
```
In addition, you can ignore length of the list and skip zeros at the end of selectors:
```
v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1,))
```
<https://docs.python.org/2/library/it... |
PyCharm & Pyenv local? | 22,756,788 | 5 | 2014-03-31T08:24:45Z | 22,845,314 | 7 | 2014-04-03T17:53:15Z | [
"python",
"virtualenv",
"pycharm"
] | After I broke my Ubuntu precise with a Cython compilation I like to keep the system Python clean. I like to have 2.7.x & 3.4.x besides each other and used Pyenv to have a global default interpreter independent from the system python. Now I also want to define local interpreters on a per project basis, usually done with... | I'd suggest to use <https://github.com/yyuu/pyenv-virtualenv> to create virtualenv for a desired interpreter and then add it as a Python interpreter in PyCharm. |
Django-rest-framework permissions for create in viewset | 22,760,191 | 10 | 2014-03-31T11:16:22Z | 22,767,325 | 16 | 2014-03-31T16:41:12Z | [
"python",
"django",
"rest",
"django-rest-framework"
] | I am trying to create a REST API and am stuck at user registration: basically I need to have the access token before I register.
This is the view:
```
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_... | Customize the get\_queryset method:
```
def get_queryset(self):
if self.request.user.is_superuser:
return User.objects.all()
else:
return User.objects.filter(id=self.request.user.id)
```
This way, an authenticated user can only retrieve, modify or delete its own object.
Specify the `permissio... |
Overriding argparse -h behaviour part 2 | 22,763,139 | 6 | 2014-03-31T13:41:42Z | 22,763,319 | 9 | 2014-03-31T13:48:41Z | [
"python",
"argparse"
] | I am using python's argparse and would like to use the -h flag for my own purposes. Here's the catch -- I still want to have --help be available, so it seems that `parser = argparse.ArgumentParser('Whatever', add_help=False)` is not quite the solution.
Is there an easy way to re-use the -h flag while still keeping the... | Initialize `ArgumentParser` with `add_help=False`, add `--help` argument with `action="help"`:
```
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--help', action="help")
parser.add_argument('-h', help='My argument')
args = parser.parse_args()
...
```
Here's what on the command... |
NLTK Stopword List | 22,763,224 | 6 | 2014-03-31T13:45:24Z | 22,763,658 | 16 | 2014-03-31T14:02:55Z | [
"python",
"nltk",
"stop-words"
] | I have the code beneath and I am trying to apply a stop word list to list of words. However the results still show words such as "a" and "the" which I thought would have been removed by this process. Any ideas what has gone wrong would be great .
```
import nltk
from nltk.corpus import stopwords
word_list = open("xxx... | A few things of note.
* If you are going to be checking membership against a list over and over, I would use a set instead of a list.
* `stopwords.words('english')` returns a list of **lowercase** stop words. It is quite likely that your source has capital letters in it and is not matching for that reason.
* You aren'... |
py2exe change application name output | 22,765,503 | 6 | 2014-03-31T15:19:27Z | 22,766,108 | 11 | 2014-03-31T15:45:45Z | [
"python",
"py2exe"
] | I am working on my first Python project and I need compile with py2exe. I wrote this setup.py code :
```
from distutils.core import setup
import py2exe
import sys
import os
if len(sys.argv) == 1:
sys.argv.append("py2exe")
setup( options = {"py2exe": {"compressed": 1, "optimize": 2,"dll_excludes": "w9xpopen.exe"... | Add `"dest_base" : "app_name"` to your console dict as such:
> ```
> console = [
> {
> "script": "myapplication.py", ### Main Python script
> "icon_resources": [(0, "favicon.ico")], ### Icon to embed into the PE file.
> "dest_base" : "app_name"
> }]
> ``` |
Django REST Custom Errors | 22,766,366 | 5 | 2014-03-31T15:56:42Z | 22,767,436 | 9 | 2014-03-31T16:46:28Z | [
"python",
"django",
"api"
] | Iâm trying to create a custom error response from the REST Django framework.
Iâve included the following in my **views.py**,
```
from rest_framework.views import exception_handler
def custom_exception_handler(exc):
"""
Custom exception handler for Django Rest Framework that adds
the `status_code` to ... | As Bibhas said, with custom exception handlers, you only can return own defined errors when an exception is called. If you want to return a custom response error without exceptions being triggered, you need to return it in the view itself. For example:
```
return Response({'detail' : "Invalid arguments", 'args' : ... |
Python unimplemented methods versus abstract methods, which is more pythonic? PyCharm doesn't like methods not implemented in the base class | 22,766,798 | 3 | 2014-03-31T16:17:28Z | 22,767,063 | 7 | 2014-03-31T16:29:20Z | [
"python",
"abstract",
"pycharm"
] | I have a specific problem closely related to PyCharm (Community 3.1.1). The following simple example illustrates this. I will use the screenshot of PyCharm rather than type the code, for reasons that will be clear shortly.

As you can see, the call to `self.say_hello()` is highl... | I would implement `say_hello()` as a stub:
```
class Base(object):
# ...as above...
def say_hello(self):
raise NotImplementedError
```
Alternatively, put only pass in the body of `say_hello()`.
This would also signal to the user of your `Base` class that `say_hello()` should be implemented before sh... |
sklearn Ridge and sample_weight gives Memory Error | 22,766,978 | 2 | 2014-03-31T16:25:31Z | 22,810,670 | 7 | 2014-04-02T11:56:21Z | [
"python",
"scikit-learn",
"regression"
] | I'm trying to run a simple Sklearn Ridge regression using an array of sample weights.
X\_train is a ~200k by 100 2D Numpy array. I get a Memory error when I try to use sample\_weight option. It works just fine without that option. For the sake of simplicity I reduced the features to 2 and sklearn still throws me a Memo... | Setting sample weights can cause big differences in the way the sklearn linear\_model Ridge object processes your data - especially if the matrix is tall (n\_samples > n\_features), as is your case. Without sample weights it will exploit the fact that X.T.dot(X) is a relatively small matrix (100x100 in your case) and w... |
Python get the x first words in a string | 22,767,509 | 5 | 2014-03-31T16:49:55Z | 22,767,557 | 9 | 2014-03-31T16:52:39Z | [
"python",
"string"
] | I'm looking for a code that takes the 4 (or 5) first words in a script.
I tried this:
```
import re
my_string = "the cat and this dog are in the garden"
a = my_string.split(' ', 1)[0]
b = my_string.split(' ', 1)[1]
```
But I can't take more than 2 strings:
```
a = the
b = cat and this dog are in the garden
`... | The second argument of the `split()` method is the limit. Don't use it and you will get all words.
Use it like this:
```
my_string = "the cat and this dog are in the garden"
splitted = my_string.split()
first = splitted[0]
second = splitted[1]
...
```
Also, don't call `split()` every time when you want a word, ... |
unable to load a simple csv in networkx in Python | 22,768,224 | 2 | 2014-03-31T17:27:22Z | 22,768,350 | 7 | 2014-03-31T17:34:55Z | [
"python",
"csv",
"networkx"
] | I am a complete noobie in Python, and I would like to study a dataset using the networkx package. I do not understand what is wrong here:
I have a csv which looks like this (extract):
```
['152027', '-6167']
['152027', '-4982']
['152027', '-3810']
['152027', '-2288']
['152027', '-1253']
['152100', '-152100']
['152100... | `nx.read_edgelist` expects the first variable to be a file handle or filename string, not a `csv.reader` object.
Don't use `csv` at all; try just
```
G = nx.read_edgelist('nodes', delimiter=',', nodetype=int, encoding="utf-8")
```
**Edit:** if you need to skip a header line, you could do
```
with open('nodes', 'rb'... |
how to share a variable across modules for all tests in py.test | 22,768,976 | 8 | 2014-03-31T18:08:15Z | 22,793,013 | 12 | 2014-04-01T17:40:52Z | [
"python",
"unit-testing",
"testing",
"global-variables",
"py.test"
] | I have multiple tests run by py.test that are located in multiple classes in multiple files. What is the simplest way to share a large dictionary - which I do not want to duplicate - with every method of every class in every file to be used by py.test? In short, I need to make a "global variable" for every test. ... Ou... | You mention the obvious and least magical option: using a fixture. You can apply it to entire modules using `pytestmark = pytest.mark.usefixtures('big_dict')` in your module, but then it won't be in your namespace so explicitly requesting it might be best.
Alternatively you can assign things into the pytest namespace ... |
Pandas group by time windows | 22,769,047 | 3 | 2014-03-31T18:11:48Z | 22,769,285 | 7 | 2014-03-31T18:24:35Z | [
"python",
"pandas"
] | EDIT: [Session generation from log file analysis with pandas](http://stackoverflow.com/questions/17547391/session-generation-from-log-file-analysis-with-pandas) seems to be exactly what I was looking for.
I have a dataframe that includes non-unique time stamps, and I'd like to group them by time windows. The basic log... | This is how to use to create a custom grouper. (requires pandas >= 0.13) for the timedelta computations, but otherwise would work in other versions.
Create your series
```
In [31]: s = Series(range(6),pd.to_datetime(['20130101 10:34','20130101 10:34:08', '20130101 10:34:08', '20130101 10:34:15', '20130101 10:34:28', ... |
To preallocate or not to preallocate lists in Python | 22,769,666 | 7 | 2014-03-31T18:45:04Z | 22,769,736 | 15 | 2014-03-31T18:48:35Z | [
"python",
"list",
"obfuscation",
"allocation"
] | When should and shouldn't I preallocate a list of lists in python?
For example, I have a function that takes 2 lists and creates a lists of lists out of it.
Quite like, but not exactly, matrix multiplication. Should I preallocate the result,
```
X = Len(M)
Y = Len(F)
B = [[None for y in range(Y)] for x in range(X)]
fo... | Simply create the list using list comprehension:
```
[[foo(m, f) for f in F] for m in M]
```
Related to pre-allocation: [Pre-allocating a list of `None`](http://stackoverflow.com/questions/22225666/pre-allocating-a-list-of-none) |
python mysql.connector DictCursor? | 22,769,873 | 11 | 2014-03-31T18:55:49Z | 22,853,435 | 9 | 2014-04-04T04:13:28Z | [
"python",
"mysql",
"mysql-python",
"mysql-connector-python"
] | In Python `mysqldb` I could declare a cursor as a dictionary cursor like this:
```
cursor = db.cursor(MySQLdb.cursors.DictCursor)
```
This would enable me to reference columns in the `cursor` loop by name like this:
```
for row in cursor: # Using the cursor as iterator
city = row["city"]
state = row["stat... | A possible solution involves subclassing the `MySQLCursor` class like this:
```
class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
def _row_to_python(self, rowdata, desc=None):
row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
if row:
return dict(zip(self.column_n... |
python mysql.connector DictCursor? | 22,769,873 | 11 | 2014-03-31T18:55:49Z | 25,148,062 | 9 | 2014-08-05T20:50:35Z | [
"python",
"mysql",
"mysql-python",
"mysql-connector-python"
] | In Python `mysqldb` I could declare a cursor as a dictionary cursor like this:
```
cursor = db.cursor(MySQLdb.cursors.DictCursor)
```
This would enable me to reference columns in the `cursor` loop by name like this:
```
for row in cursor: # Using the cursor as iterator
city = row["city"]
state = row["stat... | According to this article it is available by passing in 'dictionary=True' to the cursor constructor:
<http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html>
so I tried:
```
cnx = mysql.connector.connect('database='bananas')
cursor = cnx.cursor(dictionary=True)
```
and got:
**TypeErro... |
auto.arima() equivalent for python | 22,770,352 | 20 | 2014-03-31T19:22:58Z | 22,770,973 | 19 | 2014-03-31T19:56:02Z | [
"python",
"time-series",
"forecasting",
"statsmodels"
] | I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `auto.arima()` which will tune the (p,d,q) parameters.
How do I go about choosing the right order for my model? Are there any libraries available in python... | You can implement a number of approaches:
1. [`ARIMAResults`](http://statsmodels.sourceforge.net/devel/generated/statsmodels.tsa.arima_model.ARIMAResults.html#statsmodels.tsa.arima_model.ARIMAResults) include `aic` and `bic`. By their definition, (see [here](http://en.wikipedia.org/wiki/Akaike_information_criterion) a... |
get "1" for a one-dimensional numpy.array using a shape-like function | 22,772,257 | 6 | 2014-03-31T21:11:12Z | 22,772,308 | 8 | 2014-03-31T21:13:37Z | [
"python",
"arrays",
"numpy",
"multidimensional-array",
"dimension"
] | In a function, I give a Numpy array : It can be multi-dimentional but also one-dimentional
So when I give a multi-dimentional array :
```
np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape
>>> (3, 4)
```
and
```
np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]]).shape[1]
>>> 4
```
Fine.
But when I ask the shape of
```... | ```
>>> a
array([1, 2, 3, 4])
>>> a.ndim
1
>>> b = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
>>> b.ndim
2
```
If you wanted a column vector, you can use the `.reshape` method - in fact, `.shape` is actually a settable property so numpy also lets you do this:
```
>>> a
array([1, 2, 3, 4])
>>> a.shape += (1,)
>>> a
... |
Generating plain text from a Wikipedia database dump | 22,772,952 | 6 | 2014-03-31T21:53:22Z | 22,772,997 | 9 | 2014-03-31T21:56:41Z | [
"python",
"xml",
"database",
"shell",
"wikipedia"
] | I found a Python script ([here: Wikipedia Extractor](http://medialab.di.unipi.it/wiki/Wikipedia_Extractor)) that can generate plain text from [(English) Wikipedia database dump](http://dumps.wikimedia.org/enwiki/20140304/).
When I use this command (as it's stated on the script's page):
```
$ python enwiki-latest-pages... | The first argument to `python` should be the script name.
You probably need to swap `xml` and `py` file names:
```
$ python WikiExtractor.py enwiki-latest-pages-articles.xml -b 500K -o extracted
``` |
Mac using default Python despite Anaconda install | 22,773,432 | 10 | 2014-03-31T22:27:46Z | 22,773,514 | 14 | 2014-03-31T22:34:55Z | [
"python",
"osx",
".bash-profile",
"anaconda",
"conda"
] | I am running Mac 10.9 Mavericks and have installed Anaconda. However, despite that, when I access python via terminal, I still get the default Apple version:
```
Python 2.7.5 (default, Sep 2 2013, 05:24:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
```
My .bash\_profile is this:
```
export P... | The first matching executable is the one that is run. From what I can gather you are concatenating your PATH variable in such a way that:
```
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
```
comes before:
```
$HOME/anaconda/bin
```
So **make sure** that the anaconda directory is the **first** one, meaning that it w... |
What is the safest way to removing Python framework files that are located in different place than Brew installs | 22,774,529 | 37 | 2014-04-01T00:11:09Z | 22,800,774 | 53 | 2014-04-02T03:06:59Z | [
"python",
"osx",
"homebrew",
"brew-doctor"
] | I want to remove a Python installed in location that brew complains about, when I run `brew doctor`
> **Warning:** Python is installed at /Library/Frameworks/Python.framework
**What is the best way?**
**Here are more details / research:**
The message from the brew git [website](https://github.com/Homebrew/homebrew/... | I'll self-answer. I went through steps and it's straight forward. Pycharms (the IDE I'm use) automatically found the new libraries too. Here are the steps I followed to remove the extra Python libraries on Mavericks that were not native to it and not installed by brew.
**Step 1:**
The native Python 2.7.x version lives... |
numpy - evaluate function on a grid of points | 22,774,726 | 9 | 2014-04-01T00:35:06Z | 22,778,484 | 10 | 2014-04-01T06:34:22Z | [
"python",
"arrays",
"numpy"
] | What is a good way to produce a numpy array containing the values of a function evaluated on an n-dimensional grid of points?
For example, suppose I want to evaluate the function defined by
```
def func(x, y):
return <some function of x and y>
```
Suppose I want to evaluate it on a two dimensional array of point... | shorter, faster and clearer answer, avoiding meshgrid:
```
import numpy as np
def func(x, y):
return np.sin(y * x)
xaxis = np.linspace(0, 4, 10)
yaxis = np.linspace(-1, 1, 20)
result = func(x[:,None], y[None,:])
```
This will be faster in memory if you get something like x^2+y as function, since than x^2 is don... |
How to specify long url patterns using Regex so that they follow PEP8 guidelines | 22,775,697 | 8 | 2014-04-01T02:26:02Z | 22,775,761 | 13 | 2014-04-01T02:32:40Z | [
"python",
"django",
"pep8"
] | I have a long url pattern in Django similar to this:
```
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)/(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',
```
Definitely it doesn't follow PEP8 guide as the characters are more than 80 in a single line. I have found two approach ... | Adjacent strings are concatenated, so you can do something like this:
```
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
r'(?P<second_slug>[-\w]+?)/'
r'(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',)
``` |
How to make nosetests use python3 | 22,779,289 | 13 | 2014-04-01T07:21:13Z | 30,114,754 | 8 | 2015-05-08T02:17:50Z | [
"python",
"nose"
] | I try to use `nosetests`
⯠nosetests '/pathTo/test'
but it uses `python 2.7` for my tests:
```
sys.version_info(major=2, minor=7, micro=5, releaselevel='final', serial=0)
```
So some of them fails, because they were written in `python 3.3`.
I work it around and installed virtual environment:
```
pyvenv-3.3 py3... | In `Python 3.4` and higher versions: in order to make nose use `python3` just run ...
```
python3 -m "nose"
```
... in the target directory with the tests.
The environment setups are not required. |
when to use if vs elif in python | 22,782,785 | 5 | 2014-04-01T10:11:29Z | 22,783,232 | 7 | 2014-04-01T10:30:38Z | [
"python",
"conditional-statements",
"idioms"
] | If I have function with multiple conditional statements where the branch that gets executed returns from the function, should I use multiple if statements, or if/elif/else? For example say I have a function:
```
def example(x):
if x > 0:
return 'positive'
if x < 0:
return 'negative'
return ... | I'll expand out my comment to an answer.
In the case that all cases return, these are indeed equivalent. What becomes important in choosing between them is then what is more readable.
Your latter example uses the `elif` structure to explicitly state that the cases are mutually exclusive, rather than relying on the fa... |
Initialize List to a variable in a Dictionary inside a loop | 22,783,778 | 3 | 2014-04-01T10:55:07Z | 22,783,812 | 9 | 2014-04-01T10:56:55Z | [
"python",
"dictionary"
] | I have been working for a while in Python and I have solved this issue using "try" and "except", but I was wondering if there is another method to solve it.
Basically I want to create a dictionary like this:
```
example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]}
```
So if I have a variable with ... | Your code is not appending elements to the lists; you are instead replacing the list with single elements. To access values in your existing dictionaries, you must use indexing, not attribute lookups (`item['name']`, not `item.name`).
Use [`collections.defaultdict()`](https://docs.python.org/2/library/collections.html... |
How to avoid HTTP error 429 (Too Many Requests) python | 22,786,068 | 23 | 2014-04-01T12:35:42Z | 23,367,215 | 41 | 2014-04-29T14:14:16Z | [
"python",
"http",
"mechanize"
] | I am trying to use Python to login to a website and gather information from several webpages and I get the following error:
> ```
> Traceback (most recent call last):
> File "extract_test.py", line 43, in <module>
> response=br.open(v)
> File "/usr/local/lib/python2.7/dist-packages/mechanize/_mechanize.py", li... | Receiving a status 429 is *not an error*, it is the other server "kindly" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.
You should not seek to "dodge" this, or even try to circumvent server security settings by trying to sp... |
How to have clusters of stacked bars with python (Pandas) | 22,787,209 | 18 | 2014-04-01T13:22:11Z | 22,845,857 | 20 | 2014-04-03T18:22:46Z | [
"python",
"matplotlib",
"plot",
"pandas",
"bar-chart"
] | So here is how my data set looks like :
```
In [1]: df1=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])
In [2]: df2=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])
In [3]: df1
Out[3]:
I J
A 0.675616 0.177597
B 0.675693 0.598682
C 0.63137... | So, I eventually found a trick :
Here it is with a more complete example :
```
import pandas as pd
import matplotlib.cm as cm
import numpy as np
import matplotlib.pyplot as plt
def plot_clustered_stacked(dfall, labels=None, title="multiple stacked bar plot", H="/", **kwargs):
"""Given a list of dataframes, with... |
Getting 'str' object has no attribute 'get' in Django | 22,788,135 | 10 | 2014-04-01T13:58:33Z | 22,788,493 | 32 | 2014-04-01T14:12:02Z | [
"python",
"django",
"django-views",
"django-urls"
] | This is my first question here on stackoverflow:
views.py
```
def generate_xml(request, number):
caller_id = 'x-x-x-x'
resp = twilio.twiml.Response()
with resp.dial(callerId=caller_id) as r:
if number and re.search('[\d\(\)\- \+]+$', number):
r.number(number)
else:
... | You can not pass directly `str` as a `django response` .
You must use
```
from django.http import HttpResponse
```
if you want to render string data as django view response.
have a look [here](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponse)
```
return HttpResponse(resp)
``` |
ImportError: No module named _imagingtk | 22,788,454 | 5 | 2014-04-01T14:10:29Z | 22,788,542 | 9 | 2014-04-01T14:14:16Z | [
"python",
"python-2.7",
"user-interface",
"tkinter"
] | I wanted to start using Tkinter with python and have following code:
```
#!/usr/bin/python
from Tkinter import *
from PIL import ImageTk, Image
top = Tk()
dir(top)
top.title("Erstes Frame")
erstesFrame = Frame(top, height=250, width=250)
erstesFrame.pack_propagate(0)
erstesFrame.pack()
img = ImageTk.PhotoImage(Ima... | You need to install [`ImageTk`](http://effbot.org/imagingbook/imagetk.htm) module.
In debian, ubuntu, you can use following command to install it:
```
sudo apt-get install python-imaging-tk
``` |
str.isdecimal() and str.isdigit() difference example | 22,789,392 | 14 | 2014-04-01T14:48:47Z | 22,789,660 | 12 | 2014-04-01T15:00:32Z | [
"python",
"python-3.x"
] | Reading python docs I have come to .isdecimal() and .isdigit() string functions and i'm not finding literature too clear on their usable distinction. Could someone supply me with code examples of where these two functions differentiate please.
Similar behaviour:
```
>>> str.isdecimal('1')
True
>>> str.isdigit('1')
Tr... | There *are* differences, but they're somewhat rare\*. It mainly crops up with various unicode characters, such as `2`:
```
>>> c = '\u00B2'
>>> c.isdecimal()
False
>>> c.isdigit()
True
```
You can also go further down the careful-unicode-distinction rabbit hole with the `isnumeric` method:
```
>>> c = '\u00BD' # ½
... |
How to break up one print command in two lines of code in Python 3 | 22,792,101 | 2 | 2014-04-01T16:52:32Z | 22,792,131 | 7 | 2014-04-01T16:54:12Z | [
"python",
"python-3.x",
"printing"
] | I want to print one continuous message with two lines of code using print, how can I do this?
```
print('Hello how are you')
print('today?')
```
But this gives me
```
Hello how are you
today?
```
While I want
```
Hello how are you today?
``` | Use `end=' '` to replace the newline with a space:
```
print('Hello how are you', end=' ')
print('today?')
``` |
how to set local rcParams or rcParams for one figure in matplotlib | 22,792,779 | 5 | 2014-04-01T17:28:18Z | 22,794,651 | 11 | 2014-04-01T19:02:30Z | [
"python",
"matplotlib",
"plot"
] | I am writing a plotting function in `python` using `matplotlib`. The user can specify some things, e.g. "tick lines". The easiest way would be to change the `rcParams`, but those are global properties, so all new plots will have tick lines after that plotting function was called.
Is there a way to set the plotting def... | You can use the `rc_context` function in a `with` statement, which will set the rc parameters with a dictionary you provide for the block indented below and then reset them to whatever they were before after the block. For example:
```
with plt.rc_context({"axes.grid": True, "grid.linewidth": 0.75}):
f, ax = plt.s... |
Pretty print JSON python | 22,792,848 | 5 | 2014-04-01T17:32:36Z | 22,792,883 | 30 | 2014-04-01T17:34:24Z | [
"python",
"json",
"string",
"google-visualization",
"pprint"
] | if anybody with some knowledge about pretty printing JSON could help me with this I would be extremely grateful!
I'm looking to convert a complex python string into JSON format, using the function below to move the JSON string to a file:
```
with open('data.txt', 'wt') as out:
pprint(string, stream=out)
```
The ... | You are writing *Python representations*, not JSON.
Use the [`json.dump()` function](https://docs.python.org/2/library/json.html#json.dump) to write pretty-printed JSON instead, directly to your file:
```
with open('data.txt', 'wt') as out:
res = json.dump(obj, out, sort_keys=True, indent=4, separators=(',', ': '... |
Using VirtualEnv with multiple Python versions on windows | 22,793,650 | 6 | 2014-04-01T18:13:05Z | 22,793,687 | 9 | 2014-04-01T18:14:54Z | [
"python",
"virtualenv"
] | I have python 2.7.6 and 3.4.0 on my machine. The 2.7 version is on my path. I would like to set up a virtualenv using 3.4. There are many postings on SO and elsewhere that suggest I do the following from a command prompt:
```
virtualenv -p c:\python34 myvirtualenv
```
but this does not work for me. The console sessio... | Better:
```
py -3.4 -m venv c:\path\to\wherever\you\want\it
```
If you don't have the `py.exe` launcher (but it should be installed) you can replace `py -3.4` with `c:\Python34\python.exe` (assuming the default location)
---
This works because of the handy-dandy, Windows-versioningest, super nice runtime picker `py... |
Plotting time-series data with seaborn | 22,795,348 | 8 | 2014-04-01T19:38:35Z | 22,798,911 | 20 | 2014-04-01T23:35:58Z | [
"python",
"matplotlib",
"pandas",
"seaborn"
] | Say I create a fully random `Dataframe` using the following:
```
from pandas.util import testing
from random import randrange
def random_date(start, end):
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
return start + timedelta(seconds=r... | I don't think `tsplot` is going to work with the data you have. The assumptions it makes about the input data are that you've sampled the same units at each timepoint (although you can have missing timepoints for some units).
For example, say you measured blood pressure from the same people every day for a month, and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.