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 |
|---|---|---|---|---|---|---|---|---|---|
Shuffle a numpy array | 22,426,609 | 7 | 2014-03-15T16:38:13Z | 22,426,647 | 10 | 2014-03-15T16:41:09Z | [
"python",
"random",
"numpy",
"shuffle"
] | I have a 2-d numpy array that I would like to shuffle. Is the best way to reshape it to 1-d, shuffle and reshape again to 2-d or is it possible to shuffle without reshaping?
just using the random.shuffle doesn't yield expected results and numpy.random.shuffle shuffles only rows:
```
import random
import numpy as np
a... | You can tell `np.random.shuffle` to act on the flattened version:
```
>>> a = np.arange(9).reshape((3,3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.random.shuffle(a.flat)
>>> a
array([[3, 5, 8],
[7, 6, 2],
[1, 4, 0]])
``` |
Shuffle a numpy array | 22,426,609 | 7 | 2014-03-15T16:38:13Z | 22,426,661 | 7 | 2014-03-15T16:42:12Z | [
"python",
"random",
"numpy",
"shuffle"
] | I have a 2-d numpy array that I would like to shuffle. Is the best way to reshape it to 1-d, shuffle and reshape again to 2-d or is it possible to shuffle without reshaping?
just using the random.shuffle doesn't yield expected results and numpy.random.shuffle shuffles only rows:
```
import random
import numpy as np
a... | You could shuffle `a.flat`:
```
>>> np.random.shuffle(a.flat)
>>> a
array([[6, 1, 2],
[3, 5, 0],
[7, 8, 4]])
``` |
Python Gensim: how to calculate document similarity using the LDA model? | 22,433,884 | 14 | 2014-03-16T06:51:25Z | 22,561,795 | 12 | 2014-03-21T14:39:26Z | [
"python",
"nlp",
"lda",
"gensim"
] | I've got a trained LDA model and I want to calculate the similarity score between two documents from the corpus I trained my model on.
After studying all the Gensim tutorials and functions, I still can't get my head around it. Can somebody give me a hint? Thanks! | Don't know if this'll help but, I managed to attain successful results on document matching and similarities when using the actual document as a query.
```
dictionary = corpora.Dictionary.load('dictionary.dict')
corpus = corpora.MmCorpus("corpus.mm")
lda = models.LdaModel.load("model.lda") #result from running online ... |
Python Gensim: how to calculate document similarity using the LDA model? | 22,433,884 | 14 | 2014-03-16T06:51:25Z | 22,756,647 | 16 | 2014-03-31T08:16:41Z | [
"python",
"nlp",
"lda",
"gensim"
] | I've got a trained LDA model and I want to calculate the similarity score between two documents from the corpus I trained my model on.
After studying all the Gensim tutorials and functions, I still can't get my head around it. Can somebody give me a hint? Thanks! | Depends what similarity metric you want to use.
[Cosine similarity](http://en.wikipedia.org/wiki/Cosine_similarity) is universally useful & [built-in](http://radimrehurek.com/gensim/matutils.html#gensim.matutils.cossim):
```
sim = gensim.matutils.cossim(vec_lda1, vec_lda2)
```
[Hellinger distance](http://en.wikipedi... |
Django Rest Framework and JSONField | 22,434,869 | 32 | 2014-03-16T08:57:23Z | 23,076,584 | 18 | 2014-04-15T06:56:54Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] | Given a Django model with a [JSONField](https://github.com/bradjasper/django-jsonfield), what is the correct way of serializing and deserializing it using [Django Rest Framework](http://www.django-rest-framework.org/)?
I've already tried crating a custom `serializers.WritableField` and overriding `to_native` and `from... | In 2.4.x:
```
from rest_framework import serializers # get from https://gist.github.com/rouge8/5445149
class WritableJSONField(serializers.WritableField):
def to_native(self, obj):
return obj
class MyModelSerializer(serializers.HyperlinkedModelSerializer):
my_json_field = WritableJSONField() # you n... |
Django Rest Framework and JSONField | 22,434,869 | 32 | 2014-03-16T08:57:23Z | 28,200,902 | 36 | 2015-01-28T19:37:14Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] | Given a Django model with a [JSONField](https://github.com/bradjasper/django-jsonfield), what is the correct way of serializing and deserializing it using [Django Rest Framework](http://www.django-rest-framework.org/)?
I've already tried crating a custom `serializers.WritableField` and overriding `to_native` and `from... | If you're using Django Rest Framework >= 3.3, then the JSONField serializer is [now included](http://www.django-rest-framework.org/api-guide/fields/#jsonfield). This is now the correct way.
If you're using Django Rest Framework < 3.0, then see gzerone's answer.
If you're using DRF 3.0 - 3.2 AND you can't upgrade AND ... |
Rendering vectors in a sphere, with better perception | 22,436,968 | 4 | 2014-03-16T12:42:07Z | 22,440,051 | 7 | 2014-03-16T17:10:54Z | [
"python",
"matplotlib",
"data-visualization"
] | I need to render some 3D vectors starting in (0,0,0) ending all on a sphere. Currently I do this with python and matplotlib:
```
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import proj3d
from matplotlib.patches import FancyArrowPatch
fig = plt.figure()
ax = fig.gca(projection='3d')
ax... | The apparent lack of depth in your current rendering is mostly due to the lack of shading.
`matplotlib` isn't set up to handle "true" 3D rendering (i.e. occlusion, shading, etc), and you're going to need a lot of the subtle visual hints that this gives to get the impression of depth.
`mayavi.mlab` is a good choice fo... |
Python 3, range().append() returns error: 'range' object has no attribute 'append' | 22,437,297 | 4 | 2014-03-16T13:11:09Z | 22,437,321 | 14 | 2014-03-16T13:13:32Z | [
"python",
"python-2.7",
"python-3.x",
"append",
"range"
] | In Python 2.7 the following works without a problem:
```
myrange = range(10,100,10)
myrange.append(200)
print(my range)
```
Output: [10,20,30,40,50,60,70,80,90,200]
Conversely, in Python 3.3.4 the same code snippet returns the error: **'range' object has no attribute 'append'**
Please could someone explain the reas... | In Python2, `range` returns a list.
In Python3, `range` returns a [range object](http://docs.python.org/3/library/stdtypes.html#ranges).
The range object does not have an append method. To fix, convert the range object to a list:
```
>>> myrange = list(range(10,100,10))
>>> myrange.append(200)
>>> myrange
[10, 20, 30... |
AttributeError: 'module' object has no attribute 'python_implementation' running pip | 22,438,609 | 9 | 2014-03-16T15:09:41Z | 22,570,609 | 7 | 2014-03-21T22:27:27Z | [
"python",
"cygwin",
"pip"
] | I installed Cygwin with Python set-up tools. When I try to run pip install `awscli` I get the following error:
```
$ pip install awscli
Traceback (most recent call last):
File "/usr/bin/pip", line 8, in <module>
load_entry_point('pip==1.5.4', 'console_scripts', 'pip')()
File "build/bdist.linux-i686/egg/pkg_res... | Re-installing `pip` might fix it, try it using [`easy_install`](https://pypi.python.org/pypi/setuptools):
`sudo easy_install pip` |
Python local vs global variables | 22,439,752 | 10 | 2014-03-16T16:47:20Z | 22,439,876 | 10 | 2014-03-16T16:57:57Z | [
"python",
"scope",
"runtime",
"global-variables",
"local-variables"
] | I understand the concept of local and global variables in Python, but I just have a question about why the error comes out the way it is in the following code. Python execute the codes line by line, so it does not know that a is a local variable until it reads line 5. Does Python go back one line and tag it as an error... | **Setup and Testing**
To analyze your question, let's create two separate test functions that replicate your issue:
```
a=0
def test1():
print(a)
test1()
```
prints `0`. So, calling this function is not problematic, but on the next function:
```
def test2():
print(a) # Error : local variable 'a' referenc... |
How to inspect variables after Traceback? | 22,441,139 | 17 | 2014-03-16T18:41:27Z | 22,441,243 | 11 | 2014-03-16T18:49:12Z | [
"python",
"debugging"
] | My Python script is crashing. To debug it, I ran it in interactive mode `python -i example.py`
```
Traceback (most recent call last):
File "example.py", line 5, in <module>
main()
File "example.py", line 3, in main
message[20]
IndexError: string index out of range
```
At this point, I would like to inspec... | To drop to a debugger *only if there is an exception* you could define a [custom excepthook](https://docs.python.org/2/library/sys.html#sys.excepthook):
```
import sys
def excepthook(type_, value, tb):
import traceback
import pdb
traceback.print_exception(type_, value, tb)
pdb.post_mortem(tb)
sys.excep... |
What is the difference between `sorted(list)` vs `list.sort()` ? python | 22,442,378 | 19 | 2014-03-16T20:16:10Z | 22,442,440 | 35 | 2014-03-16T20:21:27Z | [
"python",
"list",
"sorting"
] | `list.sort()` sorts the list and save the sorted list, while `sorted(list)` returns a sorted list without changing the original list.
* But when to use which?
* And which is faster? And how much faster?
* Can a list's original positions be retrieved after `list.sort()`? | `sorted()` returns a **new** sorted list, leaving the original list unaffected. `list.sort()` sorts the list **in-place**, mutating the list indices, and returns `None` (like all in-place operations).
`sorted()` works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc... |
Predicting how long an scikit-learn classification will take to run | 22,443,041 | 17 | 2014-03-16T21:07:58Z | 22,443,643 | 25 | 2014-03-16T22:01:31Z | [
"python",
"machine-learning",
"classification",
"scikit-learn"
] | Is there a way to predict how long it will take to run a classifier from sci-kit learn based on the parameters and dataset? I know, pretty meta, right?
Some classifiers/parameter combinations are quite fast, and some take so long that I eventually just kill the process. I'd like a way to estimate in advance how long i... | There are very specific classes of classifier or regressors that directly report remaining time or progress of your algorithm (number of iterations etc.). Most of this can be turned on by passing `verbose=2` (any high number > 1) option to the constructor of individual models. **Note:** this behavior is according to sk... |
Iterating over lists of lists in Python | 22,443,378 | 3 | 2014-03-16T21:37:46Z | 22,443,444 | 8 | 2014-03-16T21:43:28Z | [
"python",
"nested-lists"
] | I have a list of lists:
```
lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
```
I want to iterate over each element and perform some string operations on them for example:
```
replace("(", "")
```
I tried iterating over the list using:
```
for l1 in lst1:
for i in l1:
lst2.append(list(map(str... | **Edit:**
Yes, you should use normal for-loops if you want to:
1. Preform multiple operations on each item contained in each sub-list.
2. Keep both the main list as well as the sub-lists as the same objects.
Below is a simple demonstration of how to do this:
```
main = [["(a)", "(b)", "(c)"], ["(d)", "(e)", "(f)", ... |
Python built-in function "compile". What is it used for? | 22,443,939 | 13 | 2014-03-16T22:29:23Z | 22,444,002 | 20 | 2014-03-16T22:35:24Z | [
"python",
"builtin"
] | I came across a built-in function [`compile`](http://docs.python.org/2.7/library/functions.html#compile) today. Though i read the documentation but still do not understand it's usage or where it is applicable. Please can anyone explain with example the use of this function. I will really appreciate examples.
From the ... | It is not that commonly used. It is used when you have Python source code in string form, and you want to make it into a Python code object that you can keep and use. Here's a trivial example:
```
>>> codeobj = compile('x = 2\nprint "X is", x', 'fakemodule', 'exec')
>>> exec(codeobj)
X is 2
```
Basically, the code ob... |
asyncio yield from concurrent.futures.Future of an Executor | 22,445,054 | 8 | 2014-03-17T00:31:10Z | 22,445,134 | 9 | 2014-03-17T00:39:27Z | [
"python",
"python-3.x",
"python-asyncio",
"concurrent.futures"
] | I have a `long_task` function which runs a heavy cpu-bound calculation and I want to make it asynchronous by using the new asyncio framework. The resulting `long_task_async` function uses a `ProcessPoolExecutor` to offload work to a different process to not be constrained by the GIL.
The trouble is that for some reaso... | You want to use [`loop.run_in_executor`](http://docs.python.org/3.4/library/asyncio-eventloop.html#executor), which uses a `concurrent.futures` executor, but maps the return value to an `asyncio` future.
The original `asyncio` PEP [suggests that](http://legacy.python.org/dev/peps/pep-3156/#futures) `concurrent.futures... |
Python webbrowser.open() to open Chrome browser | 22,445,217 | 9 | 2014-03-17T00:50:55Z | 24,353,812 | 11 | 2014-06-22T17:28:33Z | [
"python",
"python-3.x"
] | According to the documentation <http://docs.python.org/3.3/library/webbrowser.html> it's supposed to open in the default browser, but for some reason on my machine it opens IE. I did a google search and I came across an answer that said I need to register browsers, but I'm not sure how to use webbrowser.register() and ... | You can call get() with the path to Chrome. Below is an example - replace chrome\_path with the correct path for your platform.
```
import webbrowser
url = 'http://docs.python.org/'
# MacOS
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
# Windows
# chrome_path = 'C:\Program Files (x86)\Google\Chrome\Ap... |
Python webbrowser.open() to open Chrome browser | 22,445,217 | 9 | 2014-03-17T00:50:55Z | 31,262,561 | 9 | 2015-07-07T07:40:16Z | [
"python",
"python-3.x"
] | According to the documentation <http://docs.python.org/3.3/library/webbrowser.html> it's supposed to open in the default browser, but for some reason on my machine it opens IE. I did a google search and I came across an answer that said I need to register browsers, but I'm not sure how to use webbrowser.register() and ... | In the case of Windows, the path uses a UNIX-style path, so make the backslash into forward slashes.
```
webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("http://google.com")
```
See: [Python: generic webbrowser.get().open() for chrome.exe does not work](http://stackoverflow.com/q... |
Unable to connect aws s3 bucket using boto | 22,454,559 | 6 | 2014-03-17T12:41:05Z | 22,462,419 | 23 | 2014-03-17T18:28:16Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] | ```
AWS_ACCESS_KEY_ID = '<access key>'
AWS_SECRET_ACCESS_KEY = '<my secret key>'
Bucketname = 'Bucket-name'
import boto
from boto.s3.key import Key
import boto.s3.connection
conn = boto.connect_s3(AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,
host ='s3.ap-southeast-1.amazonaws.com',
is_secure=True, ... | You can also use the following (boto.s3.connect\_to\_region):
```
import boto
from boto.s3.key import Key
import boto.s3.connection
AWS_ACCESS_KEY_ID = '<access key>'
AWS_SECRET_ACCESS_KEY = '<my secret key>'
Bucketname = 'Bucket-name'
conn = boto.s3.connect_to_region('ap-southeast-1',
aws_access_key_id=AWS... |
Configure pep8.py command line options in pycharm | 22,458,107 | 11 | 2014-03-17T15:15:26Z | 23,626,653 | 8 | 2014-05-13T08:50:32Z | [
"python",
"pycharm",
"pep8"
] | Can I configure the command line arguments that PyCharm sends to pep8.py when it does its automatic PEP8 style checking? I would like to do something like
```
$ pep8 --ignore=E231 foo.py
```
However, in PyCharm under Project Settings -> Inspections I only see options to enable/disable PEP8 style checks in aggregate, ... | Found the solution here: <http://iambigblind.blogspot.de/2013/02/configuring-pep8py-support-in-pycharm-27.html>
Just add E501 to the list of ignore errors and the warning will go away in PyCharm 3 (and 4). |
Extending python with C: Pass a list to PyArg_ParseTuple | 22,458,298 | 6 | 2014-03-17T15:22:50Z | 22,487,015 | 7 | 2014-03-18T17:42:50Z | [
"python",
"c",
"python-c-api",
"python-c-extension"
] | I have been trying to get to grips with extending python with C, and so far, based on the [documentation](http://docs.python.org/2/extending/extending.html), I have had reasonable success in writing small C functions and extending it with Python.
However, I am now struck on a rather simple problem - to which I am not ... | [`PyArg_ParseTuple`](http://docs.python.org/2/c-api/arg.html) can only handle simple C types, complex numbers, `char *`, `PyStringObject *`, `PyUnicodeObject *`, and `PyObject *`. The only way to work with a PyListObject is by using some variant of "O" and extracting the object as a PyObject \*. You can then use the [L... |
Normalize / Translate ndarray - Numpy / Python | 22,459,381 | 4 | 2014-03-17T16:06:36Z | 22,459,424 | 7 | 2014-03-17T16:07:58Z | [
"python",
"numpy",
"normalization",
"multidimensional-array"
] | There is a simple way to normalize a ndarray (every values between 0.0, 1.0)?
For example, I have a matrix like:
```
a = [[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]]
```
Until now I'm getting the max value with
```
max(max(p[1:]) for p in a)
a / p
```
Besides I think **numpy** may have a method to this in ... | You could use `np.ptp`1 (peak to peak) in conjunction with `np.min` to do this in the general case:
```
new_arr = (a - a.min())/np.ptp(a)
```
example:
```
>>> a = np.array([[-1., 0, 1], [0, 2, 1]])
>>> np.ptp(a)
3.0
>>> a
array([[-1., 0., 1.],
[ 0., 2., 1.]])
>>> (a - a.min())/np.ptp(a)
array([[ 0. ... |
Python: Object does not support indexing | 22,463,866 | 4 | 2014-03-17T19:43:15Z | 22,464,096 | 10 | 2014-03-17T19:57:48Z | [
"python",
"object",
"indexing",
"typeerror"
] | Yes, this question has been asked before. No, none of the answers I read could fix the problem I have.
I'm trying to create a little Bounce game. I've created the bricks like this:
```
def __init__(self,canvas):
self.canvas = canvas
self.brick1 = canvas.create_rectangle(0,0,50,20,fill=random_fill_colour(),out... | In order for the Brick object to be iterable, you must implement the methods:
```
__getitem__
__setitem__
__delitem__
```
You don't need all of them, only the ones you use.
However, this seems like a case of self.bricks being a brick instead of a list of bricks. A list of bricks is indexable; however, a brick itself... |
demystify Flask app.secret_key | 22,463,939 | 17 | 2014-03-17T19:47:51Z | 22,463,969 | 22 | 2014-03-17T19:49:35Z | [
"python",
"web",
"flask"
] | If app.secret\_key is not set, the Flask framework will not allow you to set or access the session dictionary. This is all that the flask user guide has to say on the subject.
I am very new to web development and I have no idea how/why any security stuff works. I would like to understand what flask is doing under the ... | Anything that requires encryption (for safe-keeping against tampering by attackers) requires the secret key to be set. For *just* Flask itself, that 'anything' is the `Session` object, but other extensions can make use of the same secret.
`secret_key` is merely the value set for the `SECRET_KEY` configuration key, or ... |
Do Dictionaries have a key length limit? | 22,464,900 | 8 | 2014-03-17T20:40:49Z | 22,465,159 | 7 | 2014-03-17T20:54:29Z | [
"python",
"dictionary"
] | I was wondering if Python had a limit on the length of a dictionary key.
For clarification, I'm not talking about the number of keys, but the length of each individual key. I'm going to be building my dictionaries based on dynamic values (after validation), but I'm not sure if I should be taking length into account in... | Here's a bit of sample code:
```
from string import ascii_letters
from random import choice
def make_str(length):
return "".join(choice(ascii_letters) for i in range(length))
test_dict = {make_str(10000000): i for i in range(5)}
```
Conclusion: Python will quite happily use a 10-million-character string as a di... |
How to zip a folder and file in python? | 22,465,629 | 4 | 2014-03-17T21:18:38Z | 22,465,826 | 10 | 2014-03-17T21:29:45Z | [
"python",
"file",
"zip",
"folder",
"archive"
] | I've got a folder called: 'files' which contains lots of jpg photographs. I've also got a file called 'temp.kml'. I want to create a KMZ file (basically a zip file) which contains the temp.kml file AND the files directory which has the photographs sitting inside it.
Here is my code:
```
zfName = 'simonsZip.kmz'
foo =... | You can use [shutil](http://docs.python.org/2.7/library/shutil.html)
```
import shutil
shutil.make_archive("simonsZip", "zip", "files")
``` |
Python Equivalent to System('PAUSE') | 22,466,398 | 2 | 2014-03-17T22:02:13Z | 22,466,429 | 7 | 2014-03-17T22:03:55Z | [
"python",
"python-3.x"
] | I have been coding a basic calculator in python 3.3 and I want to be able to run it in command window.
but as soon as i get to the end it shuts the windows before I have time to view the final answer.
so I was wondering if there is an equivalent to the c++ System('PAUSE') command to tell it not to go any further unti... | Use `input()` on p3k or `raw_input()` on p2.7x - it will read anything from stdin, so it will wait until user is ready. |
Celery beat schedule multiple tasks under same time-interval group | 22,466,696 | 8 | 2014-03-17T22:23:27Z | 22,698,811 | 10 | 2014-03-27T20:44:52Z | [
"python",
"flask",
"celery",
"celerybeat"
] | I'm trying to set up two tasks that both run every minute. Is there any way to group them in one to run?
I specified `CELERYBEAT_SCHEDULE` in my `celeryconfig.py` as following:
```
CELERYBEAT_SCHEDULE = {
'every-minute': {
'task': 'tasks.add',
'schedule': crontab(minute='*/1'),
'args': (1,... | The [Celery Documentation: Periodic Tasks](http://celery.readthedocs.org/en/latest/userguide/periodic-tasks.html#beat-entries) states that you can only have the name of the task to be executed (not a list, etc.)
You could create two different schedule entries:
```
CELERYBEAT_SCHEDULE = {
'every-minute_add': {
... |
How to read image from StringIO into PIL in python | 22,468,108 | 5 | 2014-03-18T00:23:24Z | 22,468,203 | 9 | 2014-03-18T00:32:20Z | [
"python",
"python-imaging-library"
] | How to read image from StringIO into PIL in python? I will have a stringIO object. How to I read from it with a image in it? I cant event have ot read a image from a file. Wow!
```
from StringIO import StringIO
from PIL import Image
image_file = StringIO(open("test.gif",'rb').readlines())
im = Image.open(image_file)
... | Don't use [`readlines()`](http://docs.python.org/2.7/library/stdtypes.html?highlight=readlines#file.readlines), it returns a list of strings which is not what you want. To retrieve the bytes from the file, use [`read()`](http://docs.python.org/2.7/library/stdtypes.html?highlight=readlines#file.read) function instead.
... |
Managing Tweepy API Search | 22,469,713 | 3 | 2014-03-18T03:18:47Z | 23,996,991 | 7 | 2014-06-02T14:31:58Z | [
"python",
"twitter",
"tweepy"
] | Please forgive me if this is a gross repeat of a question previously answered elsewhere, but I am lost on how to use the tweepy API search function. Is there any documentation available on how to search for tweets using the `api.search()` function?
Is there any way I can control features such as number of tweets retur... | I originally worked out a solution based on [Yuva Raj](http://stackoverflow.com/users/2135811/yuva-raj)'s [suggestion](http://stackoverflow.com/questions/22469713/managing-tweepy-api-search#comment34277304_22473254) to use additional parameters in [GET search/tweets](https://dev.twitter.com/docs/api/1.1/get/search/twee... |
How To Get All The Contiguous Substrings Of A String In Python? | 22,469,997 | 8 | 2014-03-18T03:48:49Z | 22,470,047 | 8 | 2014-03-18T03:53:42Z | [
"python",
"string",
"python-2.7",
"substring"
] | Here is my code, but I want a better solution, how do you think about the problem?
```
def get_all_substrings(string):
length = len(string)
alist = []
for i in xrange(length):
for j in xrange(i,length):
alist.append(string[i:j + 1])
return alist
print get_all_substring('abcde')
``` | The only improvement I could think of is, to use list comprehension like this
```
def get_all_substrings(input_string):
length = len(input_string)
return [input_string[i:j+1] for i in xrange(length) for j in xrange(i,length)]
print get_all_substrings('abcde')
```
The timing comparison between, yours and mine
``... |
get list of pandas dataframe columns based on data type | 22,470,690 | 31 | 2014-03-18T04:54:22Z | 22,471,217 | 10 | 2014-03-18T05:38:28Z | [
"python",
"pandas"
] | If I have a dataframe with the following columns:
```
1. NAME object
2. On_Time object
3. On_Budget object
4. %actual_hr float64
5. Baseline Start Date datetime6... | You can use boolean mask on the dtypes attribute:
```
In [11]: df = pd.DataFrame([[1, 2.3456, 'c']])
In [12]: df.dtypes
Out[12]:
0 int64
1 float64
2 object
dtype: object
In [13]: msk = df.dtypes == np.float64 # or object, etc.
In [14]: msk
Out[14]:
0 False
1 True
2 False
dtype: bool
```
Yo... |
get list of pandas dataframe columns based on data type | 22,470,690 | 31 | 2014-03-18T04:54:22Z | 22,475,141 | 65 | 2014-03-18T09:29:34Z | [
"python",
"pandas"
] | If I have a dataframe with the following columns:
```
1. NAME object
2. On_Time object
3. On_Budget object
4. %actual_hr float64
5. Baseline Start Date datetime6... | If you want a list of columns of a certain type, you can use `groupby`:
```
>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
A B C D E
0 1 2.3456 c d 78
[1 rows x 5 columns]
>>> df.dtypes
A int64
B float64
C object
D object
E int64
dtype: object
>... |
get list of pandas dataframe columns based on data type | 22,470,690 | 31 | 2014-03-18T04:54:22Z | 27,954,411 | 32 | 2015-01-14T23:29:22Z | [
"python",
"pandas"
] | If I have a dataframe with the following columns:
```
1. NAME object
2. On_Time object
3. On_Budget object
4. %actual_hr float64
5. Baseline Start Date datetime6... | As of pandas v0.14.1, you can utilize `select_dtypes()` to select columns by dtype
```
In [2]: df = pd.DataFrame({'NAME': list('abcdef'),
'On_Time': [True, False] * 3,
'On_Budget': [False, True] * 3})
In [3]: df.select_dtypes(include=['bool'])
Out[3]:
On_Budget On_Time
0 False True
1 True Fals... |
How do I check if a numpy dtype is integral? | 22,471,644 | 10 | 2014-03-18T06:12:32Z | 22,476,290 | 23 | 2014-03-18T10:16:45Z | [
"python",
"numpy",
"integral",
"abc"
] | How do I check if a numpy dtype is integral? I tried:
```
issubclass(np.int64, numbers.Integral)
```
but it gives `False`.
---
Update: it now gives `True`. | Numpy has a hierarchy of dtypes similar to a class hierarchy (the scalar types actually have a bona fide class hierarchy that mirrors the dtype hierarchy). You can use `np.issubdtype(some_dtype, np.integer)` to test if a dtype is an integer dtype. Note that like most dtype-consuming functions, `np.issubdtype()` will co... |
Fastest way to grep multiple values from file in python | 22,480,514 | 10 | 2014-03-18T13:14:48Z | 22,483,885 | 8 | 2014-03-18T15:30:47Z | [
"python",
"grep"
] | * I have a file of 300m lines (inputFile), all with 2 columns separated by a tab.
* I also have a list of 1000 unique items (vals).
I want to create a dictionary with column 1 as key and column 2 as value for all lines in *inputFile* where the first columns occurs in *vals*. A few items in *vals* do not occur in the f... | You clarified in a comment that each key occurs at most once in the data. It follows from that and the fact that there are only 1000 keys that the amount of work being done in Python is trivial; almost all your time is spent waiting for output from `grep`. Which is fine; your strategy of delegating line extraction to a... |
Plot mean and standard deviation | 22,481,854 | 16 | 2014-03-18T14:07:39Z | 22,482,010 | 23 | 2014-03-18T14:14:05Z | [
"python",
"matplotlib",
"plot"
] | I have several values of a function at different x points. I want to plot the mean and std in python, like the answer of [this SO question](http://stackoverflow.com/questions/19797846/plot-mean-standard-deviation-standard-error-of-the-mean-and-confidence-interv). I know this must be easy using matplotlib, but I have no... | [`plt.errorbar`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.errorbar) can be used to plot x, y, error data (as opposed to the usual `plt.plot`)
```
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4... |
How can I plot separate Pandas DataFrames as subplots? | 22,483,588 | 27 | 2014-03-18T15:18:11Z | 22,484,249 | 51 | 2014-03-18T15:45:26Z | [
"python",
"matplotlib",
"pandas"
] | I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking `df.plot()`, I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate s... | You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the `ax` keyword. For example for 4 subplots (2x2):
```
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=2)
df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...
```
Here `axes` is an ar... |
Python - Check if list of lists of lists contains a specific list | 22,483,730 | 3 | 2014-03-18T15:24:38Z | 22,483,768 | 7 | 2014-03-18T15:26:03Z | [
"python",
"list"
] | I have a list that contains other lists with coordinates for multiple tile positions and I need to check if that list contains another list of coordinates, like in this example:
```
totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
redList = [ [0,1], [2,7], [6,3] ]
if totalList contains redList:
#do st... | Just use a containment test:
```
if redList in totalList:
```
This returns `True` for your sample data:
```
>>> totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
>>> redList = [ [0,1], [2,7], [6,3] ]
>>> redList in totalList
True
``` |
Efficiently select rows that match one of several values in Pandas DataFrame | 22,485,375 | 16 | 2014-03-18T16:29:19Z | 22,485,573 | 24 | 2014-03-18T16:37:36Z | [
"python",
"pandas"
] | ## Problem
Given data in a Pandas DataFrame like the following:
```
Name Amount
---------------
Alice 100
Bob 50
Charlie 200
Alice 30
Charlie 10
```
I want to select all rows where the `Name` is one of several values in a collection `{Alice, Bob}`
```
Name Amount
-------------... | You can use the [isin](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) Series method:
```
In [11]: df['Name'].isin(['Alice', 'Bob'])
Out[11]:
0 True
1 True
2 False
3 True
4 False
Name: Name, dtype: bool
In [12]: df[df.Name.isin(['Alice', 'Bob'])]
Out[12]:
Name A... |
Python dictionary comprehension gives KeyError | 22,485,399 | 3 | 2014-03-18T16:30:32Z | 22,485,502 | 8 | 2014-03-18T16:34:52Z | [
"python",
"dictionary",
"dictionary-comprehension"
] | ```
>>> a = 1
>>> print { key: locals()[key] for key in ["a"] }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
KeyError: 'a'
```
How can I create a dictionary with a comprehension like this? | A dict comprehension has its *own namespace*, and `locals()` in that namespace has no `a`. Technically speaking, everything but the initial iterable for the outermost iterable (here `["a"]`) is run almost as a nested function with the outermost iterable passed in as an argument.
Your code works if you used `globals()`... |
How can I inspect what SUDs is generating/receiving in "sudo 0.4.1 jurko 5" and newer? | 22,487,165 | 6 | 2014-03-18T17:49:51Z | 24,064,675 | 8 | 2014-06-05T15:48:36Z | [
"python",
"soap",
"suds"
] | This question is similar to this one:
[How can I output what suds is generating/receiving?](http://stackoverflow.com/questions/4426204/how-can-i-output-what-suds-is-generating-receiving)
The problem is that I am using the [suds fork by Jurko](https://bitbucket.org/jurko/suds) and after version "0.4.1 jurko 5" the `Cl... | You can use the MessagePlugin to do this
```
from suds.plugin import MessagePlugin
class LogPlugin(MessagePlugin):
def sending(self, context):
print(str(context.envelope))
def received(self, context):
print(str(context.reply))
client = Client("http://localhost/wsdl.wsdl", plugins=[LogPlugin()])
``` |
multiprocessing in python - sharing large object (e.g. pandas dataframe) between multiple processes | 22,487,296 | 12 | 2014-03-18T17:56:48Z | 22,487,898 | 8 | 2014-03-18T18:24:27Z | [
"python",
"pandas",
"multiprocessing"
] | I am using Python multiprocessing, more precisely
```
from multiprocessing import Pool
p = Pool(15)
args = [(df, config1), (df, config2), ...] #list of args - df is the same object in each tuple
res = p.map_async(func, args) #func is some arbitrary function
p.close()
p.join()
```
This approach has a huge memory cons... | The first argument to `Value` is \*typecode\_or\_type\*. That is defined as:
> typecode\_or\_type determines the type of the returned object: **it is
> either a ctypes type or a one character typecode of the kind used by
> the array module.** \*args is passed on to the constructor for the type.
Emphasis mine. So, you... |
How to paste a Numpy array to Excel | 22,488,566 | 2 | 2014-03-18T18:56:51Z | 22,488,567 | 7 | 2014-03-18T18:56:51Z | [
"python",
"excel",
"numpy"
] | I have multiple files which I process using Numpy and SciPy, but I am required to deliver an Excel file. How can I efficiently copy/paste a huge numpy array to Excel?
I have tried to convert to Pandas' DataFrame object, which has the very usefull function `to_clipboard(excel=True)`, but I spend most of my time convert... | My best solution here would be to turn the array into a string, then use `win32clipboard` to sent it to the clipboard. This is not a cross-platform solution, but then again, Excel is not avalable on every platform anyway.
Excel uses tabs (`\t`) to mark column change, and `\r\n` to indicate a line change.
The relevant... |
Sqlite insert query not working with python? | 22,488,763 | 2 | 2014-03-18T19:07:16Z | 22,488,847 | 11 | 2014-03-18T19:12:06Z | [
"python",
"sqlite"
] | I have been trying to insert data into the database using the following code in python:
```
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
```
The code runs without any ... | You do have to commit after inserting:
```
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
```
or use the [connection as a context manager](http://docs.python.org/2/library/sqlite3.html#using-the-connection-as-a-context-manager):
```
with conn:
cursor.execute("Insert into links (li... |
PyQt: How to get most of QListWidget | 22,489,018 | 3 | 2014-03-18T19:21:02Z | 22,494,432 | 11 | 2014-03-19T01:23:27Z | [
"python",
"drag-and-drop",
"pyqt",
"pyqt4",
"qlistwidget"
] | The code builds a dialog box with a single **QListWidget** and a single **QPushButton**.
Clicking the button adds a single List Item.
Right-click on a List Item brings up a right-click menu with "Remove Item" command available.
Choosing "Remove Item" command removes a List Item from List Widget.
Would be interestin... | List-widget items can be moved up and down via drag and drop, but it is not enabled by default. To switch it on, do this:
```
self.listWidget.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
```
Multiple-selection is one of several [selection-modes](https://qt-project.org/doc/qt-4.8/qabstractitemview.html#Se... |
Python code works, but eclipse shows error - Syntax error while detecting tuple | 22,489,084 | 11 | 2014-03-18T19:24:23Z | 22,490,002 | 17 | 2014-03-18T20:12:10Z | [
"python",
"eclipse",
"python-3.x"
] | I new to python. I use Python 3.3 in Eclipse Kepler.
This is my code snippet:
```
f = Fibonacci(0,1)
for r in f.series():
if r > 100: break
print(r, end=' ')
```
At the line `print(r, end = '')`, eclipse reports a syntax
error - `Syntax error while detecting tuple`. However, the
program runs perfectly.
Why ... | You need to specify the correct `Grammar Version` in Eclipse. See here: [print function in Python3](http://stackoverflow.com/questions/19352888/print-function-in-python3?rq=1)
Is `Grammar Version` 3.3 in your setup? Steps - Project > Properties > Python Interpreter/Grammar. You might have to restart Eclipse to see the... |
Is a countvectorizer the same as tfidfvectorizer with use_idf=false? | 22,489,264 | 3 | 2014-03-18T19:33:52Z | 22,501,807 | 7 | 2014-03-19T09:45:50Z | [
"python",
"scikit-learn"
] | As the title states: Is a `countvectorizer` the same as `tfidfvectorizer` with use\_idf=false ? If not why not ?
So does this also mean that adding the `tfidftransformer` here is redundant ?
```
vect = CountVectorizer(min_df=1)
tweets_vector = vect.fit_transform(corpus)
tf_transformer = TfidfTransformer(use_idf=False... | No, they're not the same. `TfidfVectorizer` normalizes its results, i.e. each vector in its output has norm 1:
```
>>> CountVectorizer().fit_transform(["foo bar baz", "foo bar quux"]).A
array([[1, 1, 1, 0],
[1, 0, 1, 1]])
>>> TfidfVectorizer(use_idf=False).fit_transform(["foo bar baz", "foo bar quux"]).A
array(... |
cmp() isnt woking for me (python) | 22,490,366 | 2 | 2014-03-18T20:30:29Z | 22,490,617 | 7 | 2014-03-18T20:43:54Z | [
"python",
"python-3.x"
] | for some reason i cannot get the command
```
cmp()
```
To work, here is the code:
```
a = [1,2,3]
b = [1,2,3]
c = cmp(a,b)
print (c)
```
I am getting the error:
```
Traceback (most recent call last):
File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module>
c = cmp(a,b)
NameError: name 'cmp' is not defined
[F... | As mentioned in the comments, `cmp` doesn't exist in Python 3. If you really want it, you could define it yourself:
```
def cmp(a, b):
return (a > b) - (a < b)
```
which is taken from the original [What's New In Python 3.0](http://docs.python.org/3.0/whatsnew/3.0.html#ordering-comparisons). It's pretty rare -- th... |
Pandas Histogram of Filtered Dataframe | 22,492,042 | 5 | 2014-03-18T22:07:27Z | 22,492,337 | 8 | 2014-03-18T22:24:49Z | [
"python",
"matplotlib",
"pandas",
"histogram"
] | This has been driving me mad for the one last hour. I can draw a histogram when I use:
```
hist(df.GVW, bins=50, range=(0,200))
```
I use the following when I need to filter the dataframe for a given condition in one of the columns, for example:
```
df[df.TYPE=='SU4']
```
So far, everything works. When I try to get... | Maybe try to use the `.values` attribute (this returns the data as a numpy array), so:
```
hist(df[df.TYPE=='SU4'].GVW.values, bins=50, range=(0,200))
```
I assume the reason this does not work is because the matplotlib `hist` method tries to access the first `0`-index element of the input. But because the Series use... |
How do I get the IP address from a http request using the requests library? | 22,492,484 | 8 | 2014-03-18T22:35:56Z | 22,513,161 | 11 | 2014-03-19T17:06:47Z | [
"python",
"python-requests",
"pycurl",
"httplib",
"httplib2"
] | I am making HTTP requests using the requests library in python, but I need the ip address from the server that responded the http request and I'm trying to avoid to make two calls (and possibly having a different ip address from the one that responded the request.
Is that possible? Does any python http library allows ... | It turns out that it's rather involved.
Here's a monkey-patch while using `requests` version 1.2.3:
Wrapping the `_make_request` method on `HTTPConnectionPool` to store the response from `socket.getpeername()` on the `HTTPResponse` instance.
For me on python 2.7.3, this instance was available on `response.raw._origi... |
Python: Regarding variable scope. Why don't I need to pass x to Y? | 22,492,835 | 7 | 2014-03-18T22:58:12Z | 22,492,946 | 8 | 2014-03-18T23:06:12Z | [
"python",
"variables",
"global-variables",
"scope"
] | Consider the following code, why don't I need to pass x to Y?
```
class X:
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
class Y:
def A(self):
print(x.a,x.b,x.c)
x = X()
y = Y()
y.A()
```
---
Thank you to the top answers, they really helped me see what was... | When python compiles a `def` into a function, it tries to figure out if the things you are referencing are locals - and if they're not, you must be referring to a global. For example:
```
def f():
print(x)
```
Well, you haven't defined `x` within the scope of `f`, so you must be referring to a global.
This is al... |
No module named 'forms' Django | 22,493,529 | 6 | 2014-03-18T23:54:26Z | 22,493,672 | 7 | 2014-03-19T00:08:00Z | [
"python",
"django"
] | I am trying to initiate a registration process for my website. I am using Python 3.3.5, and Django 1.6.
I receive an error saying `No module named 'forms'`. I am fairly new to Python/Django.
Here are my files:
Views.py:
```
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect... | if thats an app module, change your 6th line:
```
from forms import MyRegistrationForm
```
to:
```
from .forms import MyRegistrationForm
```
(just add a dot before forms) |
Compare list elements in python | 22,494,726 | 2 | 2014-03-19T01:52:49Z | 22,494,733 | 8 | 2014-03-19T01:54:15Z | [
"python",
"list",
"compare",
"elements"
] | I have a list and want to compare if the last value is greater than the past 10 values, however, I know there is a much easier way to approach this then the code below:
```
list = [1,2,3,4,5,6,7,8,9,10]
if list[-1] > list[-2] and list[-1] > list[-3] and list[-1] > list[-4]: (etc)
print "It's bigger"
```
Any su... | One way is to take the maximum of the past values and compare it with the last:
```
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> if l[-1] > max(l[:-1]):
... print "It's bigger"
...
It's bigger
``` |
Should I deploy only the .pyc files on server if I worry about code security? | 22,495,894 | 4 | 2014-03-19T03:54:57Z | 22,496,008 | 8 | 2014-03-19T04:08:14Z | [
"python",
"django",
"cloud",
"wsgi"
] | I want to deploy a Django application to a cloud computing environment, but I am worried about source code security. Can I deploy only the compiled .pyc files there? According to official python doc, pyc files are 'moderately hard to reverse engineer'.
What are the pros and cons of taking this approach? Is this a stan... | Apparently you can. Check out [this question](https://stackoverflow.com/questions/5002150/can-i-deploy-python-pyc-files-only-to-google-app-engine) and [this blog post](http://www.curiousefficiency.org/posts/2011/04/benefits-and-limitations-of-pyc-only.html).
One thing I'd consider though... Why would you move to a clo... |
How can I access each element of a pair in a pair list? | 22,496,657 | 6 | 2014-03-19T05:02:30Z | 22,496,741 | 8 | 2014-03-19T05:08:50Z | [
"python",
"list",
"tuples"
] | I have a list called pairs.
```
pairs = [("a", 1), ("b", 2), ("c", 3)]
```
And I can access elements as:
```
for x in pairs:
print x
```
which gives output like:
```
('a', 1) ('b', 2) ('c', 3)
```
But I want to access each element in each pair, like in c++, if we use `pair<string, int>`
we are able to access,... | Use tuple unpacking:
```
>>> pairs = [("a", 1), ("b", 2), ("c", 3)]
>>> for a, b in pairs:
... print a, b
...
a 1
b 2
c 3
```
See also: [Tuple unpacking in for loops](http://stackoverflow.com/questions/10867882/tuple-unpacking-in-for-loops). |
What is a django.utils.functional.__proxy__ object and what it helps with? | 22,501,644 | 6 | 2014-03-19T09:40:12Z | 24,925,195 | 12 | 2014-07-24T04:33:34Z | [
"python",
"django"
] | I stumbled across a `django.utils.functional.__proxy__` object many times, last time in the following bit of code:
```
def formfield_for_choice_field(self, db_field, request, **kwargs):
print db_field.help_text
```
(With the result of the print being `<django.utils.functional.__proxy__ object at 0x7fc6940106d0>`)... | It is a translation string â a string that has been marked as translated but whose actual translation result isnât determined until the object is used in a string. See Django documentation: <https://docs.djangoproject.com/en/dev/ref/unicode/#translated-strings>.
Calling `unicode(object)` will generate a Unicode st... |
Scan complete directory tree using pep8 | 22,503,178 | 4 | 2014-03-19T10:41:14Z | 22,505,023 | 8 | 2014-03-19T11:54:30Z | [
"python",
"pep8-checker"
] | I'm using pep8 to check for coding guidelines. I am getting results only for the current directory. And not all directory or sub directory inside it. How to do that?
When running it from the level of container/project, I don't get pyc files' errors. When I run it from container/project/app, I get the pyc files' errors... | The `pep8` command *does* scan subdirectories automatically. It'll look for any file matching the patterns named in the `--filename` option (the default is `*.py`).
Scan your project with `pep8 .` or `pep8 directoryname`.
If you run `pep8 *` in a directory, then your shell expands the `*` into *all files* in the curr... |
all vs and AND any vs or | 22,510,205 | 6 | 2014-03-19T15:12:22Z | 22,510,330 | 11 | 2014-03-19T15:17:16Z | [
"python"
] | I was eager to know about the what is the difference between
```
all and "and"
any and "or"
```
for example:
status1=100,status2=300,status3=400
Which is better to use:
```
if status1==100 and status2 ==300 and status3 ==400:
```
or
```
if all([status1==100,status2==300,status3=400]):
```
similarly for the any a... | The keywords `and` and `or` follow Python's [short circuit evaluation](http://docs.python.org/2/library/stdtypes.html?highlight=short%20circuit#boolean-operations-and-or-not) rules. Since `all` and `any` are functions, all arguments would be evaluated. It's possible to get different behaviour if some of the conditions ... |
What do the chars %7D mean in an url query? | 22,510,329 | 4 | 2014-03-19T15:17:14Z | 22,510,399 | 13 | 2014-03-19T15:19:55Z | [
"python",
"google-app-engine",
"url",
"jinja2",
"webapp2"
] | If I access my webapp with the url
`/vi/5907399890173952.html`
then it works but when I look in the log files then googlebot is trying to access a similar url which generates an exception:
`/vi/5907399890173952.html%7D%7D`
what does it mean and how can it be handled as an exception? The message from python is:
```... | `%7D` is the ASCII code for the } character, which is probably leaking through from a template... |
GridSpec with shared axes in Python | 22,511,550 | 20 | 2014-03-19T16:00:41Z | 22,514,587 | 26 | 2014-03-19T18:10:15Z | [
"python",
"matplotlib"
] | [This solution](http://stackoverflow.com/a/19627237/283296) to another thread suggests using `gridspec.GridSpec` instead of `plt.subplots`. However, when I share axes between subplots, I usually use a syntax like the following
```
fig, axes = plt.subplots(N, 1, sharex='col', sharey=True, figsize=(3,18))
```
How can... | First off, there's an easier workaround for your original problem, as long as you're okay with being slightly imprecise. Just reset the top extent of the subplots to the default *after* calling `tight_layout`:
```
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall titl... |
Python "from [dot]package import ..." syntax | 22,511,792 | 16 | 2014-03-19T16:11:15Z | 22,511,861 | 18 | 2014-03-19T16:13:42Z | [
"python",
"import"
] | Looking through a Django tutorial I saw the following syntax:
```
from .models import Recipe, Ingredient, Instruction
```
Can someone explain how the .models works / what it does exactly? Usually I have:
```
from myapp.models import
```
How does it work without the myapp part in front of .models? | Possible duplicate: [What does a . in an import statement in Python mean?](http://stackoverflow.com/questions/7279810/what-does-a-in-an-import-statement-in-python-mean)
The `.` is a shortcut that tells it search in *current* package before rest of the `PYTHONPATH`. So, if a same-named module `Recipe` exists somewhere ... |
cpython vs cython vs numpy array performance | 22,514,730 | 14 | 2014-03-19T18:16:38Z | 22,515,315 | 7 | 2014-03-19T18:42:52Z | [
"python",
"numpy",
"cython"
] | I am doing some performance test on a variant of the prime numbers generator from <http://docs.cython.org/src/tutorial/numpy.html>.
The below performance measures are with kmax=1000
Pure Python implementation, running in CPython: 0.15s
Pure Python implementation, running in Cython: 0.07s
```
def primes(kmax):
p ... | ```
cdef DTYPE_t [:] p_view = p
```
Using this instead of p in the calculations. reduced the runtime from **580 ms** down to **2.8 ms** for me. About the exact same runtime as the implementation using \*int. And that's about the max you can expect from this.
```
DTYPE = np.int
ctypedef np.int_t DTYPE_t
@cython.bound... |
Using numpy to write an array to stdout | 22,515,522 | 5 | 2014-03-19T18:52:24Z | 22,515,821 | 10 | 2014-03-19T19:06:42Z | [
"python",
"arrays",
"python-3.x",
"numpy",
"stdout"
] | What is an idiomatic way to write a Numpy 2D Array to stdout? e.g. I have an array
```
a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]])
[[ 2. 0. 0.]
[ 0. 2. 0.]
[ 0. 0. 4.]]
```
That I would like outputted as:
```
2.0 0.0 0.0
0.0 2.0 0.0
0.0 0.0 4.0
```
I can do this by converting to a nested li... | How about the following code?
```
>>> a = numpy.array([[2., 0., 0.], [0., 2., 0.], [0., 0., 4.]])
>>> numpy.savetxt(sys.stdout, a, fmt='%.4f')
1.0000 2.0000 3.0000
0.0000 2.0000 0.0000
0.0000 0.0000 4.0000
```
In Python 3+, use `numpy.savetxt(sys.stdout.buffer, ...)`. |
Django Sass Compressor django_libsass.SassCompiler: command not found | 22,515,611 | 6 | 2014-03-19T18:56:57Z | 22,616,554 | 7 | 2014-03-24T17:33:55Z | [
"python",
"django",
"python-2.7",
"django-compressor",
"wagtail"
] | I'm using a Django-Compressor Filter as part of Wagtail (Django variant CMS with super cool UI). Environment is Wagtail 0.2 + Python 2.7 + Django 1.6 + Virtualenv + FastCGI + Apache shared hosting.
Issue occurs when trying to access admin/login page of the CMS. Django shows an Error rendering template
```
Error d... | (Reposting my comments as an answer, as requested...)
The original error: `django_libsass.SassCompiler: command not found`
meant that it was failing to import the django-libsass library. (django-compressor responded to that failure by trying to treat it as a shell command instead - django\_libsass is not a runnable c... |
Django gives "GET /static/css/style.css HTTP/1.1" 304 0 | 22,517,190 | 2 | 2014-03-19T20:18:57Z | 22,517,445 | 7 | 2014-03-19T20:31:55Z | [
"python",
"html",
"css",
"django",
"django-staticfiles"
] | ok so My
Index.html is
```
<!DOCTYPE html>
<html>
<head>
<title>Kodeworms</title>
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css" />
</head>
<body class="logged-out">
</body>
</html>
```
style.css
```
.logged-out {
background-image: href=("{{ STATIC_URL }}img/landing... | An HTTP 304 response means "I don't need to fetch it again, since it hasn't changed since I got it last". So if that's the response code you got, you may not have a problem at all. Or did you mean 404 (not found)?
In any event, you normally don't serve static files with Django directly; you do it through your front-en... |
REGEX - Differences between `^`, `$` and `\A`, `\Z` | 22,519,318 | 5 | 2014-03-19T22:16:33Z | 22,519,405 | 8 | 2014-03-19T22:21:50Z | [
"python",
"regex"
] | As I know, `re` proposes the following boundary matches.
* `^` matches at the beginning of a line.
* `$` matches at the end of a line.
* `\A` matches the beginning of the input.
* `\Z` matches the end of the input.
Can you give me a concret example showing a real difference between between `^`, `$` and `\A`, `\Z` ? | The difference only becomes apparent when you use the [`re.M` or `re.MULTILINE` multiline flag](http://docs.python.org/2/library/re.html#re.M):
```
>>> re.search(r'^word', 'Line one\nword on line two\n', flags=re.M)
<_sre.SRE_Match object at 0x10124f578>
>>> re.search(r'\Aword', 'Line one\nword on line two\n', flags=r... |
Python, remove all non-alphabet chars from string | 22,520,932 | 12 | 2014-03-20T00:16:52Z | 22,521,156 | 21 | 2014-03-20T00:36:04Z | [
"python",
"regex"
] | I am writing a python MapReduce word count program. Problem is that there are many non-alphabet chars strewn about in the data, I have found this post [Stripping everything but alphanumeric chars from a string in Python](http://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-strin... | Use `re.sub`
```
regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'
```
Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)
```
regex = re.compile('[,\.!?]'... |
Python, remove all non-alphabet chars from string | 22,520,932 | 12 | 2014-03-20T00:16:52Z | 22,521,235 | 7 | 2014-03-20T00:43:31Z | [
"python",
"regex"
] | I am writing a python MapReduce word count program. Problem is that there are many non-alphabet chars strewn about in the data, I have found this post [Stripping everything but alphanumeric chars from a string in Python](http://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-strin... | You can use the re.sub() function to remove these characters:
```
>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'
```
re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)
* `"[^a-zA-Z]+"` - look for any group of characters that are NOT
a-zA-z.
* `""` - Replace the matched characters wit... |
Python, remove all non-alphabet chars from string | 22,520,932 | 12 | 2014-03-20T00:16:52Z | 29,350,747 | 9 | 2015-03-30T15:54:47Z | [
"python",
"regex"
] | I am writing a python MapReduce word count program. Problem is that there are many non-alphabet chars strewn about in the data, I have found this post [Stripping everything but alphanumeric chars from a string in Python](http://stackoverflow.com/questions/1276764/stripping-everything-but-alphanumeric-chars-from-a-strin... | If you prefer not to use regex, you might try
```
''.join([i for i in s if i.isalpha()])
``` |
Can't get past illogical line pep8 error | 22,521,608 | 4 | 2014-03-20T01:21:37Z | 22,521,768 | 14 | 2014-03-20T01:38:31Z | [
"python",
"if-statement",
"pep8"
] | I've been trying to fix this for a while now and i just can't get it to pass pep8.
Here is my code:
1.
```
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
sum(regex.count(char) for char in splitter) == 1 and
regex.count('(') == 1 and regex.count(')') == 1):
print('hi')
```
2.
```
if (... | 1.
```
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
sum(regex.count(char) for char in splitter) == 1 and
regex.count('(') == 1 and regex.count(')') == 1):
print('hi')
```
2.
```
if (len(regex) > 2 and regex[0] == '(' and regex[-1] == ')' and
sum(regex.count(char) for c... |
Return None when attribute does not exist | 22,522,929 | 2 | 2014-03-20T03:32:34Z | 22,522,951 | 7 | 2014-03-20T03:35:05Z | [
"python",
"class",
"python-2.7",
"oop",
"attributes"
] | ```
class test(object):
def __init__(self, a = 0):
test.a = a
t = test()
print test.a ## obviously we get 0
''' ====== Question ====== '''
print test.somethingelse ## I want if attributes not exist, return None. How to do that?
``` | First of all, you are adding the variable to the class `test.a = a`. You should be adding it to the instance, `self.a = a`. Because, when you add a value to the class, all the instances will share the data.
You can use [`__getattr__`](http://docs.python.org/2/reference/datamodel.html?object.__getattr__#object.__getatt... |
Selecting a value from a drop-down option using selenium python | 22,524,621 | 12 | 2014-03-20T05:59:54Z | 22,524,923 | 26 | 2014-03-20T06:18:29Z | [
"python",
"selenium"
] | I want to select a value from a drop-down option. The html is as follows:
```
<span id="searchTypeFormElementsStd">
<label for="numReturnSelect"></label>
<select id="numReturnSelect" name="numReturnSelect">
<option value="200"></option>
<option value="250"></option>
<option value="500"... | Adrian Ratnapala is right and also i would choose `id` over `name`, so you can try the following :
```
find_element_by_xpath("//select[@id='numReturnSelect']/option[@value='15000']").click()
```
OR
```
find_element_by_css_selector("select#numReturnSelect > option[value='15000']").click()
```
OR
you can use [`selec... |
Brackets around if and for | 22,526,510 | 4 | 2014-03-20T07:43:55Z | 22,526,575 | 7 | 2014-03-20T07:47:21Z | [
"python"
] | I am a python newbie and have a question. Why can a if allow a brackets and not for.
1. `if (1==2):`
2. `for (i in range(1,10)):`
3. `while (i<10):`
First one and third one are valid syntax but not second one.
```
File "<stdin>", line 2
for (i in range(1,10)):
^
``` | Because `for (i in range(1,10))` isn't syntactically correct.
Lets assume `(i in range(1,10))` was parsed anyway, it would return a boolean. So then you're trying to say `for True` or `for False`, and booleans can't be iterated, and it's invalid syntax.
---
The reason why your other examples work is because they exp... |
passing command line argument to python-behave | 22,528,535 | 9 | 2014-03-20T09:26:21Z | 22,702,647 | 13 | 2014-03-28T01:42:33Z | [
"python",
"bdd",
"python-behave"
] | I am using python-behave for BDD testing, I have to pass an URL (e.g. www.abc.com) from command line.
```
$behave -u "www.abc.com"
```
To achieve this, I have read [behave documentation](http://pythonhosted.org/behave/behave.html#configuration-files) but there are not enough materials as well as explanations given fo... | No, it's not possible, because there is a `parser` that is [defined](https://github.com/behave/behave/blob/77ebf779452a826601f21629f4351027f3639dda/behave/configuration.py#L421) in `configuration.py` file, and only [allow](https://github.com/behave/behave/blob/77ebf779452a826601f21629f4351027f3639dda/behave/configurati... |
passing command line argument to python-behave | 22,528,535 | 9 | 2014-03-20T09:26:21Z | 28,638,924 | 10 | 2015-02-20T21:56:52Z | [
"python",
"bdd",
"python-behave"
] | I am using python-behave for BDD testing, I have to pass an URL (e.g. www.abc.com) from command line.
```
$behave -u "www.abc.com"
```
To achieve this, I have read [behave documentation](http://pythonhosted.org/behave/behave.html#configuration-files) but there are not enough materials as well as explanations given fo... | The suggested solutions above were needed in the past.
behave-1.2.5 provides a "userdata" concept that allows the user to define its data:
```
behave -D browser=firefox ...
```
**SEE ALSO:** [behave: userdata](http://pythonhosted.org//behave/new_and_noteworthy_v1.2.5.html#index-7) |
No module named setuptools | 22,531,360 | 23 | 2014-03-20T11:20:15Z | 22,540,309 | 26 | 2014-03-20T17:09:16Z | [
"python",
"python-2.7",
"twilio"
] | I want to install setup file of twilio. When I install it through given command it is given me an error "No module named setuptools".
Could you please let me know what should I do?
I am using python 2.7.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
```
C:\Pytho... | Install
```
setuptools
```
<https://pypi.python.org/pypi/setuptools>
and try again |
No module named setuptools | 22,531,360 | 23 | 2014-03-20T11:20:15Z | 24,733,673 | 11 | 2014-07-14T09:45:26Z | [
"python",
"python-2.7",
"twilio"
] | I want to install setup file of twilio. When I install it through given command it is given me an error "No module named setuptools".
Could you please let me know what should I do?
I am using python 2.7.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
```
C:\Pytho... | The [PyPA recommended](https://python-packaging-user-guide.readthedocs.org/en/latest/current.html) tool for installing and managing Python packages is `pip`. `pip` is included with Python 3.4 ([PEP 453](http://legacy.python.org/dev/peps/pep-0453/)), but for older versions here's [how to install](https://pip.pypa.io/en/... |
Strange behaviour when subclassing datetime.timedelta | 22,531,489 | 7 | 2014-03-20T11:25:10Z | 22,531,773 | 9 | 2014-03-20T11:37:31Z | [
"python",
"datetime",
"python-2.7",
"timedelta"
] | for convenience I want to create subclasses of datetime.timedelta. The idea is to define a class as such:
```
class Hours(datetime.timedelta):
def __init__(self, hours):
super(Hours, self).__init__(hours=hours)
```
so I can quickly create timedeltas like that:
```
x = Hours(n)
```
However, the code abov... | If you use `__new__`, instead of `__init__`:
```
import datetime as DT
class Hours(DT.timedelta):
def __new__(self, hours):
return DT.timedelta.__new__(self, hours=hours)
x = Hours(10)
print(x)
```
yields
```
10:00:00
```
---
If you override `__init__`, but not `__new__`, then `DT.timedelta.__new__` ge... |
Pandas: peculiar performance drop for inplace rename after dropna | 22,532,302 | 5 | 2014-03-20T11:59:42Z | 22,533,110 | 12 | 2014-03-20T12:30:32Z | [
"python",
"performance",
"pandas",
"in-place"
] | I have reported this as an issue on [pandas issues](https://github.com/pydata/pandas/issues/6674).
In the meanwhile I post this here hoping to save others time, in case they encounter similar issues.
Upon profiling a process which needed to be optimized I found that renaming columns NOT inplace improves performance (e... | This is a copy of the explanation on github.
Their is **no guarantee** that an `inplace` operation is actually faster. Often they are actually the same operation that works on a copy, but the top-level reference is reassigned.
The reason for the difference in performance in this case is as follows.
The `(df1-df2).dr... |
How to output a paragraph with line breaks in django and mysql? | 22,538,454 | 8 | 2014-03-20T15:56:53Z | 22,538,524 | 11 | 2014-03-20T15:59:16Z | [
"python",
"mysql",
"django",
"django-templates"
] | I have text saved in a column that looks like this.
```
This is the text
This is on a new line with a space in between
```
But when i output it on the Django template, it comes out like this
```
This is the text This is on a new line with a space in between
```
Do I have to process this in the views or the templat... | Use [`linebreaks`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#linebreaks) or [`linebreaksbr`](https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#linebreaksbr) filter:
```
{{ text|linebreaks }}
```
Or surround the text with `<pre>...</pre>`.
```
<pre>{{ text }}</pre>
``` |
Django: reverse accessors for foreign keys clashing | 22,538,563 | 27 | 2014-03-20T16:00:36Z | 22,538,875 | 41 | 2014-03-20T16:12:18Z | [
"python",
"django"
] | I have two Django models which inherit from a base class:
```
- Request
- Inquiry
- Analysis
```
Request has two foreign keys to the built-in User model.
```
create_user = models.ForeignKey(User, related_name='requests_created')
assign_user = models.ForeignKey(User, related_name='requests_assigned')
```
For... | The related\_name would ensure that the fields were not conflicting with each other, but you have two models, each of which has both of those fields. You need to put the name of the concrete model in each one, which you can do with some special [string substitution](https://docs.djangoproject.com/en/1.6/topics/db/model... |
Slice pandas DataFrame where column's value exists in another array | 22,542,312 | 6 | 2014-03-20T18:43:20Z | 22,542,608 | 9 | 2014-03-20T18:58:15Z | [
"python",
"numpy",
"pandas"
] | I have a `pandas.DataFrame` with a large amount of data. In one column are randomly repeating keys. In another array I have a list of of theys keys for which I would like to slice from the `DataFrame` along with the data from the other columns in their row.
**keys**:
```
keys = numpy.array([1,5,7])
```
**data**:
``... | You can use `isin`:
```
>>> df[df.a.isin(keys)]
a b c d
indx
0 5 25.0 42.1 13
3 7 43.1 11.0 10
4 1 11.2 31.6 10
5 5 15.6 2.8 11
6 7 14.2 19.0 4
[5 rows x 4 columns]
```
or `query`:
```
>>> df.query("a in @keys")
a b c d
indx ... |
ggplot styles in Python | 22,543,208 | 18 | 2014-03-20T19:28:24Z | 22,543,333 | 20 | 2014-03-20T19:34:47Z | [
"python",
"matplotlib",
"pandas",
"ipython"
] | When I look at the [plotting style in the Pandas documentation](http://pandas.pydata.org/pandas-docs/dev/visualization.html), the plots look different from the default one. It seems to mimic the ggplot "look and feel".
Same thing with the [seaborn's package](http://nbviewer.ipython.org/github/mwaskom/seaborn/blob/mast... | **Update:** If you have matplotlib >= 1.4, there is a new `style` module which has a `ggplot` style by default. To activate this, use:
```
from matplotlib import pyplot as plt
plt.style.use('ggplot')
```
This is recommended above the styling through the pandas options as explained below (and is also used in the panda... |
using pandas to select rows conditional on multiple equivalencies | 22,546,425 | 14 | 2014-03-20T22:23:36Z | 22,546,459 | 20 | 2014-03-20T22:25:58Z | [
"python",
"pandas"
] | I have a pandas df and would like to accomplish something along these lines (in SQL terms):
```
SELECT * FROM df WHERE column1 = 'a' OR column2 = 'b' OR column3 = 'c' etc...
```
Now this works, for one column/value pair:
```
foo = df.ix[df['column']==value]
```
However, I'm not sure how to expand that to multiple c... | You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (`&`) and or (`|`) operators:
```
foo = df.ix[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c']
```
The bitwise operators are because if you don't and use `and` or `or` then it is likely to thr... |
How to retrieve Facebook friend's information with Python-Social-auth and Django | 22,548,223 | 9 | 2014-03-21T00:57:57Z | 22,790,358 | 11 | 2014-04-01T15:31:21Z | [
"python",
"django",
"facebook",
"facebook-graph-api",
"python-social-auth"
] | How can I retrieve Facebook friend's information using Python-Social-auth and Django? I already retrieve a profile information and authenticate the user, but I want to get more information about their friends and invite them to my app.
Thanks! | You can do it using Facebook API. Firstly, you need obtain the token of your Facebook application (`FACEBOOK_APP_ACCESS_TOKEN`) <https://developers.facebook.com/tools/accesstoken/>
or from `social_user.extra_data['access_token']`
Then with this token you can send the requests you need, for example, this code gets all ... |
How to reverse sklearn.OneHotEncoder transform to recover original data? | 22,548,731 | 5 | 2014-03-21T01:50:31Z | 35,898,452 | 7 | 2016-03-09T17:25:29Z | [
"python",
"machine-learning",
"scipy",
"scikit-learn"
] | Excuse my lack of knowledge. I have only been dallying with Python for less than a month. I encoded my categorical data using `sklearn.OneHotEncoder` and fed them to a random forest classifier. Everything seems to work and I got my predicted output back. Is there a way to reverse the encoding and convert my output back... | A good systematic way to figure this out is to start with some test data and work through the [`sklearn.OneHotEncoder`](https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/preprocessing/data.py#L1655) source with it. If you don't much care about how it works and simply want a quick answer, skip to the bot... |
How to send Autobahn/Twisted WAMP message from outside of protocol? | 22,549,370 | 4 | 2014-03-21T03:04:03Z | 22,559,675 | 7 | 2014-03-21T13:07:30Z | [
"python",
"twisted",
"autobahn",
"wamp-protocol"
] | I am following the basic wamp pubsub examples in [the github code](https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/basic/pubsub/basic):
This example publishes messages from within the class:
```
class Component(ApplicationSession):
"""
An application component that publishes an event ev... | Upon your app session joining the WAMP realm, it sets a reference to itself on the app session factory:
```
class MyAppComponent(ApplicationSession):
... snip
def onJoin(self, details):
if not self.factory._myAppSession:
self.factory._myAppSession = self
```
You then can access this session fro... |
Python pandas Filtering out nan from a data selection of a column of strings | 22,551,403 | 18 | 2014-03-21T06:04:19Z | 22,553,757 | 29 | 2014-03-21T08:33:05Z | [
"python",
"pandas",
"dataframe"
] | Without using `groupby` how would I filter out data without `NaN`?
Let say I have a matrix where customers will fill in 'N/A','n/a' or any of its variations and others leave it blank:
```
import pandas as pd
import numpy as np
df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
... | Just drop them:
```
nms.dropna(thresh=2)
```
this will drop all rows where there are at least two `NaN`
then you could then drop where name is `NaN`:
```
In [87]:
nms
Out[87]:
movie name rating
0 thg John 3
1 thg NaN 4
3 mol Graham NaN
4 lob NaN NaN
5 lob NaN ... |
how to avoid Permission denied while installing package for Python without sudo | 22,551,461 | 4 | 2014-03-21T06:07:52Z | 22,551,674 | 8 | 2014-03-21T06:21:28Z | [
"python",
"centos",
"tesseract",
"python-tesseract"
] | I am trying to install the `tesseract` wrapper for python as user `mike` so that I can `import tesseract`. I'm following the guide here <https://code.google.com/p/python-tesseract/wiki/HowToCompilePythonTesseractForCentos>
However, when I execute `python setup.py install`
I get the error below:
```
[Errno 13] Pe... | try `python setup.py install --user` |
Print a list of space-separated elements in Python 3 | 22,556,449 | 6 | 2014-03-21T10:38:56Z | 22,556,506 | 18 | 2014-03-21T10:41:58Z | [
"python",
"python-3.x",
"pretty-print"
] | I have a list `L` of elements, say natural numbers. I want to print them in one line with a **single space** as a separator. But I **don't want** a space after the last element of the list (or before the first).
In Python 2, this can easily be done with the following code. The implementation of the `print` statement (... | You can apply the list as separate arguments:
```
print(*L)
```
and let `print()` take care of converting each element to a string. You can, as always, control the separator by setting the `sep` keyword argument:
```
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, ... |
AttributeError 'tuple' object has no attribute 'get' | 22,557,014 | 2 | 2014-03-21T11:05:33Z | 22,557,095 | 17 | 2014-03-21T11:09:26Z | [
"python",
"django"
] | I have a Django application. But i can't an error that i have been struggling with for some time now.
```
Exception Value: 'tuple' object has no attribute 'get'
Exception Location: /Library/Python/2.7/site-packages/django/middleware/clickjacking.py in process_response, line 30
```
And this is the traceback django pr... | You are returning a tuple here:
```
elif retailer_pk:
return (request, 'page-retailer-single.html', {
"products": products,
"sorting": filt["sorting"],
"filtering": filt["filtering"],
"retailer": retailer,
})
```
Did you forget to add `render` there perhaps:
```
elif retailer_... |
numpy savetxt formated as integer is not saving zeroes | 22,557,322 | 5 | 2014-03-21T11:18:23Z | 22,582,992 | 7 | 2014-03-22T20:13:16Z | [
"python",
"arrays",
"csv",
"numpy"
] | I am trying to save numpy.array to .csv in the following way.
```
with open("resultTR.csv", "wb") as f:
f.write(b'ImageId,Label\n')
numpy.savetxt(f, result, fmt='%i', delimiter=",")
```
result is numpy.array that consists of two columns, first column are indices (numbers 1 through n) and second column values ... | I would try saving the array as an int array, as in `result.astype(int)`, or in full:
```
with open("resultTR.csv", "wb") as f:
f.write(b'ImageId,Label\n')
numpy.savetxt(f, result.astype(int), fmt='%i', delimiter=",")
``` |
How can I condense this simple "if" line of code? | 22,558,248 | 4 | 2014-03-21T12:02:47Z | 22,558,337 | 15 | 2014-03-21T12:07:28Z | [
"python"
] | I have a line of code in my program that checks if a number is divisible by several numbers.
However, the way I currently have it is extremely inefficient and ugly.
It currently looks like:
`if(x % 1 == 0 and x % 2 == 0 and x % 3 == 0)` and so forth for several other numbers. I was hoping someone could teach me how ... | ```
if all(x % k == 0 for k in [1, 2, 3]):
print 'yay'
``` |
eval SyntaxError: invalid syntax in python | 22,558,548 | 6 | 2014-03-21T12:18:05Z | 22,558,661 | 7 | 2014-03-21T12:22:30Z | [
"python"
] | I want to assign :
```
x0='123'
x1='123'
x2='123'
x3='123'
x4='123'
x5='123'
x6='123'
x7='123'
x8='123'
x9='123'
```
I write the code to express that i can get the output of a string `123` when input `x1` or `x8` .
```
for i in range(0,10):
eval("x"+str(i)+"='123'")
Traceback... | `eval()` only allows for *expressions*. Assignment is not an expression but a statement; you'd have to use `exec` instead.
Even then you could use the `globals()` dictionary to add names to the global namespace and you'd not need to use any arbitrary expression execution.
You **really** don't want to do this, you nee... |
'str' object has no attribute 'get' | 22,559,446 | 10 | 2014-03-21T12:56:59Z | 22,560,189 | 13 | 2014-03-21T13:30:07Z | [
"python",
"django",
"braintree"
] | I'm working on Braintree intergration in Django. I've followed [this guide](https://www.braintreepayments.com/docs/python/guide/getting_paid):
However, I'm getting the error `'str' object has no attribute 'get'`.
Views.py
```
from django.shortcuts import render, render_to_response
from django.http.response import Ht... | You're returning strings directly from `create_transaction` inside the POST block. You need to wrap them in an HttpResponse. |
error: [Errno 32] Broken pipe | 22,560,259 | 11 | 2014-03-21T13:33:54Z | 22,560,461 | 19 | 2014-03-21T13:41:36Z | [
"python",
"django",
"python-2.7",
"broken-pipe"
] | I am working on a Django project. All went well till I created an Ajax request to send values from the html page to the backend (views.py).
When I send the data using Ajax, I am able to view the values being passed to views.py, and it even reaches the render\_to\_response method and displays my page, but throws the br... | You haven't posted any code, but this is probably because you have triggered the Ajax request on a button submit but haven't prevented the default action. So the Ajax request is made, but by the time it comes to return the data, the browser has already requested the next page anyway, so there is nothing to receive it. |
Django rest framework ignores has_object_permission | 22,561,698 | 3 | 2014-03-21T14:35:43Z | 22,567,895 | 8 | 2014-03-21T19:30:38Z | [
"python",
"django",
"django-rest-framework"
] | I'm trying to limit the access to objects for users. Only creaters should modify objects. For that purpose like they say in tutorial I've written
```
class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return False
```
and added it to permission\_class... | the permission-checks for objects are done by DRF in the method `APIView.check_object_permissions`.
Since you don't use the `GenericAPIView`, you define your own `get_object` method and you have to call `check_object_permissions` yourself. Since you are mis-using get\_object a bit, you have to check for GET (single), ... |
Circular Histogram for Python | 22,562,364 | 13 | 2014-03-21T15:03:50Z | 22,568,292 | 15 | 2014-03-21T19:52:54Z | [
"python",
"matplotlib",
"plot",
"visualization",
"histogram"
] | I have periodic data and the distribution for it is best visualised around a circle. Now the question is how can I do this visualisation using matplotlib? If not, can it be done easily in Python?
My code here will demonstrate a crude approximation of distribution around a circle:
```
from matplotlib import pyplot as ... | Building off of [this](http://matplotlib.org/examples/pie_and_polar_charts/polar_bar_demo.html) example from the gallery, you can do

```
import numpy as np
import matplotlib.pyplot as plt
N = 80
bottom = 8
max_height = 4
theta = np.linspace(0.0, 2 ... |
AttributeError: can't set attribute in python | 22,562,425 | 12 | 2014-03-21T15:06:27Z | 22,562,687 | 18 | 2014-03-21T15:18:31Z | [
"python",
"attributes"
] | Here is my code
```
N = namedtuple("N", ['ind', 'set', 'v'])
def solve()
items=[]
stack=[]
R = set(range(0,8))
for i in range(0,8):
items.append(N(i,R,8))
stack.append(N(0,R-set(range(0,1)),i))
while(len(stack)>0):
node = stack.pop()
print node
print i... | ```
items[node.ind] = items[node.ind]._replace(v=node.v)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.