title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How do I create a Python namespace (argparse.parse_args value)? | 28,345,780 | 4 | 2015-02-05T13:55:42Z | 28,345,836 | 15 | 2015-02-05T13:58:03Z | [
"python",
"namespaces",
"argparse"
] | To interactively test my python script, I would like to create a `Namespace` object, similar to what would be returned by `argparse.parse_args()`.
The obvious way,
```
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.parse_args()
Namespace()
>>> parser.parse_args("-a")
usage: [-h]
: error: unrecog... | You can create a simple class:
```
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
```
and it'll work the exact same way as the `argparse` `Namespace` class when it comes to attributes:
```
>>> args = Namespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'
```
Alternatively, just *... |
Palindromic numbers in two bases, Project Euler #36 | 28,351,928 | 4 | 2015-02-05T19:01:19Z | 28,351,991 | 10 | 2015-02-05T19:04:56Z | [
"python"
] | Here is my solution for [Project Euler problem 36](https://projecteuler.net/problem=36), which reads:
> The decimal number, 585 = 1001001001â (binary), is palindromic in both bases.
>
> Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
>
> (Please note that the palindro... | You missed something in the problem description:
> Please note that the palindromic number, in either base, **may not include leading zeros**.
Yet you are using leading zeros:
```
temp = '{0:08b}'.format(i)
```
Drop the `08` from the format; there is no need to pad it to a width at all here:
```
temp = '{0:b}'.for... |
Why is an empty DataFrame of dtype=str filled of "n"? | 28,354,207 | 4 | 2015-02-05T21:19:21Z | 28,355,909 | 7 | 2015-02-05T23:17:33Z | [
"python",
"string",
"pandas",
null
] | I cannot understand why
```
In [2]: pandas.Series(index=range(2), dtype=str)
Out[2]:
0 NaN
1 NaN
dtype: object
```
but
```
In [3]: pandas.DataFrame(index=range(2), columns=[0], dtype=str)
Out[3]:
0
0 n
1 n
```
Why strings with just the letter "n"?
Why this difference between Series and DataFrame?
And... | *This is now [fixed in master](https://github.com/pydata/pandas/pull/10658) and shouldn't be an issue from 17.0 onwards.*
---
In short, both DataFrames and Series create an empty NumPy array and fill it with `np.nan` values, but DataFrame uses the passed `str` dtype for this array while Series overrides it with the `... |
One colorbar for seaborn heatmaps in subplot | 28,356,359 | 4 | 2015-02-06T00:04:15Z | 28,356,816 | 10 | 2015-02-06T00:53:12Z | [
"python",
"matplotlib",
"heatmap",
"seaborn"
] | Here is an example that shows a colorbar for each subplot:
```
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((10,10,)))
fig,axn = plt.subplots(2, 2, sharex=True, sharey=True)
for ax in axn.flat:
sns.heatmap(df, ax=ax)
```
![enter... | The `cbar` parameter controls whether a colorbar should be added, and the `cbar_ax` parameter can optionally specify the axes where the colorbar should go. So, you could do:
```
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((10,10,)))
... |
What are the advantages of using numpy.identity over numpy.eye? | 28,363,447 | 6 | 2015-02-06T10:19:23Z | 28,363,694 | 9 | 2015-02-06T10:30:52Z | [
"python",
"arrays",
"performance",
"numpy"
] | Having looked over the man pages for `numpy`'s [`eye`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html) and [`identity`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.identity.html), I'd assumed that `identity` was a special case of `eye`, since it has less options (e.g. `eye` can fill sh... | `identity` just calls `eye` so there is no difference in how the arrays are constructed. Here's the code for [`identity`](https://github.com/numpy/numpy/blob/v1.9.1/numpy/core/numeric.py#L2125):
```
def identity(n, dtype=None):
from numpy import eye
return eye(n, dtype=dtype)
```
As you say, the main differen... |
How do I configure PyCharm to automatically and continuously run my unit tests? | 28,365,136 | 3 | 2015-02-06T11:48:47Z | 28,395,522 | 7 | 2015-02-08T15:10:47Z | [
"python",
"pycharm"
] | I would like to have some background unit tests run automatically continuously.
Can this be done in PyCharm ? | This is very simple. Once you have created a run configuration for the unit tests, run them once manually. With the Run dialog open you will notice on the left hand size there are a group of icons arranged vertically. In that group is an icon with a circular arrow. Click that for the auto-run you seek. It behaves smart... |
TypeError: 'int' object is not iterable - Python | 28,365,580 | 3 | 2015-02-06T12:13:07Z | 28,365,615 | 7 | 2015-02-06T12:15:36Z | [
"python",
"mysql",
"python-2.7",
"mysql-python"
] | I got the following error:
```
File "/home/ec2-user/test/test_stats.py", line 43, in get_test_ids_for_id
cursor.execute("""select test_id from test_logs where id = %s """, (id))
File "/home/ec2-user/.etl/lib/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute
query = query % tuple([db.literal... | You need to give `cursor.execute` a tuple, but you only gave it one integer:
```
(id)
```
Add a comma to make that a tuple:
```
(id,)
```
The full line then'd be:
```
cursor.execute("""select test_id from test_logs where id = %s """, (id,))
```
Putting an expressione in parentheses just 'groups' that one expressi... |
How to output NLTK chunks to file? | 28,365,626 | 4 | 2015-02-06T12:16:01Z | 28,381,060 | 7 | 2015-02-07T10:30:04Z | [
"python",
"regex",
"file-io",
"nlp",
"nltk"
] | I have this python script where I am using nltk library to parse,tokenize,tag and chunk some lets say random text from the web.
I need to format and write in a file the output of `chunked1`,`chunked2`,`chunked3`. These have type `class 'nltk.tree.Tree'`
More specifically I need to write only the lines that match the ... | Firstly, see this video: <https://www.youtube.com/watch?v=0Ef9GudbxXY>

Now for the proper answer:
```
import re
import io
from nltk import pos_tag, word_tokenize, sent_tokenize, RegexpParser
xstring = u"An electronic library (also referred to as ... |
Is it possible to rewind a python StringIO in-memory file? | 28,368,659 | 3 | 2015-02-06T15:04:33Z | 28,368,708 | 8 | 2015-02-06T15:07:12Z | [
"python",
"stringio"
] | Let's say I have a StringIO file-like object I just created from a string. I pass it to a function which expects files. This functions reads the entire file through the end. I want to now pass it to another function which expects a file-like object. Can I rewind it so that it can be read from the beginning? If not, wha... | certainly: most file-like objects in python that can possibly be rewound already support [`seek()`](https://docs.python.org/2/library/stdtypes.html#file.seek)
```
>>> import StringIO
>>> f = StringIO.StringIO("hello world")
>>> f.read(6)
'hello '
>>> f.tell()
6
>>> f.seek(0)
>>> f.tell()
0
>>> f.read()
'hello world'
>... |
Performance of asyncio | 28,370,574 | 8 | 2015-02-06T16:41:09Z | 28,370,840 | 11 | 2015-02-06T16:56:18Z | [
"python",
"python-asyncio"
] | I'm trying to get familiar with asyncio, so I've decided to write a database client. However, performance exactly matches synchronous code. I'm sure this is my misunderstanding of a concept. Could someone explain what am I doing wriong?
Please see example of code below:
```
class Connection:
def __init__(self, re... | You've made a mistake in the way you're calling `send_data`. Right now, you've got this:
```
@asyncio.coroutine
def benchmark():
connection = yield from create_connection(loop=loop, ...)
for i in range(10000):
yield from connection.send_data(...)
```
By using `yield from` inside the for loop, you're ... |
Python curve_fit with multiple independent variables | 28,372,597 | 12 | 2015-02-06T18:41:19Z | 28,373,422 | 10 | 2015-02-06T19:35:55Z | [
"python",
"scipy",
"curve-fitting"
] | Python's [`curve_fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) calculates the best-fit parameters for a function with a single independent variable, but is there a way, using `curve_fit` or something else, to fit for a function with multiple independent variables? For example:... | You can pass `curve_fit` a multi-dimensional array for the independent variables, but then your `func` must accept the same thing. For example, calling this array `X` and unpacking it to `x`, `y` for clarity:
```
import numpy as np
from scipy.optimize import curve_fit
def func(X, a, b, c):
x,y = X
return np.l... |
AttributeError: 'NoneType' object has no attribute 'format' | 28,378,257 | 2 | 2015-02-07T03:33:48Z | 28,378,258 | 7 | 2015-02-07T03:34:23Z | [
"python",
"string",
"python-3.x"
] | ```
print ("Hello World")
print ("{} World").format(Hello)
```
I'm working on my first "Hello World" program and I can get it to work by using the print function and just a simple string text but when I try to use `.format` it gives me the error:
```
AttributeError: 'NoneType' object has no attribute 'format'
```
Is... | Your brackets are wrong
```
print("Hello World")
print("{} World".format('Hello'))
```
Note - the errors
* The `format` function is an attribute of `str` so it needs to be called on the string
* Unless declared, `Hello` is a string and should be `'Hello'`
For Py2 you can do
```
print "{} World".format('Hello')
``` |
Strange behavior: ternary operator for functions | 28,378,825 | 9 | 2015-02-07T05:11:39Z | 28,378,837 | 8 | 2015-02-07T05:14:02Z | [
"python",
"function",
"ternary-operator"
] | Here is a simplified example of my problem. I thought that these functions would have exactly the same behavior:
```
def f1(l):
if type(l[0][0])==list: f=lambda x:x[0][0]
else: f=lambda x:x[0]
l.sort(key=f,reverse=True)
def f2(l):
f=lambda x:x[0][0] if type(l[0][0])==list else lambda x:x[0]
l.sort... | `lambda` has the [lowest precedence among operators](https://docs.python.org/3/reference/expressions.html?highlight=lambda#operator-precedence). This is why Python parses that line as
```
f = lambda x: (x[0][0] if type(l[0][0]) == list else lambda x: x[0])
```
The fix is to wrap individual `lambda`s in parentheses:
... |
Python Pandas does not read the first row of csv file | 28,382,735 | 5 | 2015-02-07T13:34:52Z | 28,382,819 | 11 | 2015-02-07T13:41:51Z | [
"python",
"numpy",
"pandas",
"load"
] | I have a problem with reading CSV(or txt file) on pandas module
Because numpy's loadtxt function takes too much time, I decided to use pandas read\_csv instead.
I want to make a numpy array from txt file with four columns separated by space, and has very large number of rows (like, 256^3. In this example, it is 64^3).... | By default, `pd.read_csv` uses `header=0` (when the `names` parameter is also not specified) which means the first (i.e. 0th-indexed) line is interpreted as column names.
If your data has no header, then use
```
pd.read_csv(..., header=None)
```
---
For example,
```
import io
import pandas as pd
text = '''\
1 2 3... |
Scikit-Learn's Pipeline: A sparse matrix was passed, but dense data is required | 28,384,680 | 9 | 2015-02-07T16:43:17Z | 28,384,887 | 16 | 2015-02-07T17:03:01Z | [
"python",
"numpy",
"pandas",
"scikit-learn"
] | I'm finding it difficult to understand how to fix a Pipeline I created (read: largely pasted from a tutorial). It's python 3.4.2:
```
df = pd.DataFrame
df = DataFrame.from_records(train)
test = [blah1, blah2, blah3]
pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', RandomForestClassifier())])
p... | Unfortunately those two are incompatible. A `CountVectorizer` produces a sparse matrix and the RandomForestClassifier requires a dense matrix. It is possible to convert using `X.todense()`. Doing this will substantially increase your memory footprint.
Below is sample code to do this that I found at <http://zacstewart.... |
Scikit-Learn's Pipeline: A sparse matrix was passed, but dense data is required | 28,384,680 | 9 | 2015-02-07T16:43:17Z | 28,648,525 | 12 | 2015-02-21T17:05:07Z | [
"python",
"numpy",
"pandas",
"scikit-learn"
] | I'm finding it difficult to understand how to fix a Pipeline I created (read: largely pasted from a tutorial). It's python 3.4.2:
```
df = pd.DataFrame
df = DataFrame.from_records(train)
test = [blah1, blah2, blah3]
pipeline = Pipeline([('vectorizer', CountVectorizer()), ('classifier', RandomForestClassifier())])
p... | Random forests in 0.16-dev now accept sparse data. |
C++ appears to be significantly slower than both Python Ruby for Project Euler | 28,389,563 | 3 | 2015-02-08T01:25:54Z | 28,389,580 | 9 | 2015-02-08T01:28:36Z | [
"python",
"c++",
"ruby",
"performance",
"algorithm"
] | I have 3 solutions to the following problem from Project Euler.
> If p is the perimeter of a right angle triangle with integral length
> sides, {a,b,c}, there are exactly three solutions for p = 120.
>
> {20,48,52}, {24,45,51}, {30,40,50}
>
> For which value of p ⤠1000, is the number of solutions maximised?
My thr... | You claim you're timing
> The lookup gen time is the time it takes to construct a **hash table** with 1500 elements, with the keys being a perfect square and the values being their respective roots.
That is true for the Python and Ruby solutions, but in the C++ example you're constructing a `std::map<int, int>`. That... |
C++ appears to be significantly slower than both Python Ruby for Project Euler | 28,389,563 | 3 | 2015-02-08T01:25:54Z | 28,390,049 | 11 | 2015-02-08T02:48:35Z | [
"python",
"c++",
"ruby",
"performance",
"algorithm"
] | I have 3 solutions to the following problem from Project Euler.
> If p is the perimeter of a right angle triangle with integral length
> sides, {a,b,c}, there are exactly three solutions for p = 120.
>
> {20,48,52}, {24,45,51}, {30,40,50}
>
> For which value of p ⤠1000, is the number of solutions maximised?
My thr... | Your code has another serious problem--much more serious than `map` vs. `unordered_map` (at least IMO).
In particular, where you do:
```
int result = square_lookup[(i*i) + (j*j)];
if(result) {
int perimeter = i + j + result;
if(perimeter <= 1000) {
occurences[perimeter] += 1;
}
}
```
This code ... |
OpenCV HOGDescripter Python | 28,390,614 | 4 | 2015-02-08T04:38:02Z | 31,042,147 | 10 | 2015-06-25T05:47:50Z | [
"python",
"opencv",
"image-processing"
] | I was wondering if anyone knew why there is no documentation for HOGDescriptors in the Python bindings of OpenCV.
Maybe I've just missed them, but the only code I've found of them is this thread: [Get HOG image features from OpenCV + Python?](http://stackoverflow.com/questions/6090399/get-hog-image-features-from-openc... | **1. Get Inbuilt Documentation:**
Following command on your python console will help you know the structure of class HOGDescriptor:
`import cv2
help(cv2.HOGDescriptor())`
**2. Example code:**
Here is a snippet of code to initialize an cv2.HOGDescriptor with different parameters (The terms I used here are standard ter... |
Using (Ana)conda within PyCharm | 28,390,961 | 24 | 2015-02-08T05:38:21Z | 31,937,300 | 25 | 2015-08-11T08:53:08Z | [
"python",
"virtualenv",
"pycharm",
"anaconda",
"conda"
] | I've got Pycharm 4 running on my Linux (Ubuntu 14.04) machine. In addition to the system python, I've also got Anaconda installed. Getting the two to play nicely together seems to be a bit of a problem... PyCharm provides some interesting integration for `virtualenv`s and `pip`, but the Anaconda Python distribution see... | I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda *and pip* work well together.
## The short answer
Just manage Conda **from the command line**. PyCharm will automatically notice changes once they happen, just like it does with **pip**.
## The long answer
Create a new Conda envir... |
How do i check the time complexity of a comprehension | 28,393,210 | 4 | 2015-02-08T11:05:19Z | 28,393,223 | 7 | 2015-02-08T11:07:15Z | [
"python",
"python-2.7",
"list-comprehension"
] | I have gone through many blogs regarding python time complexity and posting my doubt:
In case of list comprehensions how will the time complexity be analysed?
For example:
```
x = [(i,xyz_list.count(i)) for i in xyz_set]
```
where `xyz_list = [1,1,1,1,3,3,4,5,3,2,2,4,5,3]` and `xyz_set = set([1, 2, 3, 4, 5])`
So, ... | This is quadratic `O(n^2)`:
```
x = [(i,xyz_list.count(i)) for i in xyz_set]
xyz_list.count(i)) # 0(n) operation
```
for every `i` in `xyz_set` you do a `0(n)` `xyz_list.count(i)`
You can write it using a double for loop which will make it more obvious:
```
res = []
for i in xyz_set: # 0(n)
count = 0
for ... |
Python 3.4 urllib.request error (http 403) | 28,396,036 | 8 | 2015-02-08T15:57:26Z | 28,396,430 | 16 | 2015-02-08T16:34:29Z | [
"python",
"python-3.x",
"urllib"
] | I'm trying to open and parse a html page. In python 2.7.8 I have no problem:
```
import urllib
url = "https://ipdb.at/ip/66.196.116.112"
html = urllib.urlopen(url).read()
```
and everything is fine. However I want to move to python 3.4 and there I get HTTP error 403 (Forbidden). My code:
```
import urllib.request
ht... | It seems like the site does not like the user agent of Python 3.x.
Specifying `User-Agent` will solve your problem:
```
import urllib.request
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
html = urllib.request.urlopen(req).read()
```
**NOTE** Python 2.x urllib version also receives 403 sta... |
Python Django e-mail form example | 28,400,943 | 7 | 2015-02-09T00:09:38Z | 28,419,417 | 24 | 2015-02-09T21:08:59Z | [
"python",
"html",
"django",
"forms",
"email"
] | I wanted to make a contact form on my website. I can find PHP e-mail forms everywhere, but there are no Django examples. I have no idea how to do it myself, so I'm asking if there is anyone who could tell me from scratch - how to make an e-mail contact form on website using Django? | A simple example could be:
**urls.py**
```
from django.conf.urls import patterns, url
from yourapp import views
urlpatterns = patterns(
'',
url(r'^email/$',
views.email,
name='email'
),
url(r'^thanks/$',
views.thanks,
name='thanks'
),
)
```
**forms.py**
`... |
How to remove outline of circle marker when using pyplot.plot in matplotlib | 28,403,179 | 7 | 2015-02-09T05:11:21Z | 28,403,443 | 7 | 2015-02-09T05:37:54Z | [
"python",
"matplotlib"
] | I'm producing a scatter plot using pyplot.plot (instead of scatter - I'm having difficulties with the colormap)
I am plotting using the 'o' marker to get a circle, but the circle always has a black outline.
How do I remove the outline, or adjust its colour? | To remove the outline of a marker, and adjust its color, use `markeredgewidth` (aka `mew`), and `markeredgecolor` (aka `mec`) respectively.
Using [this as a guide](http://matplotlib.org/api/pyplot_api.html):
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x,
... |
Execute a command on Remote Machine in Python | 28,411,960 | 4 | 2015-02-09T14:24:02Z | 28,411,997 | 16 | 2015-02-09T14:26:21Z | [
"python",
"ubuntu",
"terminal",
"tkinter",
"paramiko"
] | I am writing a program in python on Ubuntu, to execute a command `ls -l` on RaspberryPi, connect with Network.
Can anybody guide me on how do I do that? | Sure, there are several ways to do it!
Let's say you've got a Raspberry Pi on a `raspberry.lan` host and your username is `irfan`.
# subprocess
It's the default Python library that runs commands.
You can make it run `ssh` and do whatever you need on a remote server.
scrat [has it covered in his answer](http://sta... |
How to define C-Enumeration types in python | 28,413,638 | 4 | 2015-02-09T15:47:05Z | 28,414,641 | 7 | 2015-02-09T16:35:48Z | [
"python",
"ctypes",
"memmove"
] | I have an enumeration data type in C. How should I declare that in python-ctypes? I want this enum variable to be part of a structure and the assignment of the values to this structure would be done through memmove. After assigning, I want to display the values of each variables in the structure, and for the enum types... | [The Enumeration class suggested by Raj Kumar](http://code.activestate.com/recipes/576415-ctype-enumeration-class/) was broken in that it required the `__init__` to be run to set a new value in a variable, and thus unusable if the value was changed on C side. Here is a fixed version thereof:
```
class EnumerationType(... |
Installing NumPy on Windows | 28,413,824 | 3 | 2015-02-09T15:56:41Z | 28,414,059 | 15 | 2015-02-09T16:08:03Z | [
"python",
"numpy",
"pip"
] | I'm simply unable to install NumPy on Windows. I keep getting this error -
```
PS C:\python27> pip install http://sourceforge.net/projects/numpy/file/NumPy/
Collecting http://sourceforge.net/projects/numpy/files/NumPy/
Downloading http://sourceforge.net/projects/numpy/files/NumPy/ (58kB)
100% |########################... | ## Some explanations
In the first case, I didn't check but I guess that `pip` directly downloads the resource corresponding to the given URL: <http://sourceforge.net/projects/numpy/file/NumPy/>. The server returns a HTML document, while `pip` expects an archive one. So that can't work.
Then there are basically two wa... |
How to continue to the next loop iteration in Python PDB? | 28,414,453 | 5 | 2015-02-09T16:26:20Z | 28,414,723 | 7 | 2015-02-09T16:41:00Z | [
"python",
"debugging",
"pdb"
] | Given this sample code:
```
import pdb
for i in range(10):
pdb.set_trace()
print(str(i))
```
When I get the prompt from PDB, how can I skip an iteration of the loop, with the *continue* loop control statement, when it's also used by PDB, to continue code execution? | You cannot use `continue` because new statements in the debugger need to be *complete* and valid without any other context; `continue` must be given inside a loop construct *when being compiled*. As such using `!continue` (with the `!` to prevent `pdb` from interpreting the command) cannot be used even if the debugger ... |
How to get a list of the <li> elements in an <ul> with Selenium in Python? | 28,415,029 | 2 | 2015-02-09T16:54:56Z | 28,415,391 | 7 | 2015-02-09T17:13:47Z | [
"python",
"html",
"selenium",
"selenium-webdriver",
"gui-testing"
] | I'm using Selenium WebDriver using Python for UI tests and I want to check the following HTML:
```
<ul id="myId">
<li>Something here</li>
<li>And here</li>
<li>Even more here</li>
</ul>
```
From this unordered list I want to loop over the elements and check the text in them. I selected the ul-element by i... | You need to use the `.find_elements_by_` method.
For example,
```
html_list = self.driver.find_element_by_id("myId")
items = html_list.find_elements_by_tag_name("li")
for item in items:
text = item.text
print text
``` |
Scikit-learn: How to run KMeans on a one-dimensional array? | 28,416,408 | 4 | 2015-02-09T18:08:55Z | 28,416,647 | 7 | 2015-02-09T18:22:56Z | [
"python",
"scikit-learn",
"data-mining",
"k-means"
] | I have an array of 13.876(13,876) values between 0 and 1. I would like to apply `sklearn.cluster.KMeans` to only this vector to find the different clusters in which the values are grouped. However, it seems KMeans works with a multidimensional array and not with one-dimensional ones. I guess there is a trick to make it... | You have many samples of 1 feature, so you can reshape the array to (13,876, 1) using numpy's [reshape](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html):
```
from sklearn.cluster import KMeans
import numpy as np
x = np.random.random(13876)
km = KMeans()
km.fit(x.reshape(-1,1)) # -1 will be cal... |
Assert mocked function called with json string in python | 28,417,805 | 4 | 2015-02-09T19:34:09Z | 28,418,085 | 7 | 2015-02-09T19:51:58Z | [
"python",
"json",
"magicmock"
] | Writing some unit tests in python and using MagicMock to mock out a method that accepts a JSON string as input. In my unit test, I want to assert that it is called with given arguments, however I run into issues with the assert statement, since the ordering of objects within the dict doesn't matter, besides in the asse... | Unfortunately, you'll need to do your own checking here. You can get the calls from the mock via it's `call_args_list` attribute (or, simply [`call_args`](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args) in this case since you have already asserted that it is called only once). I'll as... |
NoReverseMatch at /rest-auth/password/reset/ | 28,418,233 | 9 | 2015-02-09T19:59:30Z | 29,505,964 | 9 | 2015-04-08T04:30:32Z | [
"python",
"django",
"authentication"
] | I have a django application with an angular front-end. When from the front-end I try to send a request for passwordReset, I get the following error:
> Reverse for 'password\_reset\_confirm' with arguments '()' and keyword
> arguments '{u'uidb64': 'MTE', u'token': u'3z4-eadc7ab3866d7d9436cb'}'
> not found. 0 pattern(s)... | I also was having this problem, and found this [github issue](http://github.com/Tivix/django-rest-auth/issues/63) it said we need to add
```
url(r'^', include('django.contrib.auth.urls')),
```
on the urlpatterns.
As stated there it says that The PasswordReset view depends on `django.contrib.auth.views.password_reset... |
Why does python's os.walk() not reflect directory deletion? | 28,418,669 | 7 | 2015-02-09T20:25:21Z | 28,419,015 | 9 | 2015-02-09T20:46:37Z | [
"python",
"os.walk"
] | I'm attempting to write a Python function that will recursively delete all empty directories. This means that if directory "a" contains only "b", "b" should be deleted, then "a" should be deleted (since it now contains nothing). If a directory contains anything, it is skipped. Illustrated:
```
top/a/b/
top/c/d.txt
top... | The [documentation](https://docs.python.org/2/library/os.html#os.walk) has this ...
> No matter the value of topdown, the list of subdirectories is
> retrieved before the tuples for the directory and its subdirectories
> are generated. |
Django email with smtp.gmail SMTPAuthenticationError 534 Application-specific password required | 28,421,887 | 2 | 2015-02-10T00:09:26Z | 28,421,995 | 7 | 2015-02-10T00:20:31Z | [
"python",
"django",
"email",
"python-2.7"
] | I am trying to have django send emails but I am getting this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/Library/Python/2.7/site-packages/django/core/... | Because you use 2 factor authentication, you must create a password for this application to access your Google account without the 2 factor auth.
Perform all the steps on the Google support page to generate an application password, and then update your EMAIL\_HOST\_PASSWORD to use that, rather than your regular accoun... |
Can't silence warnings that django-cms produces | 28,424,420 | 5 | 2015-02-10T04:56:48Z | 30,716,923 | 7 | 2015-06-08T18:54:53Z | [
"python",
"django",
"django-cms"
] | I installed Django-cms with the `djangocms-installer` script, and all works fine except that I get a bunch of `RemovedInDjango18Warning` warnings in the shell every time I start the server, do anything with manage.py, or even do a manage.py tab-autocomplete (most annoying)! So thought I'd silence the warnings, using `w... | The surgical way to solve this is to create a **logging filter** that will only filter out warnings that are explicitly specified to be silenced. You know:
> Errors should never pass silently.
> Unless explicitly silenced.
---
With that in mind, here is my filter machinery, all in `settings.py` (for now anyways):
... |
normalize a matrix row-wise in theano | 28,427,416 | 6 | 2015-02-10T08:50:35Z | 28,527,317 | 7 | 2015-02-15T14:54:59Z | [
"python",
"matrix",
"normalization",
"theano"
] | Lets say I have a Matrix `N` with size `n_i x n_o` and I want to normalize it row-wise,i.e.,
the sum of each row should be one. How can I do this in theano?
Motivation: using softmax returns back error for me, so I try to kind of sidestep it by implementing my own version of softmax. | See if the following is useful for you:
```
import theano
import theano.tensor as T
m = T.matrix(dtype=theano.config.floatX)
m_normalized = m / m.sum(axis=1).reshape((m.shape[0], 1))
f = theano.function([m], m_normalized)
import numpy as np
a = np.exp(np.random.randn(5, 10)).astype(theano.config.floatX)
b = f(a)
c... |
Pycharm's code style inspection: ignore/switch off specific rules | 28,428,307 | 9 | 2015-02-10T09:36:29Z | 34,001,622 | 13 | 2015-11-30T15:04:58Z | [
"python",
"ide",
"pycharm",
"pep8"
] | I'm trying to import existing project into PyCharm. I can refactor the code so that PyCharm will be pleased, but we like to have spaces around colons in dictionaries, like this: `{"A" : "B"}`. We also like aligning assignments:
```
a = 1
abc = 3
```
Is there a way to configure PyCharm, so that he'll ignore all erro... | Using **PyCharm 5 (community edition)**, you can do the following. **Code -> Inspect Code**. Then select the required inspection error, and click on the "**Suppress**" option or "**Ignore errors like this**" option on right hand side.
Please see screenshot below:
[
for f in files:
ax.scatter(args) # all datasets end up same colour
#plt.plot(args) # cycles through palette correctly
``` | You have to tell matplotlib which color to use. To Use, for example, seaborn's default color palette:
```
import matplotlib.pyplot as plt
import seaborn as sns
import itertools
ax=fig.add_subplot(111)
palette = itertools.cycle(sns.color_palette())
for f in files:
ax.scatter(args, color=next(palette))
```
The [`... |
TypeError: Type str doesn't support the buffer API when splitting string | 28,431,269 | 2 | 2015-02-10T12:07:38Z | 28,431,304 | 7 | 2015-02-10T12:09:09Z | [
"python",
"python-3.x"
] | Hi all I have this code:
```
data = data.split('&')
```
And I get the following error:
> data = data.split('&') TypeError: Type str doesn't support the buffer
> API
How to split my string? | `data`is a `bytes` object. You can only use another `bytes` value to split it, you can use a `bytes` literal (starting with the `b` prefix) to create one:
```
data.split(b'&')
``` |
How to change default Anaconda python environment | 28,436,769 | 36 | 2015-02-10T16:31:05Z | 28,460,907 | 24 | 2015-02-11T17:44:45Z | [
"python",
"python-2.7",
"python-3.x",
"environment",
"anaconda"
] | I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from... | First, make sure you have the latest version of conda by running
```
conda update conda
```
Then run
```
conda update --all python=3.5
```
This will attempt to update all your packages in your root environment to Python 3 versions. If it is not possible (e.g., because some package is not built for Python 3), it wil... |
How to change default Anaconda python environment | 28,436,769 | 36 | 2015-02-10T16:31:05Z | 34,376,031 | 10 | 2015-12-19T22:27:48Z | [
"python",
"python-2.7",
"python-3.x",
"environment",
"anaconda"
] | I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from... | Under Linux there is an easier way to set the default environment by modifying `~/.bashrc`.
At the end you'll find something like
```
# added by Anaconda 2.1.0 installer
export PATH="/home/user/anaconda/bin:$PATH"
```
Replace it with
```
# set python3 as default
export PATH="/home/jev/anaconda/envs/python3/bin:$PATH... |
pylint 1.4 reports E1101(no-member) on all C extensions | 28,437,071 | 18 | 2015-02-10T16:44:19Z | 28,442,092 | 21 | 2015-02-10T21:25:26Z | [
"python",
"pylint",
"python-extensions"
] | We've been long-time fans of `pylint`. Its static analysis has become a critical part of all our python projects and has saved tons of time chasing obscure bugs. But after upgrading from 1.3 -> 1.4, almost all compiled c extensions result in E1101(no-member) errors.
Projects that previously run perfectly clean through... | Shortly after posting my question, I found the answer. The change was in fact done on purpose as a security measure. Pylint imports modules to effectively identify valid methods and attributes. It was decided that importing c extensions that are not part of the python stdlib is a security risk and could introduce malic... |
Django manage.py Unknown command: 'syncdb' | 28,444,614 | 22 | 2015-02-11T00:41:02Z | 28,444,650 | 77 | 2015-02-11T00:44:16Z | [
"python",
"django",
"django-syncdb",
"syncdb"
] | I'm trying to follow [this tutorial](http://www.creativebloq.com/netmag/get-started-django-7132932) but I'm stuck on the 5th step.
When I execute
[~/Django Projects/netmag$] `python manage.py syncdb`
I get the following error message :
```
Unknown command: 'syncdb'
Type 'manage.py help' for usage.
```
and here is ... | `syncdb` command is [deprecated](https://docs.djangoproject.com/en/1.7/ref/django-admin/#syncdb) in django 1.7. Use the `python manage.py migrate` instead. |
Writing to hbase table from python (happybase) | 28,456,422 | 2 | 2015-02-11T14:08:51Z | 30,013,985 | 8 | 2015-05-03T12:47:00Z | [
"python",
"hadoop",
"hbase",
"thrift",
"happybase"
] | I am running a map-reduce job and now I want to enter values into hbase. I stream values from the map-reduce job over stdin and have a python script that inserts (puts) rows over [happybase](http://happybase.readthedocs.org/).
I am running into different kinds of problems, doing the put from python. The most recent pr... | Happybase author here.
This line in your code contains an error:
```
>>> table.put('2',{'f1','hey'}) # fails, see log
```
The `{'f1', 'hey'}` is a set literal, while you should pass a dict instead. I assume you meant this?
```
>>> table.put('2',{'f1': 'hey'})
``` |
Installing numpy from wheel format: "...is not a supported wheel on this platform" | 28,460,783 | 3 | 2015-02-11T17:36:29Z | 28,460,861 | 12 | 2015-02-11T17:41:46Z | [
"python",
"numpy",
"matplotlib",
"pip",
"python-wheel"
] | I realize a question that relates to this has already been asked at [Cannot install numpy from wheel format](http://stackoverflow.com/questions/28107123/cannot-install-numpy-from-wheel-format/28460036#28460036) , but the solution presented there does not work for me. I have asked on that thread too (by answering!) but ... | The "cp26" in that filename means "CPython 2.6". If you're using Python 3.4 you'll need a file that has "cp34" in the filename. |
Django 1.7.3 - Lookup failed for model referenced by field | 28,468,646 | 7 | 2015-02-12T03:13:25Z | 29,307,696 | 15 | 2015-03-27T18:26:50Z | [
"python",
"django",
"postgresql",
"django-migrations"
] | I am trying create a new model with Django, but I keep running into the error `Lookup failed for model referenced by field help.HelpDefinition.org: account.Organization`. `Organization` has been imported. You can see the model below.
*models.py*
```
org = models.ForeignKey(Organization, unique=True)
help_type = model... | It happens when you change the target objects in relationship. Even if they have the same name and fields they are not the same objects. I had the same issue and deleting all previous migrations from `migrations` folder solved it. |
what is wrong with my factorial code in python | 28,475,637 | 3 | 2015-02-12T10:55:25Z | 28,475,657 | 9 | 2015-02-12T10:56:27Z | [
"python",
"python-2.7"
] | I have the following code for calculating the factorial of a number in python. but I couldnt understand why I am getting the answer as 1.
can some one correct my code. I want to calculate the factorial without using recursion.
```
def factorial (n):
result =1
num = n
while n<1:
res... | ```
while n < 1:
```
should instead be
```
while num > 1:
``` |
Combining random forest models in scikit learn | 28,489,667 | 3 | 2015-02-12T23:11:56Z | 28,508,619 | 7 | 2015-02-13T20:58:18Z | [
"python",
"python-2.7",
"scikit-learn",
"classification",
"random-forest"
] | I have two RandomForestClassifier models, and I would like to combine them into one meta model. They were both trained using similar, but different, data. How can I do this?
```
rf1 #this is my first fitted RandomForestClassifier object, with 250 trees
rf2 #this is my second fitted RandomForestClassifier object, also ... | I believe this is possible by modifying the `estimators_` and `n_estimators` attributes on the RandomForestClassifier object. Each tree in the forest is stored as a DecisionTreeClassifier object, and the list of these trees is stored in the `estimators_` attribute. To make sure there is no discontinuity, it also makes ... |
How to combine python asyncio with threads? | 28,492,103 | 11 | 2015-02-13T03:42:00Z | 28,492,261 | 17 | 2015-02-13T03:59:35Z | [
"python",
"multithreading",
"python-asyncio",
"aiohttp"
] | I have successfully built a [RESTful microservice](https://github.com/fxstein/SentientHome/blob/develop/engine/event.engine.py) with Python asyncio and aiohttp that listens to a POST event to collect realtime events from various feeders.
It then builds an in-memory structure to cache the last 24h of events in a nested... | It's pretty simple to delegate a method to a thread or sub-process using [`BaseEventLoop.run_in_executor`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_in_executor):
```
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
def cpu_bound_operation(x):
... |
Precision of repr(f), str(f), print(f) when f is float | 28,493,114 | 4 | 2015-02-13T05:32:36Z | 28,493,269 | 11 | 2015-02-13T05:46:28Z | [
"python",
"floating-point-precision"
] | If I run:
```
>>> import math
>>> print(math.pi)
3.141592653589793
```
Then pi is printed with 16 digits,
However, according to:
```
>>> import sys
>>> sys.float_info.dig
15
```
My precision is 15 digits.
So, should I rely on the last digit of that value (i.e. that the value of Ï indeed is 3.141592653589793nnnn... | **TL;DR**
The last digit of `str(float)` or `repr(float)` can be "wrong" in that it seems that the decimal representation is not correctly rounded.
```
>>> 0.100000000000000040123456
0.10000000000000003
```
But that value is still closer to the original than `0.1000000000000000` (with 1 digit less).
In the case of ... |
how to check which version of nltk, scikit learn installed? | 28,501,072 | 15 | 2015-02-13T13:46:40Z | 28,501,150 | 24 | 2015-02-13T13:51:06Z | [
"python",
"linux",
"shell",
"scikit-learn",
"nltk"
] | In shell script I am checking whether this packages are installed or not, if not installed then install it. So withing shell script:
```
import nltk
echo nltk.__version__
```
but it stops shell script at `import` line
in linux terminal tried to see in this manner:
```
which nltk
```
which gives nothing thought it ... | `import nltk` is Python syntax, and as such won't work in a shell script.
To test the version of `nltk` and `scikit_learn`, you can write a **Python script** and run it. Such a script may look like
```
import nltk
import sklearn
print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn versio... |
how to check which version of nltk, scikit learn installed? | 28,501,072 | 15 | 2015-02-13T13:46:40Z | 28,501,202 | 13 | 2015-02-13T13:53:51Z | [
"python",
"linux",
"shell",
"scikit-learn",
"nltk"
] | In shell script I am checking whether this packages are installed or not, if not installed then install it. So withing shell script:
```
import nltk
echo nltk.__version__
```
but it stops shell script at `import` line
in linux terminal tried to see in this manner:
```
which nltk
```
which gives nothing thought it ... | Try this:
```
$ python -c "import nltk; print nltk.__version__"
``` |
ValueError "Expected version spec" when installing local wheel via pip | 28,502,283 | 5 | 2015-02-13T14:55:40Z | 28,507,753 | 12 | 2015-02-13T19:57:37Z | [
"python",
"python-2.7",
"pip",
"python-wheel"
] | I have a closed-source Python module I am developing and would like to share with people in my workplace. I have built a wheel via `setup.py bdist_wheel` with this setup.py file:
```
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='mypkg',
version='0.0.1',
description='tools ... | I was using a very out-of-date version of PIP.
```
$ pip -V
pip 1.3.1 from C:\Python27\lib\site-packages (python 2.7)
```
I upgraded to `pip 6.0.8` and all is well. |
Python - List files and folders in Bucket | 28,505,222 | 6 | 2015-02-13T17:24:59Z | 28,510,351 | 7 | 2015-02-13T23:16:25Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] | I am playing around with the `boto` library to access an amazon s3 bucket. I am trying to list all the file and folders in a given folder in the bucket. I use this to get all the file and folders:
```
for key in bucket.list():
print key.name
```
This gives me all the files and folders within the root , along with... | All of the information is the other answers is correct but because so many people store objects with path-like keys in S3, the API does provide some tools to help you deal with them.
For example, in your case if you wanted to list only the "subdirectories" of `root` without listing all of the objects below that you wo... |
Why is an inline if/else faster than a .get() in Python? | 28,509,261 | 10 | 2015-02-13T16:35:47Z | 28,509,262 | 28 | 2015-02-13T16:44:24Z | [
"python",
"performance"
] | I was reviewing some code earlier and the developer wrote an inline `if`/`else` rather than a `get()` to retrieve an element from a list if it exists (otherwise give it a default value). I decided to spring some `timeit` code on repl and was pretty confused by the result. The `if`/`else` takes 1/3 the time of the `get(... | The `D.get()` path includes an attribute lookup, and a method call:
```
>>> import dis
>>> D = {"a": 1, "b": 2, "c": 3}
>>> def gt(): return D.get('a', 1)
...
>>> dis.dis(gt)
1 0 LOAD_GLOBAL 0 (D)
3 LOAD_ATTR 1 (get)
6 LOAD_CONST 1 ('a'... |
how to add custom search box in django admin | 28,512,710 | 9 | 2015-02-14T05:20:41Z | 28,512,855 | 19 | 2015-02-14T05:46:25Z | [
"python",
"django"
] | I know this is gonna be a very basic question.
In django i have successfully created a admin panel.Now i want a add a custom search box in one of my field namely `Photo` field.But i don't know **how to add custom search box** in a django admin panel.If i get some proper hints than i believe that i can do it.
**Admin.... | Use the [`search_fields`](https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields) attribute of the `ModelAdmin`:
```
class PhotoAdmin(admin.ModelAdmin):
...
search_fields = ('name', 'description', 'keyword', )
``` |
Problems using psycopg2 on Mac OS (Yosemite) | 28,515,972 | 42 | 2015-02-14T13:12:19Z | 28,618,942 | 70 | 2015-02-19T23:22:24Z | [
"python",
"eclipse",
"osx",
"postgresql",
"psycopg2"
] | Currently i am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
> Error: pg\_config executable not found.
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATHâ`... | You need to replace the /usr/lib/libpq.5.dylib library because its version is too old.
Here's my solution to this problem:
```
$ sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
$ sudo ln -s /Library/PostgreSQL/9.4/lib/libpq.5.dylib /usr/lib
``` |
Problems using psycopg2 on Mac OS (Yosemite) | 28,515,972 | 42 | 2015-02-14T13:12:19Z | 29,605,817 | 25 | 2015-04-13T12:51:48Z | [
"python",
"eclipse",
"osx",
"postgresql",
"psycopg2"
] | Currently i am installing psycopg2 for work within eclipse with python.
I am finding a lot of problems:
1. The first problem `sudo pip3.4 install psycopg2` is not working and it is showing the following message
> Error: pg\_config executable not found.
FIXED WITH:`export PATH=/Library/PostgreSQL/9.4/bin/:"$PATHâ`... | If you are using PostgresApp, you need to run the following two commands:
```
sudo mv /usr/lib/libpq.5.dylib /usr/lib/libpq.5.dylib.old
sudo ln -s /Applications/Postgres.app/Contents/Versions/9.4/lib/libpq.5.dylib /usr/lib
``` |
Can I create model in Django without automatic ID? | 28,516,086 | 3 | 2015-02-14T13:26:11Z | 28,516,109 | 11 | 2015-02-14T13:29:22Z | [
"python",
"django",
"orm",
"model"
] | I need a table without a primary key (in Django it was created automatically). So my question is: **Can I create a model without an ID/primary key?**
I'm using Django 1.7. | You *can* create a model without an auto-incrementing key, but you *cannot* create one without a primary key.
From the [Django Documentation](https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields):
> If Django sees youâve explicitly set [`Field.primary_key`](https://docs.djangoproject... |
How to check if an object is created with `with` statement? | 28,517,238 | 7 | 2015-02-14T15:41:58Z | 28,517,416 | 9 | 2015-02-14T16:04:09Z | [
"python",
"with-statement"
] | I would like to ensure that the class is only instantiated within a "with" statement.
i.e. this one is ok:
```
with X() as x:
...
```
and this is not:
```
x = X()
```
How can I ensure such functionality? | There is no straight forward way, as far as I know. But, you can have a boolean flag, to check if `__enter__` was invoked, before the actual methods in the objects were called.
```
class MyContextManager(object):
def __init__(self):
self.__is_context_manager = False
def __enter__(self):
print... |
How to check if an object is created with `with` statement? | 28,517,238 | 7 | 2015-02-14T15:41:58Z | 28,517,560 | 7 | 2015-02-14T16:19:10Z | [
"python",
"with-statement"
] | I would like to ensure that the class is only instantiated within a "with" statement.
i.e. this one is ok:
```
with X() as x:
...
```
and this is not:
```
x = X()
```
How can I ensure such functionality? | There is no foolproof approach to ensure that an instance is constructed within a `with` clause, but you can create an instance in the `__enter__` method and return that instead of `self`; this is the value that will be assigned into `x`. Thus you can consider `X` as a factory that creates the actual instance in its `_... |
Read Excel cell value and not the formula computing it -openpyxl | 28,517,508 | 3 | 2015-02-14T16:14:34Z | 35,624,928 | 9 | 2016-02-25T10:40:13Z | [
"python",
"openpyxl"
] | I am using openpyxl to read cell value (excel addin-webservice update this column.
)
I have used `data_only = True` but it is not showing the current cell value instead it is the value stored the last time Excel read the sheet.
```
wbFile = openpyxl.load_workbook(filename = xxxx,data_only=True)
wsFile = wbFile[c_sShe... | ```
wb = openpyxl.load_workbook(filename, data_only=True)
```
The `data_only` flag helps. |
How can I upgrade numpy? | 28,517,937 | 10 | 2015-02-14T17:00:00Z | 28,518,106 | 17 | 2015-02-14T17:17:21Z | [
"python",
"opencv",
"numpy",
"homebrew",
"anaconda"
] | When I installed OpenCV using brew, I got this problem whenever I run this command to test `python -c "import cv2"`
```
RuntimeError: module compiled against API version 9 but this version of numpy is 6
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: numpy.core.multiarray failed ... | Because we have two numpy in the system. One is install by brew and second is install by pip. So in order to solve the problem, we need to delete one and use the default numpy install by opencv.
Check the path
```
import numpy
print numpy.__path__
```
and manually delete it using `rm` |
How can I upgrade numpy? | 28,517,937 | 10 | 2015-02-14T17:00:00Z | 34,640,003 | 7 | 2016-01-06T18:19:24Z | [
"python",
"opencv",
"numpy",
"homebrew",
"anaconda"
] | When I installed OpenCV using brew, I got this problem whenever I run this command to test `python -c "import cv2"`
```
RuntimeError: module compiled against API version 9 but this version of numpy is 6
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: numpy.core.multiarray failed ... | The error you mentioned happens when you have two versions of numpy on your system. As you mentioned the version of numpy you imported is still not upgraded since you tried to upgrade it through pip (It will upgrade the version exist in `'/Library/Python/2.7/site-packages'` ). However Python still loads the packages fr... |
Play Animations in GIF with Tkinter | 28,518,072 | 6 | 2015-02-14T17:13:39Z | 28,519,037 | 7 | 2015-02-14T18:54:26Z | [
"python",
"animation",
"tkinter",
"gif"
] | I've been trying to play an animated gif using `Tkinter.PhotoImage`, but haven't been seeing any success. It displays the image, but not the animation. The following is my code:
```
root = Tkinter.Tk()
photo = Tkinter.PhotoImage(file = "path/to/image.gif")
label = Tkinter.Label(image = photo)
label.pack()
root.mainloo... | You have to drive the animation yourself in Tk. An animated gif consists of a number of frames in a single file. Tk loads the first frame but you can specify different frames by passing an index parameter when creating the image. For example:
```
frame2 = PhotoImage(file=imagefilename, format="gif -index 2")
```
If y... |
requests: how to disable / bypass proxy | 28,521,535 | 6 | 2015-02-14T23:42:50Z | 28,521,696 | 19 | 2015-02-15T00:06:48Z | [
"python",
"python-requests"
] | I am getting an url with:
```
r = requests.get("http://myserver.com")
```
As I can see in the 'access.log' of "myserver.com", the client's system proxy is used. But I want to disable using proxies at all with `requests`. | The only way I'm currently aware of for disabling proxies *entirely* is the following:
* Create a session
* Set `session.trust_env` to `False`
* Create your request using that session
```
import requests
session = requests.Session()
session.trust_env = False
response = session.get('http://www.stackoverflow.com')
``... |
Why java String.length gives different result than python len() for the same string | 28,524,215 | 4 | 2015-02-15T08:17:33Z | 28,524,237 | 8 | 2015-02-15T08:21:27Z | [
"java",
"python",
"string"
] | I have a string like the follwoing
`("استÙÙØ§Ø±" OR "Ø§ÙØ£Ø³ØªÙÙØ§Ø±" OR "Ø§ÙØ§Ø³ØªÙÙØ§Ø±" OR "Ø§ÙØ¥Ø³ØªÙÙØ§Ø±" OR "ÙØ§Ø³ØªÙÙØ§Ø±" OR "باستÙÙØ§Ø±" OR "ÙØ³ØªÙÙØ§Ø±" OR "ÙØ§Ø³ØªÙÙØ§Ø±" OR "ÙØ§ÙأستÙÙØ§Ø±" OR "Ø¨Ø§ÙØ£Ø³ØªÙÙØ§Ø±" OR "ÙÙØ£Ø³ØªÙÙØ§Ø±" OR "ÙØ§ÙأستÙÙØ§Ø±" OR "Ù... | It seems like , in python (2.x), you count the byte length, not the character count.
Convert the byte string into unicode object using `str.decode`, then count the characters:
```
len(byte_string_object.decode('utf-8'))
```
You may also need to strip surround spaces:
```
len(byte_string_object.decode('utf-8').strip... |
Convert map object to numpy array in python 3 | 28,524,378 | 2 | 2015-02-15T08:40:49Z | 28,526,475 | 8 | 2015-02-15T13:18:59Z | [
"python",
"python-3.x",
"numpy"
] | In Python 2 I could do the following:
```
import numpy as np
f = lambda x: x**2
seq = map(f, xrange(5))
seq = np.array(seq)
print seq
# prints: [ 0 1 4 9 16]
```
In Python 3 it does not work anymore:
```
import numpy as np
f = lambda x: x**2
seq = map(f, range(5))
seq = np.array(seq)
print(seq)
# prints: ... | One more alternative, other than the valid solutions @jonrsharpe already pointed out is to use [`np.fromiter`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html):
```
>>> import numpy as np
>>> f = lambda x: x**2
>>> seq = map(f, range(5))
>>> np.fromiter(seq, dtype=np.int)
array([ 0, 1, 4,... |
Traceback when updating status on twitter via Tweepy | 28,527,352 | 9 | 2015-02-15T14:57:59Z | 28,527,452 | 20 | 2015-02-15T15:06:55Z | [
"python",
"twitter",
"tweepy"
] | I've been trying to post the readings from my Rpi on Twitter using `tweepy`, but first I wanted to check if `tweepy` was working properly, but it's not.
I installed the packages properly, but when I'm trying to run a simple code to post something, I got an error (Yes, I already created an app and have the 4 credential... | The first positional argument to the `update_status()` method is interpreted as the [`media_ids` parameter](https://dev.twitter.com/rest/reference/post/statuses/update#api-param-media_ids). You need to explicitly name your `status` parameter to avoid this:
```
api.update_status(status=single_tweet)
```
This is a [rec... |
Why am i getting WindowsError: [Error 5] Access is denied? | 28,528,020 | 10 | 2015-02-15T16:03:49Z | 28,528,104 | 13 | 2015-02-15T16:11:54Z | [
"python",
"program-files",
"windowserror"
] | Trying to create program that adds folders into program files-recieving this error:
```
WindowsError: [Error 5] Access is denied 'C:\\Program Files\\IMP'
```
Here is my code
```
import os, sys, random
numb= 1
x=True
while x==True:
newpath = ((r'C:\Program Files\IMP\folder_%s') % (numb))
if not os.path.exists... | Because you have to have the "system administrator privileges" to create dirs under `C:\Program Files`.
So try run the script with system administrators privilege.
---
To start a command prompt as an administrator
1. Click Start.
2. In the Start Search box, type `cmd`, and then press `CTRL`+`SHIFT`+`ENTER`.
3. Run ... |
Dynamically changing dropdowns in IPython notebook widgets and Spyre | 28,529,157 | 10 | 2015-02-15T17:53:48Z | 29,333,253 | 10 | 2015-03-29T18:41:00Z | [
"python",
"ipython",
"ipython-notebook"
] | I have a dropdown in an IPython notebook (as part of the HTML widgets) and in a Spyre app (as a `dropdown` element), say to pick a continent and I'd like to add a second dropdown to select the country within the continent. Now obviously the options within the second dropdown are dependent on the value of the first one.... | Use `interactive` instead of `interact` and update your widget:
```
from IPython.html import widgets
from IPython.display import display
geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}
def print_city(city):
print city
def select_city(country):
cityW.options = geo[country]
scW = widgets.Select(options=geo... |
How to test a function inside a function? | 28,531,452 | 4 | 2015-02-15T21:35:20Z | 28,531,465 | 8 | 2015-02-15T21:36:32Z | [
"python",
"python-3.x"
] | If I have a function like this:
```
def any_function(type_name, field_name):
def another_function(name):
...
```
How would I go about testing `any_function`?
PS: Just in case I use the wrong "definition" of testing, I mean by writing
`print(any_function(...))` | You wouldn't test an inner function. You'd just test the functionality of the outer function; the inner function is an implementation detail, not the API presented by the unit. You'd normally use an inner function to produce a closure, making the inner function dependent on the scope.
Now, if the inner function is ret... |
Getting parameter name | 28,535,795 | 8 | 2015-02-16T06:38:33Z | 28,535,925 | 7 | 2015-02-16T06:48:55Z | [
"python",
"python-2.7"
] | I searched about it and got the following, [python obtain variable name of argument in a function](http://stackoverflow.com/questions/11583526/python-obtain-variable-name-of-argument-in-a-function?answertab=oldest#tab-top) but i am not getting required answer and am actually getting an error saying add () takes exactly... | You should use func\_code.co\_varnames attribute of your function to access parameters names:
```
def add(arg1, arg2):
z = arg1 + arg2
print ' '.join(add.func_code.co_varnames[:2]) + ' ' + str(z)
add(10, 5)
```
Output:
```
arg1 arg2 15
```
You can read more about internal attributes here:
<https://docs.pyt... |
How to filter/smooth with SciPy/Numpy? | 28,536,191 | 8 | 2015-02-16T07:10:22Z | 28,541,805 | 10 | 2015-02-16T12:50:56Z | [
"python",
"numpy",
"scipy",
"filtering",
"smoothing"
] | I am trying to filter/smooth signal obtained from a pressure transducer of sampling frequency 50 kHz. A sample signal is shown below:

I would like to obtain a smooth signal obtained by loess in MATLAB (I am not plotting the same data, values are diff... | Here are a couple suggestions.
First, try the `lowess` function from `statsmodels` with `it=0`, and tweak the `frac` argument a bit:
```
In [328]: from statsmodels.nonparametric.smoothers_lowess import lowess
In [329]: filtered = lowess(pressure, time, is_sorted=True, frac=0.025, it=0)
In [330]: plot(time, pressure... |
Save a python 3.x dictionary to JSON | 28,541,705 | 3 | 2015-02-16T12:44:25Z | 28,541,723 | 7 | 2015-02-16T12:45:30Z | [
"python",
"json",
"dictionary"
] | The solution suggested in [this answer](http://stackoverflow.com/a/7100202/671013) allows saving a `dict` into `json`. For instance:
```
import json
with open('data.json', 'wb') as fp:
json.dump(data, fp)
```
However, this doesn't work with `3.x`. I get the following error:
```
TypeError: 'str' does not support ... | remove the `b`:
```
with open('data.json', 'w') as fp:
json.dump(data, fp)
```
[json.dump](https://docs.python.org/3.4/library/json.html#json.dump)
*The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.* |
How convert this type of data <hdf5 object reference> to something more readable in the python? | 28,541,847 | 3 | 2015-02-16T12:52:53Z | 28,544,767 | 7 | 2015-02-16T15:27:12Z | [
"python",
"python-2.7",
"hdf5",
"h5py"
] | I have quite big dataset. All information stored in the hdf5 format file. I found [h5py library](http://docs.h5py.org/en/latest/#) for python. All works properly except of the
```
[<HDF5 object reference>]
```
I have no idea how to convert it in something more readable. Can I do it at all ? Because documentation in t... | My friend answered on my question and I understood how it was easy. But I spent more than 4 hours solving my small problem. The solving is:
```
import numpy as np
import h5py
import time
f = h5py.File('myfile1.mat','r')
#print f.keys()
test = f['db/path']
st = test[0][0]
obj = f[st]
str1 = ''.join(chr(i) for i in o... |
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128) | 28,544,686 | 3 | 2015-02-16T15:23:20Z | 28,544,721 | 10 | 2015-02-16T15:25:07Z | [
"python",
"python-2.7",
"utf-8",
"decode"
] | I'm simply trying to decode \uXXXX\uXXXX\uXXXX-like string. But I get an error:
```
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u041e\u043b\u044c\u0433\u0430'... | Python is trying to be helpful. You *cannot decode* Unicode data, it is already decoded. So Python first will **encode** the data (using the ASCII codec) to get bytes to decode. It is this implicit encoding that fails.
If you have Unicode data, it only makes sense to **encode** to UTF-8, not decode:
```
>>> print u'\... |
Python and RabbitMQ - Best way to listen to consume events from multiple channels? | 28,550,140 | 2 | 2015-02-16T20:52:49Z | 28,552,654 | 9 | 2015-02-17T00:18:48Z | [
"python",
"rabbitmq",
"pika"
] | I have two, separate RabbitMQ instances. I'm trying to find the best way to listen to events from both.
For example, I can consume events on one with the following:
```
credentials = pika.PlainCredentials(user, pass)
connection = pika.BlockingConnection(pika.ConnectionParameters(host="host1", credentials=credentials)... | The answer to "what is the best way" depends heavily on your usage pattern of queues and what you mean by "best". Since I can't comment on questions yet, I'll just try to suggest some possible solutions.
In each example I'm going to assume exchange is already declared.
# Threads
You can consume messages from two que... |
Is there a numpy biginteger? | 28,552,599 | 5 | 2015-02-17T00:13:32Z | 28,552,630 | 8 | 2015-02-17T00:16:28Z | [
"python",
"numpy",
"biginteger"
] | Hmm. There doesn't seem to me a way to store Python's bigintegers in a numpy array. Is there something special you have to do, to declare a numpy array with bigints? | Not specifically, no. You can create an array with `dtype='object'`, which creates an array of Python objects (including but not limited to ints). This will get you a lot of Numpy array-like functionality but few to none of the performance benefits.
Which is to say, an array of Python objects is not significantly diff... |
Python requests.exception.ConnectionError: connection aborted "BadStatusLine" | 28,557,466 | 6 | 2015-02-17T08:18:22Z | 28,564,235 | 9 | 2015-02-17T14:54:05Z | [
"python",
"http",
"http-headers"
] | I am trying to use the Python requests module to issue Http GET commands to access some REST based APIs. The urls are working fine on a RESTClient but when I use the same url in python, I get a connection error.
The code I am trying to execute is:
```
payload={"mac":new_mac,"token":token}
userloginurl="http://192.168... | The problem was with the url. This connection was meant to be established over https and I was using http in the python script. Hence the issue. |
How to update yaml file using python | 28,557,626 | 5 | 2015-02-17T08:28:50Z | 29,604,834 | 7 | 2015-04-13T12:01:57Z | [
"python",
"pyyaml"
] | I have a `some.yaml` file with the below contents.
```
init_config: {}
instances:
- host: <IP>
username: <username>
password: <password>
```
The yaml file should be parsed and updated as below.
```
init_config: {}
instances:
- host: 1.2.3.4
username: User... | The [ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml) package was specifically enhanced (by me starting from PyYAML)) to do this kind of round-trip, programmatic, updating.
If you start with (please note I removed the extra initial spaces):
```
init_config: {}
instances:
- host: <IP> # update w... |
Django MySQL error when creating tables | 28,561,458 | 19 | 2015-02-17T12:26:03Z | 32,454,730 | 21 | 2015-09-08T09:57:33Z | [
"python",
"mysql",
"django"
] | I am building a django app with a MySQL DB. When I run 'python manage.py migrate' for the first time, some tables are created well then some errors appear. The error brought out is:
> django.db.utils.IntegrityError: (1215, 'Cannot add foreign key
> constraint')
When I run this MySQL command -
> SHOW ENGINE INNODB ST... | This will works
```
python manage.py migrate auth
python manage.py migrate
```
The issue because of other migration run before the auth, so this will make sure "authtools"'s migration run first |
Why is 2**100 so much faster than math.pow(2,100)? | 28,563,187 | 6 | 2015-02-17T14:01:36Z | 28,563,800 | 8 | 2015-02-17T14:34:21Z | [
"python",
"performance",
"pow"
] | When discussing the question [Exponentials in python x.\*\*y vs math.pow(x, y)](http://stackoverflow.com/q/20969773/2932052),
[Alfe stated](https://stackoverflow.com/questions/20969773/exponentials-in-python-x-y-vs-math-powx-y#comment31503032_20969773) that there would be no good reason for using `math.pow` instead of ... | Essentially the reason that the power operator looks like it's doing so well in your examples is because Python has most likely [folded the constant](http://en.wikipedia.org/wiki/Constant_folding) at compile time.
```
import dis
dis.dis('3.0 ** 100')
i = 100
dis.dis('3.0 ** i')
```
This gives the following output... |
Make a numpy array monotonic without a Python loop | 28,563,711 | 12 | 2015-02-17T14:30:04Z | 28,563,925 | 13 | 2015-02-17T14:39:43Z | [
"python",
"arrays",
"numpy"
] | I have a 1D array of values which is supposed to be monotonic (let's say decreasing), but there are random regions where the value increases with index.
I need an array where each region is replaced with a value directly preceding it, so that the resulting array is sorted.
So if given array is:
```
a = np.array([10.... | You can use `np.minimum.accumulate` to collect the minimum values as you move through the array:
```
>>> np.minimum.accumulate(a)
array([ 10. , 9.5, 8. , 7.2, 7.2, 7.2, 7. , 5. , 3. ,
2.5, 2.5, 2. ])
```
At each element in the array, this function returns the minimum value seen so far.
I... |
How do I create an "OR" filter using elasticsearch-dsl-py? | 28,564,303 | 6 | 2015-02-17T14:57:20Z | 28,564,809 | 8 | 2015-02-17T15:21:22Z | [
"python",
"elasticsearch",
"boolean",
"dsl"
] | The query below is what I would like to construct using elasticsearch-dsl-py, but I do not know how to do it.
```
GET /my_index/_search
{
"query": {
"filtered": {
"filter": {
"bool": {
"must": [
{
"term": {
"status": "published"
}
... | Solution:
```
s = Search(using=client,
index="my_index"
).filter(
"term", status=PUBLISHED
).filter(
"or", [F("range", start_publication={"lte": now}, ),
F("missing", field="start_publication")]
).filter(
"or", [F("range", end_publication={"gte": now}, ),
... |
Is it safe to use frozen set as Dict key? | 28,566,797 | 4 | 2015-02-17T16:58:14Z | 28,566,901 | 7 | 2015-02-17T17:03:20Z | [
"python",
"python-2.7",
"hashmap",
"frozenset"
] | It obviously works but are there cases where two sets of same elements happen to add two entries in Dict? I guess I got this condition earlier and changed my code from `frozenset(...)` to `tuple(sorted(frozenset(...)))`. Can someone who knows how Dict and frozenset implementation confirm if that is required or not? | According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.
From the [FrozenSet docs](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset)
> The frozenset type is immutabl... |
filename.whl is not supported wheel on this platform | 28,568,070 | 70 | 2015-02-17T18:05:06Z | 28,568,118 | 79 | 2015-02-17T18:07:28Z | [
"python",
"pip"
] | I would like to install `scipy-0.15.1-cp33-none-win_amd64.whl` that I have saved to local drive. I am using:
```
pip 6.0.8 from C:\Python27\Lib\site-packages
python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)]
```
when I run:
```
pip install scipy-0.15.1-cp33-none-win_amd64.whl
```
I get the f... | `cp33` means `CPython 3.3` you need `scipyâ0.15.1âcp27ânoneâwin_amd64.whl` instead. |
filename.whl is not supported wheel on this platform | 28,568,070 | 70 | 2015-02-17T18:05:06Z | 36,046,420 | 60 | 2016-03-16T20:36:04Z | [
"python",
"pip"
] | I would like to install `scipy-0.15.1-cp33-none-win_amd64.whl` that I have saved to local drive. I am using:
```
pip 6.0.8 from C:\Python27\Lib\site-packages
python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)]
```
when I run:
```
pip install scipy-0.15.1-cp33-none-win_amd64.whl
```
I get the f... | This can also be caused by using an out-of-date `pip` with a recent wheel file.
I was very confused, because I was installing `numpy-1.10.4+mkl-cp27-cp27m-win_amd64.whl` (from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/)), and it is definitely the correct version for my Python installation (Windows 64-bit Python... |
filename.whl is not supported wheel on this platform | 28,568,070 | 70 | 2015-02-17T18:05:06Z | 36,158,157 | 27 | 2016-03-22T15:10:42Z | [
"python",
"pip"
] | I would like to install `scipy-0.15.1-cp33-none-win_amd64.whl` that I have saved to local drive. I am using:
```
pip 6.0.8 from C:\Python27\Lib\site-packages
python 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)]
```
when I run:
```
pip install scipy-0.15.1-cp33-none-win_amd64.whl
```
I get the f... | I had the same problem while installing scipy-0.17.0-cp35-none-win\_amd64.whl and my Python version is 3.5. It returned the same error message:
```
scipy-0.17.0-cp35-none-win_amd64.whl is not supported wheel on this platform.
```
I realized that amd64 is not about my Windows, but about the Python version. Actually I... |
Get last three digits of an integer | 28,570,505 | 6 | 2015-02-17T20:26:55Z | 28,570,538 | 17 | 2015-02-17T20:29:01Z | [
"python",
"integer",
"int",
"digit"
] | I wish to change an integer such as 23457689 to 689, 12457245 to 245 etc.
I do not require the numbers to be rounded and do not wish to have to convert to String.
Any ideas how this can be done in Python 2.7? | Use the `%` operation:
```
>>> x = 23457689
>>> x % 1000
689
```
`%` is the `mod` (i.e. [`modulo`](https://en.wikipedia.org/wiki/Modulo_operation)) operation. |
Get last three digits of an integer | 28,570,505 | 6 | 2015-02-17T20:26:55Z | 28,570,584 | 9 | 2015-02-17T20:31:27Z | [
"python",
"integer",
"int",
"digit"
] | I wish to change an integer such as 23457689 to 689, 12457245 to 245 etc.
I do not require the numbers to be rounded and do not wish to have to convert to String.
Any ideas how this can be done in Python 2.7? | To handle both positive and negative integers correctly:
```
>>> x = -23457689
>>> print abs(x) % 1000
689
```
As a function where you can select the number of leading digits to keep:
```
import math
def extract_digits(integer, digits=3, keep_sign=False):
sign = 1 if not keep_sign else int(math.copysign(1, integ... |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,572,898 | 58 | 2015-02-17T23:04:41Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | There are four strong cases for preferring Python's more-specific methods in the [`os`](https://docs.python.org/2/library/os.html) module over using [`os.system`](https://docs.python.org/2/library/os.html#os.system) or the [`subprocess`](https://docs.python.org/2/library/subprocess.html) module when executing a command... |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,572,958 | 21 | 2015-02-17T23:08:08Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | For a simple reason - when you call a shell function, it creates a sub-shell which is destroyed after your command exists, so if you change directory in a shell - it does not affect your environment in Python.
Besides, creating sub-shell is time consuming, so using OS commands directly will impact your performance
**... |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,572,983 | 132 | 2015-02-17T23:10:03Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | It is safer. To give you an idea here is an example script
```
import os
file = raw_input("Please enter a file: ")
os.system("chmod 777 " + file)
```
If the input from the user was `test; rm -rf ~` this would then delete the home directory.
This is why it is safer to use the built in function.
Hence why you should ... |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,573,425 | 16 | 2015-02-17T23:47:46Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | Shell call are OS specific whereas Python os module functions are not, in most of the case. And it avoid spawning a subprocess. |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,582,402 | 11 | 2015-02-18T11:23:11Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | It's far more efficient. The "shell" is just another OS binary which contains a lot of system calls. Why incur the overhead of creating the whole shell process just for that single system call?
The situation is even worse when you use `os.system` for something that's not a shell built-in. You start a shell process whi... |
Why use Python's os module methods instead of executing shell commands directly? | 28,572,833 | 149 | 2015-02-17T23:00:28Z | 28,583,621 | 317 | 2015-02-18T12:23:30Z | [
"python",
"linux",
"operating-system"
] | I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via `os.system()` or `subprocess.call()`?
For example, why would I want to use `os.chmod` ... | 1. It's **faster**, `os.system` and `subprocess.call` create new processes which is unnecessary for something this simple. In fact, `os.system` and `subprocess.call` with the `shell` argument usually create at least two new processes: the first one being the shell, and the second one being the command that you're runni... |
@login_required trouble in flask app | 28,575,234 | 4 | 2015-02-18T03:03:04Z | 28,575,314 | 10 | 2015-02-18T03:12:11Z | [
"python",
"flask",
"flask-login",
"login-required"
] | I have created a blueprint that handles authenticating. This blue print uses Flask-Login. And has the following, as well as more code not shown.
In the blueprint I have the following:
```
from flask.ext.login import LoginManager
from flask.ext.login import UserMixin
from flask.ext.login import current_user
from flask... | You have to change the order of the decorators. Quoting the [Flask documentation](http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/#login-required-decorator):
> So how would you use that decorator now? Apply it as innermost
> decorator to a view function. When applying further decorators, always
> remember tha... |
How to bind (authenticate) a user with ldap3 in python3 | 28,575,359 | 4 | 2015-02-18T03:17:59Z | 28,616,485 | 7 | 2015-02-19T20:42:35Z | [
"python",
"python-3.x",
"ldap"
] | I'm trying to update some code to python3, using [ldap3](http://ldap3.readthedocs.org/en/latest/quicktour.html) version '0.9.7.4'.
(<https://pypi.python.org/pypi/ldap3>)
Previously, I used python-ldap with python2 to authenticate a user like this:
```
import ldap
address = "ldap://HOST:389"
con = ldap.initialize(addr... | I'm the author of ldap3, please set `raise_exceptions=False` in the Connection definition and check the `connection.result` after the bind. You should get the reason why your `bind()` is unsuccessful. |
How can I normalize the data in a range of columns in my pandas dataframe | 28,576,540 | 7 | 2015-02-18T05:24:03Z | 28,577,480 | 13 | 2015-02-18T06:38:28Z | [
"python",
"pandas"
] | Suppose I have a pandas data frame surveyData:
I want to normalize the data in each column by performing:
```
surveyData_norm = (surveyData - surveyData.mean()) / (surveyData.max() - surveyData.min())
```
This would work fine if my data table only contained the columns I wanted to normalize. However, I have some col... | You can perform operations on a sub set of rows or columns in pandas in a number of ways. One useful way is indexing:
```
# Assuming same lines from your example
cols_to_norm = ['Age','Height']
survey_data[cols_to_norm] = survey_data[cols_to_norm].apply(lambda x: (x - x.mean()) / (x.max() - x.min()))
```
This will ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.