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 |
|---|---|---|---|---|---|---|---|---|---|
TypeError: cannot concatenate 'str' and 'list' objects in email | 26,521,899 | 4 | 2014-10-23T05:36:09Z | 26,521,956 | 15 | 2014-10-23T05:43:39Z | [
"python"
] | I am working on sending an email in python. Right now, I want to send entries from a list via email but I am encountering an error saying "TypeError: cannot concatenate 'str' and 'list' objects" and I have no idea to debug it. The following is the code that I have. I'm still new in this language (3 weeks) so I have a l... | The problem is with `msg = header + x`. You're trying to apply the `+` operator to a string and a list.
I'm not exactly sure how you want `x` to be displayed but, if you want something like "[1, 2, 3]", you would need:
```
msg = header + str(x)
```
Or you could do,
```
msg = '{header}{lst}'.format(header=header, ls... |
Plotting datetimeindex on x-axis with matplotlib creates wrong ticks in pandas 0.15 in contrast to 0.14 | 26,526,230 | 7 | 2014-10-23T10:34:12Z | 26,529,774 | 9 | 2014-10-23T13:56:07Z | [
"python",
"matplotlib",
"pandas"
] | I create a simple pandas dataframe with some random values and a DatetimeIndex like so:
```
import pandas as pd
from numpy.random import randint
import datetime as dt
import matplotlib.pyplot as plt
# create a random dataframe with datetimeindex
dateRange = pd.date_range('1/1/2011', '3/30/2011', freq='D')
randomInts ... | The reason for this change in behaviour is that starting from 0.15, the pandas `Index` object is no longer a numpy ndarray subclass. But the *real reason* is that matplotlib does not support the `datetime64` dtype.
As a workaround, in the case you want to use the matplotlib `plot` function, you can convert the index t... |
Ansible multiple hosts with port forwarding | 26,527,458 | 2 | 2014-10-23T11:54:36Z | 26,528,359 | 8 | 2014-10-23T12:41:57Z | [
"python",
"networking",
"ansible",
"portforwarding",
"ansible-playbook"
] | I have hosts inventory with multiple hosts each with port forwarding, Hosts file is :
```
[all]
10.80.238.11:20003
10.80.238.11:20001
10.80.238.11:20007
10.80.238.11:20009
```
I am trying to ping them with a playbook, but always get response from first entry in this case `10.80.238.11:20003` not from others. Auth... | I suppose that the port forwarding you're doing is for SSH.
So you have to tell ansible which ssh port to connect to. The problem is that all your hosts have the same IP. So you have to use hostnames, so Ansible can distinguish them.
Let's assume that you refer to host with SSH port forwarded to `2000X` as `hostX`, t... |
Pandas 0.15 DataFrame: Remove or reset time portion of a datetime64 | 26,531,109 | 3 | 2014-10-23T15:01:32Z | 26,811,942 | 8 | 2014-11-07T23:45:00Z | [
"python",
"pandas"
] | I have imported a CSV file into a pandas DataFrame and have a datetime64 column with values such as:
```
2014-06-30 21:50:00
```
I simply want to either remove the time or set the time to midnight:
```
2014-06-30 00:00:00
```
What is the easiest way of doing this? | Pandas has a builtin function `pd.datetools.normalize_date` for that purpose:
```
df['date_col'] = df['date_col'].apply(pd.datetools.normalize_date)
```
It's [implemented in Cython](https://github.com/pydata/pandas/blob/v0.15.0/pandas/tslib.pyx#L3440) and does the following:
```
if PyDateTime_Check(dt):
return d... |
Python/Flask error: "ImportError: cannot import name _compare_digest" | 26,535,043 | 8 | 2014-10-23T18:40:16Z | 26,550,917 | 10 | 2014-10-24T15:14:34Z | [
"python",
"python-2.7",
"flask"
] | With Windows, I am following [this Flask tutorial](http://flask.pocoo.org/docs/0.10/quickstart/#a-minimal-application) when I came across the following error:
```
C:\Users\Gregory Gundersen\Documents\Research\flask-test>python run.py
Traceback (most recent call last):
File "run.py", line 2, in <module>
from app ... | You appear to have *half* the changes made for [issue 21306 (backporting hmac.compare\_digest to 2.7)](http://bugs.python.org/issue21306).
Your `hmac` module has the lines:
```
from operator import _compare_digest as compare_digest
```
at the top, but your `sys.version_info` shows you are running Python 2.7.6; quoti... |
Serialize queryset in Django rest framework | 26,535,055 | 2 | 2014-10-23T18:41:03Z | 26,535,337 | 15 | 2014-10-23T18:57:03Z | [
"python",
"django",
"django-rest-framework"
] | I am trying to serialize a collection of objects. I have define the following view method:
```
@csrf_exempt
def venue_list(request, user_id):
"""
Check that the user is requesting his own venues.
"""
profile = get_profile_for_user_if_match(request.user, user_id)
if profile is None:
return ... | To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. So in your case try this:
```
...
venues = profile.venue_set.all()
serializer = VenueSerializer(venues, many=True)
...
``` |
Querying for NaN and other names in Pandas | 26,535,563 | 7 | 2014-10-23T19:09:28Z | 26,535,881 | 17 | 2014-10-23T19:28:05Z | [
"python",
"pandas"
] | Say I have a dataframe `df` with a column `value` holding some float values and some `NaN`. How can I get the part of the dataframe where we have `NaN` **using the query syntax**?
The following, for example, does not work:
```
df.query( '(value < 10) or (value == NaN)' )
```
I get `name NaN is not defined` (same for... | In general, you could use `@local_variable_name`, so something like
```
>>> pi = np.pi; nan = np.nan
>>> df = pd.DataFrame({"value": [3,4,9,10,11,np.nan,12]})
>>> df.query("(value < 10) and (value > @pi)")
value
1 4
2 9
```
would work, but `nan` isn't equal to itself, so `value == NaN` will always be fal... |
Is it possible to dynamically update a rendered template in Flask, server-side? | 26,536,187 | 3 | 2014-10-23T19:46:43Z | 26,536,387 | 8 | 2014-10-23T20:00:02Z | [
"python",
"json",
"flask"
] | I currently have a Flask web server that pulls data from a JSON API using the built-in requests object.
For example:
```
def get_data():
response = requests.get("http://myhost/jsonapi")
...
return response
@main.route("/", methods=["GET"])
def index():
return render_template("index.html", response=re... | You're discussing what are perhaps two different issues.
1. Let's assume the problem is you're calling the dynamic data source, `get_data()`, only once and keeping its (static) value in a global `response`. This one-time-call is not shown, but let's say it's somewhere in your code. Then, if you are willing to refresh ... |
How can I find endpoints of binary skeleton image in OpenCV? | 26,537,313 | 5 | 2014-10-23T20:55:21Z | 26,541,105 | 7 | 2014-10-24T03:39:54Z | [
"python",
"c++",
"opencv",
"image-processing"
] | I have a skeleton as binary pixels, such as this:

I would like to find the coordinates of the end points of this skeleton (in this case there are four), using Open CV if applicable.
Efficiency is important as I'm analysing a number of these in real... | Given your tags of your questions and answers in your profile, I'm going to assume you want a C++ implementation. When you skeletonize an object, the object should have a 1 pixel thickness. Therefore, one thing that I could suggest is find those pixels that are non-zero in your image, then search in an 8-connected neig... |
Python3.3 HTML Client TypeError: 'str' does not support the buffer interface | 26,537,592 | 3 | 2014-10-23T21:14:06Z | 26,537,632 | 8 | 2014-10-23T21:16:45Z | [
"python",
"html",
"string",
"client"
] | ```
import socket
# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Connect as client to a selected server
# on a specified port
s.connect(("www.wellho.net",80))
# Protocol exchange - sends and receives
s.send("GET /robots.txt HTTP/1.0\n\n")
while True:
resp = s.recv(1024)
... | Sockets can only accept *bytes*, while you are trying to send it a Unicode string instead.
Encode your strings to bytes:
```
s.send("GET /robots.txt HTTP/1.0\n\n".encode('ascii'))
```
or give it a bytes literal (a string literal starting with a `b` prefix):
```
s.send(b"GET /robots.txt HTTP/1.0\n\n")
```
Take into... |
Pandas sum across columns and divide each cell from that value | 26,537,878 | 8 | 2014-10-23T21:35:20Z | 26,538,379 | 12 | 2014-10-23T22:13:03Z | [
"python",
"pandas",
"dataframe"
] | I have read a csv file and pivoted it to get to following structure.
```
pivoted = df.pivot('user_id', 'group', 'value')
lookup = df.drop_duplicates('user_id')[['user_id', 'group']]
lookup.set_index(['user_id'], inplace=True)
result = pivoted.join(lookup)
result = result.fillna(0)
```
Section of the result:
```
... | Try the following:
```
In [1]: import pandas as pd
In [2]: df = pd.read_csv("test.csv")
In [3]: df
Out[3]:
id value1 value2 value3
0 A 1 2 3
1 B 4 5 6
2 C 7 8 9
In [4]: df["sum"] = df.sum(axis=1)
In [5]: df
Out[5]:
id value1 value2 value3 sum
0 ... |
Generate temporary file names without creating actual file in Python | 26,541,416 | 22 | 2014-10-24T04:19:59Z | 26,541,521 | 15 | 2014-10-24T04:32:34Z | [
"python",
"temporary-files"
] | The question, [number 10501247](http://stackoverflow.com/questions/10501247/best-way-to-generate-random-file-names-in-python), in stackoverflow gives answer how to create temporary file in Python.
I only need to have temporary file name in my case.
Calling tempfile.NamedTemporaryFile() returns file handle after act... | If you want a temp file name only you can call inner tempfile function `_get_candidate_names()`:
```
import tempfile
temp_name = next(tempfile._get_candidate_names())
% e.g. px9cp65s
```
Calling `next` again, will return another name, etc. This does not give you the path to temp folder. To get default 'tmp' director... |
Delete every non utf-8 symbols froms string | 26,541,968 | 11 | 2014-10-24T05:24:20Z | 26,549,192 | 11 | 2014-10-24T13:45:49Z | [
"python",
"mongodb",
"encode"
] | I have a big amount of files and parser. What I Have to do is strip all non utf-8 symbols and put data in mongodb.
Currently I have code like this.
```
with open(fname, "r") as fp:
for line in fp:
line = line.strip()
line = line.decode('utf-8', 'ignore')
line = line.encode('utf-8', 'ignore'... | Try below code line instead of last two lines. Hope it helps:
```
line=line.decode('utf-8','ignore').encode("utf-8")
``` |
Python 3 asyncio - yield from vs asyncio.async stack usage | 26,542,686 | 4 | 2014-10-24T06:36:50Z | 26,578,642 | 10 | 2014-10-26T22:19:23Z | [
"python",
"python-3.x",
"coroutine",
"python-asyncio"
] | I'm evaluating different patterns for periodic execution (actual sleep/delays ommited for brevity) using the Python 3 asyncio framework, and I have two pieces of code that behave diffrently and I can't explain why. The first version, which uses `yield from` to call itself recursively exhausts the stack in about 1000 it... | The first example, using `yield from`, actually blocks each instance of `call_self` until its recursive call to `call_self` returns. This means the call stack keeps growing until you run out of stack space. As you mentioned, this is the obvious behavior.
The second example, using `asyncio.async`, doesn't block anywher... |
python 3 map/lambda method with 2 inputs | 26,543,349 | 4 | 2014-10-24T07:28:52Z | 26,543,472 | 8 | 2014-10-24T07:39:12Z | [
"python",
"python-3.x",
"dictionary",
"syntax",
"lambda"
] | I have a dictionary like the following in python 3:
```
ss = {'a':'2', 'b','3'}
```
I want to convert all he values to int using `map` function, and I wrote something like this:
```
list(map(lambda key,val: int(val), ss.items())))
```
but the python complains:
> TypeError: () missing 1 required positional argument... | `ss.items()` will give an iterable, which gives tuples on every iteration. In your `lambda` function, you have defined it to accept two parameters, but the tuple will be treated as a single argument. So there is no value to be passed to the second parameter.
1. You can fix it like this
```
print(list(map(lambda... |
Is there a way to delete created variables, functions, etc from the memory of the interpreter? | 26,545,051 | 12 | 2014-10-24T09:20:33Z | 26,545,111 | 18 | 2014-10-24T09:24:25Z | [
"python",
"memory-management",
"dir"
] | I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.
When I'm in the shell of Python, I type: `dir()` and I can see all the names of all the objects in the current sco... | You can delete individual names with `del`:
```
del x
```
or you can remove them from the `globals()` object:
```
for name in dir():
if not name.startswith('_'):
del globals()[name]
```
This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not un... |
setup.py sdist exclude packages in subdirectory | 26,545,668 | 8 | 2014-10-24T09:56:14Z | 26,547,314 | 9 | 2014-10-24T11:49:46Z | [
"python",
"setuptools"
] | I have the following project structure I would like to package:
```
âââ doc
â  âââ source
âââ src
â  âââ core
â  â  âââ config
â  â  â  âââ log.tmpl
â  â  âââ job
â  âââ scripts
â  âââ test
âââ tools
```
... | `find_packages("src", exclude=["test"])` works.
**The trick is to remove stale files such as `core.egg-info` directory.** In your case you need to remove `src/core.egg-info`.
Here's `setup.py` I've used:
```
from setuptools import setup, find_packages
setup(name='core',
version='0.1',
package_dir={'':'... |
How to check if a pymongo cursor has query results | 26,549,787 | 11 | 2014-10-24T14:18:15Z | 26,558,360 | 10 | 2014-10-25T01:06:57Z | [
"python",
"mongodb",
"pymongo",
"mongodb-query"
] | I need to check if a `find` statement returns a non-empty query.
What I was doing was the following:
```
query = collection.find({"string": field})
if not query: #do something
```
Then I realized that my `if` statement was never executed because `find` returns a cursor, either the query is empty or not.
Therefore I... | `.count()` is the correct way to find the number of results that are returned in the query. The `count()` method does not exhaust the iterator for your cursor, so you can safely do a `.count()` check before iterating over the items in the result set.
Performance of the count method was greatly improved in MongoDB 2.4.... |
Flask Blueprint AttributeError: 'module' object has no attribute 'name' error | 26,550,180 | 6 | 2014-10-24T14:38:26Z | 26,550,241 | 11 | 2014-10-24T14:41:21Z | [
"python",
"attributeerror",
"flask"
] | My API is being built to allow developers to extend it's functionality. My plan is to do this by providing an "extensions" directory where they can drop in Blueprints and they will be dynamically loaded. This is the code I am utilizing to import (modifed from this [tutorial](https://lextoumbourou.com/blog/posts/dynamic... | You are trying to register the *module* and not the contained `Blueprint` object.
You'll need to introspect the module to find `Blueprint` instances instead:
```
if mod_name not in sys.modules:
loaded_mod = __import__(EXTENSIONS_DIR+"."+mod_name+"."+mod_name, fromlist=[mod_name])
for obj in vars(loaded_mod).v... |
import text to pandas with multiple delimiters | 26,551,662 | 3 | 2014-10-24T15:56:17Z | 26,551,913 | 10 | 2014-10-24T16:10:50Z | [
"python",
"import",
"pandas",
"delimited-text"
] | I have some data that looks like this:
```
c stuff
c more header
c begin data
1 1:.5
1 2:6.5
1 3:5.3
```
I want to import it into a 3 column data frame, with columns e.g.
```
a , b, c
1, 1, 0.5
etc
```
I have been trying to read in the data as 2 columns split on ':', and then to split the first column ... | One way might be to use the regex separators permitted by the python engine. For example:
```
>>> !cat castle.dat
c stuff
c more header
c begin data
1 1:.5
1 2:6.5
1 3:5.3
>>> df = pd.read_csv('castle.dat', skiprows=3, names=['a', 'b', 'c'],
sep=' |:', engine='python')
>>> df
a b ... |
Rollback transactions not working with py.test and Flask | 26,555,125 | 8 | 2014-10-24T19:41:30Z | 26,624,146 | 11 | 2014-10-29T06:41:45Z | [
"python",
"flask",
"flask-sqlalchemy",
"py.test"
] | I'm using py.test to test my Flask application but I am getting IntegrityError because I am creating the same model in two different tests.
I am using postgreSQL 9.3.5 and Flask-SQLAlchemy 1.0.
**EDIT I've updated my sessoin fixture with Jeremy Allen's answer and it fixed a lot of the errors. However it seems when I ... | It looks like you are trying to [join a Session into an External Transaction](http://docs.sqlalchemy.org/en/rel_0_9/orm/session.html?highlight=testing%20transactions#joining-a-session-into-an-external-transaction-such-as-for-test-suites) and you are using flask-sqlalchemy.
Your code is not working as expected because ... |
CAP_PROP_FRAME_COUNT constant is missing in opencv `cv2` python module | 26,559,179 | 2 | 2014-10-25T03:53:12Z | 26,568,593 | 7 | 2014-10-26T00:22:03Z | [
"python",
"opencv",
"video-capture",
"attributeerror"
] | How to access to `CAP_PROP_FRAME_COUNT` from opencv in python?
I tried this:
```
import cv2
cap = cv2.VideoCapture('myvideo.avi')
frames_count, fps, width, height = cap.get(cv2.CAP_PROP_FRAME_COUNT), cap.get(cv2.CAP_PROP_FPS), cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
```
And this:
```
im... | The constants in the first version of OpenCV python module have a `CV_` prefix. You could thus either use `cv.CV_CAP_PROP_FRAME_COUNT` or `cv2.cv.CV_CAP_PROP_FRAME_COUNT`. |
Python Binomial Coefficient | 26,560,726 | 4 | 2014-10-25T08:50:26Z | 26,561,091 | 10 | 2014-10-25T09:40:31Z | [
"python"
] | ```
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == 1 or y == x:
print(1)
if y>x:
print(0)
else:
a = math.factorial(x)
b = math.factorial(y)
div = (a//(b*(x-y)))
print(div)
```
This binomial coe... | Here's a version that actually uses the [correct formula](http://en.wikipedia.org/wiki/Binomial_coefficient) . :)
```
#! /usr/bin/env python
''' Calculate binomial coefficient xCy = x! / (y! (x-y)!)
'''
from math import factorial as fac
def binomial(x, y):
try:
binom = fac(x) // fac(y) // fac(x - y)
... |
Python Binomial Coefficient | 26,560,726 | 4 | 2014-10-25T08:50:26Z | 31,435,571 | 23 | 2015-07-15T16:05:42Z | [
"python"
] | ```
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == 1 or y == x:
print(1)
if y>x:
print(0)
else:
a = math.factorial(x)
b = math.factorial(y)
div = (a//(b*(x-y)))
print(div)
```
This binomial coe... | This question is old but as it comes up high on search results I will point out that scipy has a binomial coefficient function,
scipy.special.binom(10, 5)
(See [documentation](https://docs.scipy.org/doc/scipy/reference/tutorial/special.html).) |
flask-migrate doesn't detect models | 26,564,784 | 5 | 2014-10-25T16:45:26Z | 26,566,691 | 8 | 2014-10-25T20:04:17Z | [
"python",
"postgresql",
"flask",
"alembic",
"flask-migrate"
] | I am reading (and watching) about Flask-Migrate here:
<https://realpython.com/blog/python/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/>
and here <https://www.youtube.com/watch?v=YJibNSI-iaE#t=21>
and doing everything from this tutorial:
* I started a local postgres server (using Postgres.App, which starte... | Make sure your model is imported by your app. In most cases your `views.py` should do that. But you can also import it directly from your `app.py`. |
Selenium Python: how to wait until the page is loaded? | 26,566,799 | 22 | 2014-10-25T20:14:30Z | 26,567,563 | 21 | 2014-10-25T21:44:05Z | [
"python",
"selenium"
] | I want to scrape all the data of a page implemented by a infinite scroll. The following python code works.
```
for i=1:100
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
```
This means every time I scroll down to the bottom, I need to wait for 5 seconds, which is genera... | As @user227215 said you should use `WebDriverWait` to wait for an element located in your page:
```
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = ... |
Selenium Python: how to wait until the page is loaded? | 26,566,799 | 22 | 2014-10-25T20:14:30Z | 30,385,843 | 11 | 2015-05-21T23:09:40Z | [
"python",
"selenium"
] | I want to scrape all the data of a page implemented by a infinite scroll. The following python code works.
```
for i=1:100
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
```
This means every time I scroll down to the bottom, I need to wait for 5 seconds, which is genera... | Find below 3 methods:
Checking page readyState (not reliable):
```
def page_has_loaded(self):
self.log.info("Checking if {} page is loaded.".format(self.driver.current_url))
page_state = self.driver.execute_script('return document.readyState;')
return page_state == 'complete'
```
Comparing new page ids w... |
Selenium Python: how to wait until the page is loaded? | 26,566,799 | 22 | 2014-10-25T20:14:30Z | 37,303,115 | 12 | 2016-05-18T14:49:05Z | [
"python",
"selenium"
] | I want to scrape all the data of a page implemented by a infinite scroll. The following python code works.
```
for i=1:100
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
```
This means every time I scroll down to the bottom, I need to wait for 5 seconds, which is genera... | Trying to pass `find_element_by_id` to the constructor for `presence_of_element_located` (as shown in the [accepted answer](http://stackoverflow.com/a/26567563/3657941)) caused `NoSuchElementException` to be raised. I had to use the syntax in [fragles](http://stackoverflow.com/users/3111047/fragles)' [comment](http://s... |
remove unicode emoji using re in python | 26,568,722 | 5 | 2014-10-26T00:45:27Z | 26,568,779 | 16 | 2014-10-26T00:56:04Z | [
"python",
"regex",
"unicode",
"emoji",
"tweets"
] | I tried to remove the emoji from a unicode tweet text and print out the result in python 2.7 using
```
myre = re.compile(u'[\u1F300-\u1F5FF\u1F600-\u1F64F\u1F680-\u1F6FF\u2600-\u26FF\u2700-\u27BF]+',re.UNICODE)
print myre.sub('', text)
```
but it seems almost all the characters are removed from the text. I have check... | You are not using the correct notation for non-BMP unicode points; you want to use `\U0001FFFF`, a *capital* `U` and 8 digits:
```
myre = re.compile(u'['
u'\U0001F300-\U0001F5FF'
u'\U0001F600-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
```
This can be reduced... |
Resource u'tokenizers/punkt/english.pickle' not found | 26,570,944 | 36 | 2014-10-26T07:52:51Z | 26,575,754 | 17 | 2014-10-26T17:20:49Z | [
"python",
"unix",
"nltk"
] | My Code:
```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
ERROR Message:
```
[ec2-user@ip-172-31-31-31 sentiment]$ python mapper_local_v1.0.py
Traceback (most recent call last):
File "mapper_local_v1.0.py", line 16, in <module>
tokenizer = nltk.data.load('nltk:tokenize... | I got the solution:
```
import nltk
nltk.download()
```
## once the NLTK Downloader starts
## d) Download l) List u) Update c) Config h) Help q) Quit
Downloader> d
Download which package (l=list; x=cancel)?
Identifier> punkt |
Resource u'tokenizers/punkt/english.pickle' not found | 26,570,944 | 36 | 2014-10-26T07:52:51Z | 26,578,793 | 32 | 2014-10-26T22:40:37Z | [
"python",
"unix",
"nltk"
] | My Code:
```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
ERROR Message:
```
[ec2-user@ip-172-31-31-31 sentiment]$ python mapper_local_v1.0.py
Traceback (most recent call last):
File "mapper_local_v1.0.py", line 16, in <module>
tokenizer = nltk.data.load('nltk:tokenize... | To install **ALL** datasets, models and taggers from NLTK:
```
import nltk
nltk.download('all')
```
With the above command, there is no need to use the GUI to download the datasets. |
Resource u'tokenizers/punkt/english.pickle' not found | 26,570,944 | 36 | 2014-10-26T07:52:51Z | 27,382,044 | 83 | 2014-12-09T15:01:55Z | [
"python",
"unix",
"nltk"
] | My Code:
```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
ERROR Message:
```
[ec2-user@ip-172-31-31-31 sentiment]$ python mapper_local_v1.0.py
Traceback (most recent call last):
File "mapper_local_v1.0.py", line 16, in <module>
tokenizer = nltk.data.load('nltk:tokenize... | To add to [alvas' answer](http://stackoverflow.com/questions/26570944/resource-utokenizers-punkt-english-pickle-not-found/26578793#26578793), you can download only the `punkt` corpus:
```
nltk.download('punkt')
```
Downloading `all` sounds like overkill to me. Unless that's what you want. |
Resource u'tokenizers/punkt/english.pickle' not found | 26,570,944 | 36 | 2014-10-26T07:52:51Z | 34,375,831 | 7 | 2015-12-19T22:00:50Z | [
"python",
"unix",
"nltk"
] | My Code:
```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
ERROR Message:
```
[ec2-user@ip-172-31-31-31 sentiment]$ python mapper_local_v1.0.py
Traceback (most recent call last):
File "mapper_local_v1.0.py", line 16, in <module>
tokenizer = nltk.data.load('nltk:tokenize... | From the shell you can execute:
```
sudo python -m nltk.downloader punkt
```
If you want to install all NLTK corpora:
```
sudo python -m nltk.downloader all
```
To list the resources you have downloaded:
```
python -c 'import os; import nltk; print os.listdir(nltk.data.find("corpora"))'
python -c 'import os; impor... |
python getting upload/download speeds | 26,573,681 | 2 | 2014-10-26T13:49:30Z | 26,853,086 | 9 | 2014-11-10T21:13:50Z | [
"python",
"linux",
"networking",
"conky"
] | I want to monitor on my computer the upload and download speeds. A program called conky already does it with the following in conky conf:
```
Connection quality: $alignr ${wireless_link_qual_perc wlan0}%
${downspeedgraph wlan0}
DLS:${downspeed wlan0} kb/s $alignr total: ${totaldown wlan0}
```
and it shows me the spee... | You can calculate the speed yourself based on the rx\_bytes and tx\_bytes for the device and polling those values over an interval
Here is a very simplistic solution I hacked together using Python 3
```
#!/usr/bin/python3
import time
def get_bytes(t, iface='wlan0'):
with open('/sys/class/net/' + iface + '/stati... |
Virtualenv fails on OS X Yosemite with OSError | 26,574,954 | 4 | 2014-10-26T16:04:03Z | 26,575,556 | 7 | 2014-10-26T17:02:44Z | [
"python",
"pip",
"virtualenv"
] | I recently updated to OSX Yosemite, and now I can't use `virtualenv` / `pip`.
Whenever I execute:
```
virtualenv env
```
It throws a:
```
OSError: Command /Users/administrator...ux/env/bin/python2.7 -c "import sys, pip; sys...d\"] + sys.argv[1:]))" setuptools pip failed with error code 1
```
And within that stack ... | Solved with:
```
brew uninstall python
brew install python
pip install --upgrade pip
```
\*Note: You'll also need to a do a fresh pip install for any current projects you're working on. |
How can I get 2.x-like sorting behaviour in Python 3.x? | 26,575,183 | 20 | 2014-10-26T16:27:09Z | 26,575,514 | 9 | 2014-10-26T16:59:34Z | [
"python",
"sorting",
"python-3.x",
"order",
"python-2.x"
] | I'm trying to replicate (and if possible improve on) Python 2.x's sorting behaviour in 3.x, so that mutually orderable types like `int`, `float` etc. are sorted as expected, and mutually unorderable types are grouped within the output.
Here's an example of what I'm talking about:
```
>>> sorted([0, 'one', 2.3, 'four'... | Stupid idea: make a first pass to divide all the different items in groups that can be compared between each other, sort the individual groups and finally concatenate them. I assume that an item is comparable to all members of a group, if it is comparable with the first member of a group. Something like this (Python3):... |
How can I get 2.x-like sorting behaviour in Python 3.x? | 26,575,183 | 20 | 2014-10-26T16:27:09Z | 26,652,245 | 11 | 2014-10-30T11:51:17Z | [
"python",
"sorting",
"python-3.x",
"order",
"python-2.x"
] | I'm trying to replicate (and if possible improve on) Python 2.x's sorting behaviour in 3.x, so that mutually orderable types like `int`, `float` etc. are sorted as expected, and mutually unorderable types are grouped within the output.
Here's an example of what I'm talking about:
```
>>> sorted([0, 'one', 2.3, 'four'... | The actual Python 2 implementation is quite involved, but [`object.c`'s `default_3way_compare`](https://hg.python.org/cpython/file/4252bdba6e89/Objects/object.c#l756) does the final fallback after instances have been given a chance to implement normal comparison rules.
Implementing that function as pure Python in a wr... |
Can't install Scipy through pip | 26,575,587 | 43 | 2014-10-26T17:05:12Z | 26,704,405 | 7 | 2014-11-02T21:05:32Z | [
"python",
"scipy"
] | When installing scipy through pip with :
```
pip install scipy
```
Pip fails to build scipy and throws the following error:
```
Cleaning up...
Command /Users/administrator/dev/KaggleAux/env/bin/python2.7 -c "import setuptools, tokenize;__file__='/Users/administrator/dev/KaggleAux/env/build/scipy/setup.py';exec(compi... | After finding [this answer](http://stackoverflow.com/questions/14821297/scipy-build-install-mac-osx) for some clues, I got this working by doing
```
brew install gcc
pip install scipy
```
(The first of these steps took 96 minutes on my 2011 Mac Book Air so I hope you're not in a hurry!) |
Can't install Scipy through pip | 26,575,587 | 43 | 2014-10-26T17:05:12Z | 26,964,891 | 55 | 2014-11-17T03:05:28Z | [
"python",
"scipy"
] | When installing scipy through pip with :
```
pip install scipy
```
Pip fails to build scipy and throws the following error:
```
Cleaning up...
Command /Users/administrator/dev/KaggleAux/env/bin/python2.7 -c "import setuptools, tokenize;__file__='/Users/administrator/dev/KaggleAux/env/build/scipy/setup.py';exec(compi... | After opening up an [issue](https://github.com/scipy/scipy/issues/4102) with the SciPy team, we found that you need to upgrade pip with:
```
pip install --upgrade pip
```
And in `Python 3` this works:
```
python3 -m pip install --upgrade pip
```
for SciPy to install properly. Why? Because:
> Older versions of pip ... |
Can't install Scipy through pip | 26,575,587 | 43 | 2014-10-26T17:05:12Z | 29,527,939 | 35 | 2015-04-09T00:59:15Z | [
"python",
"scipy"
] | When installing scipy through pip with :
```
pip install scipy
```
Pip fails to build scipy and throws the following error:
```
Cleaning up...
Command /Users/administrator/dev/KaggleAux/env/bin/python2.7 -c "import setuptools, tokenize;__file__='/Users/administrator/dev/KaggleAux/env/build/scipy/setup.py';exec(compi... | I face same problem when install Scipy under ubuntu.
I had to use command:
```
$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy
```
You can get more details here [Installing SciPy with pip](http://stackoverflow.com/questions/2213551/installing-scipy-with-pip)
Sorry don't know how to ... |
Can't install Scipy through pip | 26,575,587 | 43 | 2014-10-26T17:05:12Z | 33,984,261 | 11 | 2015-11-29T15:09:35Z | [
"python",
"scipy"
] | When installing scipy through pip with :
```
pip install scipy
```
Pip fails to build scipy and throws the following error:
```
Cleaning up...
Command /Users/administrator/dev/KaggleAux/env/bin/python2.7 -c "import setuptools, tokenize;__file__='/Users/administrator/dev/KaggleAux/env/build/scipy/setup.py';exec(compi... | Microsoft Windows users of 64 bit Python installations will need to download the 64 bit .whl of Scipy from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy> then simply cd into the folder you've downloaded the .whl file and run:
```
pip install scipy-0.16.1-cp27-none-win_amd64.whl
``` |
pandas test if str contains one of a list | 26,577,516 | 7 | 2014-10-26T20:23:37Z | 26,577,689 | 11 | 2014-10-26T20:40:33Z | [
"python",
"pandas"
] | Is there any function that would the the equivalent of a combination of `df.isin()` and `df[col].str.contains()`?
For example, say I have the series
`s = pd.Series(['cat','hat','dog','fog','pet'])`, and I want to find all places where `s` contains any of `['og', 'at']`, I would want to get everything but pet.
I have ... | One option is just to use the regex `|` character to try to match each of the substrings in the words in your Series `s` (still using `str.contains`).
You can construct the regex by joining the words in `searchfor` with `|`:
```
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat... |
Why is Flask application not creating any logs when hosted by Gunicorn? | 26,578,733 | 11 | 2014-10-26T22:31:30Z | 26,579,510 | 13 | 2014-10-27T00:16:12Z | [
"python",
"logging",
"flask",
"gunicorn"
] | I'm trying to add logging to a web application which uses Flask.
When hosted using the built-in server (i.e. `python3 server.py`), logging works. When hosted using Gunicorn, the log file is not created.
The simplest code which reproduces the problem is this one:
```
#!/usr/bin/env python
import logging
from flask i... | When you use `python3 server.py` you are running the server3.py script.
When you use `gunicorn server:flaskApp ...` you are running the gunicorn startup script which then **imports** the module `server` and looks for the variable `flaskApp` in that module.
Since `server.py` is being imported the `__name__` var will c... |
SQLAlchemy group_concat and duplicates | 26,583,832 | 4 | 2014-10-27T08:47:01Z | 26,584,469 | 7 | 2014-10-27T09:28:03Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] | When I try to join a *many-to-many* table and group it by the *main-id* I am getting **duplicates** when I add the second *many-to-many* table.
Here is how my models look like:
## Models
**user**
```
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
user_fistName = db.Column(db.S... | Found out the solution, and it is quite simple.
**RAW SQL**
```
SELECT
class.class_id,
class.class_name,
GROUP_CONCAT(DISTINCT course.course_name),
GROUP_CONCAT(DISTINCT user.user_fistName)
FROM
class
JOIN class_course_identifier ON class.class_id = class_course_identifier.class_id
JOIN course ON class_co... |
Getting boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden when uploading file | 26,594,944 | 2 | 2014-10-27T19:04:29Z | 27,984,752 | 17 | 2015-01-16T13:13:31Z | [
"python",
"amazon-s3",
"boto"
] | There are a few other questions on this issue:
[boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden](http://stackoverflow.com/questions/10854095/boto-exception-s3responseerror-s3responseerror-403-forbidden)
[S3ResponseError: S3ResponseError: 403 Forbidden](http://stackoverflow.com/questions/5296966/s3respo... | This will also happen if your machine's time settings are incorrect |
Return and yield in the same function | 26,595,895 | 18 | 2014-10-27T20:04:27Z | 26,595,922 | 21 | 2014-10-27T20:06:38Z | [
"python",
"yield"
] | What exactly happens, when yield and return are used in the same function in Python, like this?
```
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) # use start += 1 to find overlapping matches
``... | Yes, it' still a generator. The `return` is (almost) equivalent to raising `StopIteration`.
[PEP 255](http://www.python.org/dev/peps/pep-0255/) spells it out:
> ## Specification: Return
>
> A generator function can also contain return statements of the form:
>
> ```
> "return"
> ```
>
> Note that an expression\_list ... |
Return and yield in the same function | 26,595,895 | 18 | 2014-10-27T20:04:27Z | 26,595,928 | 11 | 2014-10-27T20:06:50Z | [
"python",
"yield"
] | What exactly happens, when yield and return are used in the same function in Python, like this?
```
def find_all(a_str, sub):
start = 0
while True:
start = a_str.find(sub, start)
if start == -1: return
yield start
start += len(sub) # use start += 1 to find overlapping matches
``... | Yes, it is still a generator. An empty `return` or `return None` can be used to end a generator function. It is equivalent to raising a `StopIteration`(see [@NPE's answer](http://stackoverflow.com/a/26595922/846892) for details).
Note that a return with non-None arguments is a `SyntaxError` in Python versions prior to... |
Finding "decent" numbers algorithm reasoning? | 26,596,535 | 7 | 2014-10-27T20:46:11Z | 26,597,726 | 15 | 2014-10-27T22:11:08Z | [
"python",
"algorithm",
"python-3.x"
] | # Problem
Sherlock Holmes is getting paranoid about Professor Moriarty, his archenemy. All his efforts to subdue Moriarty have been in vain. These days Sherlock is working on a problem with Dr. Watson. Watson mentioned that the CIA has been facing weird problems with their supercomputer, 'The Beast', recently.
This a... | A mathematical solution:
Let a = len of the '5's, b = len of the '3's. So
`a + b = N`
We know that 3 divides a, and 5 divides b, so let a = 3n, b = 5m
`3n+5m = N`
This is a diophantine equation (<http://en.wikipedia.org/wiki/Diophantine_equation>) with one solution being (n0, m0) = (2N, -N), and general solution
... |
How to install libpython2.7.so | 26,597,527 | 5 | 2014-10-27T21:54:59Z | 26,597,848 | 8 | 2014-10-27T22:20:18Z | [
"python",
"linux",
"python-2.7",
"centos",
"sysadmin"
] | I have installed Python 2.6.6 at
```
[17:50:21 [email protected]:~]# which python
/usr/local/bin/python
```
also Python 2.7.6 at
```
[17:51:12 [email protected]:~]# which python2.7
/usr/local/bin/python2.7
```
But libpython2.7.so is missing
```
[17:48:52 [email protected]:~]# locate libpython2.6.so
/usr/lib64/libpython2.6.so
... | You could try compiling it from sources, in root :
```
yum -y install python-devel openssl openssl-devel gcc sqlite-devel
wget http://www.python.org/ftp/python/2.7.5/Python-2.7.5.tar.bz2
tar -xvjf Python-2.7.5.tar.bz2
cd Python-2.7.5
./configure --prefix=/usr/local/python2.7 --with-threads --enable-shared
make
make i... |
Preserve custom attributes when pickling subclass of numpy array | 26,598,109 | 13 | 2014-10-27T22:44:13Z | 26,599,346 | 13 | 2014-10-28T01:08:02Z | [
"python",
"arrays",
"numpy",
"pickle",
"python-multiprocessing"
] | I've created a subclass of numpy ndarray following [the numpy documentation](http://docs.scipy.org/doc/numpy/user/basics.subclassing.html). In particular, I have [added a custom attribute](http://docs.scipy.org/doc/numpy/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray) by modifying the ... | `np.ndarray` uses `__reduce__` to pickle itself. We can take a look at what it actually returns when you call that function to get an idea of what's going on:
```
>>> obj = RealisticInfoArray([1, 2, 3], info='foo')
>>> obj.__reduce__()
(<built-in function _reconstruct>, (<class 'pick.RealisticInfoArray'>, (0,), 'b'), ... |
BeautifulSoup - TypeError: 'NoneType' object is not callable | 26,603,435 | 6 | 2014-10-28T08:05:34Z | 26,603,486 | 11 | 2014-10-28T08:09:27Z | [
"python",
"beautifulsoup",
"backwards-compatibility"
] | I need to make my code backwards compatible with python2.6 and BeautifulSoup 3. My code was written using python2.7 and at this case using BS4. But when I try to run it at squeezy server, I get this error (it has python2.6 and bs3):
```
try:
from bs4 import BeautifulSoup
except ImportError:
from BeautifulSoup ... | You are using BeautifulSoup 3, but are using BeautifulSoup 4 syntax.
Your fallback is at fault here:
```
try:
from bs4 import BeautifulSoup
except ImportError:
from BeautifulSoup import BeautifulSoup
```
If you want to use either version 3 or 4, stick to version 3 syntax:
```
p = soup.body.div.findAll('p')
... |
Get the indices of N highest values in an ndarray | 26,603,747 | 5 | 2014-10-28T08:29:03Z | 26,604,096 | 8 | 2014-10-28T08:51:13Z | [
"python",
"numpy",
"indexing",
"multidimensional-array"
] | Considering an histogram of shape 100x100x100, I would like to find the 2 highest values a and b, and their indices (a1, a2, a3) and (b1, b2, b3), such as:
```
hist[a1][a2][a3] = a
hist[b1][b2][b3] = b
```
We can easily get the highest value with hist.max(), but how can we get the X highest values in a ndarray?
I un... | You can use [`numpy.argpartition`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argpartition.html) on flattened version of array first to get the indices of top `k` items, and then you can convert those 1D indices as per the array's shape using [`numpy.unravel_index`](http://docs.scipy.org/doc/numpy/refere... |
Django Template does not exist error, although it shows 'file exists' | 26,604,294 | 4 | 2014-10-28T09:01:43Z | 31,718,987 | 21 | 2015-07-30T08:39:36Z | [
"python",
"django",
"django-templates"
] | I am not able to render any html pages in Django 1.7. My 'index.html' is in '`project/seatalloc/templates/index.html`' and my view.py in `project/seatalloc/views.py` looks like:
```
def index(request):
return render(request, 'index.html', dirs=('templates',))
```
project/project/settings.py has templates dirs... | If - as in your case - you get a TemplateDoesNotExist error and the debug page states "File exists" next to the template in question this usually (always?) means this template refers to another template that can't be found.
In your case, index.html contains a statement (`{% extends %}, {% include %}, ...` ) referring ... |
Flask-login AttributeError: 'User' object has no attribute 'is_active' | 26,606,391 | 4 | 2014-10-28T10:49:24Z | 26,608,805 | 9 | 2014-10-28T12:49:16Z | [
"python",
"flask",
"flask-login"
] | I have a problem with flask-login.
After filling login form and clicking 'Submit' i'm get this error:
Flask-login AttributeError: 'User' object has no attribute 'is\_active'
Some test users are created. And no problems with login template
Traceback:
```
Traceback (most recent call last):
File "C:\flask_prj\proj... | You should subclass `UserMixin` on your model. You should also add a user\_loader
```
from flask.ext.login import UserMixin
from yourapp import login_manager
@login_manager.user_loader
def get_user(ident):
return User.query.get(int(ident))
class User(db.Model, UserMixin)
id = db.Column(db.Integer, primary_key=T... |
What is "module" in the docstring of len? | 26,609,559 | 6 | 2014-10-28T13:26:25Z | 26,609,708 | 9 | 2014-10-28T13:33:16Z | [
"python",
"python-3.4"
] | ```
>>> print(len.__doc__)
len(module, object)
Return the number of items of a sequence or mapping.
>>> len(os, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (2 given)
```
Notice the *two* parameters in the first line of the docstring.
When wo... | This was a bug submitted on 2014-04-18 [here](http://bugs.python.org/issue21294). It has since been fixed in 3.4.1.
Quoting Vedran ÄaÄiÄ, the original author of the bug report:
```
From recently, help(len) gives the wrong signature of len.
Help on built-in function len in module builtins:
len(...)
len(module... |
__getitem__ overloading in python | 26,611,554 | 2 | 2014-10-28T14:59:16Z | 26,611,639 | 9 | 2014-10-28T15:03:56Z | [
"python",
"python-2.7",
"operator-overloading"
] | I am trying to understand the operator overloading in python and I have written a small programs which overloads `__getitem__()` method and calls a for loop:
```
class Ovl:
data = [1,2,3,4,5]
def __getitem__(self, index):
return "Hiii"
x=Ovl()
for item in x:
print item
```
This program goes in t... | According to the [`object.__getitem__`](https://docs.python.org/2/reference/datamodel.html#object.__getitem__) NOTE,
> NOTE: `for` loops expect that **an `IndexError` will be raised** for illegal indexes to **allow proper detection of the end of the sequence**.
```
>>> class Ovl:
... data = [1,2,3,4,5]
... de... |
Is there a way to append/extend a list with another list at a specific index in python? | 26,612,737 | 8 | 2014-10-28T15:51:36Z | 26,612,769 | 11 | 2014-10-28T15:52:59Z | [
"python",
"list"
] | In other words, I want to accomplish something like the following:
```
a = [1, 2, 3, 7, 8]
b = [4, 5, 6]
# some magic here to insert list b into list a at index 3 so that
a = [1, 2, 3, 4, 5, 6, 7, 8]
``` | You can assign to a [slice](http://stackoverflow.com/q/509211/2555451) of list `a` like so:
```
>>> a = [1, 2, 3, 7, 8]
>>> b = [4, 5, 6]
>>> a[3:3] = b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
```
The `[3:3]` may look weird, but it is necessary to have the items in list `b` be inserted into list `a` correctly. Otherwise, ... |
Why would Python's variable length arguments be used over passing in a list/dictionary? | 26,613,025 | 2 | 2014-10-28T16:04:58Z | 26,613,129 | 7 | 2014-10-28T16:09:31Z | [
"python",
"coding-style",
"variable-length-arguments"
] | Python allows you to declare a function like
```
def print_all(*arguments):
for a in arguments:
print(a)
print_all(1,2,3)
```
Which allows one to pass in a variable amount of data. This seems much less readable to me than building a list or a dictionary, and passing those in as arguments like so.
```
def... | Very opinion based, but sometimes you want to use a function providing the arguments in-line. It just looks a bit clearer:
```
function("please", 0, "work this time", 2.3)
```
than:
```
function(["please", 0, "work this time", 2.3])
```
In fact, there is a good example, which you even mention in your question: `pri... |
Why would Python's variable length arguments be used over passing in a list/dictionary? | 26,613,025 | 2 | 2014-10-28T16:04:58Z | 26,613,132 | 8 | 2014-10-28T16:09:51Z | [
"python",
"coding-style",
"variable-length-arguments"
] | Python allows you to declare a function like
```
def print_all(*arguments):
for a in arguments:
print(a)
print_all(1,2,3)
```
Which allows one to pass in a variable amount of data. This seems much less readable to me than building a list or a dictionary, and passing those in as arguments like so.
```
def... | > Is there a time when using \*arguments is more Pythonic?
Not only "more pythonic", but it's often **necessary**.
Your *need* to use `*args` whenever you don't know how many arguments a function will recieve.
Think, for example, about decorators:
```
def deco(fun):
def wrapper(*args, **kwargs):
do_stuff... |
In what world would \\u00c3\\u00a9 become é? | 26,614,323 | 2 | 2014-10-28T17:08:12Z | 26,614,526 | 10 | 2014-10-28T17:18:25Z | [
"python",
"encoding",
"utf-8"
] | I have a likely improperly encoded json document from a source I do not control, which contains the following strings:
```
d\u00c3\u00a9cor
business\u00e2\u20ac\u2122 active accounts
the \u00e2\u20ac\u0153Made in the USA\u00e2\u20ac\u009d label
```
From this, I am gathering they intend for `\u00c3\u00a9` to beceom... | You should try the [ftfy](https://github.com/LuminosoInsight/python-ftfy) module:
```
>>> print ftfy.ftfy(u"d\u00c3\u00a9cor")
décor
>>> print ftfy.ftfy(u"business\u00e2\u20ac\u2122 active accounts")
business' active accounts
>>> print ftfy.ftfy(u"the \u00e2\u20ac\u0153Made in the USA\u00e2\u20ac\u009d label")
the "M... |
Python Proportion test similar to prop.test in R | 26,615,019 | 3 | 2014-10-28T17:45:09Z | 26,615,434 | 7 | 2014-10-28T18:08:11Z | [
"python",
"statistics",
"scipy"
] | I am looking for a test in Python that does this:
```
> survivors <- matrix(c(1781,1443,135,47), ncol=2)
> colnames(survivors) <- c('survived','died')
> rownames(survivors) <- c('no seat belt','seat belt')
> survivors
survived died
no seat belt 1781 135
seat belt 1443 47
> prop.test(survivor... | I think I got it:
```
In [11]: from scipy import stats
In [12]: import numpy as np
In [13]: survivors = np.array([[1781,135], [1443, 47]])
In [14]: stats.chi2_contingency(survivors)
Out[14]:
(24.332761232771361, # x-squared
8.1048817984512269e-07, # p-value
1,
array([[ 1813.61832061, 102.38167939],
... |
with and closing of files in Python | 26,619,404 | 5 | 2014-10-28T22:11:49Z | 26,619,459 | 7 | 2014-10-28T22:16:35Z | [
"python",
"with-statement",
"urlopen",
"contextmanager"
] | I have read, that file opened like this is closed automatically when leaving the with block:
```
with open("x.txt") as f:
data = f.read()
do something with data
```
yet when opening from web, I need this:
```
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('http://www.... | You don't. `urlopen('http://www.python.org')` returns a context manager too:
```
with urlopen('http://www.python.org') as page:
```
This is documented on the [`urllib.request.urlopen()` page](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen):
> For ftp, file, and data urls and requests ex... |
Replace values in a dataframe column based on condition | 26,620,647 | 5 | 2014-10-29T00:05:44Z | 26,621,422 | 7 | 2014-10-29T01:30:56Z | [
"python",
"pandas",
"dataframe"
] | I have a seemingly easy task. Dataframe with 2 columns: A and B. If values in B are larger than values in A - replace those values with values of A. I used to do this by doing `df.B[df.B > df.A] = df.A`, however recent upgrade of pandas started giving a `SettingWithCopyWarning` when encountering this chained assignment... | This is a buggie, fixed [here](https://github.com/pydata/pandas/pull/8671).
Since pandas allows basically anything to be set on the right-hand-side of an expression in loc, there are probably 10+ cases that need to be disambiguated. To give you an idea:
```
df.loc[lhs, column] = rhs
```
where rhs could be: `list,arr... |
Can't catch SystemExit exception Python | 26,623,026 | 4 | 2014-10-29T04:55:20Z | 26,623,043 | 11 | 2014-10-29T04:57:20Z | [
"python",
"exception",
"exception-handling"
] | I am trying to catch a `SystemExit` exception in the following fashion:
```
try:
raise SystemExit
except Exception as exception:
print "success"
```
But, it doesn't work.
It does work however when I change my code like that:
```
try:
raise SystemExit
except:
print "success"
```
As far as I am aware... | As [documented](https://docs.python.org/3/library/exceptions.html#SystemExit), SystemExit does not inherit from Exception. You would have to use `except BaseException`.
However, this is for a reason:
> The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caugh... |
How to provide public key pass phrase in python fabric | 26,626,598 | 2 | 2014-10-29T09:22:44Z | 26,626,682 | 9 | 2014-10-29T09:27:39Z | [
"python",
"ssh",
"fabric",
"ssh-keys"
] | The simple code I have written is :
```
env.host_string = '15.21.18.24'
with settings(user=user, key_filename='/home/amby/.ssh/id_rsa.pub'):
put(local_path, remote_path)
```
Now I have pass\_phrase for the public key. How do I code that pass phrase? Iwant it to be automated.
Right now it is asking for pass phras... | A quick note on terminology. The passphrase is for the **private** key, as the prompt indicates. With ssh key pairs, the key is in two parts - the private key needs to be kept secure, and secret and never leaves the ssh initiating session. The public key is safe to share, and can be transmitted freely.
When you are tr... |
Can't uninstall Python 3.4.2 from Windows 7 after system restore | 26,629,379 | 8 | 2014-10-29T11:39:11Z | 26,629,632 | 10 | 2014-10-29T11:52:30Z | [
"python",
"windows-7",
"uninstall",
"python-3.4",
"system-restore"
] | A couple of days after uninstalling Python 3.4.2 I had to carry out a system restore (I'm using Windows 7) due to accidentally installing a bunch of rubbish-ware that was messing with my computer even after installation. This system restore effectively "reinstalled" Python, or rather a broken version of it. I now can't... | Just delete the `c:\Python3.4\` directory, Reinstall python 3.4 (any sub version, just has to be 3.4), and uninstall that.
Python is, for the most part, totally self-contained in the Python3.4 directory. Reinstalling python is only needed so you can get a fresh uninstaller to remove the registry keys installation crea... |
Can't uninstall Python 3.4.2 from Windows 7 after system restore | 26,629,379 | 8 | 2014-10-29T11:39:11Z | 27,374,542 | 14 | 2014-12-09T08:40:07Z | [
"python",
"windows-7",
"uninstall",
"python-3.4",
"system-restore"
] | A couple of days after uninstalling Python 3.4.2 I had to carry out a system restore (I'm using Windows 7) due to accidentally installing a bunch of rubbish-ware that was messing with my computer even after installation. This system restore effectively "reinstalled" Python, or rather a broken version of it. I now can't... | Just had this problem and solved it by hitting repair first then uninstall. |
Reassign a function attribute makes it 'unreachable' | 26,636,105 | 7 | 2014-10-29T16:45:28Z | 26,636,704 | 7 | 2014-10-29T17:14:11Z | [
"python",
"function-attributes"
] | I have a simple little decorator, that caches results from function calls in a `dict` as a function attribute.
```
from decorator import decorator
def _dynamic_programming(f, *args, **kwargs):
try:
f.cache[args]
except KeyError:
f.cache[args] = f(*args, **kwargs)
return f.cache[args]
def d... | The problem is with the `decorator` module. If you add some `print` statements to your decorator:
```
from decorator import decorator
def _dynamic_programming(f, *args, **kwargs):
print "Inside decorator", id(f.cache)
try:
f.cache[args]
except KeyError:
f.cache[args] = f(*args, **kwargs)
... |
With statement sets variable to None | 26,637,482 | 4 | 2014-10-29T17:57:29Z | 26,637,547 | 9 | 2014-10-29T18:01:10Z | [
"python",
"syntax"
] | I am trying to run this code:
```
class A:
def __enter__(self):
print "enter"
def __exit__(self, *args):
print "exit"
def __init__(self, i):
self.i = i
with A(10) as a:
print a.i
```
And I get this error:
```
enter
exit
Traceback (most recent call last):
File ".last_tmp.py", l... | You will need to return `self` from `__enter__`:
```
def __enter__(self):
print "enter"
return self
```
Your `with` statement is effectively equivalent to:
```
a = A(10).__enter__() # with A(10) as a:
try:
print a.i # Your with body
except:
a.__exit__(exception and type)
raise
else:
a.__exi... |
How do I detect long blocking functions in Tornado application | 26,638,183 | 2 | 2014-10-29T18:40:19Z | 26,638,397 | 11 | 2014-10-29T18:52:47Z | [
"python",
"profiling",
"tornado"
] | I have a Tornado application and sometimes somebody adds a code that blocks for an inappropriate time.
How do I detect such functions, maybe even log which handler/coroutine method blocks for a time longer than, say, 50ms?
I'm looking at `_make_coroutine_wrapper()` in `tornado.gen`, and don't see a way to cut in, exc... | You can use the [IOLoop.set\_blocking\_log\_threshold](http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.set_blocking_log_threshold) method. `set_blocking_log_threshold(0.050)` will print a stack trace any time the IOLoop is blocked for longer than 50ms. |
Search for String in all Pandas DataFrame columns and filter | 26,640,129 | 5 | 2014-10-29T20:33:19Z | 26,641,085 | 7 | 2014-10-29T21:35:32Z | [
"python",
"pandas"
] | Thought this would be straight forward but had some trouble tracking down an elegant way to search all columns in a dataframe at same time for a partial string match. Basically how would I apply `df['col1'].str.contains('^')` to an entire dataframe at once and filter down to any rows that have records containing the ma... | The `Series.str.contains` method expects a regex pattern (by default), not a literal string. Therefore `str.contains("^")` matches the beginning of any string. Since every string has a beginning, everything matches. Instead use `str.contains("\^")` to match the literal `^` character.
To check every column, you could u... |
Python Pandas: How to get the row names from index of a dataframe? | 26,640,145 | 12 | 2014-10-29T20:34:16Z | 26,640,189 | 23 | 2014-10-29T20:36:33Z | [
"python",
"pandas",
"dataframe"
] | So assume I have a dataframe with rownames that aren't a column of their own per se such as the following:
```
X Y
Row 1 0 5
Row 2 8 1
Row 3 3 0
```
How would I extract these row names as a list, if I have their index?
For example, it would look something like:
function\_name(dataframe[indices])
>... | ```
df.index
```
That will output the row names as pandas Index object. You can get it as a pure list via:
```
list(df.index)
```
Finally, the index supports slicing similar to columns. IE:
```
df.index['Row 2':'Row 5'] etc...
``` |
Execute a function randomly | 26,640,169 | 2 | 2014-10-29T20:35:45Z | 26,640,201 | 12 | 2014-10-29T20:36:59Z | [
"python",
"function",
"random"
] | Consider the following functions:
```
def a():
print "a"
def b():
print "b"
```
Is there a way to pick a function to run randomly? I tried using:
```
random.choice([a(),b()])
```
but it returns both functions, I just want it to return one function. | Only call the *selected* function, not both of them:
```
random.choice([a,b])()
```
Below is a demonstration:
```
>>> import random
>>> def a():
... print "a"
...
>>> def b():
... print "b"
...
>>> random.choice([a,b])()
a
>>> random.choice([a,b])()
b
>>>
```
Your old code called *both* functions when the l... |
Why do I get "python int too large to convert to C long" errors when I use matplotlib's DateFormatter to format dates on the x axis? | 26,642,133 | 5 | 2014-10-29T22:59:27Z | 26,642,851 | 8 | 2014-10-30T00:07:40Z | [
"python",
"python-3.x",
"matplotlib",
"pandas"
] | Following [this answer's use of DateFormatter](http://stackoverflow.com/a/5502162/2766558), I tried to plot a time series and label its x axis with years using pandas 0.15.0 and matplotlib 1.4.2:
```
import datetime as dt
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas.io.data as pdio
import sci... | This is a 'regression' in pandas 0.15 (due to the refactor of Index), see <https://github.com/matplotlib/matplotlib/issues/3727> and <https://github.com/pydata/pandas/issues/8614>, but **is fixed in 0.15.1**.
---
Short story: matplotlib now sees the pandas index as an array of `datetime64[ns]` values (which are actua... |
Python: Exporting environment variables in subprocess.Popen(..) | 26,643,719 | 10 | 2014-10-30T01:48:26Z | 26,643,847 | 17 | 2014-10-30T02:04:02Z | [
"python",
"python-2.7",
"environment-variables"
] | I am having an issue with setting an environment variable on a call to `subprocess.Popen`. The environment variable does not seem to be getting set. Any suggestions on how to properly set environmental variables for a Python commandline call?
My goal is to run a script that uses an environmental variable determined fr... | The substitution of environment variables *on the command line* is done by the shell, not by /bin/echo. So you need to run the command in a shell to get the substitution:
```
In [22]: subprocess.Popen('/bin/echo $TEST_VARIABLE', shell=True, env=d).wait()
1234
Out[22]: 0
```
That doesn't mean the environment variable ... |
Pandas join issue: columns overlap but no suffix specified | 26,645,515 | 18 | 2014-10-30T05:09:05Z | 26,654,201 | 22 | 2014-10-30T13:24:22Z | [
"python",
"join",
"pandas"
] | I have following 2 data frames:
```
df_a =
mukey DI PI
0 100000 35 14
1 1000005 44 14
2 1000006 44 14
3 1000007 43 13
4 1000008 43 13
df_b =
mukey niccdcd
0 190236 4
1 190237 6
2 190238 7
3 190239 4
4 190240 7
```
When I try to join these 2 datafr... | Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:
```
In [173]:
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_... |
Pandas groupby month and year | 26,646,191 | 4 | 2014-10-30T06:10:51Z | 26,649,199 | 16 | 2014-10-30T09:24:40Z | [
"python",
"pandas"
] | I have the following dataframe:
```
Date abc xyz
01-Jun-13 100 200
03-Jun-13 -20 50
15-Aug-13 40 -5
20-Jan-14 25 15
21-Feb-14 60 80
```
I need to group the data by year and month. ie: Group by Jan 2013, Feb 2013, Mar 2013 etc...
I will be using the newly grouped data to create a ... | You can use either resample or TimeGrouper (which resample uses under the hood).
First make the datetime column is actually of datetimes (hit it with `pd.to_datetime`). It's easier if it'd a DatetimeIndex:
```
In [11]: df1
Out[11]:
abc xyz
Date
2013-06-01 100 200
2013-06-03 -20 50
2013-08-15 40 ... |
NumPy array is not JSON serializable | 26,646,362 | 12 | 2014-10-30T06:23:48Z | 32,850,511 | 20 | 2015-09-29T17:44:51Z | [
"python",
"django",
"numpy"
] | After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:
```
array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
```
What does this mean? | I regularly "jsonify" np.arrays. Try using the ".tolist()" method on the arrays first, like this:
```
import numpy as np
import codecs, json
a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
file_path = "/path.json" ## your path variable
json.dump(b, codecs.open(fi... |
py.test to test flask register, AssertionError: Popped wrong request context | 26,647,032 | 8 | 2014-10-30T07:10:06Z | 28,139,033 | 7 | 2015-01-25T17:08:05Z | [
"python",
"py.test",
"flask-login"
] | I'm using flask to do register and login:
```
from flask.ext.security.views import register, login
class Register(Resource):
def post(self):
return register()
class Login(Resource):
def post(self):
return login()
api.add_resource(Login, '/login')
api.add_resource(Register, '/register')
```
... | It's a known flask [problem](https://github.com/jarus/flask-testing/issues/21). You receive two exceptions instead one. Simply add `PRESERVE_CONTEXT_ON_EXCEPTION = False` to your test config. |
How to show PIL Image in ipython notebook | 26,649,716 | 15 | 2014-10-30T09:49:10Z | 26,649,884 | 20 | 2014-10-30T09:56:34Z | [
"python",
"ipython",
"python-imaging-library",
"ipython-notebook"
] | This is my code
```
from PIL import Image
pil_im = Image.open('data/empire.jpg')
```
I would like to do some image manipulation on it, and then show it on screen.
I am having problem with showing PIL Image in python notebook.
I have tried:
```
print pil_im
```
And just
```
pil_im
```
But both just give me:
``... | You can use IPython's `Module: display` to load the image. You can read more from [the Doc](http://ipython.org/ipython-doc/2/api/generated/IPython.core.display.html#IPython.core.display.Image).
```
from IPython.display import Image
Image(filename='data/empire.jpg')
```
### updated
As OP's requirement is to use `PIL... |
How use MethodFilter from django-filter app? | 26,656,153 | 2 | 2014-10-30T14:49:39Z | 26,670,407 | 9 | 2014-10-31T08:37:25Z | [
"python",
"django",
"django-filters"
] | I don't know how to use MethodFilter in django-filter app and I can't find it in the documentation (<http://django-filter.readthedocs.org/en/latest/index.html>). I need create filter with from and to input for date field. Do you have any idea how I can do this with MethodFilter or another way?
I have some class:
```
... | To answer the *How to use MethodFilter* part of the question, define a method on your `FilterSet` and assign that as the filter's `action`.
For example to filter by a username you would do something such as:
```
class F(FilterSet):
username = MethodFilter(action='filter_username')
class Meta:
model =... |
Installing NumPy and SciPy on 64-bit Windows (with Pip) | 26,657,334 | 4 | 2014-10-30T15:39:47Z | 26,670,308 | 9 | 2014-10-31T08:30:01Z | [
"python",
"numpy",
"scipy",
"windows64"
] | I found out that it's impossible to install NumPy/SciPy via installers on Windows 64-bit, that's only possible on 32-bit. Because I need more memory than a 32-bit installation gives me, I need the 64-bit version of everything.
I tried to install everything via Pip and most things worked. But when I came to SciPy, it c... | Numpy (as also some other packages like Scipy, Pandas etc.) includes lot's of C-, Cython, and Fortran code that needs to be compiled properly, before you can use it. This is, btw, also the reason why these Python-packages provide such fast Linear Algebra.
To get precompiled packages for Windows, have a look at [Gohlke... |
cat, grep and cut - translated to python | 26,659,142 | 6 | 2014-10-30T17:06:07Z | 26,659,479 | 21 | 2014-10-30T17:23:51Z | [
"python",
"linux",
"bash",
"grep",
"cut"
] | maybe there are enough questions and/or solutions for this, but I just can't help myself with this one question: I've got the following command I'm using in a bash-script:
```
var=$(cat "$filename" | grep "something" | cut -d'"' -f2)
```
Now, because of some issues I have to translate all the code to python. I never ... | You need to have better understanding of the python language and its standard library to translate the expression
[cat "$filename"](http://unixhelp.ed.ac.uk/CGI/man-cgi?cat): Reads the file `cat "$filename"` and dumps the content to stdout
`|`: pipe redirects the `stdout` from previous command and feeds it to the `st... |
Django: Dynamically set SITE_ID in settings.py based on URL? | 26,659,877 | 2 | 2014-10-30T17:44:29Z | 26,661,121 | 8 | 2014-10-30T18:53:20Z | [
"python",
"django",
"website"
] | What is a good way to dynamically set SIDE\_ID in settings.py based on domain name in URL?
I have an app that will be running with too many domain names (city based) that a custom settings.py file for each domain is just not doable.
Is there a way to set it dynamically? | You can do a custom middleware which reads the request and sets the SITE\_ID. I use this code on one of my sites:
```
class SiteMiddleware(object):
def process_request(self, request):
try:
current_site = Site.objects.get(domain=request.get_host())
except Site.DoesNotExist:
c... |
How to embed python in an Objective-C OS X application for plugins? | 26,660,287 | 4 | 2014-10-30T18:08:37Z | 26,692,673 | 8 | 2014-11-01T20:03:50Z | [
"python",
"objective-c",
"xcode",
"osx",
"cocoa"
] | I'm trying to use python in a new OS X application for plugin scripting. I'm looking to offload some of the program logic to python for easy, on-the-fly modification. I had started by looking at the [Big Nerd Ranch tutorial](http://www.informit.com/blogs/blog.aspx?uk=Ask-Big-Nerd-Ranch-Adding-Python-Scripting-to-Cocoa-... | I've come up with a method that seems to work fairly well.
First, download source of the python version you want to use from the [official website](https://www.python.org/downloads/source/). Extract the archive somewhere. I'm using Python 3.4.2. Adjust the commands on your system for the specific version you're using.... |
How to do Python package management? | 26,660,601 | 13 | 2014-10-30T18:25:01Z | 26,661,475 | 13 | 2014-10-30T19:14:22Z | [
"python",
"pip",
"virtualenv"
] | Coming from a Node.js + npm background, it is really nightmarish trying to understand all the things related to Python package management. After a few hours of research, I've stumbled upon all those keywords:
* easy\_install
* virtualenv
* pip
* setuptools
* distutils
* pypi
* wheel
* egg
* site-packages
Can someone ... | **Types of Packages**
[Egg](http://stackoverflow.com/questions/2051192/what-is-a-python-egg) vs [Wheel](https://pypi.python.org/pypi/wheel) vs Neither. What's meant by neither is that a python package can be installed from its "source" without being packaged as an egg or wheel.
**Packaging Utilities**
There are se... |
How do I print the key-value pairs of a dictionary in python | 26,660,654 | 19 | 2014-10-30T18:27:21Z | 26,660,696 | 7 | 2014-10-30T18:29:31Z | [
"python",
"dictionary"
] | I want to output my key value pairs from a python dictionary as such:
```
key1 \t value1
key2 \t value2
```
I thought I could maybe do it like this:
```
for i in d:
print d.keys(i), d.values(i)
```
but obviously that's not how it goes as the `keys()` and `values()` don't take an argument...
Thanks. | Or, for Python 3:
```
for k,v in dict.items():
print(k, v)
``` |
How do I print the key-value pairs of a dictionary in python | 26,660,654 | 19 | 2014-10-30T18:27:21Z | 26,660,785 | 28 | 2014-10-30T18:33:54Z | [
"python",
"dictionary"
] | I want to output my key value pairs from a python dictionary as such:
```
key1 \t value1
key2 \t value2
```
I thought I could maybe do it like this:
```
for i in d:
print d.keys(i), d.values(i)
```
but obviously that's not how it goes as the `keys()` and `values()` don't take an argument...
Thanks. | Your existing code just needs a little tweak. `i` *is* the key, so you would just need to use it:
```
for i in d:
print i, d[i]
```
You can also get an iterator that contains both keys and values. In Python 2, `d.items()` returns a list of (key, value) tuples, while `d.iteritems()` returns an iterator that provid... |
Why can I not create a wheel in python? | 26,664,102 | 53 | 2014-10-30T22:02:12Z | 26,664,184 | 82 | 2014-10-30T22:08:40Z | [
"python",
"pip",
"setuptools",
"python-wheel"
] | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | Install the [`wheel` package](https://pypi.python.org/pypi/wheel) first:
```
pip install wheel
```
The documentation isn't overly clear on this, but *"the wheel project provides a bdist\_wheel command for setuptools"* actually means *"the wheel **package**..."*. |
Why can I not create a wheel in python? | 26,664,102 | 53 | 2014-10-30T22:02:12Z | 27,868,004 | 56 | 2015-01-09T19:43:15Z | [
"python",
"pip",
"setuptools",
"python-wheel"
] | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | I also ran into the error message `invalid command 'bdist_wheel'`
It turns out the package setup.py used distutils rather than setuptools.
Changing it as follows enabled me to build the wheel.
```
#from distutils.core import setup
from setuptools import setup
``` |
Why can I not create a wheel in python? | 26,664,102 | 53 | 2014-10-30T22:02:12Z | 29,853,019 | 18 | 2015-04-24T16:42:57Z | [
"python",
"pip",
"setuptools",
"python-wheel"
] | Here are the commands I am running:
```
$ python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'
$ pip --version
pip 1.5.6 from /usr/local/... | Update your setuptools, too.
```
pip install setuptools --upgrade
```
If that fails too, you could try with additional `--force` flag. |
Django/Python assertRaises with message check | 26,664,112 | 7 | 2014-10-30T22:03:19Z | 26,664,795 | 12 | 2014-10-30T22:54:48Z | [
"python",
"django",
"validation",
"unit-testing"
] | I am relatively new to Python and want to use a `assertRaises` test to check for a `ValidationError`, which works ok. However, I have many `ValidationError`s and I want to make sure the right one is returned. I figured I could pass something into `assertRaises` but it doesn't look like I can, so I figured I would just ... | You can just use [`assertRaisesRegexp`](https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaisesRegexp).
```
with self.assertRaisesRegexp(ValidationError, "Both"):
de.full_clean()
```
When you use it as a context manager the 2nd argument is a regular expression to search through the exceptio... |
Would it be pythonic to use `or`, similar to how PHP would use `or die()`? | 26,664,855 | 6 | 2014-10-30T23:00:18Z | 26,664,910 | 18 | 2014-10-30T23:04:02Z | [
"python",
"conditional-statements",
"boolean-expression"
] | Is it pythonic to use `or`, similar to how PHP would use `or die()`?
I have been using
`quiet or print(stuff)`
instead of
`if verbose:
print(stuff)`
lately.
I think it looks nicer, they do the same thing, and it saves on a line. Would one be better than the other in terms of performance?
The bytecode for bot... | No, this is definitely not Pythonic. Many of the decision made along the way have been specifically to discourage this kind of coding.
---
The right way to write this is the obvious way:
```
if verbose:
print(stuff)
```
Or, if computing `stuff` in itself isn't expensive/dangerous/irrevocable, just wrap `print` ... |
Django Model() vs Model.objects.create() | 26,672,077 | 63 | 2014-10-31T10:09:49Z | 26,672,182 | 58 | 2014-10-31T10:14:42Z | [
"python",
"django",
"database"
] | What it the difference between running two commands:
```
foo = FooModel()
```
and
```
bar = BarModel.objects.create()
```
Does the second one immediately creates a BarModel at database, while for FooModel the save() method has to be called explicitly to add it? | <https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects>
> To create and save an object in a single step, use the `create()` method. |
Python: How to set local variable in list comprehension? | 26,672,532 | 3 | 2014-10-31T10:31:45Z | 26,672,589 | 12 | 2014-10-31T10:35:02Z | [
"python",
"list-comprehension"
] | I have a method that take a list and return an object
```
# input a list, returns an object
def map_to_obj(lst):
a_list = f(lst)
return a_list[0] if a_list else None
```
I want to get a list that contains all the mapped elements that isn't `None`.
Like this:
```
v_list = [v1, v2, v3, v4]
[map_to_obj(v) for... | Use nested list comprehension:
`[x for x in [map_to_obj(v) for v in v_list] if x]`
or better still, a list comprehension around a generator expression:
`[x for x in (map_to_obj(v) for v in v_list) if x]` |
Python multiprocessing apply_async never returns result on Windows 7 | 26,680,468 | 2 | 2014-10-31T17:38:02Z | 26,680,596 | 7 | 2014-10-31T17:47:57Z | [
"python",
"windows",
"multiprocessing"
] | I am trying to follow a very simple multiprocessing example:
```
import multiprocessing as mp
def cube(x):
return x**3
pool = mp.Pool(processes=2)
results = [pool.apply_async(cube, args=x) for x in range(1,7)]
```
However, on my windows machine, I am not able to get the result (on ubuntu 12.04LTS it runs per... | There are a couple of mistakes here. First, you must declare the `Pool` inside an `if __name__ == "__main__":` guard [when running on Windows](https://docs.python.org/2.7/library/multiprocessing.html#windows). Second, you have to pass the `args` keyword argument a sequence, even if you're only passing one argument. So ... |
Django - Rotating File Handler stuck when file is equal to maxBytes | 26,682,413 | 5 | 2014-10-31T19:51:37Z | 26,848,236 | 7 | 2014-11-10T16:22:34Z | [
"python",
"django"
] | I have a problem with the RotatingFileHander with Django.
The problem is that when the file is up to the maxBytes size, it will not create a new file, and give an error message when you are trying to do logger.info("any message"):
The strange part is:
1. Nobody is sharing loggers, views would have their own logger, ... | I guess you are facing the problem described in this post: [Django logging with RotatingFileHandler error](http://azaleasays.com/2014/05/01/django-logging-with-rotatingfilehandler-error/)
That is, when running Django development server, actually there are two processes running.
> by default, two processes of Django s... |
TypeError: unsupported operand type(s) for -: 'list' and 'list' | 26,685,679 | 6 | 2014-11-01T02:20:04Z | 26,685,716 | 9 | 2014-11-01T02:30:19Z | [
"python",
"list",
"python-2.7",
"operand"
] | I am trying to implement the Naive Gauss and getting the unsupported operand type error on execution.
Output:
```
execfile(filename, namespace)
File "/media/zax/MYLINUXLIVE/A0N-.py", line 26, in <module>
print Naive_Gauss([[2,3],[4,5]],[[6],[7]])
File "/media/zax/MYLINUXLIVE/A0N-.py", line 20, in Naive_Gauss... | You can't subtract a list from a list.
```
>>> [3, 7] - [1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
```
Simple way to do it is using [`numpy`](http://numpy.org/):
```
>>> import numpy as np
>>> np.array([3, 7]) - np.a... |
How do you scroll a GridLayout inside Kivy ScrollView? | 26,686,631 | 2 | 2014-11-01T06:02:36Z | 26,689,402 | 8 | 2014-11-01T12:40:35Z | [
"python",
"kivy"
] | At the moment this is my kv code that is not scrollable:
```
BoxLayout:
id: bl
orientation: 'vertical'
padding: 10, 10
row_default_height: '48dp'
row_force_default: True
spacing: 10, 10
GridLayout:
id: layout_content
cols: 1
row_default_height: '20dp'
row_fo... | According to the [documentation for ScrollView](http://kivy.org/docs/api-kivy.uix.scrollview.html?highlight=scrollview#managing-the-content-size-and-position) you have to disable at least one of the ScrollView's child size\_hint:
```
<Controller>:
layout_content: layout_content
BoxLayout:
id: bl
... |
Add n tasks to celery queue and wait for the results | 26,686,850 | 9 | 2014-11-01T06:42:07Z | 26,687,086 | 11 | 2014-11-01T07:24:34Z | [
"python",
"django",
"celery",
"django-celery"
] | I would add multiple tasks to celery queue and wait for results. I have various ideas how I would achieve this utilising some form of shared storage (memcached, redis, db, etc.), however, I would have thought it's something that Celery can handle automatically but I can't find any resources online.
**Code example**
`... | [`Task.delay`](http://celery.readthedocs.org/en/latest/reference/celery.app.task.html#celery.app.task.Task.delay) returns [`AsyncResult`](http://celery.readthedocs.org/en/latest/reference/celery.result.html#celery.result.AsyncResult). Use [`AsyncResult.get`](http://celery.readthedocs.org/en/latest/reference/celery.resu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.