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 |
|---|---|---|---|---|---|---|---|---|---|
Delaunay Triangulation of points from 2D surface in 3D with python? | 29,800,749 | 13 | 2015-04-22T14:28:51Z | 29,872,732 | 7 | 2015-04-26T01:39:27Z | [
"python",
"numpy",
"matplotlib",
"data-visualization"
] | I have a collection of 3D points. These points are sampled at constant levels (z=0,1,...,7). An image should make it clear:

These points are in a numpy ndarray of shape `(N, 3)` called `X`. The above plot is created using:
```
import matplotlib.pyplot as plt
fr... | I realise that you mentioned in your question that you didn't want to use the convex hull because you might lose some shape information. I have a simple solution that works pretty well for your 'jittered spherical' example data, although it does use [`scipy.spatial.ConvexHull`](http://docs.scipy.org/doc/scipy-dev/refer... |
Testing for a Palindrome in Python | 29,801,025 | 2 | 2015-04-22T14:40:04Z | 29,801,092 | 7 | 2015-04-22T14:42:27Z | [
"python",
"string",
"palindrome",
"splice"
] | I now know there are better solutions for this, but I'm confused as to why I'm getting the result I am.
```
import sys
def isPalindrome(test):
if len(test) == 1:
return("Is a palindrome")
else:
if test[0] == test[-1]:
isPalindrome(test[1:-1])
else:
return("Not a... | Change to the following line:
```
return isPalindrome(test[1:-1])
```
You have to return a value or the value returned is `None`. |
Python multiprocessing doesn't seem to use more than one core | 29,802,503 | 33 | 2015-04-22T15:40:20Z | 29,802,608 | 49 | 2015-04-22T15:45:22Z | [
"python",
"multiprocessing"
] | I want to use Python multiprocessing to run grid search for a predictive model.
When I look at core usage, it always seem to be using only one core. Any idea what I'm doing wrong?
```
import multiprocessing
from sklearn import svm
import itertools
#first read some data
#X will be my feature Numpy 2D array
#y will be ... | Your problem is that you *join* each job immediately after you started it:
```
for g in grid:
p = multiprocessing.Process(target=worker, args=(g,GRID_hx))
jobs.append(p)
p.start()
p.join()
```
*join* blocks until the respective process has finished working. This means that your code starts **only one ... |
Is there a way to start unit tests which related only to changed code? | 29,803,333 | 10 | 2015-04-22T16:13:40Z | 29,862,370 | 7 | 2015-04-25T07:31:36Z | [
"python",
"unit-testing",
"dependencies",
"code-coverage",
"python-unittest"
] | In my Python project, we have a big number of unit tests (some thousands). Though they are logically distributed between files and classes, I need sometimes a lot of time in order to find ones, which cover the functionality I'm changing.
Of course, I can run all test from some specific file/class, but again because of... | You might like to checkout [pytest-incremental](http://pytest-incremental.readthedocs.org/):
> The idea is to execute your tests faster by executing not all of them but only the ârequiredâ ones.
Install via [pypi](https://pypi.python.org/pypi/pytest-incremental):
```
pip install pytest-incremental
```
Usage:
`... |
Why use re.match(), when re.search() can do the same thing? | 29,806,650 | 14 | 2015-04-22T19:03:11Z | 29,806,772 | 11 | 2015-04-22T19:09:26Z | [
"python",
"regex"
] | From the documentation, it's very clear that:
* `match()` -> apply pattern match at the beginning of the string
* `search()` -> search through the string and return first match
And `search` with `'^'` and without `re.M` flag would work the same as `match`.
Then why does python have `match()`? Isn't it redundant?
Are... | The `pos` argument behaves differently in important ways:
```
>>> s = "a ab abc abcd"
>>> re.compile('a').match(s, pos=2)
<_sre.SRE_Match object; span=(2, 3), match='a'>
>>> re.compile('^a').search(s, pos=2)
None
```
`match` makes it possible to write a tokenizer, and ensure that characters are never skipped. `search... |
Different ways of deleting lists | 29,810,632 | 35 | 2015-04-22T23:14:24Z | 29,810,740 | 7 | 2015-04-22T23:25:14Z | [
"python",
"list",
"memory-management"
] | I want to understand why:
* `a = []`;
* `del a`; and
* `del a[:]`;
behave so differently.
I ran a test for each to illustrate the differences I witnessed:
```
>>> # Test 1: Reset with a = []
...
>>> a = [1,2,3]
>>> b = a
>>> a = []
>>> a
[]
>>> b
[1, 2, 3]
>>>
>>> # Test 2: Reset with del a
...
>>> a = [1,2,3]
>... | `Test 1:` rebinds `a` to a new object, `b` still holds a *reference* to the original object, `a` is just a name by rebinding `a` to a new object does not change the original object that `b` points to.
`Test 2:` you del the name `a` so it no longer exists but again you still have a reference to the object in memory wit... |
Different ways of deleting lists | 29,810,632 | 35 | 2015-04-22T23:14:24Z | 29,810,816 | 23 | 2015-04-22T23:31:48Z | [
"python",
"list",
"memory-management"
] | I want to understand why:
* `a = []`;
* `del a`; and
* `del a[:]`;
behave so differently.
I ran a test for each to illustrate the differences I witnessed:
```
>>> # Test 1: Reset with a = []
...
>>> a = [1,2,3]
>>> b = a
>>> a = []
>>> a
[]
>>> b
[1, 2, 3]
>>>
>>> # Test 2: Reset with del a
...
>>> a = [1,2,3]
>... | ## Test 1
```
>>> a = [1,2,3] # set a to point to a list [1, 2, 3]
>>> b = a # set b to what a is currently pointing at
>>> a = [] # now you set a to point to an empty list
# Step 1: A --> [1 2 3]
# Step 2: A --> [1 2 3] <-- B
# Step 3: A --> [ ] [1 2 3] <-- B
# at this point a points to a new empty list
# whe... |
Different ways of deleting lists | 29,810,632 | 35 | 2015-04-22T23:14:24Z | 29,810,830 | 14 | 2015-04-22T23:32:50Z | [
"python",
"list",
"memory-management"
] | I want to understand why:
* `a = []`;
* `del a`; and
* `del a[:]`;
behave so differently.
I ran a test for each to illustrate the differences I witnessed:
```
>>> # Test 1: Reset with a = []
...
>>> a = [1,2,3]
>>> b = a
>>> a = []
>>> a
[]
>>> b
[1, 2, 3]
>>>
>>> # Test 2: Reset with del a
...
>>> a = [1,2,3]
>... | Of your three *"ways of deleting Python lists"*, **only one** actually alters the original list object; the other two only affect *the name*.
1. `a = []` creates a *new list object*, and assigns it to the name `a`.
2. `del a` deletes *the name*, **not** the object it refers to.
3. `del a[:]` deletes *all references* f... |
finding needle in haystack, what is a better solution? | 29,810,883 | 14 | 2015-04-22T23:36:57Z | 29,921,752 | 7 | 2015-04-28T14:02:11Z | [
"python",
"dynamic-programming"
] | so given "needle" and "there is a needle in this but not thisneedle haystack"
I wrote
```
def find_needle(n,h):
count = 0
words = h.split(" ")
for word in words:
if word == n:
count += 1
return count
```
This is O(n) but wondering if there is a better approach? maybe not by using ... | I don't think it's possible to get bellow `O(n)` with this (because you need to iterate trough the string at least once). You can do some optimizations.
I assume you want to match "*whole words*", for example looking up `foo` should match like this:
```
foo and foo, or foobar and not foo.
^^^ ^^^ ... |
Python for loop - why does this not infinite loop? | 29,812,626 | 5 | 2015-04-23T02:38:04Z | 29,812,639 | 9 | 2015-04-23T02:39:38Z | [
"python",
"for-loop",
"infinite-loop"
] | Consider the following snippet of Python code:
```
x = 14
for k in range(x):
x += 1
```
At the end of execution, `x` is equal to 28.
My question: shouldn't this code loop forever? At each iteration, it checks if `k` is less than `x`. However, `x` is incremented within the for loop, so it has a higher value for t... | `range(x)` is not a "command". It creates a range object one time, and the loop iterates over that. Changing x does not change all objects that were made using it.
```
>>> x = 2
>>> k = range(x)
>>> list(k)
[0, 1]
>>> x += 1
>>> list(k)
[0, 1]
``` |
How to add a title to Seaborn Facet Plot | 29,813,694 | 21 | 2015-04-23T04:28:39Z | 29,814,281 | 35 | 2015-04-23T05:15:49Z | [
"python",
"visualization",
"seaborn"
] | How do I add a title to this Seaborne plot? Let's give it a title 'I AM A TITLE'.
```
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="sex", row="smoker", margin_titles=True)
g.map(sns.plt.scatter, "total_bill", "tip")
```
 | After those lines:
```
plt.subplots_adjust(top=0.9)
g.fig.suptitle('THIS IS A TITLE, YOU BET') # can also get the figure from plt.gcf()
```
If you add a suptitle without adjusting the axis, the seaborn facet titles overlap it.
(With different data):

