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 |
|---|---|---|---|---|---|---|---|---|---|
dynamic module does not define init function (PyInit_fuzzy) | 29,657,319 | 7 | 2015-04-15T17:51:53Z | 29,685,650 | 9 | 2015-04-16T20:49:24Z | [
"python",
"cython"
] | I am using Python3.4 and I am trying to install the module fuzzy
```
https://pypi.python.org/pypi/Fuzzy.
```
Since it is mentioned it works only for Python2, I tried to convert it using cython. These are the steps that I followed:
1. cython fuzzy.pyx
2. gcc -g -02 -fpic `python-config --cflags` -c fuzzy.c -o fuzzy.o... | This was solved with a quick comment, but posted as an answer for the sake of giving a bit more detail...
The very short answer is to replace all instances of `python-config` for `python3-config` or `python3.4-config`.
*Unnecessary detail follows*
OP was trying to use a Pyrex module in Python 3 (this isn't especiall... |
google-app-engine 1.9.19 deploy failure | 29,657,557 | 9 | 2015-04-15T18:04:49Z | 32,111,611 | 13 | 2015-08-20T07:04:19Z | [
"python",
"google-app-engine"
] | When trying to deploy using the new Python GoogleAppEngine-1.9.19 in the form of the GAE launcher on Windows 7, I'm not asked to authenticate. Instead, I get a page for accepting GAE management, and then I'm running locally. Moreover, clicking the close box on the launcher does nothing and I have to kill it externally.... | It's an issue with Google App Engine SDK, which doesn't allow the user authentication process to be completed, if local server is running.
Step 1. Stop the local server.
Step 2. Click on 'Deploy'
Step 3. You should get a message `"The authentication flow has completed."`
Step 4. Close the Window.
Step 5. Deploy ag... |
Create vertical numpy arrays in python | 29,658,567 | 5 | 2015-04-15T18:58:01Z | 29,658,610 | 9 | 2015-04-15T19:00:26Z | [
"python",
"arrays",
"numpy"
] | I'm using `NumPy` in `Python` to work with arrays. This is the way I'm using to create a vertical array:
```
import numpy as np
a = np.array([[1],[2],[3]])
```
Is there any simple and more direct way to create vertical arrays? | You can use `reshape` or [`vstack`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html) :
```
>>> a=np.arange(1,4)
>>> a
array([1, 2, 3])
>>> a.reshape(3,1)
array([[1],
[2],
[3]])
>>> np.vstack(a)
array([[1],
[2],
[3]])
```
Also, you can use [*broadcasting*](http://docs.... |
How to extract the decimal value of float in python | 29,661,465 | 3 | 2015-04-15T21:43:13Z | 29,661,500 | 11 | 2015-04-15T21:45:51Z | [
"python"
] | I have a program that is a converter for times in minutes and seconds and returns a float value with a decimal, for example:
`6.57312`
I would like to extract the `.57312` part in order to convert it to seconds.
How can I get python to take only the value after the decimal point and put it into a variable that I can... | You can do just a simple operation
```
dec = 6.57312 % 1
``` |
How to extract the decimal value of float in python | 29,661,465 | 3 | 2015-04-15T21:43:13Z | 29,661,504 | 7 | 2015-04-15T21:46:05Z | [
"python"
] | I have a program that is a converter for times in minutes and seconds and returns a float value with a decimal, for example:
`6.57312`
I would like to extract the `.57312` part in order to convert it to seconds.
How can I get python to take only the value after the decimal point and put it into a variable that I can... | [`math.modf`](https://docs.python.org/2/library/math.html#math.modf) does that. It also has the advantage that you get the whole part in the same operation.
```
import math
f,i = math.modf(6.57312)
# f == .57312, i==6.0
```
Example program:
```
import math
def dec_to_ms(value):
frac,whole = math.modf(value)
... |
Normalize numpy array columns in python | 29,661,574 | 11 | 2015-04-15T21:51:13Z | 29,661,707 | 23 | 2015-04-15T22:02:04Z | [
"python",
"numpy",
"normalize"
] | I have a numpy array where each cell of a specific row represents a value for a feature. I store all of them in an 100\*4 matrix.
```
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
```
Any idea how I can normalize rows of this numpy.array where each value is between 0 and 1?
My desired output is:
```
A ... | If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using [broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).
Starting with your example array:
```
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5... |
Comparing each element between 2 sets? | 29,661,739 | 3 | 2015-04-15T22:04:37Z | 29,661,754 | 8 | 2015-04-15T22:05:17Z | [
"python",
"set"
] | I'm trying to compare 2 sets of data
`set1 = [a,b,c,d,e,f]
set2 = [a,c,e]`
How would I go about finding out which variable from `set2` are in `set1` then output this to another set showing the results? | Use [intersection](http://en.wikibooks.org/wiki/Python_Programming/Sets#Intersection):
```
set2.intersection(set1)
```
Or `set(set2).intersection(set1)` if you actually have a list.
Based on your comment maybe a dict where the values are booleans based on whether each element from set1 is in the intersection set:
`... |
Strange if statement | 29,663,428 | 24 | 2015-04-16T00:43:35Z | 29,663,465 | 33 | 2015-04-16T00:48:29Z | [
"python",
"python-2.7",
"if-statement"
] | I found this strange `if`-statement in somebody elseâs code:
```
if variable & 1 == 0:
```
I don't understand it. It should have two `==`, right?
Can somebody explain this? | The conditional is a [bitwise operator](https://wiki.python.org/moin/BitwiseOperators) comparison:
```
>>> 1 & 1
1
>>> 0 & 1
0
>>> a = 1
>>> a & 1 == 0
False
>>> b = 0
>>> b & 1 == 0
True
```
---
As many of the comments say, for integers this conditional is True for evens and False for odds. The prevalent way to wri... |
Strange if statement | 29,663,428 | 24 | 2015-04-16T00:43:35Z | 29,663,482 | 29 | 2015-04-16T00:50:04Z | [
"python",
"python-2.7",
"if-statement"
] | I found this strange `if`-statement in somebody elseâs code:
```
if variable & 1 == 0:
```
I don't understand it. It should have two `==`, right?
Can somebody explain this? | This code just checks if the lowest bit of `variable` is a 0. Based on operator precedence this is:
```
if (variable & 1) == 0:
```
First AND the lowest bit with one (extract just the lowest bit), then check if it is 0. |
Strange if statement | 29,663,428 | 24 | 2015-04-16T00:43:35Z | 29,663,494 | 14 | 2015-04-16T00:51:27Z | [
"python",
"python-2.7",
"if-statement"
] | I found this strange `if`-statement in somebody elseâs code:
```
if variable & 1 == 0:
```
I don't understand it. It should have two `==`, right?
Can somebody explain this? | The & is a [bitwise operator](https://wiki.python.org/moin/BitwiseOperators). It returns an integer with 1 bit for every bit of its two operands that are both 1, and 0 in all other places. For example:
```
a = 10 # 0b1010
b = 6 # 0b0110
a & b # 0b0010
```
Now, if you have `variable & 1`, you're comparing `variable`... |
Python app does not print anything when running detached in docker | 29,663,459 | 19 | 2015-04-16T00:47:16Z | 29,745,541 | 16 | 2015-04-20T10:37:19Z | [
"python",
"docker",
"dockerfile"
] | I have a Python (2.7) app which is started in my dockerfile:
```
CMD ["python","main.py"]
```
*main.py* prints some strings when it is started and goes into a loop afterwards:
```
print "App started"
while True:
time.sleep(1)
```
As long as I start the container with the -it flag, everything works as expected:
... | Finally I found a solution to see Python output when running daemonized in Docker, thanks to @ahmetalpbalkan over at [GitHub](https://github.com/docker/docker/issues/12447#issuecomment-94417192). Answering it here myself for further reference :
Using unbuffered output with
```
CMD ["python","-u","main.py"]
```
inste... |
Determine if an image exists within a larger image, and if so, find it, using Python | 29,663,764 | 4 | 2015-04-16T01:22:57Z | 29,669,787 | 12 | 2015-04-16T08:52:50Z | [
"python",
"opencv",
"image-processing",
"numpy",
"graphics"
] | I need a Python program that I am working on to be able to take a small image, determine if it exists inside a larger image, and if so, report its location. If not, report that. (In my case, the large image will be a screenshot, and the small image an image that may or may not be on the screen, in an HTML5 canvas.) Loo... | I will propose an answer that works fast and perfectly if you are looking for `exact match` both in size and in image values.
The idea is to calculate a brute force search of the wanted `h x w` *template* in a larger `H x W` image. The bruteforce approach would consist in looking at all the possible `h x w` windows ov... |
Does the order of addition expressions matter in Python? | 29,665,382 | 4 | 2015-04-16T04:32:59Z | 29,665,413 | 8 | 2015-04-16T04:36:34Z | [
"python",
"methods"
] | This sounds kind of stupid but I'm not talking about `1 + 2 = 2 + 1`. I am talking about where an object with an `__add__` method is added to a number. An example will be:
```
>>> class num:
... def __add__(self,x):
... return 1+x
...
>>> n = num()
>>> 1+n
Traceback (most recent call last):
File "<s... | Addition isn't assumed to be commutative - for example, `[1] + [2] != [2] + [1]` - so there's a separate method you need to implement when your object is on the right side of a `+` and the thing on the left doesn't know how to handle it.
```
def __radd__(self, other):
# Called for other + self when other can't han... |
Django error: relation "users_user" does not exist | 29,672,190 | 3 | 2015-04-16T10:36:33Z | 29,672,770 | 7 | 2015-04-16T11:03:07Z | [
"python",
"django"
] | I'm getting the following error during migration:
> django.db.utils.ProgrammingError: relation "users\_user" does not exist
```
File "/Users/user/Documents/workspace/api/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
... | Inside your user app, you should have a folder `migrations`. It should only contain `0001_initial.py` and `__init__.py`. Is that correct?
Try running `./manage.py sqlmigrate user 0001_initial` and see what it does, because thats where the error comes from |
Histogram in matplotlib, time on x-Axis | 29,672,375 | 2 | 2015-04-16T10:45:28Z | 29,679,443 | 9 | 2015-04-16T15:32:52Z | [
"python",
"time",
"matplotlib",
"plot",
"histogram"
] | I am new to matplotlib (1.3.1-2) and I cannot find a decent place to start.
I want to plot the distribution of points over time in a histogram with matplotlib.
Basically I want to plot the cumulative sum of the occurrence of a date.
```
date
2011-12-13
2011-12-13
2013-11-01
2013-11-01
2013-06-04
2013-06-04
2014-01-01... | Matplotlib uses its own format for dates/times, but also provides simple functions to convert which are provided in the `dates` module. It also provides various `Locators` and `Formatters` that take care of placing the ticks on the axis and formatting the corresponding labels. This should get you started:
```
import r... |
Unlike Numpy, Pandas doesn't seem to like memory strides | 29,673,396 | 6 | 2015-04-16T11:31:55Z | 29,674,364 | 10 | 2015-04-16T12:11:55Z | [
"python",
"numpy",
"pandas"
] | Pandas seems to be missing a R-style matrix-level rolling window function (`rollapply(..., by.column = FALSE)`), providing only the vector based version. Thus I tried to follow [this question](http://stackoverflow.com/questions/26371509/n-dimensional-sliding-window-with-pandas-or-numpy) and it works beautifully with th... | It seems that the `.values` returns the underlying data in Fortran order (as you speculated):
```
>>> mm.flags # NumPy array
C_CONTIGUOUS : True
F_CONTIGUOUS : False
...
>>> pp.flags # array from DataFrame
C_CONTIGUOUS : False
F_CONTIGUOUS : True
...
```
This confuses `as_strided` which expects the data ... |
Get the index of the minimium N elements of a list in Python | 29,677,673 | 3 | 2015-04-16T14:24:38Z | 29,677,986 | 7 | 2015-04-16T14:35:41Z | [
"python",
"arrays",
"list"
] | I want to get the index of the minimum N elements of a list. It would be great if I can get that output on another list.
For example:
```
[1, 1, 10, 5, 3, 5]
output = [0, 1]
[10, 5, 12, 5, 0, 10]
output = [4]
[9, 2, 8, 2, 3, 4, 2]
output = [1, 3, 6]
[10, 10, 10, 10, 10, 10]
output = [0, 1, 2, 3, 4, 5]
```
I know ... | ```
>>> L = [9, 2, 8, 2, 3, 4, 2]
>>> minL = min(L)
>>> [i for i, x in enumerate(L) if x == minL]
[1, 3, 6]
```
Currently, the other solutions *will* call `min` during the iteration, resulting in a poor and unnecessary *O(n^2)* complexity.
---
Edit for Kasra: evidence of n^2 complexity of the naive solution:
```
>>... |
How to use the user_passes_test decorator in class based views? | 29,682,704 | 5 | 2015-04-16T18:06:25Z | 29,683,126 | 12 | 2015-04-16T18:29:14Z | [
"python",
"django",
"python-2.7",
"decorator",
"python-decorators"
] | I am trying to check certain conditions before the user is allowed to see a particular user settings page. I am trying to achieve this using the user\_passes\_test decorator. The function sits in a class based view as follows. I am using method decorator to decorate the get\_initial function in the view.
```
class Use... | Django 1.9 has authentication mixins for class based views. You can use the [`UserPassesTest`](https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin) mixin as follows.
```
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class UserSetti... |
What should I use instead of syncdb in Django 1.9? | 29,683,494 | 43 | 2015-04-16T18:49:49Z | 29,683,785 | 43 | 2015-04-16T19:03:32Z | [
"python",
"django",
"django-1.8"
] | Take a look at this:
```
$ pypy ./manage.py syncdb
/usr/lib64/pypy-2.4.0/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
(cut)
```
I ran... | `syncdb` is deprecated because of [the migration system](https://docs.djangoproject.com/en/1.8/topics/migrations/)1.
Now you can **track** your changes using `makemigrations`. This transforms your model changes into python code to make them deployable to another databases.
After you created the migrations you have to... |
What should I use instead of syncdb in Django 1.9? | 29,683,494 | 43 | 2015-04-16T18:49:49Z | 34,635,951 | 20 | 2016-01-06T14:48:06Z | [
"python",
"django",
"django-1.8"
] | Take a look at this:
```
$ pypy ./manage.py syncdb
/usr/lib64/pypy-2.4.0/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
(cut)
```
I ran... | You should definitely use [migration system](https://docs.djangoproject.com/en/stable/topics/migrations/). Which lets you track changes in your `models.py`, and create migrations for the database. The migration system uses the commands [`makemigrations`](https://docs.djangoproject.com/en/stable/ref/django-admin/#django... |
Need Help Writing Recursive function that find cheapest route through a list of numbers | 29,684,981 | 4 | 2015-04-16T20:07:59Z | 29,686,460 | 7 | 2015-04-16T21:39:44Z | [
"python",
"recursion"
] | So I've been working on this homework problem for a few hours, I'll do my best to explain it.
I need to write a program in python that takes a list and starts you at the first item in the list, you can either move forward one space or jump over an item and land on the other side of it, each item you land on costs the ... | The following should work:
```
def player(l):
a = b = l[0]
for v in l[1:]:
a, b = b, min(a, b) + v
return b
```
Example:
```
>>> player([0, 98, 7, 44, 25, 3, 5, 85, 46, 4])
87
```
This can be actually considered a [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming) algorithm.... |
mean, nanmean and warning: Mean of empty slice | 29,688,168 | 15 | 2015-04-17T00:22:06Z | 29,688,390 | 13 | 2015-04-17T00:50:33Z | [
"python",
"numpy"
] | Say I construct two numpy arrays:
```
a = np.array([np.NaN, np.NaN])
b = np.array([np.NaN, np.NaN, 3])
```
Now I find that `np.mean` returns `nan` for both `a` and `b`:
```
>>> np.mean(a)
nan
>>> np.mean(b)
nan
```
Since numpy 1.8, we've been blessed with `nanmean`, which ignores `nan` values:
```
>>> np.nanmean(b... | I really can't see any good reason not to just suppress the warning.
The safest way would be to use the [`warnings.catch_warnings`](https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings) context manager to suppress the warning only where you anticipate it occurring - that way you won't miss ... |
How I do convert from timestamp to date in python? | 29,688,511 | 6 | 2015-04-17T01:06:36Z | 29,688,540 | 8 | 2015-04-17T01:11:30Z | [
"python",
"date",
"datetime"
] | I have this string `'2015-04-08T07:52:00Z'` and I wanna to convert it to `'08/04/2015'`, how can I do this? | You can use the `datetime.datetime.strptime()` function to create a datetime object, then `datetime.datetime.strftime()` to return your correctly formatted date like so:
```
from datetime import datetime
dt = datetime.strptime('2015-04-08T07:52:00Z', '%Y-%m-%dT%H:%M:%SZ')
print dt.strftime('%d/%m/%Y')
``` |
auth_user error with Django 1.8 and syncdb / migrate | 29,689,365 | 34 | 2015-04-17T02:46:27Z | 29,941,471 | 70 | 2015-04-29T10:47:48Z | [
"python",
"django",
"buildout",
"django-syncdb",
"django-1.8"
] | When upgrading to Django 1.8 (with zc.buildout) and running syncdb or migrate, I get this message:
`django.db.utils.ProgrammingError: relation "auth_user" does not exist`
One of my models contains django.contrib.auth.models.User:
```
user = models.ForeignKey(
User, related_name='%(app_label)s_%(class)s_user',
... | I fix this by running auth first, then the rest of my migrations:
```
python manage.py migrate auth
python manage.py migrate
``` |
auth_user error with Django 1.8 and syncdb / migrate | 29,689,365 | 34 | 2015-04-17T02:46:27Z | 30,031,219 | 14 | 2015-05-04T13:19:33Z | [
"python",
"django",
"buildout",
"django-syncdb",
"django-1.8"
] | When upgrading to Django 1.8 (with zc.buildout) and running syncdb or migrate, I get this message:
`django.db.utils.ProgrammingError: relation "auth_user" does not exist`
One of my models contains django.contrib.auth.models.User:
```
user = models.ForeignKey(
User, related_name='%(app_label)s_%(class)s_user',
... | On my environment, I fix this running `makemigrations` on all apps that have relationship with `django.contrib.auth.models`:
```
manage.py makemigrations app_with_user_relation
manage.py migrate
``` |
auth_user error with Django 1.8 and syncdb / migrate | 29,689,365 | 34 | 2015-04-17T02:46:27Z | 32,743,611 | 11 | 2015-09-23T15:25:45Z | [
"python",
"django",
"buildout",
"django-syncdb",
"django-1.8"
] | When upgrading to Django 1.8 (with zc.buildout) and running syncdb or migrate, I get this message:
`django.db.utils.ProgrammingError: relation "auth_user" does not exist`
One of my models contains django.contrib.auth.models.User:
```
user = models.ForeignKey(
User, related_name='%(app_label)s_%(class)s_user',
... | I also had the same issue I solved it by using these :
```
python manage.py migrate auth
python manage.py migrate
```
Then migrate does its job |
Python Mogo ImportError: cannot import name Connection | 29,690,786 | 3 | 2015-04-17T05:06:44Z | 32,218,936 | 9 | 2015-08-26T05:54:11Z | [
"python",
"mongodb"
] | Can't figure out why this is not working.
`mogo==0.2.4`
```
File "/Users/Sam/Envs/AdiosScraper/lib/python2.7/site-packages/mogo/connection.py", line 3, in <module>
from pymongo import Connection as PyConnection
ImportError: cannot import name Connection
``` | i had same problem and too many files had the import, so, i couldn't risk changing the `import` - (didn't knew exactly where all it is mentioned).
I just downgraded `pymongo`:
```
sudo pip install pymongo==2.7.2
```
and it worked! |
Making an object x such that "x in [x]" returns False | 29,692,140 | 25 | 2015-04-17T06:46:15Z | 29,692,536 | 11 | 2015-04-17T07:09:45Z | [
"python",
"python-internals"
] | If we make a pathological potato like this:
```
>>> class Potato:
... def __eq__(self, other):
... return False
... def __hash__(self):
... return random.randint(1, 10000)
...
>>> p = Potato()
>>> p == p
False
```
We can break sets and dicts this way (*note:* it's the same even if `__eq__` re... | `list`, `tuple`, etc., does indeed do an identity check before an equality check, and this behavior is motivated by [these invariants](http://bugs.python.org/issue4296#msg75735):
```
assert a in [a]
assert a in (a,)
assert [a].count(a) == 1
for a in container:
assert a in container # this should ALWAYS be true
... |
Making an object x such that "x in [x]" returns False | 29,692,140 | 25 | 2015-04-17T06:46:15Z | 29,692,544 | 8 | 2015-04-17T07:09:56Z | [
"python",
"python-internals"
] | If we make a pathological potato like this:
```
>>> class Potato:
... def __eq__(self, other):
... return False
... def __hash__(self):
... return random.randint(1, 10000)
...
>>> p = Potato()
>>> p == p
False
```
We can break sets and dicts this way (*note:* it's the same even if `__eq__` re... | In general, breaking the assumption that identity implies equality can break a variety of things in Python. It is true that NaN breaks this assumption, and thus NaN breaks some things in Python. Discussion can be found in [this Python bug](http://bugs.python.org/issue4296). In a pre-release version of Python 3.0, relia... |
Find the second closest index to value | 29,696,644 | 3 | 2015-04-17T10:25:38Z | 29,696,782 | 7 | 2015-04-17T10:31:46Z | [
"python",
"numpy"
] | I am using
```
index = (np.abs(array - value)).argmin()
```
to find the index in an array with the smallest absolute difference to a value.
However, is there a nice clean way such as this for finding the *second* closest index to the value? | I think this works
```
a = np.linspace(0,10,30)
array([ 0. , 0.34482759, 0.68965517, 1.03448276,
1.37931034, 1.72413793, 2.06896552, 2.4137931 ,
2.75862069, 3.10344828, 3.44827586, 3.79310345,
4.13793103, 4.48275862, 4.82758621, 5.17241379,
5.51724138... |
Get the closest datetime from a list | 29,700,214 | 4 | 2015-04-17T13:12:11Z | 29,700,303 | 8 | 2015-04-17T13:15:57Z | [
"python",
"datetime"
] | in Python, if I have a `datetime` and a list of `datetime`s, e.g.:
```
import datetime as dt
date = dt.datetime(1970, 1,1)
dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1,3)]
```
How I can get the `datetime` in the list that's closest to `date`? | You can use [`min`](https://docs.python.org/2/library/functions.html#min) with a custom `key` parameter:
```
>>> import datetime as dt
>>> date = dt.datetime(1970, 1, 1)
>>> dates = [dt.datetime(1970, 1, 2), dt.datetime(1970, 1, 3)]
>>> min(dates, key=lambda d: abs(d - date))
datetime.datetime(1970, 1, 2, 0, 0)
```
S... |
Is there a max length to a python conditional (if) statement? | 29,700,588 | 5 | 2015-04-17T13:27:46Z | 29,700,778 | 9 | 2015-04-17T13:35:41Z | [
"python",
"python-2.7",
"conditional",
"eval",
"conditional-statements"
] | I generate a conditional statement using python's (2.7) `eval()` function like so:
```
my_list = ['2 > 1','3 > 2','4 > 3']
if eval('(' + ') or ('.join(my_list) + ')'):
print 'yes'
else:
print 'no'
```
In my case, the list is generated by code, my\_list comes from a parameter file, and the list is joined with... | Perhaps I'm missing something but it would seem that:
```
any(map(eval, my_list))
```
Does exactly what you'd like.
```
from itertools import imap
any(imap(eval, my_list)) # Python 2.
```
This has the nice effect of **not** evaluating the rest of the list if the first element evals to `True` (also known as "short-... |
How to get matplotlib figure size | 29,702,424 | 5 | 2015-04-17T14:45:45Z | 29,702,596 | 7 | 2015-04-17T14:52:15Z | [
"python",
"matplotlib",
"size",
"pixels",
"figure"
] | For a project, I need to know the current size (in pixels) of my matplotlib figure, but I can't find how to do this.
Does anyone know how to do this ?
Thanks,
Tristan | ```
import matplotlib.plt
fig = plt.figure()
size = fig.get_size_inches()*fig.dpi # size in pixels
```
To do it for the current figure,
```
fig = plt.gcf()
size = fig.get_size_inches()*fig.dpi # size in pixels
```
You can get the same info by doing:
```
bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans... |
Asyncio event loop per python process (aioprocessing, multiple event loops) | 29,703,620 | 6 | 2015-04-17T15:36:40Z | 29,705,642 | 9 | 2015-04-17T17:19:31Z | [
"python",
"python-asyncio"
] | I have two processes; a main process and a subprocess. The main process is running an `asyncio` event loop, and starts the subprocess. I want to start another asyncio event loop in the subprocess. I'm using the `aioprocessing` module to launch the subprocess.
The subprocess function is:
```
def subprocess_code():
... | Sorry for disturb!
I found a solution!
```
policy = asyncio.get_event_loop_policy()
policy.set_event_loop(policy.new_event_loop())
loop = asyncio.get_event_loop()
```
put this code to start new asycnio event loop inside of subprocess started from process with asyncio event loop |
Getting TemplateDoesNotExist from Django 1.8 | 29,704,686 | 4 | 2015-04-17T16:26:57Z | 29,705,120 | 9 | 2015-04-17T16:51:23Z | [
"python",
"django"
] | \*\* I'm using Django 1.8. The templates feature has changed in this release of Django. Read more here [Upgrading templates to Django 1.8](https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/ "Upgrading templates to Django 1.8")\*\*
This is bothering me because I've come across this issue and fixed it for on... | remove the slashes: `TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')`
See [here](http://stackoverflow.com/questions/4562252/django-how-to-deal-with-the-paths-in-settings-py-on-collaborative-projects)
Things have changed with Django 1.8, in which the template system has been improved. See the [release notes](https... |
Is there a key that will always come last when a dictionary is sorted? | 29,704,997 | 3 | 2015-04-17T16:44:28Z | 29,705,116 | 9 | 2015-04-17T16:51:14Z | [
"python",
"dictionary"
] | I have a dictionary with many keys and I would like to add a dummy key which should always come last when the dictionary is sorted. And the sort is case insensitive. I was thinking of the using the last word in the dictionary `'zyzzyva'`. Would that work? And what if my keys are directory paths, where they can have /, ... | You can create an ad-hoc object that is always the last when sorted:
```
import functools
@functools.total_ordering
class Last(object):
def __eq__(self, other):
return False
def __lt__(self, other):
return False
```
Here's an usage example:
```
>>> sorted([Last(), 'c', 'a', 'b'])
['a', 'b'... |
My answer is changing with the same code | 29,707,906 | 20 | 2015-04-17T19:31:27Z | 29,707,948 | 30 | 2015-04-17T19:34:34Z | [
"python",
"python-3.x"
] | I am a complete python beginner and I am trying to solve this problem :
> A number is called triangular if it is the sum of the first n positive
> integers for some n For example, 10 is triangular because 10 = 1+2+3+4
> and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
> to find the smallest 6-digi... | ### Short Answer
In Python 3, division is always floating point division. So on the first pass you get something like `str(trinum) == '0.5'`. Which isn't what you want.
You're looking for integer division. The operator for that is `//`.
### Long Answer
The division operator changed in Python 2.x to 3.x. Previously,... |
My answer is changing with the same code | 29,707,906 | 20 | 2015-04-17T19:31:27Z | 29,707,949 | 9 | 2015-04-17T19:34:36Z | [
"python",
"python-3.x"
] | I am a complete python beginner and I am trying to solve this problem :
> A number is called triangular if it is the sum of the first n positive
> integers for some n For example, 10 is triangular because 10 = 1+2+3+4
> and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
> to find the smallest 6-digi... | In Python 2, the `/` operator performs integer division when possible: "x divided by y is a remainder b," throwing away the "b" (use the `%` operator to find "b"). In Python 3, the `/` operator always performs float division: "x divided by y is a.fgh." Get integer division in Python 3 with the `//` operator. |
My answer is changing with the same code | 29,707,906 | 20 | 2015-04-17T19:31:27Z | 29,708,052 | 8 | 2015-04-17T19:41:35Z | [
"python",
"python-3.x"
] | I am a complete python beginner and I am trying to solve this problem :
> A number is called triangular if it is the sum of the first n positive
> integers for some n For example, 10 is triangular because 10 = 1+2+3+4
> and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program
> to find the smallest 6-digi... | You have two problems here, that combine to give you the wrong answer.
The first problem is that you're using `/`, which means integer division in Python 2 (and the almost-Python language that Skulpt implements), but float division in Python 3. So, when you run it on your local machine with Python 3, you're going to g... |
What happens when converting between tuple/list? | 29,709,385 | 2 | 2015-04-17T21:09:22Z | 29,709,423 | 7 | 2015-04-17T21:12:46Z | [
"python",
"list",
"python-3.x",
"tuples",
"python-internals"
] | How does python internally make the conversion when converting a tuple to a list or the other way around.
Does it "switch a flag" (now you're immutable, now you're not!) or does it iterate through the items and convert them? | Tuples and lists are entirely separate types; so when converting a list to a tuple or vice versa a *new* object is created and element references are copied across.
Python *does* optimise this by reaching into the internal structure of the other object; for example, `list(tupleobj)` is essentially the same thing as `l... |
Python Force List Index out of Range Exception | 29,710,249 | 4 | 2015-04-17T22:09:42Z | 29,710,320 | 11 | 2015-04-17T22:14:54Z | [
"python",
"list"
] | I have a list of lists
```
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
I want the code to throw an Array Out of Bounds Exception similar to how is does in Java when the index is out of range. For example,
```
x[0][0] # 1
x[0][1] # 2
x[0-1][0-1] # <--- this returns 9 but I want it to throw an exception
x[0-1][1] ... | You can create your own list class, inheriting the default one, and implementing the `__getitem__` method that returns the element in a specified index:
```
class MyList(list):
def __getitem__(self, index):
if index < 0:
raise IndexError("list index out of range")
return super(MyList, s... |
Finding highest product of three numbers | 29,710,357 | 23 | 2015-04-17T22:18:34Z | 29,710,417 | 54 | 2015-04-17T22:24:20Z | [
"python",
"algorithm"
] | Given an array of ints, `arrayofints`, find the highest product, `Highestproduct`, you can get from three of the integers. The input array of ints will always have at least three integers.
So I've popped three numbers from `arrayofints` and stuck them in `highestproduct`:
```
Highestproduct = arrayofints[:2]
for item... | Keep track of the two minimal elements and three maximal elements, the answer should be `min1 * min2 * max1` or `max1 * max2 * max3`.
To get the maximum product of 3 ints we have to choose 3 maximum elements. However there is a catch that we can substitute 2 of the smallest of 3 max elements with the 2 min ints. If bo... |
What is the use of buffering in python's built-in open() function? | 29,712,445 | 9 | 2015-04-18T03:08:00Z | 29,712,601 | 7 | 2015-04-18T03:37:48Z | [
"python",
"python-2.7"
] | Python Documentation : <https://docs.python.org/2/library/functions.html#open>
```
open(name[, mode[, buffering]])
```
The above documentation says "The optional buffering argument specifies the fileâs desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (ap... | Enabling buffering means that you're not directly interfacing with the OS's representation of a file, or its file system API. Instead, only a chunk of data is read from the raw OS filestream into a buffer until it is consumed, at which point more data is fetched into the buffer. In terms of the objects you get, you'll ... |
How to use Twisted to check Gmail with OAuth2.0 authentication | 29,712,644 | 10 | 2015-04-18T03:45:49Z | 29,907,859 | 14 | 2015-04-27T23:44:17Z | [
"python",
"oauth-2.0",
"gmail",
"google-oauth",
"twisted"
] | I had a working IMAP client for Google mail, however it recently stopped working. I believe the problem is that gmail no longer allows TTL username/password logins, but now requires OAuth2.0.
I would like to know the best way to alter my example below such that my twisted IMAP client authenticates using OAuth2.0. (And... | After a lot of reading and testing, I was finally able to implement a working log-in to gmail using OAuth2.
One important note was that the 2-step process using a "service account" did **NOT** work for me. I'm still not clear why this process can't be used, but the service account does not seem to have access to the g... |
An extra parentheses in a call to a nested function in Python | 29,712,760 | 6 | 2015-04-18T04:10:23Z | 29,712,797 | 7 | 2015-04-18T04:17:16Z | [
"python",
"function",
"nested"
] | I'm studying the module of Mark Pilgrim's Dive Into Python Book in chapter 6, and I'm kind of stuck with what this line of code `return [getFileInfoClass(f)(f) for f in fileList]` does. getFileInfo is a nested function and I was wondering what's the duplicate (f), the extra parentheses is for. I was hoping someone can ... | `getFileInfoClass` returns a `class`; classes are then callable themselves -- calling a `class` by just a name returns an instance of it. The two pairs of parens in quick succession are just shorthand. It is effectively:
```
file_info_class = getFileInfoClass(f)
file_info_instance = file_info_class(f)
```
Generally, ... |
Recursive unittest discover | 29,713,541 | 4 | 2015-04-18T06:00:21Z | 29,715,336 | 7 | 2015-04-18T09:21:16Z | [
"python",
"python-2.7",
"python-unittest"
] | I have a package with a directory "tests" in which I'm storing my unit tests. My package looks like:
```
.
âââ LICENSE
âââ models
â  âââ __init__.py
âââ README.md
âââ requirements.txt
âââ tc.py
âââ tests
â  âââ db
â  â  âââ test_employee.py
âÂ... | In doing a bit of digging, it seems that as long as deeper modules remain importable, they'll be discovered via `python -m unittest discover`. The solution, then, was simply to add a `__init__.py` file to each directory to make them packages.
```
.
âââ LICENSE
âââ models
â  âââ __init__.py
ââ... |
Django check if checkbox is selected | 29,714,763 | 4 | 2015-04-18T08:20:23Z | 29,715,689 | 8 | 2015-04-18T09:55:27Z | [
"python",
"django",
"checkbox"
] | I'm currently working on a fairly simple django project and could use some help. Its just a simple database query front end.
Currently I am stuck on refining the search using checkboxes, radio buttons etc
The issue I'm having is figuring out how to know when a checkbox (or multiple) is selected. My code so far is as ... | **Radio Buttons:**
In the HTML for your radio buttons, you need all related radio inputs to share the same name, have a predefined "value" attribute, and optimally, have a surrounding label tag, like this:
```
<form action="" method="post">
<label for="l_box1"><input type="radio" name="display_type" value="locati... |
How can I check if a list index exists? | 29,715,501 | 5 | 2015-04-18T09:37:46Z | 29,715,530 | 8 | 2015-04-18T09:40:28Z | [
"python",
"list"
] | Seems as though
```
if not mylist[1]:
return False
```
Doesn't work. | You just have to check if the index you want is in the range of `0` and the length of the list, like this
```
if 0 <= index < len(list):
```
it is actually internally evaluated as
```
if (0 <= index) and (index < len(list)):
```
So, that condition checks if the index is within the range [0, length of list).
**Note... |
How to get class when I can't use self - Python | 29,716,828 | 3 | 2015-04-18T11:41:44Z | 29,716,841 | 7 | 2015-04-18T11:42:56Z | [
"python",
"class",
"inheritance",
"python-3.x"
] | I have one weird problem. I have following code:
```
class A:
def f():
return __class__()
class B(A):
pass
a = A.f()
b = B.f()
print(a, b)
```
And output is something like this:
```
<__main__.A object at 0x01AF2630> <__main__.A object at 0x01B09B70>
```
So how can I get `B` instead of second `A`? | The [magic `__class__` closure](https://stackoverflow.com/questions/19776056/the-difference-between-super-method-versus-superself-class-self-method/19776143#19776143) is set for the *method context* and only really meant for use by `super()`.
For methods you'd want to use `self.__class__` instead:
```
return self.__c... |
PySpark groupByKey returning pyspark.resultiterable.ResultIterable | 29,717,257 | 24 | 2015-04-18T12:18:49Z | 29,718,878 | 40 | 2015-04-18T14:52:02Z | [
"python",
"apache-spark",
"pyspark"
] | I am trying to figure out why my groupByKey is returning the following:
```
[(0, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a210>), (1, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a4d0>), (2, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a390>), (3, <pyspark.resultiterable.R... | What you're getting back is an object which allows you to iterate over the results. You can turn the results of groupByKey into a list by calling list() on the values, e.g.
```
example = sc.parallelize([(0, u'D'), (0, u'D'), (1, u'E'), (2, u'F')])
example.groupByKey().collect()
# Gives [(0, <pyspark.resultiterable.Re... |
PySpark groupByKey returning pyspark.resultiterable.ResultIterable | 29,717,257 | 24 | 2015-04-18T12:18:49Z | 31,105,759 | 9 | 2015-06-28T23:15:56Z | [
"python",
"apache-spark",
"pyspark"
] | I am trying to figure out why my groupByKey is returning the following:
```
[(0, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a210>), (1, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a4d0>), (2, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a390>), (3, <pyspark.resultiterable.R... | you can also use
```
example.groupByKey().mapValues(list)
``` |
How to read mp4 video to be processed by scikit-image? | 29,718,238 | 7 | 2015-04-18T13:49:12Z | 29,742,156 | 11 | 2015-04-20T07:54:59Z | [
"python",
"numpy",
"scikit-image"
] | I would like to apply a `scikit-image` function (specifically the template matching function `match_template`) to the frames of a `mp4` video, `h264` encoding. It's important for my application to track the time of each frame, but I know the framerate so I can easily calculate from the frame number.
Please note that I... | [Imageio](http://imageio.github.io/) python package should do what you want. Here is a python snippet using this package:
```
import pylab
import imageio
filename = '/tmp/file.mp4'
vid = imageio.get_reader(filename, 'ffmpeg')
nums = [10, 287]
for num in nums:
image = vid.get_data(num)
fig = pylab.figure()
... |
How to read mp4 video to be processed by scikit-image? | 29,718,238 | 7 | 2015-04-18T13:49:12Z | 32,041,825 | 7 | 2015-08-17T02:04:45Z | [
"python",
"numpy",
"scikit-image"
] | I would like to apply a `scikit-image` function (specifically the template matching function `match_template`) to the frames of a `mp4` video, `h264` encoding. It's important for my application to track the time of each frame, but I know the framerate so I can easily calculate from the frame number.
Please note that I... | You could use [scikit-video](https://github.com/aizvorski/scikit-video/), like this:
```
from skvideo.io import VideoCapture
cap = VideoCapture(filename)
cap.open()
while True:
retval, image = cap.read()
# image is a numpy array containing the next frame
# do something with image here
if not retval:
... |
How to test each specific digit or character | 29,722,807 | 4 | 2015-04-18T21:01:29Z | 29,722,871 | 7 | 2015-04-18T21:08:22Z | [
"python",
"string",
"function",
"if-statement",
"input"
] | I would like to receive **5 digits** inputted by the user and then print something for each specific digit.
For example, if the user enters 12345, I would like to print a specific output for 1 first, then another output for 2, etc.
How would I go about doing this? I would prefer to create a function if possible.
```... | You could use a [dictionary](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) and then iterate through the input:
```
zipcode = raw_input("Enter a zipcode: ")
codes={1:":::||",2:"::|:|",3:"::||:",4:":|::|",5:":|:|:",6:":||::",7:"|:::|",8:"|::|:",9:"|:|::",0:"||:::"}
for num in zipcode:
print ... |
Custom sort in Python 3 | 29,726,068 | 5 | 2015-04-19T05:10:34Z | 29,726,111 | 7 | 2015-04-19T05:18:22Z | [
"java",
"python",
"sorting"
] | I am starting out on learning Python 3.
I am wondering how to perform a custom sort. For instance, I might want to sort a list of animals in the following manner: sort by first character ascending, then by length descending, then by alphanumeric ascending.
A list made up of "ant", "antelope", "zebra", "anteater" when ... | The sorting key is a function that, given a list element, returns a value that Python knows how to compare natively. For example, Python knows how to compare integers and strings.
Python can also compare tuples and lists that are composed of things it knows how to compare. The way tuples and lists get compared is that... |
Python fails to open 11gb csv in r+ mode but opens in r mode | 29,729,082 | 11 | 2015-04-19T11:13:35Z | 29,742,974 | 18 | 2015-04-20T08:41:18Z | [
"python",
"windows",
"file-io"
] | I'm having problems with some code that loops through a bunch of .csvs and deletes the final line if there's nothing in it (i.e. files that end with the `\n` newline character)
My code works successfully on all files except one, which is the largest file in the directory at 11gb. The second largest file is 4.5gb.
The... | The default I/O stack in Python 2 is layered over CRT `FILE` streams. On Windows these are built on top of a POSIX emulation API that uses file descriptors (which in turn is layered over the user-mode Windows API, which is layered over the kernel-mode I/O system, which itself is a deeply layered system based on I/O req... |
django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance | 29,731,013 | 4 | 2015-04-19T14:14:24Z | 29,731,923 | 9 | 2015-04-19T15:35:32Z | [
"python",
"django",
"post",
"django-rest-framework"
] | I've the following model:
```
class NoteCategory(models.Model):
title = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return '{}'.format(self.title)
class PatientNote(models.Model):
category = models.ForeignKey(NoteCategory)
patient = models.ForeignKey(Patient)
desc... | When you want to serialize objects, you pass object as a first argument.
```
serializer = CommentSerializer(comment)
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
```
But when you want to deserialize you pass the data with a `dat... |
Check if PyObject is None | 29,732,838 | 6 | 2015-04-19T16:50:53Z | 29,732,914 | 7 | 2015-04-19T16:57:28Z | [
"python",
"c++",
"nonetype",
"pyobject"
] | I would just like to check if a `PyObject` that I have is `None`. I naively expected that any `None` `Pyobject *` returned from a function would be a NULL pointer, but that doesn't seem to be the case.
So: how do I check if a `PyObject *` of mine points to a `None` object?
I know that there are macros like `PyInt_Che... | You can just compare directly with `Py_None` using `==`:
```
if (obj == Py_None)
```
From the [docs](https://docs.python.org/2/c-api/none.html):
> Note that the `PyTypeObject` for `None` is not directly exposed in the
> Python/C API. **Since `None` is a singleton, testing for object identity
> (using `==` in C) is s... |
How to limit function parameter as array of fixed-size? | 29,733,062 | 7 | 2015-04-19T17:07:56Z | 29,733,129 | 10 | 2015-04-19T17:13:53Z | [
"python",
"arrays"
] | How can I limit python function parameter to accept only arrays of some fixed-size?
I tried this but it doesn't compile:
```
def func(a : array[2]):
```
with
```
TypeError: 'module' object is not subscriptable
```
*I'm new to this language.* | What about checking the length inside of the function? Here I just raised an error, but you could do anything.
```
def func(array):
if len(array) != 2:
raise ValueError("array with length 2 was expected")
# code here runs if len(array) == 2
``` |
Django default=datetime.now() in models always saves same datetime after uwsgi reset | 29,733,203 | 3 | 2015-04-19T17:18:21Z | 29,733,276 | 13 | 2015-04-19T17:24:11Z | [
"python",
"django",
"datetime",
"uwsgi"
] | I have this code in my model:
```
added_time = models.DateTimeField(
default=datetime.datetime.now()
)
```
After I migrate and restart uwsgi, I get first datetime in MariaDB now, and all next - exactly the same as first after resetting uwsgi.
```
2015-04-19 16:01:46
2015-04-19 16:01:46
2015-04-19 16:01:46
2015-0... | `default=datetime.datetime.now()` is evaluated at parsing/compile time of the model. It is not changed afterwards. To evaluate `now()` at the time of adding/updating an object, you have to use:
`default=datetime.datetime.now`, which sets `now` as the callable. Django will call it at runtime.
Your solution of using `a... |
Python numpy keep a list of indices of a sorted 2D array | 29,734,660 | 6 | 2015-04-19T19:19:56Z | 29,734,789 | 7 | 2015-04-19T19:30:42Z | [
"python",
"arrays",
"sorting",
"numpy"
] | I have a 2D numpy array and I want to create a new 1D array where it is indices of numbers in the first array if they are sorted in an ascending order. For the following array:
```
A = [[1,0,2],
[0,3,0]]
```
I want this to be like:
```
B = [[1,1],[0,2],[0,0],[0,1],[1,0],[1,2]]
```
Any idea how it can be done i... | You can use [`argsort`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html) to sort the indices of flattened array, followed by [`unravel_index`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unravel_index.html) to convert the flat index back to coordinates:
```
>>> i = (-a).argsort(axi... |
How to I assign each variable in a list, a number, and then add the numbers up for the same variables? | 29,734,833 | 4 | 2015-04-19T19:33:13Z | 29,734,859 | 10 | 2015-04-19T19:36:02Z | [
"python",
"list"
] | For example, if `ZZAZAAZ` is input, the sum of `A` would be `14` (since its placement is `3,5,6`), while the sum of `Z` would be `14` `(1 + 2 + 4 + 7)`.
How would I do that? | You can use a generator expression within `sum` :
```
>>> s='ZZAZAAZ'
>>> sum(i for i,j in enumerate(s,1) if j=='A')
14
``` |
python jump to a line in a txt file (a gzipped one) | 29,737,195 | 9 | 2015-04-19T23:40:53Z | 29,737,291 | 9 | 2015-04-19T23:54:40Z | [
"python",
"file-io"
] | I'm reading through a large file, and processing it.
I want to be able to jump to the middle of the file without it taking a long time.
right now I am doing:
```
f = gzip.open(input_name)
for i in range(1000000):
f.read() # just skipping the first 1M rows
for line in f:
do_something(line)
```
is there a fas... | The nature of gzipping is such that there is no longer the concept of lines when the file is compressed -- it's just a binary blob. Check out [this](http://www.gzip.org/deflate.html) for an explanation of what gzip does.
To read the file, you'll need to decompress it -- the `gzip` module does a fine job of it. Like ot... |
Lists in Python becoming very complex | 29,738,066 | 2 | 2015-04-20T01:45:32Z | 29,738,109 | 7 | 2015-04-20T01:50:48Z | [
"python"
] | I have a simple function which takes a 2D list as a parameter:
```
def get_noise_estimate(imag_array):
temp = []
temp.append(imag_array[:20])
temp.append(imag_array[-20:])
```
In an example instance, it has 305 elements, each with 129 elements. I like to think of this has 305 columns each with 129 rows. ... | Change:
```
temp.append(imag_array[:20])
temp.append(imag_array[-20:])
```
to
```
temp.extend(imag_array[:20])
temp.extend(imag_array[-20:])
```
The `append` command adds something as the last element of `temp`. So it's making the first element of `temp` be the list `imag_array[:20]`. `extend` takes all the element... |
Comprehensions with multiple input sets | 29,738,661 | 5 | 2015-04-20T03:00:16Z | 29,738,721 | 7 | 2015-04-20T03:07:58Z | [
"python",
"list",
"dictionary",
"list-comprehension",
"dictionary-comprehension"
] | **I'm experimenting** with python and am stuck trying to understand the error messages in the context of what I am doing.
I'm playing around with comprehensions and trying to find a pattern to create a list/dictionary comprehension with more than one input set (assuming this is possible):
**Note:** Here the word *inp... | You will have to create a separate comprehension for the random numbers, as it currently stands, you have only one random number. Also, you will then need to zip the results to get a combined entity:
```
>>> from random import randint
>>> mydict = {k: 0 for k in range(10)}
>>> result = {k: v + 1 for k, v in zip([randi... |
How can i get all models in django 1.8 | 29,738,976 | 11 | 2015-04-20T03:41:36Z | 29,739,109 | 23 | 2015-04-20T03:57:58Z | [
"python",
"django"
] | I am using this code in my admin.py
```
from django.db.models import get_models, get_app
for model in get_models(get_app('myapp')):
admin.site.register(model)
```
But i get warning that `get_models is deprecated`
How can i do that in django 1.8 | This should work,
```
from django.apps import apps
apps.get_models()
```
The `get_models` method returns a list of all installed models. You can also pass three keyword arguments `include_auto_created`, `include_deferred` and `include_swapped`.
If you want to get the models for a specific app, you can do something l... |
Error packaging Kivy with numpy library for Android using buildozer | 29,742,289 | 49 | 2015-04-20T08:03:29Z | 30,878,639 | 7 | 2015-06-16T21:34:24Z | [
"android",
"python",
"numpy",
"kivy"
] | I am trying to create an `Android` package of my `Kivy` application using `buildozer` but I am getting this error when I try to include the `numpy`:
resume of the error:
```
compile options: '-DNO_ATLAS_INFO=1 -Inumpy/core/include -Ibuild/src.linux-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/... | Try sudo apt-get install libatlas-base-dev it looks like you're missing some libraries |
Append to a list defined in a tuple - is it a bug? | 29,747,224 | 27 | 2015-04-20T11:56:33Z | 29,747,287 | 22 | 2015-04-20T11:58:53Z | [
"python",
"list",
"tuples"
] | So I have this code:
```
tup = ([1,2,3],[7,8,9])
tup[0] += (4,5,6)
```
which generates this error:
```
TypeError: 'tuple' object does not support item assignment
```
While this code:
```
tup = ([1,2,3],[7,8,9])
try:
tup[0] += (4,5,6)
except TypeError:
print tup
```
prints this:
```
([1, 2, 3, 4, 5, 6], [... | Yes it's expected.
A tuple cannot be changed. A tuple, like a list, is a structure that points to other objects. It doesn't care about what those objects are. They could be strings, numbers, tuples, lists, or other objects.
So doing anything to one of the objects contained in the tuple, including appending to that ob... |
Append to a list defined in a tuple - is it a bug? | 29,747,224 | 27 | 2015-04-20T11:56:33Z | 29,747,466 | 9 | 2015-04-20T12:07:48Z | [
"python",
"list",
"tuples"
] | So I have this code:
```
tup = ([1,2,3],[7,8,9])
tup[0] += (4,5,6)
```
which generates this error:
```
TypeError: 'tuple' object does not support item assignment
```
While this code:
```
tup = ([1,2,3],[7,8,9])
try:
tup[0] += (4,5,6)
except TypeError:
print tup
```
prints this:
```
([1, 2, 3, 4, 5, 6], [... | Well I guess `tup[0] += (4, 5, 6)` is translated to:
```
tup[0] = tup[0].__iadd__((4,5,6))
```
`tup[0].__iadd__((4,5,6))` is executed normally changing the list in the first element. But the assignment fails since tuples are immutables. |
Pass multiple args from bash into python | 29,750,203 | 7 | 2015-04-20T14:07:21Z | 29,750,269 | 15 | 2015-04-20T14:10:39Z | [
"python",
"string",
"bash",
"command-line-arguments"
] | I have a short inline python script that I call from a bash script, and I want to have it handle a multi-word variable (which comes from `$*`). I expected this to just work:
```
#!/bin/bash
arg="A B C"
python -c "print '"$arg"'"
```
but it doesn't:
```
File "<string>", line 1
print 'A
^
SyntaxError... | The BASH script is wrong.
```
#!/bin/bash
arg="A B C"
python -c "print '$arg'"
```
And output
```
$ sh test.sh
A B C
```
Note that to concatenate two string variables you don't need to put them outside the string constants |
Pass multiple args from bash into python | 29,750,203 | 7 | 2015-04-20T14:07:21Z | 29,750,786 | 10 | 2015-04-20T14:33:58Z | [
"python",
"string",
"bash",
"command-line-arguments"
] | I have a short inline python script that I call from a bash script, and I want to have it handle a multi-word variable (which comes from `$*`). I expected this to just work:
```
#!/bin/bash
arg="A B C"
python -c "print '"$arg"'"
```
but it doesn't:
```
File "<string>", line 1
print 'A
^
SyntaxError... | I would like to explain why your code doesn't work.
What you wanted to do is that:
```
arg="A B C"
python -c "print '""$arg""'"
```
Output:
```
A B C
```
The problem of your code is that `python -c "print '"$arg"'"` is parsed as `python -c "print '"A B C"'"` by the shell. See this:
```
arg="A B C"
python -c "prin... |
How to find a Python package's dependencies | 29,751,572 | 12 | 2015-04-20T15:05:29Z | 29,751,732 | 13 | 2015-04-20T15:12:13Z | [
"python",
"pip"
] | How can you programmatically get a Python package's list of dependencies?
The standard `setup.py` has these documented, but I can't find an easy way to access it *from* either Python or the command line.
Ideally, I'm looking for something like:
```
$ pip install somepackage --only-list-deps
kombu>=3.0.8
billiard>=3.... | Try to use `show` command in `pip`, for example:
```
$ pip show tornado
---
Name: tornado
Version: 4.1
Location: *****
Requires: certifi, backports.ssl-match-hostname
```
**Update** (retrieve deps with specified version):
```
from pip._vendor import pkg_resources
_package_name = 'somepackage'
_package = pkg_resour... |
class getting kwargs from enclosing scope | 29,759,387 | 4 | 2015-04-20T22:13:59Z | 29,759,456 | 7 | 2015-04-20T22:20:34Z | [
"python",
"dictionary",
"trie"
] | Python seems to be inferring some kwargs from the enclosing scope of a class method, and I'm not sure why. I'm implementing a Trie:
```
class TrieNode(object):
def __init__(self, value = None, children = {}):
self.children = children
self.value = value
def __getitem__(self, key):
if key == "":
... | You're having a [mutable default argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) issue. Change your `__init__` function to be like this
```
def __init__(self, value=None, children=None):
if not children:
children = {}
```
The default value fo... |
What is the proper way to print a nested list with the highest value in Python | 29,760,130 | 6 | 2015-04-20T23:19:35Z | 29,760,142 | 13 | 2015-04-20T23:20:38Z | [
"python",
"list",
"python-3.x",
"nested-lists"
] | I have a a nested list and I'm trying to get the sum and print the list that has the highest numerical value when the individual numbers are summed together
```
x = [[1,2,3],[4,5,6],[7,8,9]]
highest = list()
for i in x:
highest.append(sum(i))
for ind, a in enumerate(highest):
if a == max(highest):
pr... | How about:
```
print(max(x, key=sum))
```
Demo:
```
>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> print(max(x, key=sum))
[7, 8, 9]
```
This works because `max` (along with a number of other python builtins like `min`, `sort` ...) accepts a function to be used for the comparison. In this case, I just said that we should com... |
Scope of variables in python decorator | 29,760,593 | 17 | 2015-04-21T00:07:23Z | 29,760,724 | 14 | 2015-04-21T00:20:51Z | [
"python",
"python-3.x",
"decorator",
"python-decorators"
] | I'm having a very weird problem in a Python 3 decorator.
If I do this:
```
def rounds(nr_of_rounds):
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
return nr_of_rounds
return inner
return wrapper
```
it works just fine. However, if I do this:
```
def rounds(n... | Since `nr_of_rounds` is picked up by the **closure**, you can think of it as a "read-only" variable. If you want to write to it (e.g. to decrement it), you need to tell python explicitly -- In this case, the python3.x `nonlocal` keyword would work.
As a brief explanation, what Cpython does when it encounters a functio... |
How can I resolve 'django_content_type already exists'? | 29,760,817 | 39 | 2015-04-21T00:30:58Z | 29,760,818 | 68 | 2015-04-21T00:30:58Z | [
"python",
"django"
] | After upgrading to django 1.8 I'm recieving the error during migration:
```
ProgrammingError: relation "django_content_type" already exists
```
I'd be interested in the background behind this error, but more importantly,
How can I resolve it? | Initial migrations on a project can sometimes be troubleshot using --fake-initial
```
python manage.py migrate --fake-initial
```
It's new in 1.8. In 1.7, --fake-initial was an implicit default, but explicit in 1.8.
From the Docs:
> The --fake-initial option can be used to allow Django to skip an appâs initial mi... |
Joining elements in a list without the join command | 29,761,800 | 15 | 2015-04-21T02:25:20Z | 29,761,895 | 13 | 2015-04-21T02:36:27Z | [
"python",
"list",
"join"
] | I need to join the elements in a list **without using the join command**, so if for example I have the list:
```
[12,4,15,11]
```
The output should be:
```
1241511
```
Here is my code so far:
```
def lists(list1):
answer = 0
h = len(list1)
while list1 != []:
answer = answer + list1[0] * 10 ** h... | If you just want to print the number rather than `return` an actual `int`:
```
>>> a = [12,4,15,11]
>>> print(*a, sep='')
1241511
``` |
Understanding Markov Chains in terms of Matrix Multiplication | 29,763,108 | 2 | 2015-04-21T04:45:47Z | 29,763,320 | 7 | 2015-04-21T05:03:17Z | [
"python",
"numpy",
"probability",
"markov-chains"
] | In [a lecture on YouTube](https://www.youtube.com/watch?v=8AJPs3gvNlY&feature=player_detailpage#t=2011), a professor said Markov Chains could be simplified to `Start(S) * Transition Matrix(Q)^State#`
I'm trying to replicate this using numpy.
```
import numpy as np
S = np.zeros(shape=(1,2))
Q = np.zeros(shape=(2,2))
... | The expressions `S.dot(Q).dot(Q)` and `S.dot(np.power(Q,2))` are not the same thing. The first is the behaviour you desire, while `S.dot(np.power(Q,2))` raises each element in `Q` to the second power. Documenation [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html).
For a more compact notation... |
How to select all columns, except one column in pandas using .ix | 29,763,620 | 7 | 2015-04-21T05:24:59Z | 29,763,653 | 19 | 2015-04-21T05:27:40Z | [
"python",
"pandas"
] | I have a dataframe look like this:
```
import pandas
import numpy as np
df = DataFrame(np.random.rand(4,4), columns = list('abcd'))
df
a b c d
0 0.418762 0.042369 0.869203 0.972314
1 0.991058 0.510228 0.594784 0.534366
2 0.407472 0.259811 0.39666... | When you don't have a MultiIndex, `df.columns` is just an array of column names so you can do:
```
df.ix[:, df.columns != 'b']
a c d
0 0.561196 0.013768 0.772827
1 0.882641 0.615396 0.075381
2 0.368824 0.651378 0.397203
3 0.788730 0.568099 0.869127
``` |
How to select all columns, except one column in pandas using .ix | 29,763,620 | 7 | 2015-04-21T05:24:59Z | 37,717,675 | 9 | 2016-06-09T05:38:42Z | [
"python",
"pandas"
] | I have a dataframe look like this:
```
import pandas
import numpy as np
df = DataFrame(np.random.rand(4,4), columns = list('abcd'))
df
a b c d
0 0.418762 0.042369 0.869203 0.972314
1 0.991058 0.510228 0.594784 0.534366
2 0.407472 0.259811 0.39666... | The most readable and idiomatic way of doing this is `df.drop()`:
```
>>> df
a b c d
0 0.175127 0.191051 0.382122 0.869242
1 0.414376 0.300502 0.554819 0.497524
2 0.142878 0.406830 0.314240 0.093132
3 0.337368 0.851783 0.933441 0.949598
>>> df.drop('b', axis=1)
... |
How / why does Python type hinting syntax work? | 29,770,412 | 15 | 2015-04-21T11:04:59Z | 29,770,490 | 25 | 2015-04-21T11:09:10Z | [
"python",
"python-3.x",
"type-hinting",
"pep"
] | I have just seen the following example in [PEP 484](https://www.python.org/dev/peps/pep-0484/#compatibility-with-other-uses-of-function-annotations):
```
def greeting(name: str) -> str:
return 'Hello ' + name
print(greeting('Martin'))
print(greeting(1))
```
As expected, this does not work in Python 2:
```
Fil... | There is no type hinting going on here. All you did was provide *annotations*; these were introduced with [PEP 3107](https://www.python.org/dev/peps/pep-3107/) (only in Python 3, there is no support for this in Python 2); they let you annotate arguments and return values with arbitrary information for later inspection:... |
Make ipython notebook print in real time | 29,772,158 | 19 | 2015-04-21T12:24:20Z | 31,153,046 | 12 | 2015-07-01T05:17:37Z | [
"python",
"buffer",
"ipython-notebook"
] | Ipython Notebook doesn't seem to print results in real time, but seems to buffer in a certain way and then bulk output the prints. How can I make ipython print my results as soon as the print command is processed?
**Example code:**
```
import time
def printer():
for i in range(100):
time.sleep(5)
... | This is merely [one of the answers](http://stackoverflow.com/a/231216/420867) to the question suggested by [Carsten](http://stackoverflow.com/users/1071311/carsten) incorporating the `__getattr__` delegation suggested by [diedthreetimes](http://stackoverflow.com/users/234261/diedthreetimes) in a comment:
```
import sy... |
Python MySQL connector - unread result found when using fetchone | 29,772,337 | 6 | 2015-04-21T12:32:21Z | 33,632,767 | 12 | 2015-11-10T14:50:14Z | [
"python",
"mysql"
] | I am inserting JSON data into a MySQL database
I am parsing the JSON and then inserting it into a MySQL db using the python connector
Through trial, I can see the error is associated with this piece of code
```
for steps in result['routes'][0]['legs'][0]['steps']:
query = ('SELECT leg_no FROM leg_data WHERE trav... | All that was required was for buffered to be set to true!
```
cursor = cnx.cursor(buffered=True)
``` |
Python matching words with same index in string | 29,776,336 | 8 | 2015-04-21T15:15:06Z | 29,776,365 | 10 | 2015-04-21T15:16:30Z | [
"python",
"string",
"matching"
] | I have two strings of equal length and want to match words that have the same index. I am also attempting to match consecutive matches which is where I am having trouble.
For example I have two strings
```
alligned1 = 'I am going to go to some show'
alligned2 = 'I am not going to go the show'
```
What I am looking f... | Finding matching words is fairly simple, but putting them in contiguous groups is fairly tricky. I suggest using `groupby`.
```
import itertools
alligned1 = 'I am going to go to some show'
alligned2 = 'I am not going to go the show'
results = []
word_pairs = zip(alligned1.split(), alligned2.split())
for k, v in iter... |
Can you "restart" the current iteration of a Python loop? | 29,776,689 | 5 | 2015-04-21T15:30:34Z | 29,776,745 | 7 | 2015-04-21T15:32:57Z | [
"python",
"for-loop",
"iteration"
] | Is there a way to implement something like this:
```
for row in rows:
try:
something
except:
restart iteration
``` | You could put your `try/except` block in another loop and then break when it succeeds:
```
for row in rows:
while True:
try:
something
break
except Exception: # Try to catch something more specific
pass
``` |
How to check if python unit test started in PyCharm or not? | 29,777,737 | 3 | 2015-04-21T16:13:08Z | 29,782,618 | 8 | 2015-04-21T20:35:26Z | [
"python",
"pycharm",
"python-unittest"
] | Is there a way to check in a python unit test (or any other script) if it is executed inside the PyCharm IDE or not?
I would like to do some special things in a unit test when it started locally, things I would not like to do when the whole thing is execute on the build server.
Cheers | When running under PyCharm, the `PYCHARM_HOSTED` environment variable is defined.
```
isRunningInPyCharm = "PYCHARM_HOSTED" in os.environ
``` |
pip install reportlab error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 | 29,778,715 | 2 | 2015-04-21T17:02:54Z | 29,779,291 | 7 | 2015-04-21T17:32:46Z | [
"python",
"linux",
"django",
"ubuntu",
"reportlab"
] | use ubuntu virtualenv. i tray to install reportlab
the command is
pip install reportlab
in this directory
(company2)stefano@stefano-X550EP:~/htdocs/company2$
the error is
error: command 'x86\_64-linux-gnu-gcc' failed with exit status 1
actually the pip list is:
argparse (1.2.1)
Django (1.7.7)
html5lib (0.999)
pip (... | without your full error log, it is impossible to tell. But I bet you are just missing python-dev.
try installing it:
```
$ sudo apt-get install python-dev
```
then pip install reportlab again.
hope that helps.
see: [installing Reportlab (error: command 'gcc' failed with exit status 1 )](https://stackoverflow.com/q... |
How do I print in the middle of the screen? | 29,780,053 | 3 | 2015-04-21T18:14:11Z | 29,780,173 | 7 | 2015-04-21T18:21:01Z | [
"python"
] | For example,
```
print "hello world"
```
in the middle of screen instead of beginning? Sample output would be like:
```
hello world
``` | Python 3 offers [`shutil.get_terminal_size()`](https://docs.python.org/3/library/shutil.html#shutil.get_terminal_size), and you can use [`str.center`](https://docs.python.org/3/library/stdtypes.html#str.center) to center using spaces:
```
import shutil
columns = shutil.get_terminal_size().columns
print("hello world".... |
In python, what exactly is going on in the background such that "x = 1j" works, but "x = 1*j" throws an error? | 29,781,498 | 4 | 2015-04-21T19:32:42Z | 29,781,545 | 12 | 2015-04-21T19:35:25Z | [
"python",
"built-in"
] | Specifically, if I wanted to define an object, say z, such that
```
x = 1z
```
worked but
```
x = 1*z
```
~~failed~~ threw an error, how would I define such an object?
I don't think it involves overloading the multiplying operator. | `1j`, works because it's a [literal for a Complex Number](https://docs.python.org/2/reference/lexical_analysis.html#imaginary-literals) (you mentioned `1j` in your question title). Kind of like `[]` is a literal for a list.
Here's the relevant excerpt from the Python docs / spec:
> Imaginary literals are described by... |
Combine Pandas data frame column values into new column | 29,782,898 | 3 | 2015-04-21T20:52:15Z | 29,783,112 | 8 | 2015-04-21T21:05:58Z | [
"python",
"pandas",
"dataframe"
] | I'm working with Pandas and I have a data frame where we can have one of three values populated:
```
ID_1 ID_2 ID_3
abc NaN NaN
NaN def NaN
NaN NaN ghi
NaN NaN jkl
NaN mno NaN
pqr NaN NaN
```
And my goal is to combine these three columns into a new columns in my d... | You can use the property that summing will concatenate the string values, so you could call [`fillna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna) and pass an empty str and the call [`sum`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataF... |
Getting "weak reference" error in cryptography-0.8.2 python install | 29,784,651 | 4 | 2015-04-21T22:57:35Z | 29,784,875 | 7 | 2015-04-21T23:18:05Z | [
"python"
] | On our linux redhat RHEL 6 cluster, I downloaded cryptography-0.8.2.tar.gz and then ran
```
python setup.py install --user
```
in the cryptography-0.8.2 directory. I am getting the following error. Can anyone help me solve it? I'm not up to speed on weak references, just trying to install the cryptography module. Tha... | The problem is actually in the pycparser module.
As per <https://bugs.launchpad.net/openstack-gate/+bug/1446882> do the following:
```
pip uninstall pycparser && pip install -Iv pycparser==2.10
``` |
Setting GLOG_minloglevel=1 to prevent output in shell from Caffe | 29,788,075 | 10 | 2015-04-22T04:56:59Z | 29,788,785 | 14 | 2015-04-22T05:49:51Z | [
"python",
"deep-learning",
"caffe",
"glog"
] | I'm using Caffe, which is printing a lot of output to the shell when loading the neural net.
I'd like to suppress that output, which supposedly can be done by setting `GLOG_minloglevel=1` when running the Python script. I've tried doing that using the following code, but I still get all the output from loading the ne... | To supress the output level you need to **increase** the loglevel to at least 2
```
os.environ['GLOG_minloglevel'] = '2'
```
The levels are
0 - debug
1 - info (still a LOT of outputs)
2 - warnings
3 - errors
---
**Update:**
Since this flag is *global* to `caffe`, it must be set *prior* to importing of `ca... |
Setting GLOG_minloglevel=1 to prevent output in shell from Caffe | 29,788,075 | 10 | 2015-04-22T04:56:59Z | 31,350,273 | 11 | 2015-07-10T21:06:25Z | [
"python",
"deep-learning",
"caffe",
"glog"
] | I'm using Caffe, which is printing a lot of output to the shell when loading the neural net.
I'd like to suppress that output, which supposedly can be done by setting `GLOG_minloglevel=1` when running the Python script. I've tried doing that using the following code, but I still get all the output from loading the ne... | I was able to get [Shai's solution](http://stackoverflow.com/a/29788785/1714410) to work, but only by executing that line in Python *before* calling
```
import caffe
``` |
Using "if" as argument identifier | 29,790,344 | 2 | 2015-04-22T07:16:33Z | 29,790,493 | 7 | 2015-04-22T07:22:55Z | [
"python",
"lxml"
] | I want to generate the following xml file:
```
<foo if="bar"/>
```
I've tried this:
```
from lxml import etree
etree.Element("foo", if="bar")
```
But I got this error:
```
page = etree.Element("configuration", if="ok")
^
SyntaxError: invalid syntax
```
Any ideas?
I'm using ... | ```
etree.Element("foo", {"if": "bar"})
```
The attributes can be passed in as a dict:
```
from lxml import etree
root = etree.Element("foo", {"if": "bar"})
print etree.tostring(root, pretty_print=True)
```
output
```
<foo if="bar"/>
``` |
Given 2 int values, return True if one is negative and other is positive | 29,790,594 | 25 | 2015-04-22T07:27:00Z | 29,790,699 | 8 | 2015-04-22T07:32:26Z | [
"python",
"python-3.x",
"return",
"logical-operators"
] | ```
def logical_xor(a, b): # for example, -1 and 1
print (a < 0) # evaluates to True
print (b < 0) # evaluates to False
print (a < 0 != b < 0) # EVALUATES TO FALSE! why??? it's True != False
return (a < 0 != b < 0) # returns False when it should return True
print ( logical_xor(-1, 1) ) # returns FALSE!... | ~~Your code doesn't work as intended because `!=` takes higher [precedence](https://docs.python.org/2/reference/expressions.html#operator-precedence) than `a < 0` and `b < 0`. As itzmeontv suggests in his answer, you can simply decide the precedence yourself by surrounding logical components with parentheses:~~
```
(a... |
Given 2 int values, return True if one is negative and other is positive | 29,790,594 | 25 | 2015-04-22T07:27:00Z | 29,790,806 | 31 | 2015-04-22T07:37:57Z | [
"python",
"python-3.x",
"return",
"logical-operators"
] | ```
def logical_xor(a, b): # for example, -1 and 1
print (a < 0) # evaluates to True
print (b < 0) # evaluates to False
print (a < 0 != b < 0) # EVALUATES TO FALSE! why??? it's True != False
return (a < 0 != b < 0) # returns False when it should return True
print ( logical_xor(-1, 1) ) # returns FALSE!... | All comparison operators in Python have the [same precedence.](https://docs.python.org/3/reference/expressions.html#not-in) In addition, Python does chained comparisons. Thus,
```
(a < 0 != b < 0)
```
breaks down as:
```
(a < 0) and (0 != b) and (b < 0)
```
If any one of these is false, the total result of the expr... |
pandas - add new column to dataframe from dictionary | 29,794,959 | 9 | 2015-04-22T10:39:21Z | 29,794,993 | 17 | 2015-04-22T10:40:42Z | [
"python",
"pandas"
] | I would like to add a column 'D' to a dataframe like this:
```
U,L
111,en
112,en
112,es
113,es
113,ja
113,zh
114,es
```
based on the following Dictionary:
```
d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
```
so that the resulting dataframe appears as:
```
U,L,D
111,en,en
112,en,en
112,es,en
113,es,es
113,ja,es... | Call [`map`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html#pandas.Series.map) and pass the dict, this will perform a lookup and return the associated value for that key:
```
In [248]:
d = {112: 'en', 113: 'es', 114: 'es', 111: 'en'}
df['D'] = df['U'].map(d)
df
Out[248]:
U L D
0... |
How to test if an Enum member with a certain name exists? | 29,795,488 | 4 | 2015-04-22T11:02:25Z | 29,795,561 | 7 | 2015-04-22T11:05:39Z | [
"python",
"python-3.x",
"enums"
] | Using Python 3.4 I want to test whether an Enum class contains a member with a certain name.
Example:
```
class Constants(Enum):
One = 1
Two = 2
Three = 3
print(Constants['One'])
print(Constants['Four'])
```
gives:
```
Constants.One
File "C:\Python34\lib\enum.py", line 258, in __getitem__
return ... | You could use `Enum.__members__` - [*an ordered dictionary mapping names to members*](https://docs.python.org/3/library/enum.html#iteration):
```
In [12]: 'One' in Constants.__members__
Out[12]: True
In [13]: 'Four' in Constants.__members__
Out[13]: False
``` |
If I compare two strings in python I get false even if they are the same | 29,798,009 | 3 | 2015-04-22T12:45:07Z | 29,798,136 | 9 | 2015-04-22T12:50:21Z | [
"python",
"if-statement"
] | I am trying to compare two strings, one downloaded, one from a file, but the if-statement returns always false, even if the strings are equal.
Am I doing something wrong?
Is this a bug in Python?
Code:
```
#!/usr/bin/python
import json
import urllib2
jsonstring = urllib2.urlopen("https://xkcd.com/info.0.json").rea... | `json.loads` translates the data to Python types. You're looking at an integer and comparing it to a string.
Instead of just `print current_xkcd`, try `print repr(current_xkcd)` or `print type(current_xkcd)`, and do the same for `downloaded_xkcd`. |
When should I use a custom Manager versus a custom QuerySet in Django? | 29,798,125 | 7 | 2015-04-22T12:49:50Z | 29,798,508 | 7 | 2015-04-22T13:05:46Z | [
"python",
"django",
"orm",
"django-managers"
] | In Django, custom Managers are a great way to organize reusable query logic. The [docs](https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers) state that *there are two reasons you might want to customize a Manager: to add extra Manager methods, and/or to modify the initial QuerySet the Manager retu... | Mainly to allow for easy composition of queries. Generally if you want to be able perform some operation on an existing queryset in a chain of queryset calls you can use a `QuerySet`.
For example, say you have an `Image` model that has a `width`, `height` fields:
```
class Image(models.Model):
width = ... # Widt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.