g = sns.FacetGrid(tips, col="sex", row="smoker", margin_titles=True)
g.map(sns.plt.scatter, "total_bill", "tip")
```
 | In ipython notebook, this worked for me!
```
sns.plt.title('YOUR TITLE HERE')
``` |
Pandas DataFrame to List of Dictionaries (Dics) | 29,815,129 | 14 | 2015-04-23T06:12:18Z | 29,815,523 | 19 | 2015-04-23T06:36:59Z | [
"python",
"list",
"dictionary",
"pandas",
"dataframe"
] | I have the following DataFrame:
```
customer item1 item2 item3
1 apple milk tomato
2 water orange potato
3 juice mango chips
```
which I want to translate it to list of dictionaries per row
```
rows = [{'customer': 1, 'item1': 'apple', 'item2': 'milk',... | Use `df.T.to_dict().values()`, like below:
```
In [1]: df
Out[1]:
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'}... |
Pandas DataFrame to List of Dictionaries (Dics) | 29,815,129 | 14 | 2015-04-23T06:12:18Z | 29,816,143 | 35 | 2015-04-23T07:08:44Z | [
"python",
"list",
"dictionary",
"pandas",
"dataframe"
] | I have the following DataFrame:
```
customer item1 item2 item3
1 apple milk tomato
2 water orange potato
3 juice mango chips
```
which I want to translate it to list of dictionaries per row
```
rows = [{'customer': 1, 'item1': 'apple', 'item2': 'milk',... | Use [`df.to_dict('records')`](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.to_dict.html#pandas.DataFrame.to_dict) -- gives the output without having to transpose externally.
```
In [2]: df.to_dict('records')
Out[2]:
[{'customer': 1L, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato... |
How to run Pip commands from CMD | 29,817,447 | 7 | 2015-04-23T08:12:49Z | 29,817,514 | 11 | 2015-04-23T08:15:59Z | [
"python",
"cmd",
"pip"
] | As I understand, Python 2.7.9 comes with Pip installed, however when I try to execute a Pip command from CMD (Windows) I get the following error:
> 'pip' is not recognized as an internal or external command, operable program or batch file.
When I type `python` I do get the following, which suggests it has been instal... | To execute Pip, first of all make sure you have it, so type in your CMD:
```
> python
>>> import pip
>>>
```
And it should proceed with no error. Otherwise, if this fails, you can look [**here**](http://stackoverflow.com/questions/4750806/how-do-i-install-pip-on-windows?rq=1) to see how to install it. Now that you ar... |
What should I decorate with @asyncio.coroutine for async operations? | 29,819,151 | 4 | 2015-04-23T09:24:10Z | 29,850,732 | 8 | 2015-04-24T14:53:57Z | [
"python",
"python-3.x",
"asynchronous",
"coroutine",
"python-asyncio"
] | I want to run my code asnychronously. What should I decorate with `@asyncio.coroutine` and what should I call with `yield from` for async operations?
In my case, I have some example code without decorator. (Simple chat bot look-like IRC)
```
import asyncio
class ChatBot:
def __init__(self, loop):
conn =... | ## When to use the `@asyncio.coroutine` decorator
If you have a function that needs to use `yield from` to call a coroutine, you should decorate it with `asyncio.coroutine`. Also note that coroutines are often (not always) "viral". As soon as you add `yield from` to a function it becomes a coroutine, and additionally ... |
Can I have anonymous function with "static" variables in Python? | 29,825,365 | 3 | 2015-04-23T13:44:20Z | 29,825,946 | 8 | 2015-04-23T14:07:24Z | [
"python",
"lambda"
] | Can I have anonymous function with "static" variables in Python?
For example
```
lambda x: re.compile(r'foobar').match(x)
```
is not so great, because it may recompile every time it is called (if `re` runs out of cache - thank you responders for pointing out the cache mechanism).
I can do this without recompiling:
... | The usual trick is to provide a default value for an argument you don't intend to supply.
```
lambda x, regexobject=re.compile(r'foobar'): regexobject.match(x)
```
The default value is evaluated when the `lambda` is defined, not each time it is called.
---
Rather than using the `lambda`, though, I would just define... |
Python: "Chained definition" of ints vs lists | 29,825,842 | 8 | 2015-04-23T14:03:09Z | 29,825,915 | 13 | 2015-04-23T14:06:20Z | [
"python"
] | I just discovered in the definition of variables in Python. Namely:
```
a = b = 0
a = 1
```
gives me `a=1` and `b=0` or a and b are two independent variables.
But:
```
a = b = []
a.append(0)
```
gives me `a = [0]` and `b = [0]`, or a and b are two references to the same object. This is confusing to me, how are the... | `a` and `b` point to the *same object always*. But you cannot alter the integer, it is immutable.
In your first example, you *rebound* `a` to point to another object. You did not do that in the other example, you never assigned another object to `a`.
Instead, you asked the object `a` *references* to alter itself, to ... |
Programmatically surrounding a Python input in quotes | 29,826,257 | 2 | 2015-04-23T14:20:34Z | 29,826,354 | 7 | 2015-04-23T14:23:56Z | [
"python",
"string",
"ip"
] | Using the netaddr Python library tutorial (<https://pythonhosted.org/netaddr/tutorial_01.html>) I am creating a program that allows a user to input an IP address that gets added to a list, the only problem being it needs to be converted to an IP object first.
```
ip = input('Enter a valid IP Address/Subnet: ')
ip_list... | I'm going to guess you're using Python 2. Use `raw_input` instead of `input` and it will work. With `input`, if you enter a number you will get a number type (`int` for integer, `float` for floating point, etc). The IP address confuses things as it doesn't understand why more than one decimal point exists. |
force object to be `dirty` in sqlalchemy | 29,830,229 | 4 | 2015-04-23T17:14:40Z | 29,831,809 | 7 | 2015-04-23T18:42:06Z | [
"python",
"sqlalchemy"
] | Is there a way to force an object mapped by sqlalchemy to be considered `dirty`? For example, given the context of sqlalchemy's [Object Relational Tutorial](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html) the problem is demonstrated,
```
a=session.query(User).first()
a.__dict__['name']='eh'
session.dirty
```
... | I came across the same problem recently and it was not obvious.
Objects themselves are not dirty, but their attributes are. As SQLAlchemy will write back only changed attributes, not the whole object, as far as I know.
If you set an attribute using `set_attribute` and it is different from the original attribute data,... |
Python using ZIP64 extensions when compressing large files | 29,830,531 | 5 | 2015-04-23T17:32:15Z | 31,546,564 | 7 | 2015-07-21T18:11:04Z | [
"python",
"zip",
"zlib",
"zipfile"
] | I have a script that compresses the output files. The problem is that one of the files is over 4Gigs. How would I convert my script to use ZIP64 extensions instead of the standard zip?
Here is how I am currently zipping:
```
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile... | Check out [zipfile-objects](https://docs.python.org/2/library/zipfile.html#zipfile-objects).
You can do this:
```
zf = zipfile.ZipFile('edw_files_' + datetime.strftime(date(), '%Y%m%d') + '.zip', mode='w', allowZip64 = True)
``` |
django.db.utils.ProgrammingError: relation already exists | 29,830,928 | 22 | 2015-04-23T17:54:18Z | 32,432,472 | 16 | 2015-09-07T06:37:00Z | [
"python",
"django",
"postgresql",
"ubuntu"
] | I'm trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:
`python manage.py makemigrations crud`
```
Migrations for 'crud':
00... | This works pretty fine
```
./manage.py migrate --fake default
```
Source: -<https://github.com/nijel/weblate/issues/587> |
Numpy 1-hot array | 29,831,489 | 15 | 2015-04-23T18:24:54Z | 29,831,596 | 33 | 2015-04-23T18:30:15Z | [
"python",
"numpy",
"machine-learning"
] | Let's say I have a 1d numpy array
```
a=[1,0,3]
```
I would like to encode this as a 2d 1-hot array
```
b=[[0,1,0,0], [1,0,0,0], [0,0,0,1]]
```
Is there a quick way to do this? Quicker than just looping over a to set elements of b, that is. | Your array `a` defines the columns, you just need to define the rows and then use fancy indexing:
```
>>> a = np.array([1, 0, 3])
>>> b = np.zeros((3, 4))
>>> b[np.arange(3), a] = 1
>>> b
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
>>>
```
This is just for illustration. You... |
Numpy 1-hot array | 29,831,489 | 15 | 2015-04-23T18:24:54Z | 37,323,404 | 10 | 2016-05-19T12:35:50Z | [
"python",
"numpy",
"machine-learning"
] | Let's say I have a 1d numpy array
```
a=[1,0,3]
```
I would like to encode this as a 2d 1-hot array
```
b=[[0,1,0,0], [1,0,0,0], [0,0,0,1]]
```
Is there a quick way to do this? Quicker than just looping over a to set elements of b, that is. | ```
>>> values = [1, 0, 3]
>>> n_values = np.max(values) + 1
>>> np.eye(n_values)[values]
array([[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.],
[ 0., 0., 0., 1.]])
``` |
Manual commit in Django 1.8 | 29,831,976 | 2 | 2015-04-23T18:51:31Z | 29,834,940 | 7 | 2015-04-23T21:48:04Z | [
"python",
"django",
"django-models"
] | How do you implement `@commit_manually` in Django 1.8?
I'm trying to upgrade Django 1.5 code to work with Django 1.8, and for some bizarre reason, the `commit_manually` decorator was removed in Django 1.6 with no direct replacement. My process iterates over thousands of records, so it can't wrap the entire process in ... | Yeah, you've got it. Call `set_autocommit(False)` to start a transaction, then call `commit()` and `set_autocommit(True)` to commit it.
You could wrap this up in your own decorator:
```
def commit_manually(fn):
def _commit_manually(*args, **kwargs):
set_autocommit(False)
res = fn(*args, **kwargs)
... |
How do I filter a pandas DataFrame based on value counts? | 29,836,836 | 3 | 2015-04-24T00:48:31Z | 29,836,852 | 8 | 2015-04-24T00:50:54Z | [
"python",
"pandas",
"filtering",
"dataframe"
] | I'm working in Python with a pandas DataFrame of video games, each with a genre. I'm trying to remove any video game with a genre that appears less than some number of times in the DataFrame, but I have no clue how to go about this. I did find [a StackOverflow question](http://stackoverflow.com/questions/6796569/how-to... | Use [groupby filter](http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration):
```
In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
In [12]: df
Out[12]:
A B
0 1 2
1 1 4
2 5 6
In [13]: df.groupby("A").filter(lambda x: len(x) > 1)
Out[13]:
A B
0 1 2
1 1 4
```
I re... |
Optimize the performance of dictionary membership for a list of Keys | 29,839,397 | 19 | 2015-04-24T05:28:26Z | 29,839,421 | 37 | 2015-04-24T05:30:16Z | [
"python",
"performance",
"list",
"python-2.7",
"dictionary"
] | I am trying to write a code which should return true if any element of list is present in a dictionary. Performance of this piece is really important. I know I can just loop over list and break if I find the first search hit. Is there any faster or more Pythonic way for this than given below?
```
for x in someList:
... | Use of builtin [any](https://docs.python.org/2/library/functions.html#any) can have some performance edge over two loops
```
any(x in someDict for x in someList)
```
but you might need to measure your mileage. If your list and dict remains pretty static and you have to perform the comparison multiple times, you may c... |
Optimize the performance of dictionary membership for a list of Keys | 29,839,397 | 19 | 2015-04-24T05:28:26Z | 29,839,544 | 11 | 2015-04-24T05:39:01Z | [
"python",
"performance",
"list",
"python-2.7",
"dictionary"
] | I am trying to write a code which should return true if any element of list is present in a dictionary. Performance of this piece is really important. I know I can just loop over list and break if I find the first search hit. Is there any faster or more Pythonic way for this than given below?
```
for x in someList:
... | The cleanest and fastest way is to use [*any()*](https://docs.python.org/2.7/library/functions.html#any) and [*itertools.ifilter()*](https://docs.python.org/2.7/library/itertools.html#itertools.ifilter):
```
any(ifilter(someDict.__contains__, someList))
```
This code uses:
* a bound method, `someDict.__contains__` a... |
how to change the subject for Django error reporting emails? | 29,839,766 | 5 | 2015-04-24T05:56:00Z | 29,840,614 | 8 | 2015-04-24T06:52:19Z | [
"python",
"django"
] | i noticed about to change the subject for django error reporting emails,
is it possible to change subject?
can we modify the subject for Django error reporting emails ? | You need to set the `EMAIL_SUBJECT_PREFIX` variable in your Django settings file.
<https://docs.djangoproject.com/en/1.8/ref/settings/#email-subject-prefix>
> `EMAIL_SUBJECT_PREFIX`
>
> Default: `'[Django]'`
>
> Subject-line prefix for email messages sent with `django.core.mail.mail_admins` or `django.core.mail.mail_... |
Get variable type in bash | 29,840,525 | 4 | 2015-04-24T06:47:03Z | 29,840,856 | 8 | 2015-04-24T07:06:15Z | [
"python",
"bash",
"variables",
"types"
] | In Python I can get variable type by:
```
>>> i = 123
>>> type(i)
<type 'int'>
```
I saw on [this page](http://tldp.org/LDP/abs/html/untyped.html) that there are no variable types in bash. The explanation given is:
> Untyped variables are both a blessing and a curse. They permit more flexibility in scripting and mak... | Bash doesn't have types in the same way as Python (although I would say that Python has classes rather than types). But bash variables do have *attributes* that are given (mostly) through `declare`, but the range of attributes is fairly small. You can find an attribute using `declare -p`, for example, `declare -i` crea... |
Remove unique values from a list and keep only duplicates | 29,845,051 | 3 | 2015-04-24T10:26:21Z | 29,845,176 | 10 | 2015-04-24T10:32:34Z | [
"python"
] | I'm looking to run over a list of ids and return a list of any ids that occurred more than once. This was what I set up that is working:
```
singles = list(ids)
duplicates = []
while len(singles) > 0:
elem = singles.pop()
if elem in singles:
duplicates.append(elem)
```
But the ids list is likely to ge... | The smart way to do this is to use a data structure that makes it easy and efficient, like [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter):
```
>>> ids = [random.randrange(100) for _ in range(200)]
>>> from collections import Counter
>>> counts = Counter(ids)
>>> dupids = [id for id... |
How to count the number of digits in numbers in different bases? | 29,847,504 | 6 | 2015-04-24T12:24:36Z | 29,847,712 | 8 | 2015-04-24T12:35:56Z | [
"python",
"c",
"algorithm",
"base"
] | I'm working with numbers in different bases (base-10, base-8, base-16, etc). I'm trying to count the number of characters in each number.
Example
> Number: `ABCDEF`
>
> Number of digits: *6*
I know about the method based on logarithms but I'm facing some problems.
1. [This Python script](http://pastebin.com/cE0wVqi... | Logarithms shouldn't really be slow. And you can easily calculate logarithms to any base by this formula: `logBaseN(x)=logBaseA(x)/logBaseA(N)` - you can use `ln`(Base e = 2.718...) or `logBase10` or whatever you have. So you don't really need a program, a formular should do it:
```
num_digets(N, base) = 1 + floor(log... |
__enter__() takes exactly 3 arguments (1 given) | 29,848,620 | 2 | 2015-04-24T13:20:11Z | 29,848,663 | 10 | 2015-04-24T13:22:20Z | [
"python"
] | I have written a class like this:
```
class FooBar(object):
# some methods
# ...
def __enter__(self, param1, param2):
# do something here ...
pass
```
I try to use my class like this (imported from module mymod):
```
with (mymod.FooBar("hello", 123)) as x:
# do something here with ins... | The `__enter__` method is never given any arguments, so beyond `self` your signature should not have any other.
You should move those arguments to the `__init__` method instead:
```
class FooBar(object):
def __init__(self, param1, param2):
# do something here ...
def __enter__(self):
# someth... |
Error Installing any module using pip, but easy_install works | 29,849,892 | 3 | 2015-04-24T14:18:38Z | 29,853,308 | 7 | 2015-04-24T16:58:30Z | [
"python",
"sockets",
"pyopenssl"
] | I get this error whenever I try to install any module using pip, but easy\_install work perfectly. I have no proxies configured in my Ubuntu 12.04 machine.
Previously it was working fine, just dnt know, how it stoped working suddenly.
This is error i get, while running `sudo pip install <any_package_name>`:
```
Excep... | I found a potential solution [here](https://github.com/passslot/passslot-python-sdk/issues/1). Here's the relevant quote:
"That happend because Ubuntu 12.04 (that is my server's OS) has old `pyOpenSSL` library which not accept attribute 'set\_tlsext\_host\_name'.
For fix that, you need to add dependence `pyOpenSSL` >=... |
Can a Python function return only the second of two values? | 29,850,511 | 7 | 2015-04-24T14:45:05Z | 29,850,591 | 15 | 2015-04-24T14:48:25Z | [
"python",
"matlab",
"function",
"return"
] | I have a Python function that returns multiple values. As an example for this question, consider the function below, which returns two values.
```
def function():
...
return x, y
```
I know this function can return both values `x, y = function()`. But is it possible for this function to only return the second... | The pythonic idiom is just to ignore the first return value by assigning it to `_`:
```
_, y = function()
``` |
Combining two lists into a list of lists | 29,853,511 | 4 | 2015-04-24T17:10:29Z | 29,853,537 | 9 | 2015-04-24T17:11:35Z | [
"python",
"list"
] | I have two lists:
```
a = ['1', '2']
b = ['11', '22', '33', '44']
```
And I to combine them to create a list like the one below:
```
op = [('1', '11'), ('2', '22'), ('', '33'), ('', '44')]
```
How could I achieve this? | You want [itertools.zip\_longest](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) with a `fillvalue` of an empty string:
```
a = ['1', '2']
b = ['11', '22', '33', '44']
from itertools import zip_longest # izip_longest for python2
print(list(zip_longest(a,b, fillvalue="")))
[('1', '11'), ('2',... |
Convert a string to a list of length one | 29,854,130 | 2 | 2015-04-24T17:44:04Z | 29,854,161 | 8 | 2015-04-24T17:45:41Z | [
"python",
"string",
"list",
"split"
] | I created a method that requires a list in order to work properly. However, you can send in a list OR a simple string. I want to turn that string into a list that contains that entire string as an element. For example, if I have:
```
"I am a string"
```
I want to convert that to:
```
["I am a string"]
```
I am able... | ```
>>> "abc"
'abc'
>>> ["abc"]
['abc']
>>> abc = "abc"
>>> abc
'abc'
>>> [abc]
['abc']
>>> "I am a string".split("!@#$%^&*") == ["I am a string"]
True
```
Putting the value in square brackets makes a list with one item, just as multiple values makes a list with multiple items. The only container which does not follow... |
Error message: "'chromedriver' executable needs to be available in the path" | 29,858,752 | 4 | 2015-04-24T22:46:16Z | 29,858,817 | 9 | 2015-04-24T22:52:25Z | [
"python",
"selenium",
"selenium-chromedriver"
] | I am using selenium with python and have downloaded the chromedriver for my windows computer from this site: <http://chromedriver.storage.googleapis.com/index.html?path=2.15/>
After downloading the zip file, I unpacked the zip file to my downloads folder. Then I put the path to the executable binary (C:\Users\michael\... | You can test if it actually is in the PATH, if you open a cmd and type in `chromedriver` (assuming your chromedriver executable is still named like this) and hit Enter. If `Starting ChromeDriver 2.15.322448` is appearing, the PATH is set appropriately and there is something else going wrong.
Alternatively you can use ... |
Do numerical programming languages distinguish between a "largest finite number" and "infinity"? | 29,859,509 | 8 | 2015-04-25T00:11:42Z | 29,869,185 | 7 | 2015-04-25T18:42:58Z | [
"python",
"matlab",
"numpy",
"integer-overflow"
] | **Question motivation:**
In standard numerical languages of which I am aware (e.g. Matlab, Python numpy, etc.), if, for example, you take the exponential of a modestly large number, the output is infinity as the result of numerical overflow. If this is multiplied by 0, you get NaN. Separately, these steps are reasonab... | So... I got curious and dug around a little.
As I already mentioned in the comments, a "largest finite value" kind of exists in IEEE 754, if you consider the [exception status flags](https://en.wikipedia.org/wiki/IEEE_floating_point#Exception_handling). A value of infinity with the overflow flag set corresponds to you... |
Create "The Economist" style graphs from python | 29,859,565 | 7 | 2015-04-25T00:20:28Z | 29,872,466 | 9 | 2015-04-26T00:54:10Z | [
"python",
"matplotlib",
"seaborn"
] | Using python and marplotlib and a tool like seaborn, I'd like to create a graph like this one from The Economist (because I think the style is great.)

It's a time series graph and the key things I'd like to reproduce are the horizontal grid lines with labels matched ... | Not perfect (I've haven't had long to play with it), but to give you an idea of the kind of Matplotlib methods you need to use to customize a plot the way you want, there's some code below.
Note that to fine-tune a plot like this it is hard to keep the content and presentation separate (You may have to manually set ti... |
Memoization: Making change with coins | 29,862,046 | 2 | 2015-04-25T06:52:39Z | 29,862,260 | 7 | 2015-04-25T07:18:29Z | [
"python",
"dynamic-programming",
"memoization",
"python-decorators",
"coin-change"
] | I am working on the classic *making change with coins* problem with Python. This is my implementation.
```
def memo(fn):
def helper(*args): # here, * indicate the fn take arbitrary number of argumetns
d = {}
if args in d:
return d[args] # args is a tuple, immutable, hashable
els... | In your current code:
```
def memo(fn):
def helper(*args):
d = {}
```
you create a new *"cache"* dictionary `d` **every time the decorated function is called**. It's no wonder it's slower! The minimal fix is:
```
def memo(fn):
d = {}
def helper(*args):
```
but it could be neater generally. I use... |
Convert list to dict in Python | 29,862,081 | 3 | 2015-04-25T06:57:08Z | 29,862,096 | 19 | 2015-04-25T06:58:57Z | [
"python",
"list",
"dictionary"
] | How can I convert a list
```
my_list = ["a", "b", "c"]
```
into a dictionary
```
my_dict = {
1: "a",
2: "b",
3: "c"
}
```
The keys should just be the indexes + 1 as in my example. | A simple solution is:
```
dict(enumerate(my_list, 1))
```
For example:
```
>>> dict(enumerate(["a", "b", "c"], 1))
{1: 'a', 2: 'b', 3: 'c'}
``` |
How to write a function which takes a slice? | 29,862,628 | 11 | 2015-04-25T08:02:03Z | 29,862,837 | 10 | 2015-04-25T08:27:20Z | [
"python",
"numpy",
"slice"
] | I would like to write a function in Python which takes a slice as a parameter. Ideally a user would be to be able to call the function as follows:
```
foo(a:b:c)
```
Unfortunately, this syntax is not permitted by Python - the use of `a:b:c` is only allowed within `[]`, not `()`.
I therefore see three possibilities f... | Don't surprise your users.
If you use the slicing syntax consistently with what a developer expects from a slicing syntax, that same developer will expect square brackets operation, i.e. a `__getitem__()` method.
If instead the returned object is not somehow a slice of the original object, people will be confused if ... |
os.path.isfile() returns false for existing Windows file | 29,863,318 | 5 | 2015-04-25T09:19:53Z | 29,863,357 | 9 | 2015-04-25T09:23:52Z | [
"python"
] | For some reason **os.path.isfile()** occasionally returns **false** for some existing Windows files. At first, I assumed that spaces in the filename were causing a problem, but other file paths with spaces worked fine. Here's copy from the Python console that illustrates this issue:
```
>>> import os
>>> os.path.isfil... | `\b` in a string means backspace. If you want actual backslashes in a string, they need to be escaped with more backslashes (`\\` instead of `\`), or you need to use a raw string (`r"..."` instead of `"..."`). For file paths, I'd recommend using forward slashes. |
python asyncio run event loop once? | 29,868,372 | 7 | 2015-04-25T17:21:37Z | 29,868,627 | 8 | 2015-04-25T17:46:39Z | [
"python",
"sockets",
"asyncsocket",
"python-asyncio"
] | I am trying to understand the asyncio library, specifically with using sockets. I have written some code in an attempt to gain understanding,
I wanted to run a sender and a receiver sockets asynchrounously. I got to the point where I get all data sent up till the last one, but then I have to run one more loop. Looking... | The `stop(); run_forever()` trick works because of how `stop` is implemented:
```
def stop(self):
"""Stop running the event loop.
Every callback scheduled before stop() is called will run.
Callback scheduled after stop() is called won't. However,
those callbacks will run if run() is called again late... |
Counting consecutive alphabets and hyphens and encode them as run length | 29,869,057 | 7 | 2015-04-25T18:31:29Z | 29,869,126 | 11 | 2015-04-25T18:38:13Z | [
"python",
"python-2.7",
"collections",
"counter"
] | How do I encode my hyphenated fasta format string to group all consecutive Nucleotide and hyphens and [encode them as run length](http://en.wikipedia.org/wiki/Run-length_encoding).
Consider my sequence as "ATGC----CGCTA-----G---". The string has sequence of [Nucleotide](http://en.wikipedia.org/wiki/Nucleotide) followe... | This problem is ideal for [itertools.groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby)
**Implementation**
```
from itertools import groupby
''.join('{}{}'.format(len(list(g)), 'DM'[k])
for k, g in groupby(seq, key = str.isalpha))
```
**Output**
'4M4D5M5D1M3D'
**Explanation**
Not... |
Why is it valid to assign to an empty list but not to an empty tuple? | 29,870,019 | 26 | 2015-04-25T19:55:52Z | 29,870,228 | 12 | 2015-04-25T20:14:40Z | [
"python",
"iterable-unpacking"
] | This came up in [a recent PyCon talk](https://youtu.be/MCs5OvhV9S4?t=42m17s).
The statement
```
[] = []
```
does nothing meaningful, but it does not throw an exception either. I have the feeling this must be due to unpacking rules. You can do [tuple unpacking](http://openbookproject.net/thinkcs/python/english3e/tupl... | I decided to try to use `dis` to figure out what's going on here, when I tripped over something curious:
```
>>> def foo():
... [] = []
...
>>> dis.dis(foo)
2 0 BUILD_LIST 0
3 UNPACK_SEQUENCE 0
6 LOAD_CONST 0 (None)
9 RETURN_... |
Why is it valid to assign to an empty list but not to an empty tuple? | 29,870,019 | 26 | 2015-04-25T19:55:52Z | 29,870,332 | 18 | 2015-04-25T20:23:37Z | [
"python",
"iterable-unpacking"
] | This came up in [a recent PyCon talk](https://youtu.be/MCs5OvhV9S4?t=42m17s).
The statement
```
[] = []
```
does nothing meaningful, but it does not throw an exception either. I have the feeling this must be due to unpacking rules. You can do [tuple unpacking](http://openbookproject.net/thinkcs/python/english3e/tupl... | The comment by @user2357112 that this seems to be coincidence appears to be correct. The relevant part of the Python source code is in [`Python/ast.c`](https://hg.python.org/cpython/file/0351b0cb31d6/Python/ast.c#l916):
```
switch (e->kind) {
# several cases snipped
case List_kind:
e->v.List.ctx = ctx;... |
Python read a huge file and eliminate duplicate lines | 29,880,603 | 5 | 2015-04-26T16:57:39Z | 29,880,709 | 7 | 2015-04-26T17:07:12Z | [
"python",
"large-files"
] | I have a huge text file that has duplicate lines. The size would be about 150000000 lines. I'd like to find the most efficient way to read these lines in and eliminate duplicates. Some of the approaches I'm considering are as follows :-
1. Read the whole file in, do a list(set(lines)).
2. Read 10k lines in at a time, ... | Multiprocessing will not really help, because your bottleneck is memory. You will need to use hashes:
1. Read line
2. Calculate hash, e.g. md5, look it up in a set of all encountered hashes.
3. Output line if hash not found in set and add this hash to set.
Couple things to be mindful of:
* md5 takes 128 bits, so eve... |
How to mock asyncio coroutines? | 29,881,236 | 13 | 2015-04-26T17:51:07Z | 29,892,903 | 9 | 2015-04-27T10:13:54Z | [
"python",
"unit-testing",
"mocking",
"python-asyncio"
] | The following code fails with `TypeError: 'Mock' object is not iterable` in `ImBeingTested.i_call_other_coroutines` because I've replaced `ImGoingToBeMocked` by a Mock object.
How can I mock coroutines?
```
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_to_run(self):
yield from asyn... | Since `mock` library doesn't support coroutines I create mocked coroutines manually and assign those to mock object. A bit more verbose but it works.
Your example may look like this:
```
import asyncio
import unittest
from unittest.mock import Mock
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not... |
How to mock asyncio coroutines? | 29,881,236 | 13 | 2015-04-26T17:51:07Z | 30,177,263 | 8 | 2015-05-11T20:41:16Z | [
"python",
"unit-testing",
"mocking",
"python-asyncio"
] | The following code fails with `TypeError: 'Mock' object is not iterable` in `ImBeingTested.i_call_other_coroutines` because I've replaced `ImGoingToBeMocked` by a Mock object.
How can I mock coroutines?
```
class ImGoingToBeMocked:
@asyncio.coroutine
def yeah_im_not_going_to_run(self):
yield from asyn... | I am writting a wrapper to unittest which aims at cutting the boilerplate when writting tests for asyncio.
The code lives here: <https://github.com/Martiusweb/asynctest>
You can mock a coroutine with `asynctest.CoroutineMock`:
```
>>> mock = CoroutineMock(return_value='a result')
>>> asyncio.iscoroutinefunction(mock... |
String split in python | 29,887,425 | 3 | 2015-04-27T04:50:36Z | 29,887,448 | 7 | 2015-04-27T04:53:08Z | [
"python",
"for-loop",
"split"
] | In the loop below, `content` is a list containing an unknown amount of strings. each string contains a name with a set of numbers after the name, each delimited by a space. I am trying to use `split` to put the name and each score into a variable but I am having trouble because each name has a variable amount of scores... | You can use [slicing for assignment](https://docs.python.org/3.4/reference/expressions.html#slicings) :
```
for i in content:
s=i.split()
name,scores=s[0],s[1:]
```
At the end you'll have the name in `name` variable and list of scores in `scores`.
In python 3 you can use `star expressions` :
```
for i in cont... |
subprocess.check_output(): OSError file not found in Python | 29,891,059 | 2 | 2015-04-27T08:47:44Z | 29,891,132 | 11 | 2015-04-27T08:51:42Z | [
"python"
] | Executing following command and its variations always results in an error, which I just cannot figure out:
```
command = "/bin/dd if=/dev/sda8 count=100 skip=$(expr 19868431049 / 512)"
print subprocess.check_output([command])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/p... | Your `command` is a list with one element. Imagine if you tried to run this at the shell:
```
/bin/'dd if='/dev/'sda8 count=100 skip=$(expr 19868431049 '/' 512)'
```
That's effectively what you're doing. There's almost certainly no directory named `dd if=` in your `bin` directory, and there's even more almost certain... |
Nim equivalent of Python's list comprehension | 29,895,918 | 9 | 2015-04-27T12:33:50Z | 29,896,427 | 8 | 2015-04-27T12:55:20Z | [
"python",
"list-comprehension",
"nim",
"nimrod"
] | Since Nim shares a lot of features with Python, i would not be surprised if it implements [Python's list comprehension](http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Comprehensions.html#list-comprehensions) too:
```
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2',... | List comprehension is already implemented in Nim but currently still in the `future` package (i.e., you have to `import future`). It is implemented as a macro called `lc` and allows to write list comprehensions like this:
```
lc[x | (x <- 1..10, x mod 2 == 0), int]
lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x +... |
Run .py file until specified line number | 29,896,999 | 5 | 2015-04-27T13:20:14Z | 29,897,131 | 11 | 2015-04-27T13:26:53Z | [
"python",
"terminal"
] | In a linux terminal typing
```
python script.py
```
Will run run `script.py` and exit the python console, but what if I just want to run a part of the script and leave the console open? For example, run `script.py` until line 15 and leave the console open for further scripting. How would I do this?
Let's say it's po... | Your best bet might be `pdb`, the [Python debugger](https://docs.python.org/3/library/pdb.html). You can start you script under `pdb`, set a breakpoint on line 15, and then run your script.
```
python -m pdb script.py
b 15 # <-- Set breakpoint on line 15
c # "continue" ->... |
Print the complete string of a pandas dataframe | 29,902,714 | 6 | 2015-04-27T17:54:00Z | 29,902,819 | 8 | 2015-04-27T17:59:42Z | [
"python",
"string",
"pandas"
] | I am struggling with the seemingly very simple thing.I have a pandas data frame containing very long string.
```
df = pd.DataFrame({'one' : ['one', 'two', 'This is very long string very long string very long string veryvery long string']})
```
Now when I try to print the same, I do not see the full string I rather se... | You can use `options.display.max_colwidth` to specify you want to see more in the default representation:
```
In [2]: df
Out[2]:
one
0 one
1 two
2 This is very long string ver... |
Count most frequent 100 words from sentences in Dataframe Pandas | 29,903,025 | 3 | 2015-04-27T18:11:22Z | 29,903,102 | 7 | 2015-04-27T18:15:59Z | [
"python",
"pandas"
] | I have text reviews in one column in Pandas dataframe and I want to count the N-most frequent words with their frequency counts (in whole column - NOT in single cell). One approach is Counting the words using a counter, by iterating through each row. Is there a better alternative?
Representative data.
```
0 a hear... | ```
Counter(" ".join(df["text"]).split()).most_common(100)
```
im pretty sure would give you what you want (you might have to remove some non-words from the counter result before calling most\_common) |
Django: How to automatically change a field's value at the time mentioned in the same object? | 29,903,134 | 10 | 2015-04-27T18:18:11Z | 31,628,267 | 10 | 2015-07-25T15:47:34Z | [
"python",
"django",
"django-models",
"celery",
"django-celery"
] | I am working on a django project for racing event in which a table in the database has three fields.
1)Boolean field to know whether race is active or not
2)Race start time
3)Race end time
While creating an object of it,the start\_time and end\_time are specified. How to change the value of boolean field to True wh... | **To automatically update a model field after a specific time, you can use [Celery tasks](http://docs.celeryproject.org/en/latest/userguide/tasks.html).**
**Step-1: Create a Celery Task**
We will first create a celery task called `set_race_as_inactive` which will set the `is_active` flag of the `race_object` to `Fals... |
Operate on a list in a pythonic way when output depends on other elements | 29,903,211 | 11 | 2015-04-27T18:22:38Z | 29,903,458 | 7 | 2015-04-27T18:36:25Z | [
"python"
] | I have a task requiring an operation on every element of a list, with the outcome of the operation depending on other elements in the list.
For example, I might like to concatenate a list of strings conditional on them starting with a particular character:
This code solves the problem:
```
x = ['*a', 'b', 'c', '*d',... | You could use regex to accomplish this succinctly. This does however, sort of circumvent your question regarding how to operate on dependent list elements. Credits to [mbomb007](http://stackoverflow.com/users/2415524/mbomb007) for improving the allowed character functionality.
```
import re
z = re.findall('\*[^*]+',""... |
Operate on a list in a pythonic way when output depends on other elements | 29,903,211 | 11 | 2015-04-27T18:22:38Z | 29,903,809 | 13 | 2015-04-27T18:56:36Z | [
"python"
] | I have a task requiring an operation on every element of a list, with the outcome of the operation depending on other elements in the list.
For example, I might like to concatenate a list of strings conditional on them starting with a particular character:
This code solves the problem:
```
x = ['*a', 'b', 'c', '*d',... | A few relevant excerpts from `import this` (the arbiter of what is Pythonic):
* Simple is better than complex
* Readability counts
* Explicit is better than implicit.
I would just use code like this, and not worry about replacing the for loop with something "flatter".
```
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
... |
Why is my computation so much faster in C# than Python | 29,903,320 | 7 | 2015-04-27T18:28:05Z | 29,904,752 | 8 | 2015-04-27T19:53:51Z | [
"c#",
"python"
] | Below is a simple piece of process coded in `C#` and `Python` respectively (for those of you curious about the process, it's the solution for Problem No. 5 of [Project Euler](https://projecteuler.net/problem=5)).
My question is, the `C#` code below takes only 9 seconds to iterate, while completion of `Python` code tak... | The answer is simply that Python deals with objects for everything and that it doesn't have [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation) by default. So rather than being very efficient by modifying a few bytes on the stack and optimizing the hot parts of the code (i.e., the iteration) â Python chugs ... |
How to find the points of intersection of a line and multiple curves in Python? | 29,904,423 | 8 | 2015-04-27T19:35:09Z | 29,905,260 | 14 | 2015-04-27T20:23:53Z | [
"python",
"numpy",
"scipy",
"equation"
] | I have data represented in the figure.

The curves were extrapolated and I have a line whose equation is known. The equation of curves are unknown. Now, how do I find the points of intersection of this line with each of the curves?
The reproducible c... | We *do* know the equations of the curves. They are of the form `a*x**2 + b*x + c`, where `a`,`b`, and `c` are the elements of the vector returned by `np.polyfit`. Then we just need to find the roots of a quadratic equation in order to find the intersections:
```
def quadratic_intersections(p, q):
"""Given two quad... |
Pip install -e packages don't appear in Docker | 29,905,909 | 4 | 2015-04-27T21:04:37Z | 30,135,576 | 9 | 2015-05-09T03:18:03Z | [
"python",
"docker",
"pip",
"docker-compose"
] | I have a `requirements.txt` file containing, amongst others:
```
Flask-RQ==0.2
-e git+https://token:x-oauth-basic@github.com/user/repo.git#egg=repo
```
When I try to build a Docker container using Docker Compose, it downloads both packages, and install them both, but when I do a `pip freeze` there is no sign of the `... | I ran into a similar issue, and one possible way that the problem can appear is from:
```
WORKDIR /usr/src/app
```
being set before `pip install`. pip will create the `src/` directory (where the package is installed) inside of the WORKDIR. Now all of this shouldn't be an issue since your app files, when copied over, ... |
Microsoft Visual C++ Compiler for Python 3.4 | 29,909,330 | 26 | 2015-04-28T02:38:09Z | 29,910,249 | 12 | 2015-04-28T04:19:00Z | [
"python",
"windows",
"python-3.x",
"compilation"
] | I know that there is a ["Microsoft Visual C++ Compiler for Python 2.7"](http://www.microsoft.com/en-gb/download/details.aspx?id=44266) but is there, currently or planned, a Microsoft Visual C++ Compiler for Python 3.4 or eve Microsoft Visual C++ Compiler for Python 3.x for that matter? It would be supremely beneficial ... | Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:
* Visual Studio 2008 for Python 2.7.
See: <https://docs.python.org/2.7/using/windows.html#compiling-python-on-windows>
* Visual Studio 2010 for Python 3.4.
See: <http... |
Reading first n lines of a CSV into a dictionary | 29,911,507 | 3 | 2015-04-28T06:04:50Z | 29,911,540 | 8 | 2015-04-28T06:07:11Z | [
"python",
"csv",
"python-3.x",
"dictionary"
] | I have a CSV file I'd like to read into a dictionary for subsequent insertion into a MongoDB collection entitled projects.
I accomplished this with the following:
```
with open('opendata_projects.csv') as f:
records = csv.DictReader(f)
projects.insert(records)
```
However, I found my poor sandbox account cou... | You can use [`itertools.islice`](https://docs.python.org/3/library/itertools.html#itertools.islice), like this
```
import csv, itertools
with open('names.csv') as csvfile:
for row in itertools.islice(csv.DictReader(csvfile), 100):
print(row['first_name'], row['last_name'])
```
`islice` will create an ite... |
How to get meaningful network interface names instead of GUIDs with netifaces under Windows? | 29,913,516 | 6 | 2015-04-28T07:53:08Z | 29,918,755 | 10 | 2015-04-28T11:54:26Z | [
"python",
"python-2.7"
] | I use the `netifaces` module.
```
import netifaces
print netifaces.interfaces()
```
but this shows the result below:
```
['{CDC97813-CC28-4260-BA1E-F0CE3081DEC7}',
'{846EE342-7039-11DE-9D20-806E6F6E6963}',
'{A51BA5F0-738B-4405-975F-44E67383513F}',
'{A646FA85-2EC6-4E57-996E-96E1B1C5CD59}',
'{B5DC7787-26DC-4540-84... | It looks like `netifaces` leaves it up to us to pull the information out of the Windows Registry. The following functions work for me under Python 3.4 on Windows 8.1.
To get the connection name ...
```
import netifaces as ni
import winreg as wr
from pprint import pprint
def get_connection_name_from_guid(iface_guids)... |
Upgrading from Django 1.6 (with south) to 1.8 doesn't modify 'last_login' on the user table | 29,913,612 | 24 | 2015-04-28T07:57:40Z | 29,921,518 | 20 | 2015-04-28T13:52:36Z | [
"python",
"mysql",
"django",
"django-south",
"django-1.8"
] | I have upgraded from Django 1.6.5 (with south migrations) to Django 1.8. I have followed the instructions here:
<https://docs.djangoproject.com/en/1.8/topics/migrations/#upgrading-from-south>
So, I remove South, delete my previous migrations and run `python manage.py makemigrations` which makes a new migration file. T... | As noted in the [1.8 release notes](https://docs.djangoproject.com/en/1.8/releases/1.8/#abstractuser-last-login-allows-null-values):
> If you are using a custom user model that inherits from `AbstractUser`, youâll need to run `makemigrations` and generate a migration for your app that contains that model. |
How to write a list to a file in python | 29,915,158 | 2 | 2015-04-28T09:13:08Z | 29,915,199 | 10 | 2015-04-28T09:14:52Z | [
"python",
"list"
] | I have a program that encrypts the contents of a file into cipher text. I want the program to write the ciphertext, that Is in a list, to a file.
The part of my code I need help with is:
```
for char in encryptFile:
cipherTextList = []
if char == (" "):
print(" ",end=" ")
else:
cipherText ... | You keep overwriting opening the file with `w` so you only ever see the very last values, use `a` to append:
```
with open("newCipherFile.txt","a") as cFile:
```
Or a better idea so to open it outside the loop once:
```
with open("newCipherFile.txt","w") as cFile:
for char in encryptFile:
cipherTextList... |
Change user agent for selenium driver | 29,916,054 | 12 | 2015-04-28T09:52:22Z | 29,966,769 | 33 | 2015-04-30T11:40:17Z | [
"python",
"selenium",
"http-headers",
"user-agent"
] | I have the following code in `Python`:
```
from selenium.webdriver import Firefox
from contextlib import closing
with closing(Firefox()) as browser:
browser.get(url)
```
I would like to print the user-agent HTTP header and
possibly change it. Is it possible? | There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.
### Setting the User Agent in Firefox
The usual way to change the user agent for Firefox is to set the variable `"general.useragent.overrid... |
Why does Python allow abstract methods to have code? | 29,917,870 | 2 | 2015-04-28T11:13:52Z | 29,918,032 | 7 | 2015-04-28T11:19:56Z | [
"python",
"abstract"
] | Why does python allow one to have code inside an abstract method? I know we can invoke that code through super, but I am not able to think of reasons why would I want my abstract method to have code in it. | This is explained in the [`abc` module docs](https://docs.python.org/3/library/abc.html#abc.abstractmethod):
> Note: Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the `super()` mechanism from the class that overrides it. **This could be useful as... |
Find the column name which has maximum value for each row [pandas] | 29,919,306 | 12 | 2015-04-28T12:18:57Z | 29,919,489 | 21 | 2015-04-28T12:25:57Z | [
"python",
"pandas",
"max"
] | I have a dataframe like this one:
```
In [7]:
frame.head()
Out[7]:
Communications and Search Business General Lifestyle
0 0.745763 0.050847 0.118644 0.084746
0 0.333333 0.000000 0.583333 0.083333
0 0.617021 0.042553 0.297872 0.042553
0 0.435897 0.000000 0.410256 0.15384... | You can use [`idxmax()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html) to find the column with the greatest value on each row:
```
>>> df.idxmax(axis=1)
0 Communications
1 Business
2 Communications
3 Communications
4 Business
dtype: object
```
To create... |
Function decorated using functools.wraps raises TypeError with the name of the wrapper. Why? How to avoid? | 29,919,804 | 11 | 2015-04-28T12:40:57Z | 29,919,965 | 7 | 2015-04-28T12:47:37Z | [
"python",
"python-decorators",
"functools"
] | ```
def decorated(f):
@functools.wraps(f)
def wrapper():
return f()
return wrapper
@decorated
def g():
pass
```
`functools.wraps` does its job at preserving the name of `g`:
```
>>> g.__name__
'g'
```
But if I pass an argument to `g`, I get a `TypeError` containing the name of the wrapper:
... | The name comes from the code object; both the function and the code object (containing the bytecode to be executed, among others) contain that name:
```
>>> g.__name__
'g'
>>> g.__code__.co_name
'wrapper'
```
The attribute on the code object is read-only:
```
>>> g.__code__.co_name = 'g'
Traceback (most recent call ... |
How to gauss-filter (blur) a floating point numpy array | 29,920,114 | 6 | 2015-04-28T12:53:58Z | 29,920,953 | 10 | 2015-04-28T13:29:52Z | [
"python",
"numpy",
"filtering",
"python-imaging-library"
] | I have got a numpy array `a` of type `float64`. How can I blur this data with a Gauss filter?
I have tried
```
from PIL import Image, ImageFilter
image = Image.fromarray(a)
filtered = image.filter(ImageFilter.GaussianBlur(radius=7))
```
, but this yields `ValueError: 'image has wrong mode'`. (It has mode `F`.)
I c... | If you have a two-dimensional numpy array `a`, you can use a Gaussian filter on it directly without using Pillow to convert it to an image first. scipy has a function [`gaussian_filter`](http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.ndimage.filters.gaussian_filter.html) that does the same.
```
from ... |
When can a Python object be pickled | 29,922,373 | 10 | 2015-04-28T14:28:46Z | 29,922,428 | 7 | 2015-04-28T14:33:05Z | [
"python",
"multiprocessing",
"pickle"
] | I'm doing a fair amount of parallel processing in Python using the multiprocessing module. I know certain objects CAN be pickle (thus passed as arguments in multi-p) and others can't. E.g.
```
class abc():
pass
a=abc()
pickle.dumps(a)
'ccopy_reg\n_reconstructor\np1\n(c__main__\nabc\np2\nc__builtin__\nobject\np3\n... | From the [docs](https://docs.python.org/2/library/pickle.html#what-can-be-pickled-and-unpickled):
> The following types can be pickled:
>
> * None, True, and False
> * integers, long integers, floating point numbers, complex numbers
> * normal and Unicode strings
> * tuples, lists, sets, and dictionaries containing on... |
How to read in IRAF multispec spectra? | 29,923,315 | 4 | 2015-04-28T15:17:00Z | 29,923,316 | 8 | 2015-04-28T15:17:00Z | [
"python",
"spectrum",
"astropy"
] | I have a spectrum in a fits file that I generated with Iraf. The wavelength axis is encoded in the header as:
```
WAT0_001= 'system=multispec'
WAT1_001= 'wtype=multispec label=Wavelength units=angstroms'
WAT2_001= 'wtype=multispec spec1 = "1 1 2 1. 2.1919422441886 4200 0. 452.53 471'
WAT3_001= 'wtype=linear'
WAT2_002=... | I have been using [this](https://github.com/kgullikson88/General/blob/master/readmultispec.py) code, which was given to me by Rick White. However, the [specutils](http://specutils.readthedocs.org/en/latest/specutils/read_fits.html) package is probably the better way to do it:
```
from specutils.io import read_fits
spe... |
Why variable = object doesn't work like variable = number | 29,926,485 | 17 | 2015-04-28T17:49:20Z | 29,926,513 | 16 | 2015-04-28T17:51:12Z | [
"python",
"python-2.7",
"variables",
"object",
"python-3.x"
] | These variable assignments work as I expect:
```
>>> a = 3
>>> b = a
>>> print(a, b)
(3, 3)
>>> b=4
>>> print(a, b)
(3, 4)
```
However, these assignments behave differently:
```
>>> class number():
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> c = nu... | These lines:
```
c = number("one", 1)
d = c
```
...are effectively:
* Create a new instance of `number` and assign it to `c`
* Assign the existing reference called `c` to a new variable `d`
You haven't changed or modified anything about `c`; `d` is another name that points to the same instance.
Without cloning the... |
Why variable = object doesn't work like variable = number | 29,926,485 | 17 | 2015-04-28T17:49:20Z | 29,926,592 | 7 | 2015-04-28T17:55:46Z | [
"python",
"python-2.7",
"variables",
"object",
"python-3.x"
] | These variable assignments work as I expect:
```
>>> a = 3
>>> b = a
>>> print(a, b)
(3, 3)
>>> b=4
>>> print(a, b)
(3, 4)
```
However, these assignments behave differently:
```
>>> class number():
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> c = nu... | You are focusing on the fact that these two pairs of lines are the same (both use plain `=`):
```
# one
a = 3
b = a
#two
c = number("one", 1)
d = c
```
What you're missing is that these two lines are different:
```
# one
b = 4
# two
d.number = 2
```
The reason they aren't the same is that `d.number` has a dot in ... |
Why variable = object doesn't work like variable = number | 29,926,485 | 17 | 2015-04-28T17:49:20Z | 29,926,864 | 9 | 2015-04-28T18:10:29Z | [
"python",
"python-2.7",
"variables",
"object",
"python-3.x"
] | These variable assignments work as I expect:
```
>>> a = 3
>>> b = a
>>> print(a, b)
(3, 3)
>>> b=4
>>> print(a, b)
(3, 4)
```
However, these assignments behave differently:
```
>>> class number():
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> c = nu... | I didn't see that anyone provided details on how to make these two cases work the same by copying the object instead of just assigning a new reference to the same object.
```
import copy
c = number("one", 1)
d = c
e = copy.copy(c)
print(c.number, d.number, e.number)
d.number = 2
e.number = 5
print(c.number, d.number,... |
Why variable = object doesn't work like variable = number | 29,926,485 | 17 | 2015-04-28T17:49:20Z | 29,930,723 | 10 | 2015-04-28T22:00:56Z | [
"python",
"python-2.7",
"variables",
"object",
"python-3.x"
] | These variable assignments work as I expect:
```
>>> a = 3
>>> b = a
>>> print(a, b)
(3, 3)
>>> b=4
>>> print(a, b)
(3, 4)
```
However, these assignments behave differently:
```
>>> class number():
... def __init__(self, name, number):
... self.name = name
... self.number = number
...
>>> c = nu... | ## A picture worth a thousand words
```
a = 3
b = a
c = number("one", 1)
d = c
```

---
Step 2â¦
```
b = 4
d.number = 2
```

You can see why changing `d.number` would al... |
Calculating the averages for each KEY in a Pairwise (K,V) RDD in Spark with Python | 29,930,110 | 14 | 2015-04-28T21:18:11Z | 29,930,162 | 19 | 2015-04-28T21:21:22Z | [
"python",
"apache-spark",
"aggregate",
"average",
"rdd"
] | I want to share this particular Apache Spark with Python solution because documentation for it is quite poor.
I wanted to calculate the average value of K/V pairs (stored in a Pairwise RDD), by KEY. Here is what the sample data looks like:
```
>>> rdd1.take(10) # Show a small sample.
[(u'2013-10-09', 7.60117302052786... | Now a much better way to do this is to use the rdd.aggregateByKey() method. Because that method is so poorly documented in the Apache Spark with Python documentation (which is why I'm writing this), until recently I had been using the above code sequence. But again, it's less efficient, **so don't do it that way unless... |
Why is `if` so much faster when checked before a statement than after a statement? | 29,931,471 | 11 | 2015-04-28T23:05:26Z | 29,931,705 | 7 | 2015-04-28T23:30:08Z | [
"python",
"performance",
"python-3.x",
"performance-testing"
] | Here's an example of what I mean:
```
s = """
if x > 10:
x -= 10
else:
x = 0
"""
import timeit
print(timeit.timeit(s, setup="x=5", number=99999999))
```
Outputs approximately 3 seconds on my computer, regardless of the setup (`x=5` vs `x=15`, no difference)
---
If I were to use much shorter code, one that f... | Your premise is wrong. `setup` only gets run once for the entire `timeit`. If you make sure that `x` stays above `10` then the symptoms disappear:
```
>>> s1 = """
... if x > 10:
... x -= 10
... else:
... x = 0
... """
>>> s2 = """
... x -= 10
... if x < 0:
... x = 0
... """
>>> import timeit
>>> print(tim... |
Reduce by key in python | 29,933,189 | 4 | 2015-04-29T02:15:23Z | 29,933,270 | 7 | 2015-04-29T02:25:46Z | [
"python",
"reduce"
] | I'm trying to think through the most efficient way to do this in python.
Suppose I have a list of tuples:
```
[('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]
```
And suppose I have a function which takes two of these tuples and combines them:
```
def my_reduce(obj1, obj2):
r... | I don't think `reduce` is a good tool for this job, because you will have to first use itertools or similar to group the list by the key. Otherwise you will be comparing `cats` and `dogs` and all hell will break loose!
Instead just a simple loop is fine:
```
>>> my_list = [('dog',12,2), ('cat',15,1), ('dog',11,1), ('... |
Reduce by key in python | 29,933,189 | 4 | 2015-04-29T02:15:23Z | 29,933,308 | 7 | 2015-04-29T02:30:24Z | [
"python",
"reduce"
] | I'm trying to think through the most efficient way to do this in python.
Suppose I have a list of tuples:
```
[('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]
```
And suppose I have a function which takes two of these tuples and combines them:
```
def my_reduce(obj1, obj2):
r... | Alternatively, if you have **pandas** installed:
```
import pandas as pd
l = [('dog',12,2), ('cat',15,1), ('dog',11,1), ('cat',15,2), ('dog',10,3), ('cat',16,3)]
pd.DataFrame(data=l, columns=['animal', 'm', 'n']).groupby('animal').agg({'m':'max', 'n':'min'})
Out[6]:
m n
animal
cat 16 1
dog ... |
Virtualenv - Python 3 - Ubuntu 14.04 64 bit | 29,934,032 | 6 | 2015-04-29T03:54:33Z | 35,024,841 | 9 | 2016-01-26T21:58:56Z | [
"python",
"python-3.x",
"pip",
"virtualenv",
"ubuntu-14.04"
] | I am trying to install virtualenv for Python 3 on Ubuntu 64bit 14.04.
I have installed pip for Python3 using:
```
pip3 install virtualenv
```
and everything works fine. Now though I am trying to use virtualenv command to actually create the environment and getting the error that it is not install (i guess because I ... | I had the same issue coming from development environments on OS X where I could create Python 3 virtual environments by simply invoking `virtualenv` and the path to the target directory. You should be able to create a Python 3.x virtual environment in one of two ways:
1. Install `virtualenv` from the PyPi as you've do... |
Linear Regression on Pandas DataFrame using Sci-kit Learn | 29,934,083 | 4 | 2015-04-29T03:58:18Z | 29,937,049 | 9 | 2015-04-29T07:28:43Z | [
"python",
"pandas",
"scikit-learn",
"dataframe",
"linear-regression"
] | I'm new to Python and trying to perform linear regression using sklearn on a pandas dataframe. This is what I did:
```
data = pd.read_csv('xxxx.csv')
```
After that I got a DataFrame of two columns, let's call them 'c1', 'c2'. Now I want to do linear regression on the set of (c1,c2) so I entered
```
X=data['c1'].val... | Let's assume your csv looks something like:
```
c1,c2
0.000000,0.968012
1.000000,2.712641
2.000000,11.958873
3.000000,10.889784
...
```
I generated the data as such:
```
import numpy as np
from sklearn import datasets, linear_model
import matplotlib.pyplot as plt
length = 10
x = np.arange(length, dtype=float).resha... |
In Python, is there a way to sort a list made of lists and tuples, consistently? | 29,934,300 | 3 | 2015-04-29T04:17:54Z | 29,934,338 | 12 | 2015-04-29T04:22:39Z | [
"python"
] | sort of `a` and `b` are as expected to me, then why is `c` different? Is there a ways to make it consistent with `a` and `b`, without converting everything to either lists or tuples?
```
>>> a = [(1, 0), (0, 0)]
>>> a.sort()
>>> print a
[(0, 0), (1, 0)]
>>>
>>> b = [[1], (0)]
>>> b.sort()
>>> print b
[0, [1]]
>>>
>>> ... | It's possible to convert them only for the purpose of sorting:
```
>>> c = [[1, 0], (0, 0)]
>>> c.sort(key=tuple)
>>> c
[(0, 0), [1, 0]]
```
That being said, a list containing a mix of lists and tuples is a code smell. |
django.db.utils.OperationalError Could not connect to server | 29,937,378 | 5 | 2015-04-29T07:44:59Z | 29,937,718 | 14 | 2015-04-29T08:01:27Z | [
"python",
"django",
"postgresql"
] | I am not sure how to fix this issue
I have no idea why I am getting this error when I try to `runserver`:
```
Performing system checks...
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x1085589b0>
Traceback (most recent call last):
File "/Library/Pyth... | It can be some issues:
1. PostgreSQL is not running. Check it with sudo `service postgresql status`
2. Your PostgresSQl is not running on port 5432. You can check it typing `sudo netstat -nl | grep postgres`
3. You have something wrong trying to connect to your db like the username, the password or the databasename. C... |
What's wrong with my Python code containing recursive function? | 29,943,875 | 4 | 2015-04-29T12:32:56Z | 29,943,948 | 8 | 2015-04-29T12:36:30Z | [
"python",
"recursion"
] | I am using recursive to find a [happy number](https://github.com/karan/Projects).
The following is my Python code:
```
deepth = 0
def is_happy_number(number):
astring = str(number)
global deepth
digits = [int(char) for char in astring]
sum_digit = sum([digit**2 for digit in digits])
if sum_digit =... | You're failing to reset the global variable `depth`. A better way to deal with this is to pass the depth into the recursive call.
Something like this:
```
def is_happy_number(number, depth=0):
# ... as before ...
return is_happy_number(sum_digit, depth)
``` |
Opposite of set.intersection in python? | 29,947,844 | 7 | 2015-04-29T15:13:54Z | 29,947,893 | 18 | 2015-04-29T15:15:44Z | [
"python",
"set"
] | In Python you can use `a.intersection(b)` to find the items common to both sets.
Is there a way to do the *disjoint* opposite version of this? Items that are not common to both `a` and `b`; the unique items in `a` unioned with the unique items in `b`? | You are looking for the *symmetric difference*; all elements that appear only in set a or in set b, but not both:
```
a. symmetric_difference(b)
```
From the [`set.symmetric_difference()` method documentation](https://docs.python.org/2/library/stdtypes.html#set.symmetric_difference):
> Return a new set with elements... |
Python anaconda conda issue: updating anaconda package impossible because processes are running | 29,949,087 | 8 | 2015-04-29T16:08:39Z | 30,039,122 | 8 | 2015-05-04T20:12:28Z | [
"python",
"anaconda",
"conda"
] | I have an issue with updating anaconda's packages with conda. when I make a conda update --all there is an issue which says to me:
```
Error: Unable to remove files for package: cryptography
Please close all processes running code from cryptography and try again.
```
however, none process are running, I have just the... | This situation will be improved in the next version of conda, but for now, you can use `conda install -f cryptography` to force conda to update cryptography. |
What is the relationship between virtualenv and pyenv? | 29,950,300 | 53 | 2015-04-29T17:13:23Z | 29,950,604 | 60 | 2015-04-29T17:30:11Z | [
"python",
"virtualenv",
"virtualenvwrapper",
"pyenv"
] | I recently learned how to use virtualenv and virtualenvwrapper in my workflow but I've seen pyenv mentioned in a few guides but I can't seem to get an understanding of what pyenv is and how it is different/similar to virtualenv. Is pyenv a better/newer replacement for virtualenv or a complimentary tool? If the latter w... | **Pyenv** and **virtualenv** are very different tools that work in different ways to do different things:
* **Pyenv** is a bash extension - will not work on Windows - that intercepts your calls to python, pip, etc., to direct them to one of several of the system python tool-chains. So you always have all the libraries... |
Get last element of type string in a list | 29,950,493 | 3 | 2015-04-29T17:24:20Z | 29,950,558 | 12 | 2015-04-29T17:27:33Z | [
"python",
"arrays",
"list",
"loops"
] | Suppose I have a list of different types:
i.e.
```
[7, 'string 1', 'string 2', [a, b c], 'string 3', 0, (1, 2, 3)]
```
Is there a Pythonic way to return 'string 3' ? | If you have a given type, you can use several kinds of comprehensions to get what you need.
```
[el for el in lst if isinstance(el, given_type)][-1]
# Gives the last element if there is one, else IndexError
```
or
```
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if ... |
Ignore divide by 0 warning in python | 29,950,557 | 2 | 2015-04-29T17:27:31Z | 29,950,752 | 7 | 2015-04-29T17:38:13Z | [
"python",
"numpy",
"suppress-warnings",
"divide-by-zero"
] | I have a function for statistic issues:
```
import numpy as np
from scipy.special import gamma as Gamma
def Foo(xdata):
...
return x1 * (
( #R is a numpy vector
( ((R - x2)/beta) ** (x3 -1) ) *
( np.exp( - ((R - x2) / x4) ) ) /
( x4 * Gam... | You can disable the warning with [`numpy.seterr`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html). Put this before the possible division by zero:
```
np.seterr(divide='ignore')
```
That'll disable zero division warnings globally. If you just want to disable them for a little bit, you can use [`... |
DRF: Simple foreign key assignment with nested serializers? | 29,950,956 | 14 | 2015-04-29T17:50:33Z | 29,953,188 | 15 | 2015-04-29T19:49:20Z | [
"python",
"django",
"django-rest-framework"
] | With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.
What's the *simplest* way to get this behavior out of a nested serializer?
Note, I am only talking about assigning existing database objects, *not* nested creation... | The best solution here is to use two different fields: one for reading and the other for writing. Without doing some *heavy* lifting, it is difficult to get what you are looking for *in a single field*.
The read-only field would be your nested serializer (`ChildSerializer` in this case) and it will allow you to get th... |
DRF: Simple foreign key assignment with nested serializers? | 29,950,956 | 14 | 2015-04-29T17:50:33Z | 33,048,798 | 10 | 2015-10-10T00:01:29Z | [
"python",
"django",
"django-rest-framework"
] | With Django REST Framework, a standard ModelSerializer will allow ForeignKey model relationships to be assigned or changed by POSTing an ID as an Integer.
What's the *simplest* way to get this behavior out of a nested serializer?
Note, I am only talking about assigning existing database objects, *not* nested creation... | Here's an example of what Kevin's answer is talking about, if you want to take that approach and use 2 separate fields.
In your models.py...
```
class Child(models.Model):
name = CharField(max_length=20)
class Parent(models.Model):
name = CharField(max_length=20)
phone_number = models.ForeignKey(PhoneNum... |
Why does this empty dict break shared references? | 29,952,200 | 2 | 2015-04-29T18:55:02Z | 29,952,257 | 8 | 2015-04-29T18:57:50Z | [
"python",
"dictionary",
"pass-by-reference"
] | I have found some Python behavior that confuses me.
```
>>> A = {1:1}
>>> B = A
>>> A[2] = 2
>>> A
{1: 1, 2: 2}
>>> B
{1: 1, 2: 2}
```
So far, everything is behaving as expected. A and B both reference the same, mutable, dictionary and altering one alters the other.
```
>>> A = {}
>>> A
{} # As expected
>>... | Here is a pictorial representation \*:
```
A = {1: 1}
# A -> {1: 1}
B = A
# A -> {1: 1} <- B
A[2] = 2
# A -> {1: 1, 2: 2} <- B
A = {}
# {1: 1, 2: 2} <- B
# A -> {}
```
`A = {}` creates a **completely new object** and reassigns the identifier `A` to it, but **does not** affect `B` or the dictionary `A` previously... |
Python generate all n-permutations of n lists | 29,952,531 | 3 | 2015-04-29T19:11:44Z | 29,952,567 | 13 | 2015-04-29T19:13:46Z | [
"python",
"algorithm",
"permutation"
] | I have n lists of different lengths of wich I want to create all possible permutations.
so e.g. if `a=[1,2]` and `b=[3,4,5]` then I would love to obtain `res=[[1,3],[1,4],[1,5],[2,3],[2,4],[2,5]]`
I've been trying to achieve this using a recursive function, which turned out to be neither very efficient nor very python... | It's called the [Cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) of two sequences.
This is already available in Python as a library function: [**`itertools.product`**](https://docs.python.org/3/library/itertools.html#itertools.product).
Example:
```
>>> import itertools
>>> a = [1, 2]
>>> b = [3,... |
How can memoized functions be tested? | 29,953,764 | 6 | 2015-04-29T20:20:23Z | 29,954,160 | 7 | 2015-04-29T20:44:35Z | [
"python",
"unit-testing",
"python-decorators"
] | I have a simple memoizer which I'm using to save some time around expensive network calls. Roughly, my code looks like this:
```
# mem.py
import functools
import time
def memoize(fn):
"""
Decorate a function so that it results are cached in memory.
>>> import random
>>> random.seed(0)
>>> f = la... | Is it really desirable for your memoization to be defined at the function level?
This effectively makes the memoized data a *global variable* (just like the function, whose scope it shares).
Incidentally, that's why you're having difficulty testing it!
So, how about wrapping this into an object?
```
import functool... |
What does the term "broadcasting" mean in Pandas documentation? | 29,954,263 | 9 | 2015-04-29T20:50:04Z | 29,955,358 | 18 | 2015-04-29T22:00:53Z | [
"python",
"numpy",
"pandas"
] | I'm reading through the Pandas documentation, and the term "broadcasting" is [used extensively](http://pandas.pydata.org/pandas-docs/stable/basics.html#flexible-binary-operations), but never really defined or explained.
What does it mean? | So the term *broadcasting* comes from [numpy](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html), simply put it explains the rules of the output that will result when you perform operations between n-dimensional arrays (could be panels, dataframes, series) or scalar values.
## Broadcasting using a scalar v... |
Finding substring (nonconsecutive) | 29,954,748 | 11 | 2015-04-29T21:17:15Z | 29,954,829 | 7 | 2015-04-29T21:22:10Z | [
"python",
"string"
] | In Python if I have string `needle` and I want to see if it exists (contiguously) as a substring in `haystack`, I only need to check `if needle in haystack`.
What happens in the case of a subsequence?
Example:
```
haystack = "qabcdzzzefgyyyh"
needle = "acgh"
```
"acgh" is a subsequence of `qabcdzzzefgyyyh` -- does ... | I don't know if there's builtin function, but it is rather simple to do manually
```
def exists(a, b):
"""checks if b exists in a as a subsequence"""
pos = 0
for ch in a:
if pos < len(b) and ch == b[pos]:
pos += 1
return pos == len(b)
```
```
>>> exists("moo", "mo")
True
>>> exists... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.