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 |
|---|---|---|---|---|---|---|---|---|---|
Get the key with the maximum nested key in a python dictionary | 22,327,968 | 3 | 2014-03-11T14:00:34Z | 22,328,050 | 8 | 2014-03-11T14:03:31Z | [
"python",
"dictionary"
] | I have a dictionary like so:
```
my_dictionary = {
'key1': {'a': 1, 'b': 1, 'c': 10},
'key2': {'a': 1, 'b': 1, 'c': 11},
'key3': {'a': 1, 'b': 1, 'c': 12}
}
```
How can I compare the 'c' subkeys of this dictionary, find the greatest one, and return the corresponding parent key of that dictionary (... | ```
>>> d
{'key1': {'a': 1, 'b': 1, 'c': 10},
'key2': {'a': 1, 'b': 1, 'c': 11},
'key3': {'a': 1, 'b': 1, 'c': 12}}
>>> max(d, key=lambda v: d[v]['c'])
'key3'
``` |
How to efficiently remove the same-length elements from a list in python | 22,330,472 | 5 | 2014-03-11T16:15:02Z | 22,330,695 | 8 | 2014-03-11T16:26:59Z | [
"python"
] | For example, I have a list:
`[[1,3],[23,4],[13,45,6],[8,3],[44,33,12]]`
Is there any efficient way that I can finally get the list below?
`[[1,3],[13,45,6]]`
For every length of the list, keep only one element. | Just make a dictionary keyed off the length and get its values:
```
>>> l = [[1,3],[23,4],[13,45,6],[8,3],[44,33,12]]
>>> dict((len(i), i) for i in l).values()
[[8, 3], [44, 33, 12]]
``` |
How to get maya main window pointer using PySide? | 22,331,337 | 2 | 2014-03-11T16:52:21Z | 22,332,397 | 9 | 2014-03-11T17:39:36Z | [
"python",
"pyqt",
"pyside",
"maya"
] | I've used PyQt4 in maya quite a bit, and generally I've found it quite easy to switch to PySide, but I'm having trouble getting the pointer to the main window. Perhaps someone can understand what's going wrong.
Here's what I do in PyQt4:
```
import sip, PyQt4.QtCore
import maya.OpenMayaUI as mui
ptr = mui.MQtUtil.mai... | You need to import `shiboken` instead of `sip` and pass `QWidget` to `wrapInstance` instead of QObject
```
import shiboken
from PySide import QtGui, QtCore
import maya.OpenMayaUI as apiUI
def getMayaWindow():
"""
Get the main Maya window as a QtGui.QMainWindow instance
@return: QtGui.QMainWindow instance ... |
Why can't I call an exception after I except it? | 22,332,599 | 3 | 2014-03-11T17:48:16Z | 22,332,683 | 7 | 2014-03-11T17:51:47Z | [
"python",
"exception",
"scope"
] | Why can't I raise an Exception instance after I catch that Exception class? Oddly enough, I run into this error when I run the script from a function but not when ran directly in the python shell.
```
In [2]: def do():
...: try:
...: raise ValueError('yofoo')
...: except TypeError, ValueError:... | ```
except TypeError, ValueError:
```
should be
```
except (TypeError, ValueError):
```
When you use `except TypeError, ValueError:`, you are assigning the Exception instance to the variable name `ValueError`.
With your current code, when Python parses the `do` function, it notes `ValueError` is a local variable be... |
Vertical Histogram in Python and Matplotlib | 22,333,568 | 3 | 2014-03-11T18:31:08Z | 22,334,893 | 11 | 2014-03-11T19:36:15Z | [
"python",
"numpy",
"matplotlib",
"plot",
"histogram"
] | How can I make a vertical histogram. Is there any option for that or should it be built from the scratch? What I want is the upper graph to look like the below one but on vertical axis!
```
from matplotlib import pyplot as plt
import numpy as np
sample=np.random.normal(size=10000)
vert_hist=np.histogram(sample,bins=30... | Use `orientation="horizontal"` in `ax.hist`:
```
from matplotlib import pyplot as plt
import numpy as np
sample = np.random.normal(size=10000)
vert_hist = np.histogram(sample, bins=30)
ax1 = plt.subplot(2, 1, 1)
ax1.plot(vert_hist[0], vert_hist[1][:-1], '*g')
ax2 = plt.subplot(2, 1, 2)
ax2.hist(sample, bins=30, ori... |
Installing Pillow/PIL on Mavericks | 22,334,776 | 18 | 2014-03-11T19:30:43Z | 22,351,527 | 58 | 2014-03-12T12:27:02Z | [
"python",
"python-imaging-library",
"pip",
"easy-install",
"pillow"
] | I'm getting a strange error when trying to install Pillow using pip/easy\_install:
```
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -f... | I solved that problem the following way. Propably has something to do with todays Mavericks commandline tools update. Try adding following to the terminal before executing pip install:
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
``` |
Installing Pillow/PIL on Mavericks | 22,334,776 | 18 | 2014-03-11T19:30:43Z | 23,094,087 | 13 | 2014-04-15T20:40:28Z | [
"python",
"python-imaging-library",
"pip",
"easy-install",
"pillow"
] | I'm getting a strange error when trying to install Pillow using pip/easy\_install:
```
cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -f... | Run this command in the terminal:
`ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install pillow`
### More info:
The compiler that comes with Xcode 5.1 treats unknown passed parameters as errors.
We're telling it to ignore those "errors"
source: <http://bruteforce.gr/bypassing-clang-err... |
In Python, why can a lambda expression refer to the variable being defined but not a list? | 22,335,171 | 28 | 2014-03-11T19:49:57Z | 22,335,232 | 25 | 2014-03-11T19:52:37Z | [
"python"
] | This is more a curiosity than anything, but I just noticed the following. If I am defining a self-referential lambda, I can do it easily:
```
>>> f = lambda: f
>>> f() is f
True
```
But if I am defining a self-referential list, I have to do it in more than one statement:
```
>>> a = [a]
Traceback (most recent call l... | The expression inside a lambda is evaluated when the function is *called*, not when it is defined.
In other words, Python will not evaluate the `f` inside your lambda until you call it. And, by then, `f` is already defined in the current scope (it is the lambda itself). Hence, no `NameError` is raised.
---
Note that... |
In Python, why can a lambda expression refer to the variable being defined but not a list? | 22,335,171 | 28 | 2014-03-11T19:49:57Z | 22,335,233 | 9 | 2014-03-11T19:52:46Z | [
"python"
] | This is more a curiosity than anything, but I just noticed the following. If I am defining a self-referential lambda, I can do it easily:
```
>>> f = lambda: f
>>> f() is f
True
```
But if I am defining a self-referential list, I have to do it in more than one statement:
```
>>> a = [a]
Traceback (most recent call l... | Because a lambda is a function, and the function body is not executed until the function is called.
In other words, the other way to do it is this:
```
def f():
return f
```
But you're correct that you can't do it in an *expression* because `def` is a statement, so it can't be used in an expression. |
How to wait for a child process to finish in Node.js? | 22,337,446 | 8 | 2014-03-11T21:51:46Z | 22,365,830 | 18 | 2014-03-12T23:13:28Z | [
"python",
"node.js",
"child-process"
] | I'm running a Python script through a child process in Node.js, like this:
```
require('child_process').exec('python celulas.py', function (error, stdout, stderr) {
child.stdout.pipe(process.stdout);
});
```
but Node doesn't wait for it to finish. How can I wait for the process to finish?
EDIT: Is it possible to... | Use `exit` event for the child process.
```
var child = require('child_process').exec('python celulas.py')
child.stdout.pipe(process.stdout)
child.on('exit', function() {
process.exit()
})
```
PS: It's not really a duplicate, since you don't want to use sync code unless you really really need it. |
Django: List field in model? | 22,340,258 | 33 | 2014-03-12T01:34:55Z | 22,343,764 | 9 | 2014-03-12T06:35:57Z | [
"python",
"django"
] | In my model, I want a field that has a list of triplets. e.g. `[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database? | I think it will help you.
```
from django.db import models
import ast
class ListField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python list"
def __init__(self, *args, **kwargs):
super(ListField, self).__init__(*args, **kwargs)
def to_python(self, value):
... |
Django: List field in model? | 22,340,258 | 33 | 2014-03-12T01:34:55Z | 22,343,962 | 45 | 2014-03-12T06:47:57Z | [
"python",
"django"
] | In my model, I want a field that has a list of triplets. e.g. `[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database? | You can convert it into string by using JSON and store it as string.
For example,
```
In [3]: json.dumps([[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]])
Out[3]: '[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]'
```
You can add a method into your class to convert it automatically for you.
```
import json
class Fooba... |
Django: List field in model? | 22,340,258 | 33 | 2014-03-12T01:34:55Z | 30,820,694 | 7 | 2015-06-13T16:01:42Z | [
"python",
"django"
] | In my model, I want a field that has a list of triplets. e.g. `[[1, 3, 4], [4, 2, 6], [8, 12, 3], [3, 3, 9]]. Is there a field that can store this data in the database? | If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: <https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/>
This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.
Note that you will have to create a GIN index by ... |
get list from pandas dataframe column | 22,341,271 | 31 | 2014-03-12T03:12:33Z | 22,341,390 | 50 | 2014-03-12T03:24:24Z | [
"python",
"list",
"pandas"
] | I have an excel document which looks like this..
```
cluster load_date budget actual fixed_price
A 1/1/2014 1000 4000 Y
A 2/1/2014 12000 10000 Y
A 3/1/2014 36000 2000 Y
B 4/1/2014 15000 10000 N
B 4/1/2014 12000 11500 N
B 4/1/2014 90000 11000 N
C 7/1/2014 ... | Pandas Dataframe columns are a Pandas Series when you pull them out, which you can then call `.tolist()` on to turn them into a python list
```
from pandas import *
d = {'one' : Series([1., 2., 3.], index=['a', 'b', 'c']),
'two' : Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = DataFrame(d)
#print df... |
Why does zip on a generator return just one item? | 22,341,939 | 4 | 2014-03-12T04:17:41Z | 22,341,953 | 7 | 2014-03-12T04:18:45Z | [
"python",
"python-2.7",
"generator"
] | I tried this in Python, thinking it would give me [(1,123),(2,123)]:
```
Python 2.7.3 (default, Feb 27 2014, 19:58:35)
>>> def my_generator():
... yield 123
...
>>> zip([1,2], my_generator())
[(1, 123)]
```
Why does zip stop after creating just one item? Is there a Pythonic way to get what I was looking for? | Create an infinite generator, like this
```
def my_generator():
while True:
yield 123
print zip([1,2], my_generator())
# [(1, 123), (2, 123)]
```
The better way to do this would be, using [`itertools.repeat`](http://docs.python.org/2/library/itertools.html#itertools.repeat), like this
```
from itertools ... |
summing two columns in a pandas dataframe | 22,342,285 | 2 | 2014-03-12T04:51:03Z | 22,342,344 | 7 | 2014-03-12T04:57:20Z | [
"python",
"pandas"
] | when I use this syntax it creates a series rather than adding a column to my new dataframe (sum). Please help.
My code:
```
sum = data['variance'] = data.budget + data.actual
```
My Data (in dataframe df): (currently has everything except the budget - actual, I want to create a variance column?
```
cluster ... | I think you've misunderstood some python syntax, the following does two assignments:
```
In [11]: a = b = 1
In [12]: a
Out[12]: 1
In [13]: b
Out[13]: 1
```
So in your code it was as if you were doing:
```
sum = df['budget'] + df['actual'] Â # a Series
# and
df['variance'] = df['budget'] + df['actual'] # assigned ... |
Returning the first index of an element in a vector in C++ | 22,342,581 | 2 | 2014-03-12T05:16:29Z | 22,342,689 | 7 | 2014-03-12T05:24:40Z | [
"python",
"c++",
"vector",
"indexing"
] | I am trying to find the first index of an element in a vector in c++.
Let's say you have a vector: [2, 3, 4, 2, 6, 7, 1, 2, 6, 3].
I would like to find the position of the number 6.
So the first time the number 6 occurs is at an index value of 4.
Is there a function that can do that in C++?
I know in Python, I can... | ```
std::vector<int> vct;
//insert value
//use std::find to get iterator
auto itr=std::find(vct.begin(), vct.end(), 6);
if(itr==vct.end())
return;
auto index=std::distance(vct.begin(), itr);
``` |
Embedding a plot in a website with Python/bokeh | 22,345,249 | 10 | 2014-03-12T07:57:50Z | 22,391,260 | 7 | 2014-03-13T21:25:21Z | [
"python",
"bokeh"
] | I am trying to statically embed a bokeh plot in a personal website, and am encountering some behavior I do not understand. Basically, I am generating a plot using bokeh as follows:
```
import bokeh.plotting as bplt
import numpy as np
x=np.random.random(100)
y=np.random.random(100)
bplt.output_file("t.html")
plot=bpl... | It sounds like you want to do a "non-server embded" which really just means that the plot description and all the data for the plot is contained in the `foo.embed.js` file, instead of getting pulled from a "Bokeh server". In that case, you want to set `embed_base_url` to the location (on your server) where the embed.js... |
Embedding a plot in a website with Python/bokeh | 22,345,249 | 10 | 2014-03-12T07:57:50Z | 24,803,830 | 11 | 2014-07-17T12:38:18Z | [
"python",
"bokeh"
] | I am trying to statically embed a bokeh plot in a personal website, and am encountering some behavior I do not understand. Basically, I am generating a plot using bokeh as follows:
```
import bokeh.plotting as bplt
import numpy as np
x=np.random.random(100)
y=np.random.random(100)
bplt.output_file("t.html")
plot=bpl... | UPDATE: the `create_html_snippet` function has been deprecated. Please now use the much better `bokeh.embed` module:
<https://github.com/ContinuumIO/bokeh/blob/master/bokeh/embed.py>
You can see some examples of its use at:
<https://github.com/ContinuumIO/bokeh/tree/master/examples/embed> |
What's the difference between Model.id and Model.pk in django? | 22,345,711 | 5 | 2014-03-12T08:23:38Z | 22,345,745 | 9 | 2014-03-12T08:25:27Z | [
"python",
"django",
"web",
"django-models"
] | I saw the django documents use both sometimes? Are they identical? What's the difference and where is the reference? I only see document of pk.
BTW, does django reference cover all the methods of it's classes? | `pk` is the attribute that [contains the value of the primary key for the model](https://docs.djangoproject.com/en/dev/ref/models/instances/#the-pk-property). `id` is the name of the field created as a primary key by default [if none is explicitly specified](https://docs.djangoproject.com/en/dev/topics/db/models/#autom... |
Python requests, how to limit received size, transfer rate, and/or total time? | 22,346,158 | 5 | 2014-03-12T08:45:23Z | 22,347,526 | 7 | 2014-03-12T09:46:54Z | [
"python",
"python-requests"
] | My server does external requests and I'd like to limit the damage a failing request can do. I'm looking to cancel the request in these situations:
* the total time of the request is over a certain limit (even if data is still arriving)
* the total received size exceeds some limit (I need to cancel prior to accepting m... | You could try setting `stream=True`, then aborting a request when your time or size limits are exceeded while you read the data in chunks.
As of [`requests` release 2.3.0](https://github.com/kennethreitz/requests/releases/tag/v2.3.0) the timeout applies to streaming requests too, so all you need to do is allow for a t... |
Map string values in a Pandas Dataframe with integers | 22,346,552 | 2 | 2014-03-12T09:04:03Z | 22,346,955 | 8 | 2014-03-12T09:23:08Z | [
"python",
"pandas",
"dataframe"
] | In Pandas `DataFrame` how to map strings in one column with integers. I have around 500 strings in the `DataFrame` and need to replace them with integers starting with '1'.
Sample `DataFrame`.
```
Request count
547 GET /online/WebResource.axd 37506
424 GE... | So what you could do is construct a temporary dataframe and merge this back to your existing dataframe:
```
temp_df = pd.DataFrame({'Request': df.Request.unique(), 'Request_id':range(len(df.Request.unique()))})
```
Now merge this back to your original dataframe
```
df = df.merge(temp_df, on='Request', how='left')
``... |
How to avoid rebuilding existing wheels when using pip? | 22,346,807 | 8 | 2014-03-12T09:16:33Z | 22,617,060 | 11 | 2014-03-24T17:58:34Z | [
"python",
"pip",
"python-wheel"
] | With `pip 1.5.X`, we can use `pip wheel` to build and cache a wheel of a package, then use `--use-wheel` with `pip install` to install from the cached wheel.
I'm trying to use this feature in a environment setup script.
This is what I'm trying:
```
pip wheel --wheel-dir=/tmp Cython==0.19.2
pip install Cython==0.19.2 ... | I've been using the option
```
--find-links=/tmp
```
where /tmp is the wheelhouse. This seems to actually check the wheelhouse and not re-download things. Using your example, try this:
```
pip wheel --find-links=/tmp --wheel-dir=/tmp Cython==0.19.2
``` |
Pillow installation error: command 'gcc' failed with exit status 1 | 22,347,489 | 8 | 2014-03-12T09:44:55Z | 23,554,570 | 10 | 2014-05-08T23:53:53Z | [
"python",
"django",
"pillow"
] | I am trying to setup my Django variant (Wagtail) but have problems installing the required Pillow.
Background: Am running `Python 2.6.6`, in `virtualenv`, using Mac terminal to have shell access to domain hosted on A Small Orange, `no root access`, cannot use sudo commands
When i run
```
pip install Pillow
```
i ge... | I had a similar problem (gcc failed, but no mention of permissions), but it was dependencies that were my problem. By the way, my task was to install Pillow on a raspberry pi, which is why those dev libraries were necessary. They may not be necessary for you. It was the python-imaging command that did the trick most, I... |
Pillow installation error: command 'gcc' failed with exit status 1 | 22,347,489 | 8 | 2014-03-12T09:44:55Z | 27,840,189 | 17 | 2015-01-08T12:30:01Z | [
"python",
"django",
"pillow"
] | I am trying to setup my Django variant (Wagtail) but have problems installing the required Pillow.
Background: Am running `Python 2.6.6`, in `virtualenv`, using Mac terminal to have shell access to domain hosted on A Small Orange, `no root access`, cannot use sudo commands
When i run
```
pip install Pillow
```
i ge... | Make sure you have gcc and python-dev installed
`sudo apt-get install gcc python-dev` |
Python Script to convert Image into Byte array | 22,351,254 | 2 | 2014-03-12T12:16:05Z | 22,351,973 | 9 | 2014-03-12T12:43:59Z | [
"python"
] | I am writing a Python script where I want to do bulk photo upload.
I want to read an Image and convert it into a byte array. Any suggestions would be greatly appreciated.
```
#!/usr/bin/python
import xmlrpclib
import SOAPpy, getpass, datetime
import urllib, cStringIO
from PIL import Image
from urllib import urlopen
i... | Use `bytearray`:
```
with open("img.png", "rb") as imageFile:
f = imageFile.read()
b = bytearray(f)
print b[0]
```
You can also have a look at [struct](http://docs.python.org/2/library/struct.html) which can do many conversions of that kind. |
Apply format to a cell after being written in XlsxWriter | 22,352,907 | 10 | 2014-03-12T13:23:08Z | 22,353,696 | 9 | 2014-03-12T13:52:16Z | [
"python",
"excel",
"xlsxwriter"
] | I work on python using XlsxWriter and I've been trying to solve this problem with no success:
My app must create an Xlsx file in which data is shown in a table-like structure.
That table has some empty cells.
I'd like to set borders to some cells to make a grid for the table so I use:
```
format6 = excelbook.add_for... | I'm the author of that module and unfortunately that isn't possible.
It is a [planned feature](https://github.com/jmcnamara/XlsxWriter/issues/111), and (a small) part of the internal infrastructure is there to support it, but it isn't currently available and I can't say when it will be. |
Turning tuples into a pairwise string | 22,352,939 | 4 | 2014-03-12T13:24:28Z | 22,353,055 | 11 | 2014-03-12T13:28:43Z | [
"python"
] | I have the following tuples
```
[ ('StemCells', 16.530000000000001),
('Bcells', 13.59),
('Monocytes', 11.58),
('abTcells', 10.050000000000001),
('Macrophages', 9.6899999999999995),
('gdTCells', 9.4900000000000002),
('StromalCells', 9.3599999999999994),
('DendriticCells', 9.199999999999999... | ```
', '.join('%s(%.02f)' % (x, y) for x, y in tuplelist)
``` |
how to install the SQLALchemy on the ubuntu? | 22,353,512 | 5 | 2014-03-12T13:46:17Z | 22,353,690 | 7 | 2014-03-12T13:52:02Z | [
"python",
"linux",
"sqlalchemy"
] | I want to install Python and SQLAlchemy on Ubuntu. This is my command:
```
sudo easy_install sqlalchemy
```
But it has failed, what should I do? | Aha,sir,I can help you.
First step,you should intall the MySql,like these:
```
sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysqlclient15-dev
```
Second step,install the python-mysqldb:
```
sudo apt-get install python-mysqldb
```
Third step,install the easy\_install:
... |
Pythonic way of detecting outliers in one dimensional observation data | 22,354,094 | 25 | 2014-03-12T14:07:51Z | 22,357,811 | 51 | 2014-03-12T16:26:08Z | [
"python",
"numpy",
"matplotlib",
"statistics",
"statsmodels"
] | For the given data, I want to set the outlier values (defined by 95% confidense level or 95% quantile function or anything that is required) as nan values. Following is the my data and code that I am using right now. I would be glad if someone could explain me further.
```
import numpy as np, matplotlib.pyplot as plt
... | The problem with using `percentile` is that the points identified as outliers is a function of your sample size.
There are a huge number of ways to test for outliers, and you should give some thought to how you classify them. Ideally, you should use a-priori information (e.g. "anything above/below this value is unreal... |
Pythonic way of detecting outliers in one dimensional observation data | 22,354,094 | 25 | 2014-03-12T14:07:51Z | 29,222,992 | 7 | 2015-03-24T00:39:31Z | [
"python",
"numpy",
"matplotlib",
"statistics",
"statsmodels"
] | For the given data, I want to set the outlier values (defined by 95% confidense level or 95% quantile function or anything that is required) as nan values. Following is the my data and code that I am using right now. I would be glad if someone could explain me further.
```
import numpy as np, matplotlib.pyplot as plt
... | I've adapted the code from <http://eurekastatistics.com/using-the-median-absolute-deviation-to-find-outliers> and it gives the same results as Joe Kington's, but uses L1 distance instead of L2 distance, and has support for asymmetric distributions. The original R code did not have Joe's 0.6745 multiplier, so I also add... |
Access-Control-Allow-Origin in Django app when accesed with Phonegap | 22,355,540 | 15 | 2014-03-12T15:02:15Z | 22,360,893 | 28 | 2014-03-12T18:39:09Z | [
"python",
"ajax",
"django",
"cordova",
"cors"
] | I'm developing a Phonegap app for my Django based app, but when trying to make Ajax calls I get this error:
```
XMLHttpRequest cannot load http://domain.herokuapp.com/getcsrf/?tags=jquery%2Cjavascript&tagmode=any&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' i... | Django by default does not provide the headers necessary to provide cross origin. The easiest way would be to just use this Django app that handles it for you: <https://github.com/ottoyiu/django-cors-headers>
You can then set whichever domains you want white listed using the settings
```
CORS_ORIGIN_WHITELIST = (
... |
Is there a datetime ± infinity? | 22,356,069 | 12 | 2014-03-12T15:22:56Z | 22,356,178 | 11 | 2014-03-12T15:26:32Z | [
"python",
"sql",
"django",
"datetime"
] | For floats we have special objects like -inf (and +inf), and which are guaranteed to compare less than (and greater than) other numbers.
I need something similar for datetimes, is there any such thing? In-db ordering must work correctly with django queryset filters, and ideally it should be db-agnostic (but at the ver... | Try this:
```
>>> import datetime
>>> datetime.datetime.max
datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
```
You can get `min`/`max` for `datetime`, `date`, and `time`. |
Numpy savez / load thousands of arrays, but not in one step | 22,356,612 | 3 | 2014-03-12T15:43:03Z | 22,356,751 | 7 | 2014-03-12T15:48:04Z | [
"python",
"arrays",
"serialization",
"numpy"
] | I would like to store approx 4000 numpy arrays (of 1.5 MB each) in a serialized uncompressed file (approx 6 GB of data). Here is an example with 2 small arrays :
```
import numpy
d1 = { 'array1' : numpy.array([1,2,3,4]), 'array2': numpy.array([5,4,3,2]) }
numpy.savez('myarrays', **d1)
d2 = numpy.load('myarrays.npz')
... | I don't think you can do this with np.savez. This, however, is the perfect use-case for hdf5. See either:
<http://www.h5py.org>
or
<http://www.pytables.org>
As an example of how to do this in h5py:
```
h5f = h5py.File('test.h5', 'w')
h5f.create_dataset('array1', data=np.array([1,2,3,4]))
h5f.create_dataset('array2... |
How to assign a NULL value to a pointer in python? | 22,359,737 | 9 | 2014-03-12T17:47:23Z | 22,359,816 | 17 | 2014-03-12T17:50:58Z | [
"python"
] | I am C programmer. I am new to python. In C , when we define the structure of a binary tree node we assign NULL to it's right and left child as :
```
struct node
{
int val;
struct node *right ;
struct node *left ;
};
```
And when initializing a node , we write as :
```
val = some_value
right = N... | All objects in python are implemented with references so the distinction between objects and pointers to objects does not exist in code.
The python equivalent of `NULL` is called `None` (good info [here](http://www.pythoncentral.io/python-null-equivalent-none/)). As all objects in python are implemented with reference... |
Python JSON decoding error TypeError: can't use a string pattern on a bytes-like object | 22,359,997 | 2 | 2014-03-12T17:58:36Z | 22,360,049 | 10 | 2014-03-12T18:00:58Z | [
"python",
"json"
] | Hi there i am coding in python trying to make a user friendly currency exchange app for a school project but have encountered and error with trying to decode json for the exchange rates.
The code i'm using is:
```
import urllib.request
import json
(str) = "http://rate-exchange.appspot.com/currency?from=FRM&to=TO&q=AM"... | In Python 3, you need to *decode* the `bytes` return value from `urllib.request.urlopen()` to a unicode string:
```
decoded = json.loads(json_input.decode('utf8'))
```
This makes the assumption that the web service you are using is using the default JSON encoding of UTF-8.
You could check the response for a characte... |
How does sklearn random forest index feature_importances_ | 22,361,781 | 5 | 2014-03-12T19:22:32Z | 22,362,585 | 8 | 2014-03-12T20:03:09Z | [
"python",
"scikit-learn",
"random-forest",
"feature-selection"
] | I have used the RandomForestClassifier in sklearn for determining the important features in my dataset. How am I able to return the actual feature names (my variables are labeled x1, x2, x3, etc.) rather than their relative name (it tells me the important features are '12', '22', etc.). Below is the code that I am curr... | Feature Importances returns an array where each index corresponds to the estimated feature importance of that feature in the training set. There is no sorting done internally, it is a 1-to-1 correspondence with the features given to it during training.
If you stored your feature names as a numpy array and made sure it... |
How can I stop Python's csv.DictWriter.writerows from adding empty lines between rows in Windows? | 22,361,787 | 4 | 2014-03-12T19:22:45Z | 22,361,817 | 14 | 2014-03-12T19:24:28Z | [
"python",
"windows",
"csv"
] | When I use Python's `csv.DictWriter.writerows` on Windows, empty newlines are added between rows. How do I stop that? The code works fine on Linux. | * In Python 2: Open the file in binary mode, always; `csv.DictWriter()` writes `\r\n` line endings:
```
with open(filename, 'ab') as outputfile:
writer = csv.DictWriter(outputfile, fieldnames)
```
From the [`csv.writer()` documentation](http://docs.python.org/2/library/csv.html#csv.writer):
> If *csv... |
Import a module in Python | 22,362,449 | 4 | 2014-03-12T19:56:16Z | 22,362,505 | 7 | 2014-03-12T19:59:20Z | [
"python"
] | I have an improperly packaged Python module. It only has `__init__.py` file in the directory. This file defines the class that I wish to use. What would be the best way to use it as a module in my script?
\*\* EDIT \*\*
There was a period (.) in the the name of the folder. So the methods suggested here were not worki... | That's not improper. It's a package.
<http://docs.python.org/2/tutorial/modules.html#packages>
```
package/
__init__.py
yourmodule.py
```
In yourmodule.py, you can do either of the following:
```
import package
x = package.ClassName()
```
Or:
```
from package import ClassName
x = ClassName()
``` |
Executing a function in reverse in Python | 22,365,310 | 2 | 2014-03-12T22:32:32Z | 22,365,361 | 9 | 2014-03-12T22:35:57Z | [
"python",
"function"
] | I have a function that looks something like this:
```
def f():
call_some_function_A()
call_some_function_B()
[...]
call_some_function_Z()
```
I'd like the function to be executed in reverse; that is, the execution must look like:
```
def f'():
call_some_function_Z()
[...]
call_some_function_B()
call_... | If your `f()` consists entirely of these function calls, you can remake it into a list:
```
functions = [
call_some_function_A,
call_some_function_B,
# [...]
call_some_function_Z,
]
```
And then use it to call the functions in (reversed) order.
```
def f():
for func in functions:
func()
de... |
Python Windows `msvcrt.getch()` only detects every 3rd keypress? | 22,365,473 | 2 | 2014-03-12T22:44:24Z | 22,365,516 | 7 | 2014-03-12T22:48:04Z | [
"python",
"python-2.7",
"msvcrt",
"event-loop",
"getch"
] | My code is below:
```
import msvcrt
while True:
if msvcrt.getch() == 'q':
print "Q was pressed"
elif msvcrt.getch() == 'x':
sys.exit()
else:
print "Key Pressed:" + str(msvcrt.getch()
```
This code is based on [this question](http://stackoverflow.com/a/13207813/2714746); I was ... | you call the function 3 times in your loop. try calling it only once like this:
```
import msvcrt
while True:
pressedKey = msvcrt.getch()
if pressedKey == 'q':
print "Q was pressed"
elif pressedKey == 'x':
sys.exit()
else:
print "Key Pressed:" + str(pressedKey)
``` |
Change what the *splat and **splatty-splat operators do to my object | 22,365,847 | 6 | 2014-03-12T23:15:06Z | 22,365,935 | 8 | 2014-03-12T23:20:29Z | [
"python",
"iterable-unpacking",
"splat",
"double-splat"
] | Is there any way in python to customise the behaviour of the unpack operators or whatever they're called?
For example, can you somehow create an object x which behaves like this:
```
>>> print(*thing)
a b c
>>> print(*(x for x in thing))
d e f
>>> dict(**thing)
{'hello world': 'I am a potato!!'}
```
***Note:** the i... | `*` iterates over an object and uses its elements as arguments. `**` iterates over an object's `keys` and uses `__getitem__` (equivalent to bracket notation) to fetch key-value pairs. To customize `*` and `**`, simply make your object an iterable or mapping:
```
class MyIterable(object):
def __iter__(self):
... |
Django can't access raw_post_data | 22,368,190 | 9 | 2014-03-13T02:54:26Z | 22,368,223 | 29 | 2014-03-13T02:57:25Z | [
"python",
"django",
"django-1.6"
] | I am experiencing a strange thing with Django, here is my views.py:
```
def api(request):
return HttpResponse("%s %s" % (request.method,request.raw_post_data))
```
Now I make an HTTP POST with POSTMAN (small app for google chrome).
I set POSTMAN to make a POST request with 'test' in the raw field.
Django return... | According to [django 1.6 deprecation timeline](https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-6):
> The attribute `HttpRequest.raw_post_data` was renamed to
> `HttpRequest.body` in 1.4. The backward compatibility will be removed â
> `HttpRequest.raw_post_data` will no longer wo... |
Get Traceback of warnings | 22,373,927 | 21 | 2014-03-13T09:16:10Z | 22,374,014 | 10 | 2014-03-13T09:20:29Z | [
"python",
"warnings",
"traceback"
] | In numpy we can do [`np.seterr(invalid='raise')`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html) to get a traceback for warnings raising an error instead (see [this post](http://stackoverflow.com/questions/4190817/tracing-python-warnings-errors-to-a-line-number-in-numpy-and-scipy)).
* Is there ... | Run your program like
```
python -W error myprogram.py
```
This makes all warnings fatal, see [here](http://docs.python.org/2/using/cmdline.html#cmdoption-W) for more information |
Get Traceback of warnings | 22,373,927 | 21 | 2014-03-13T09:16:10Z | 22,376,126 | 20 | 2014-03-13T10:45:23Z | [
"python",
"warnings",
"traceback"
] | In numpy we can do [`np.seterr(invalid='raise')`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html) to get a traceback for warnings raising an error instead (see [this post](http://stackoverflow.com/questions/4190817/tracing-python-warnings-errors-to-a-line-number-in-numpy-and-scipy)).
* Is there ... | You can get what you want by assigning to `warnings.showwarning`. The [warnings module documentation](http://docs.python.org/2/library/warnings.html#warnings.showwarning) itself recommends that you do that, so it's not that you're being tempted by the *dark side of the source*. :)
> You may replace this function with ... |
How to obtain values of parameters of get request in flask? | 22,383,458 | 24 | 2014-03-13T15:31:24Z | 22,383,659 | 49 | 2014-03-13T15:40:11Z | [
"python",
"web",
"flask",
"get-request"
] | The answer that I found on the web is to use `request.args.get`. However, I cannot manage it to work. I have the following simple example:
```
from flask import Flask
app = Flask(__name__)
@app.route("/hello")
def hello():
print request.args['x']
return "Hello World!"
if __name__ == "__main__":
app.run()... | The simple answer is you have not imported the `request` global object from the flask package.
```
from flask import Flask, request
```
This is easy to determine yourself by running the development server in debug mode by doing
```
app.run(debug=True)
```
This will give you a stacktrace including:
```
print reques... |
python or on operator module | 22,385,108 | 7 | 2014-03-13T16:35:00Z | 22,385,169 | 14 | 2014-03-13T16:37:53Z | [
"python",
"operators"
] | On the `operator` module, we have the `or_` function, [which is the bitwise or](http://docs.python.org/2/library/operator.html#operator.or_) (`|`).
However I can't seem to find the logical or (`or`).
The documentation [doesn't seem to list it](http://docs.python.org/2/library/operator.html#mapping-operators-to-functi... | The `or` operator *short circuits*; the right-hand expression is not evaluated when the left-hand returns a true value. This applies to the `and` operator as well; when the left-hand side expression returns a false value, the right-hand expression is not evaluated.
You could not do this with a function; all operands *... |
Python: generator fail | 22,385,747 | 4 | 2014-03-13T17:01:46Z | 22,385,864 | 7 | 2014-03-13T17:06:31Z | [
"python",
"generator"
] | ```
def sp():
i = 0
while True:
for j in range(i):
yield(j)
i+=1
```
This generator is supposed to `yield` all the integers in the `range` of `(0, i)`, but it keeps returning `0` with every call of `next()`. Why?
Thanks. | No, it doesn't. This is the output:
```
>>> s=sp()
>>> s
<generator object sp at 0x102d1c690>
>>> s.next()
0
>>> s.next()
0
>>> s.next()
1
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
4
... |
Best practices with reading and operating on fortran ordered arrays with numpy | 22,385,801 | 6 | 2014-03-13T17:03:51Z | 22,406,034 | 7 | 2014-03-14T13:13:54Z | [
"python",
"numpy"
] | I'm reading ascii and binary files that all specify 3 dimensional arrays in fortran order. I want to perform some arbitrary manipulations on these arrays, then export them to the same ascii or binary format.
I'm confused on the best ways to deal with these arrays in my library. My current design seems prone to error b... | Numpy abstracts away the difference between Fortran ordering and C-ordering at the python level. (In fact, you can even have other orderings for >2d arrays with numpy. They're all treated the same at the python level.)
The only time you'll need to worry about C vs F ordering is when you're reading/writing to disk or p... |
Python: get item from set based on key | 22,386,287 | 4 | 2014-03-13T17:25:12Z | 22,386,379 | 8 | 2014-03-13T17:29:43Z | [
"python"
] | I have a class with a custom hash method.
```
class Test(object):
def __init__(self, key, value):
self.key = key # key is unique
self.value = value
def __hash__(self):
# 'value' is unhashable, so return the hash of 'key'
return hash(self.key)
```
I make a `set` using objects ... | > ... since key effectively determines the 'position' in the set
That's not really true. Two elements with the same `key` can coexist in the set:
```
>>> t0, t1 = Test(1,1), Test(1,2)
>>> len(set((t0,t1)))
2
```
The hash value does not define equality. That would also not be possible, because you can have hash colli... |
what does exclude in the meta class of django mean? | 22,388,281 | 5 | 2014-03-13T18:55:21Z | 22,388,318 | 7 | 2014-03-13T18:56:45Z | [
"python",
"django",
"django-models",
"metaclass"
] | I came across this code:
`drinker/models.py:`
```
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Drinker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name ... | The `exclude` attribute tells Django what fields from the model **not** to include in the form.
Quoting the [Selecting fields to use](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#selecting-the-fields-to-use) section of the model form documentation:
> 2. Set the `exclude` attribute of the `ModelForm`... |
statsmodels linear regression - patsy formula to include all predictors in model | 22,388,498 | 6 | 2014-03-13T19:05:25Z | 22,388,673 | 8 | 2014-03-13T19:15:07Z | [
"python",
"statsmodels"
] | Say I have a dataframe (let's call it `DF`) where `y` is the dependent variable and `x1, x2, x3` are my independent variables. In R I can fit a linear model using the following code, and the `.` will include all of my independent variables in the model:
```
# R code for fitting linear model
result = lm(y ~ ., data=DF)... | I haven't found `.` equivalent in patsy documentation either. But what it lacks in conciseness, it can make-up for by giving strong string manipulation in Python. So, you can get formula involving all variable columns in `DF` using
```
all_columns = "+".join(DF.columns - ["y"])
```
This gives `x1+x2+x3` in your case.... |
Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program | 22,388,519 | 49 | 2014-03-13T19:06:19Z | 22,411,624 | 63 | 2014-03-14T17:14:36Z | [
"python",
"numpy",
"virtualenv",
"pip"
] | I'm trying to install numpy (and scipy and matplotlib) into a virturalenv.
I keep getting these errors though:
```
RuntimeError: Broken toolchain: cannot link a simple C program
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1
```
I have the command l... | While it's ugly, it appears to work
```
sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install --upgrade numpy
```
Note that if you are getting this error for a package other than numpy, (such as lxml) specify that package name instead of `numpy` at the end of the commnd.
I saw a sim... |
Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program | 22,388,519 | 49 | 2014-03-13T19:06:19Z | 22,767,835 | 9 | 2014-03-31T17:07:57Z | [
"python",
"numpy",
"virtualenv",
"pip"
] | I'm trying to install numpy (and scipy and matplotlib) into a virturalenv.
I keep getting these errors though:
```
RuntimeError: Broken toolchain: cannot link a simple C program
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1
```
I have the command l... | If you don't want to use sudo (so permissions and things like that are preserved when using venv), you can add the ARCHFLAGS declaration to your .bash\_profile, and run as normal. This worked for me with Mavericks and Xcode 5.1 using with venv:
In ~/.bash\_profile:
> export ARCHFLAGS=-Wno-error=unused-command-line-ar... |
Problems with pip install numpy - RuntimeError: Broken toolchain: cannot link a simple C program | 22,388,519 | 49 | 2014-03-13T19:06:19Z | 26,764,577 | 7 | 2014-11-05T18:37:06Z | [
"python",
"numpy",
"virtualenv",
"pip"
] | I'm trying to install numpy (and scipy and matplotlib) into a virturalenv.
I keep getting these errors though:
```
RuntimeError: Broken toolchain: cannot link a simple C program
----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 1
```
I have the command l... | The problem is that you are unable to compile.
First, make sure that you have accepted the new Terms and Conditions with Xcode. To do this, just open up xCode and accept.
Then, try installing gcc with
```
brew install gcc
```
Finally, try to install Numpy with
```
pip install numpy
```
Hope this helps. |
How to extend list comprehension with values outside the set builder? | 22,390,134 | 2 | 2014-03-13T20:26:48Z | 22,390,218 | 10 | 2014-03-13T20:31:00Z | [
"python",
"list-comprehension"
] | I am basically looking for a one-liner to create a list using the python list comprehension feature, but also to add some extra value/values that do not fit the pattern. So for example I would like to get a list with the following values [1, 2, 3, 4, 5, 50]. I have tried the following:
```
a = [i for i in range(6), 50... | Simply concatenate lists using `+`:
```
>>> d = [i for i in range(6)] + [50]
>>> d
[0, 1, 2, 3, 4, 5, 50]
``` |
Setting initial Django form field value in the __init__ method | 22,390,416 | 14 | 2014-03-13T20:40:35Z | 22,390,638 | 10 | 2014-03-13T20:52:24Z | [
"python",
"django",
"django-1.6"
] | Django 1.6
I have a working block of code in a Django form class as shown below. The data set from which I'm building the form field list can include an initial value for any of the fields, and I'm having no success in setting that initial value in the form. The `if field_value:` block below does indeed populate the i... | Try this way:
```
super(ViagemForm, self).__init__(*args, **kwargs)
if field_value:
#self.initial[field_name] = field_value
self.fields[field_name].initial = field_value
``` |
Setting initial Django form field value in the __init__ method | 22,390,416 | 14 | 2014-03-13T20:40:35Z | 26,887,842 | 15 | 2014-11-12T13:12:18Z | [
"python",
"django",
"django-1.6"
] | Django 1.6
I have a working block of code in a Django form class as shown below. The data set from which I'm building the form field list can include an initial value for any of the fields, and I'm having no success in setting that initial value in the form. The `if field_value:` block below does indeed populate the i... | I had that exact same problem and I solved it doing this:
```
def __init__(self, *args, **kwargs):
instance = kwargs.get('instance', None)
kwargs.update(initial={
# 'field': 'value'
'km_partida': '1020'
})
super(ViagemForm, self).__init__(*args, **kwargs)
# all other stuff
``` |
Is it possible to get formal argument names/values as a dictionary? | 22,390,464 | 5 | 2014-03-13T20:43:02Z | 22,390,654 | 7 | 2014-03-13T20:52:54Z | [
"python",
"parameters"
] | If I have a Python function defined as `f(a, b, c)`, is there a straightforward way to get a dictionary mapping the formal names to the values passed in? That is, from inside `f`, I'd like to be able to get a dictionary `{'a': 1, 'b': 2, 'c': 3}` for the call `f(1, 2, 3)`.
I'd like to do this so I can directly use the... | ```
>>> import inspect
>>> def foo(a,b,c):
... pass
...
>>> inspect.getargspec(foo)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
>>> inspect.getargspec(foo).args
['a', 'b', 'c']
```
Now you can filter `locals()` based on those.
```
>>> x = 'outer'
>>> G = 'GLOBAL'
>>> def foo(a, b, c... |
Exiting while loop by pressing enter without blocking. How can I improve this method? | 22,391,134 | 2 | 2014-03-13T21:19:01Z | 22,391,379 | 7 | 2014-03-13T21:31:16Z | [
"python",
"loops",
"input",
"exit",
"enter"
] | So I've been doing a little bit of reading up on how to exit a while loop by the user pressing the enter key and I've come up with the following:
```
import sys, select, os
switch = 1
i = 1
while switch == 1:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
... | This worked for me:
```
import sys, select, os
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print "I'm doing stuff. Press Enter to stop me!"
print i
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line = raw_input()
break
i += 1
```
You only need to... |
What is the difference between curly brace and square bracket in Python? | 22,391,419 | 34 | 2014-03-13T21:33:39Z | 22,391,457 | 50 | 2014-03-13T21:35:42Z | [
"python",
"curly-braces",
"square-bracket"
] | what is the difference between curly brace and square bracket in python?
```
A ={1,2}
B =[1,2]
```
when I print `A` and `B` on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use `{}` and `[]` to initialize different variables.
E.g. `A=[]`, `B={}`
Is there any difference there? | Curly braces create [dictionaries](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) or [sets](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). Square brackets create [lists](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range).
They are called *li... |
count the frequency that a value occurs in a dataframe column | 22,391,433 | 13 | 2014-03-13T21:34:41Z | 22,391,554 | 24 | 2014-03-13T21:41:34Z | [
"python",
"pandas"
] | I have a dataset
```
|category|
cat a
cat b
cat a
```
I'd like to be able to return something like (showing unique values and frequency)
```
category | freq |
cat a 2
cat b 1
``` | Use `groupby` and `count`:
```
In [37]:
df = pd.DataFrame({'a':list('abssbab')})
df.groupby('a').count()
Out[37]:
a
a
a 2
b 3
s 2
[3 rows x 1 columns]
```
See the online docs: <http://pandas.pydata.org/pandas-docs/stable/groupby.html>
Also `value_counts()` as @DSM has commented, many ways to skin a cat h... |
ImportError: No module named pip when trying to install packages | 22,391,580 | 7 | 2014-03-13T21:42:40Z | 30,198,294 | 7 | 2015-05-12T18:02:55Z | [
"python",
"python-2.7",
"python-3.x",
"package",
"pip"
] | Have a fresh install of Ubuntu 13.10 with PyCharm and when setting up the python interpreter I selected 'install setuptools', then 'install pip'. Now if I try and do anything with pip I get the following:
```
ciaran@ciaran-desktop:~/pycharm/bin$ pip
Traceback (most recent call last):
File "/usr/local/bin/pip", l... | Download the file get-pip.py from the pip-website (<http://pip.readthedocs.org/en/stable/installing/>).
Open the terminal, cd in to the folder where you placed *get-pip.py*
and run:
> sudo python3 get-pip.py
Open pycharm and install desired package... |
How to add a new row to an empty numpy array | 22,392,497 | 25 | 2014-03-13T22:39:26Z | 22,392,768 | 7 | 2014-03-13T22:56:45Z | [
"python",
"numpy",
"scipy"
] | Using standard Python arrays, I can do the following:
```
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
# arr is now [[1,2,3],[4,5,6]]
```
However, I cannot do the same thing in numpy. For example:
```
arr = np.array([])
arr = np.append(arr, np.array([1,2,3]))
arr = np.append(arr, np.array([4,5,6]))
# arr is now ... | In this case you might want to use the functions np.hstack and np.vstack
```
arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]
arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]
```
You also can use the np.concatenate function.
Cheers |
How to add a new row to an empty numpy array | 22,392,497 | 25 | 2014-03-13T22:39:26Z | 22,394,181 | 27 | 2014-03-14T01:03:18Z | [
"python",
"numpy",
"scipy"
] | Using standard Python arrays, I can do the following:
```
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
# arr is now [[1,2,3],[4,5,6]]
```
However, I cannot do the same thing in numpy. For example:
```
arr = np.array([])
arr = np.append(arr, np.array([1,2,3]))
arr = np.append(arr, np.array([4,5,6]))
# arr is now ... | The way to "start" the array that you want is:
```
arr = np.empty((0,3), int)
```
Which is an empty array but it has the proper dimensionality.
```
>>> arr
array([], shape=(0, 3), dtype=int64)
```
Then be sure to append along axis 0:
```
arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.arr... |
excluding rows from a pandas dataframe based on column value and not index value | 22,392,786 | 8 | 2014-03-13T22:57:59Z | 22,392,870 | 18 | 2014-03-13T23:05:13Z | [
"python",
"pandas"
] | I looked at the unique values in a column of a dataframe - pandas that I have. And there are some names in one of the columns that I do not want to include, how do I remove those rows from the dataframe, without using index value notation, but by saying if row value = "this" then remove
like...
```
new = df.copy
df[... | See [**indexing with `isin`**](http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-with-isin) (also, [boolean indexing](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing)):
```
mask = df['some column'].isin(['this', 'that', 'other'])
df[~mask]
``` |
Invalid control character with Python json.loads | 22,394,235 | 12 | 2014-03-14T01:10:09Z | 22,409,840 | 12 | 2014-03-14T15:50:15Z | [
"python",
"json"
] | Below is my string that is getting printed out with the below code -
```
jsonString = data.decode("utf-8")
print jsonString
```
And below is the string that got printed out on the console -
```
{"description":"Script to check testtbeat of TEST 1 server.", "script":"#!/bin/bash\nset -e\n\nCOUNT=60 #number of 10 se... | [There is no error in your json text.](http://ideone.com/sUFlEw)
You can get the error if you copy-paste the string into your Python source code as a string literal. In that case `\n` is interpreted as a single character (newline). You can fix it by using raw-string literals instead (`r''`, Use triple-quotes `r'''..''... |
Invalid control character with Python json.loads | 22,394,235 | 12 | 2014-03-14T01:10:09Z | 29,827,074 | 9 | 2015-04-23T14:51:20Z | [
"python",
"json"
] | Below is my string that is getting printed out with the below code -
```
jsonString = data.decode("utf-8")
print jsonString
```
And below is the string that got printed out on the console -
```
{"description":"Script to check testtbeat of TEST 1 server.", "script":"#!/bin/bash\nset -e\n\nCOUNT=60 #number of 10 se... | The control character can be allowed inside a string as follows,
```
jStr = json.loads(jsonString, strict=False)
``` |
Select specific CSV columns (Filtering) - Python/pandas | 22,394,598 | 3 | 2014-03-14T01:44:58Z | 22,394,655 | 9 | 2014-03-14T01:50:25Z | [
"python",
"csv",
"pandas"
] | I have a very large CSV File with 100 columns. In order to illustrate my problem I will use a very basic example.
Let's suppose that we have a CSV file.
> ```
> in value d f
> 0 975 f01 5
> 1 976 F 4
> 2 977 d4 1
> 3 978 B6 0
> 4 979 2C 0
> ```
I want to select a s... | This selects the second and fourth columns (since Python uses 0-based indexing):
```
In [272]: df.iloc[:,(1,3)]
Out[272]:
value f
0 975 5
1 976 4
2 977 1
3 978 0
4 979 0
[5 rows x 2 columns]
```
`df.ix` can select by location or label. `df.iloc` always selects by location. When indexing by l... |
Why Recursive Generator doesn't work in Python 3.3? | 22,395,116 | 6 | 2014-03-14T02:36:02Z | 22,395,151 | 11 | 2014-03-14T02:39:48Z | [
"python",
"python-3.x"
] | I'm trying to create a recursive generator in Python, but I'm doing something wrong. Here's a minimal example. I would expect the function f() to return an iterable that would give me all the positive numbers >= n.
```
>>> def f(n):
... yield n
... if n>0:
... f(n-1)
...
>>> [ i for i in f(30) ]
[30]
... | Since `f(n-1)` is again a generator, which can be consumed only with the `next` protocol. If you are using Python 3.3+, you can use `yield from`, like this
```
def f(n):
yield n
if n > 0:
yield from f(n-1)
print(list(f(10)))
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
```
If you want to fix with out `yield ... |
Finding the Values of the Arrow Keys in Python: Why are they triples? | 22,397,289 | 12 | 2014-03-14T05:57:51Z | 22,398,481 | 13 | 2014-03-14T07:16:16Z | [
"python",
"input",
"ascii",
"non-ascii-characters",
"control-characters"
] | I am trying to find the values that my local system assigns to the arrow keys, specifically in Python. I am using the following script to do this:
```
import sys,tty,termios
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try... | I think I figured it out.
I learned from [here](http://stackoverflow.com/a/4136019/2844655) that each arrow key is represented by a unique ANSI escape code. Then I learned that the ANSI escape codes vary by system and application: in my terminal, hitting `cat` and pressing the up-arrow gives `^[[A`, in C it seems to b... |
default values on empty user input in python | 22,402,548 | 8 | 2014-03-14T10:33:31Z | 22,402,654 | 13 | 2014-03-14T10:37:39Z | [
"python",
"default"
] | Here I have to set the default value if the user will enter the value from keyboard. Here is the code that user can enter value:
```
input= int(raw_input("Enter the inputs : "))
```
here the value will assign to variable `input` after entering value and hit 'Enter', is there any method that if we don't enter value an... | ```
input = int(raw_input("Enter the inputs : ") or "42")
```
How does it work?
If nothing was entered then raw\_input returns empty string. Empty string in python is `False` `bool("") -> False`. Operator `or` returns first trufy value, which in this case is `"42"`.
This is not sophisticated input validation, becaus... |
Locate first and last non NaN values in a Pandas DataFrame | 22,403,469 | 12 | 2014-03-14T11:15:17Z | 22,455,322 | 14 | 2014-03-17T13:16:22Z | [
"python",
"datetime",
"pandas"
] | I have a Pandas `DataFrame` indexed by date. There a number of columns but many columns are only populated for part of the time series. I'd like to find where the first and last values non-`NaN` values are located so that I can extracts the dates and see how long the time series is for a particular column.
Could someb... | @behzad.nouri's solution worked perfectly to return the first and last non-`NaN values` using [Series.first\_valid\_index](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html#pandas.Series.first_valid_index) and [Series.last\_valid\_index](http://pandas.pydata.org/pandas-docs/stab... |
Fortran - Cython Workflow | 22,404,060 | 11 | 2014-03-14T11:44:08Z | 22,524,071 | 13 | 2014-03-20T05:18:50Z | [
"python",
"fortran",
"cython",
"fortran-iso-c-binding"
] | I would like to set up a workflow to reach fortran routines from Python using Cython on a Windows Machine
after some searching I found :
<http://www.fortran90.org/src/best-practices.html#interfacing-with-c> and <http://stackoverflow.com/tags/fortran-iso-c-binding/info>
and some code pices:
Fortran side:
pygfunc.h:
... | Here's a minimum working example.
I used gfortran and wrote the compile commands directly into the setup file.
`gfunc.f90`
```
module gfunc_module
implicit none
contains
subroutine gfunc(x, n, m, a, b, c)
double precision, intent(in) :: x
integer, intent(in) :: n, m
double precision, dimension(n), intent(... |
How to get a file close event in python | 22,406,309 | 7 | 2014-03-14T13:25:34Z | 22,406,720 | 14 | 2014-03-14T13:43:10Z | [
"python",
"windows",
"file",
"process",
"file-monitoring"
] | Using python 2.7 on windows 7 64 bit machine.
How to get a file close event:
1. when file is opened in a new process of file opener (like notepad, wordpad which opens file everytime in new process of wordpad)
2. when file is opened in a tab of file opener (like notepad++, which opens all files in new tab but there ex... | This has proven to be a very easy task for \*nix systems, but on Windows, getting a file close event is not a simple task. Read below the summary of common methods grouped by OS'es.
# For Linux
On Linux, the filesystem changes can be easily monitored, and in great detail. The best tool for this is the kernel feature ... |
pandas: group by: how to reset indexes for all groups in one step? | 22,407,798 | 4 | 2014-03-14T14:27:16Z | 22,409,983 | 7 | 2014-03-14T15:56:27Z | [
"python",
"group-by",
"pandas"
] | I've tried to split my dataframe to groups
```
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['1', '2', '3', '4',
'5', '6', '7', '8'],
})
grouped = df.groupby('A')
```
I get 2 groups
```
... | Pass in `as_index=False` to the groupby, then you don't need to `reset_index` to make the groupby-d columns columns again:
```
In [11]: grouped = df.groupby('A', as_index=False)
In [12]: grouped.get_group('foo')
Out[12]:
A B
0 foo 1
2 foo 3
4 foo 5
6 foo 7
7 foo 8
```
Note: As pointed out (and seen i... |
Named colors in matplotlib | 22,408,237 | 112 | 2014-03-14T14:45:19Z | 22,408,462 | 189 | 2014-03-14T14:54:02Z | [
"python",
"matplotlib",
"colors"
] | What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names:
```
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
```
However, I've found that these colors can also be used, at least in this context:
... | There is a complete dictionary in colors.py in the matplotlib directory.
```
import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
print(name, hex)
```
This is the complete dictionary:
```
cnames = {
'aliceblue': '#F0F8FF',
'antiquewhite': '#FAEBD7',
'aqua': ... |
Named colors in matplotlib | 22,408,237 | 112 | 2014-03-14T14:45:19Z | 29,676,907 | 98 | 2015-04-16T13:54:44Z | [
"python",
"matplotlib",
"colors"
] | What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names:
```
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
```
However, I've found that these colors can also be used, at least in this context:
... | In addition to BoshWash's answer, here is the picture generated by his code:
 |
Named colors in matplotlib | 22,408,237 | 112 | 2014-03-14T14:45:19Z | 37,232,760 | 52 | 2016-05-14T23:02:05Z | [
"python",
"matplotlib",
"colors"
] | What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names:
```
b: blue
g: green
r: red
c: cyan
m: magenta
y: yellow
k: black
w: white
```
However, I've found that these colors can also be used, at least in this context:
... | I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the [matplotlib... |
Why can't Python's import work like C's #include? | 22,408,302 | 3 | 2014-03-14T14:47:45Z | 22,408,375 | 8 | 2014-03-14T14:50:15Z | [
"python",
"c",
"import"
] | I've literally been trying to understand Python imports for about a year now, and I've all but given up programming in Python because it just seems too obfuscated. I come from a C background, and I assumed that `import` worked like `#include`, yet if I try to import something, I invariably get errors.
If I have two fi... | To do what you want, you can use (not recommended, read further for explanation):
```
from foo import *
```
This will import everything to your current namespace, and you will be able to call `print a`.
However, the issue with this approach is the following. Consider the case when you have two modules, `moduleA` and... |
Why np.array([1e5])**2 is different from np.array([100000])**2 in Python? | 22,410,803 | 5 | 2014-03-14T16:33:31Z | 22,410,895 | 7 | 2014-03-14T16:38:42Z | [
"python",
"arrays",
"numpy",
"exponent"
] | May someone please explain me why `np.array([1e5])**2` is not the equivalent of `np.array([100000])**2`? Coming from Matlab, I found it confusing!
```
>>> np.array([1e5])**2
array([ 1.00000000e+10]) # correct
>>> np.array([100000])**2
array([1410065408]) # Why??
```
I found that this behaviour starts from... | `1e5` is a floating point number, but 10000 is an integer:
```
In [1]: import numpy as np
In [2]: np.array([1e5]).dtype
Out[2]: dtype('float64')
In [3]: np.array([10000]).dtype
Out[3]: dtype('int64')
```
But in numpy, integers have a fixed width (as opposed to python itself in which they are arbitrary length number... |
python pandas pivot_table count frequency in one colume | 22,412,033 | 5 | 2014-03-14T17:35:45Z | 22,412,152 | 8 | 2014-03-14T17:42:51Z | [
"python",
"pandas"
] | I am still new to Python pandas' pivot\_table and would like to ask a way to count frequencies of values in one column, which is also linked to another column of ID. The DataFrame looks like the following.
```
import pandas as pd
df = pd.DataFrame({'Account_number':[1,1,2,2,2,3,3], 'Product':['A', 'A', 'A', 'B', 'B','... | You need to specify the agg function as len:
```
In [11]: df.pivot_table(rows='Account_number', cols='Product', aggfunc=len, fill_value=0)
Out[11]:
Product A B
Account_number
1 2 0
2 1 2
3 1 1
```
*It looks like count, is counting the instances of each column (`Ac... |
python pandas pivot_table count frequency in one colume | 22,412,033 | 5 | 2014-03-14T17:35:45Z | 35,469,065 | 8 | 2016-02-17T22:29:53Z | [
"python",
"pandas"
] | I am still new to Python pandas' pivot\_table and would like to ask a way to count frequencies of values in one column, which is also linked to another column of ID. The DataFrame looks like the following.
```
import pandas as pd
df = pd.DataFrame({'Account_number':[1,1,2,2,2,3,3], 'Product':['A', 'A', 'A', 'B', 'B','... | In new version of Pandas, slight modification is required. I had to spend some time figuring out so just wanted to add that here so that someone can directly use this.
```
df.pivot_table(index='Account_number', columns='Product', aggfunc=len, fill_value=0)
``` |
Error: The 'elasticsearch' backend requires the installation of 'requests'. How do I fix it? | 22,412,045 | 2 | 2014-03-14T17:36:49Z | 24,595,772 | 9 | 2014-07-06T12:25:00Z | [
"python",
"django",
"elasticsearch",
"django-haystack"
] | I´m having a issue when I ran "python manage.py rebuild\_index" in my app supported by haystack and elasticsearch.
Python 2.7
Django version 1.6.2
Haystack 2.1.0
Elasticsearch 1.0
Please see the error that is appearing:
> Traceback (most recent call last):
> File "manage.py", line 10, in
> execute\_from\_command\_l... | just do
```
pip install pyelasticsearch
``` |
Get the first element of each tuple in a list in Python | 22,412,258 | 35 | 2014-03-14T17:48:16Z | 22,412,308 | 50 | 2014-03-14T17:50:27Z | [
"python",
"syntax"
] | An SQL query gives me a list of tuples, like this:
```
[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]
```
I'd like to have all the first elements of each tuple. Right now I use this:
```
rows = cur.fetchall()
res_list = []
for row in rows:
res_list += [row[0]]
```
But I think there ... | Use a [list comprehension](http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
res_list = [x[0] for x in rows]
```
Below is a demonstration:
```
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>
```
---
Alternately, you could use unpacking instead of `x[0]`:
``... |
Get the first element of each tuple in a list in Python | 22,412,258 | 35 | 2014-03-14T17:48:16Z | 22,412,315 | 7 | 2014-03-14T17:50:38Z | [
"python",
"syntax"
] | An SQL query gives me a list of tuples, like this:
```
[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]
```
I'd like to have all the first elements of each tuple. Right now I use this:
```
rows = cur.fetchall()
res_list = []
for row in rows:
res_list += [row[0]]
```
But I think there ... | You can use list comprehension:
```
res_list = [i[0] for i in rows]
```
This should make the trick |
Get the first element of each tuple in a list in Python | 22,412,258 | 35 | 2014-03-14T17:48:16Z | 32,888,245 | 8 | 2015-10-01T13:00:53Z | [
"python",
"syntax"
] | An SQL query gives me a list of tuples, like this:
```
[(elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), (elt1, elt2), ...]
```
I'd like to have all the first elements of each tuple. Right now I use this:
```
rows = cur.fetchall()
res_list = []
for row in rows:
res_list += [row[0]]
```
But I think there ... | If you don't want to use list comprehension by some reasons, you can use [map](https://docs.python.org/2/library/functions.html#map) and [operator.itemgetter](https://docs.python.org/2/library/operator.html#operator.itemgetter):
```
>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemge... |
Getting a sublist of a Python list, with the given indices? | 22,412,509 | 5 | 2014-03-14T18:00:43Z | 22,412,533 | 11 | 2014-03-14T18:01:44Z | [
"python",
"list",
"python-2.7"
] | I have a Python list, say `a = [0,1,2,3,4,5,6]`. I also have a list of indices, say `b = [0,2,4,5]`. How can I get the list of elements of `a` with indices in `b`? | You can use *list comprehension* to get that list:
```
c = [a[index] for index in b]
print c
```
This is equivalent to:
```
c= []
for index in b:
c.append(a[index])
print c
```
**Output:**
```
[0,2,4,5]
```
**Note:**
Remember that `some_list[index]` is the notation used to access to an element of a `list` in... |
Getting a sublist of a Python list, with the given indices? | 22,412,509 | 5 | 2014-03-14T18:00:43Z | 22,412,680 | 7 | 2014-03-14T18:09:00Z | [
"python",
"list",
"python-2.7"
] | I have a Python list, say `a = [0,1,2,3,4,5,6]`. I also have a list of indices, say `b = [0,2,4,5]`. How can I get the list of elements of `a` with indices in `b`? | Something different...
```
>>> a = range(7)
>>> b = [0,2,4,5]
>>> import operator
>>> operator.itemgetter(*b)(a)
(0, 2, 4, 5)
```
The [`itemgetter`](http://docs.python.org/2/library/operator.html#operator.itemgetter) function takes one or more keys as arguments, and returns a function which will return the items at t... |
Can't install python mysql library on Mac Mavericks | 22,413,050 | 13 | 2014-03-14T18:32:09Z | 22,413,418 | 40 | 2014-03-14T18:51:59Z | [
"python",
"django",
"osx",
"osx-mavericks",
"mysql-python"
] | It was working like a charm before the update from Mountain Lion.
After the update it is broken and I cannot get the environment up again.
Does anybody know how to fix this?
The error is bolded, below.
```
fedorius@this:~$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.5.... | The problem is due to changes introduced in Xcode 5.1 and due to the way the Apple-supplied system Python 2.7 is built. Try adding these environment variable values before running `pip`:
```
export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments
```
See [clang error: unknown argument: '-mno-fused-madd' (... |
Why can't I use print in if ternary operator in python? | 22,413,910 | 5 | 2014-03-14T19:18:42Z | 22,413,981 | 8 | 2014-03-14T19:22:11Z | [
"python"
] | Why is that invalid
```
print('true') if False else print('false')
```
but this one is not
```
def p(t):
print(t)
p('true') if False else p('false')
``` | As has been pointed out (@NPE, @Blender, and others), in Python2.x `print` is a statement which is the source of your problem. However, you don't need the second `print` to use the ternary operator in your example:
```
>>> print 'true' if False else 'false'
false
``` |
Best way to initialize and fill an numpy array? | 22,414,152 | 11 | 2014-03-14T19:32:15Z | 22,414,391 | 11 | 2014-03-14T19:45:35Z | [
"python",
"arrays",
"numpy",
"multidimensional-array",
"initialization"
] | I want to initialize and fill a `numpy` array. What is the best way?
This works as I expect:
```
>>> import numpy as np
>>> np.empty(3)
array([ -1.28822975e-231, -1.73060252e-077, 2.23946712e-314])
```
But this doesn't:
```
>>> np.empty(3).fill(np.nan)
>>>
```
Nothing?
```
>>> type(np.empty(3))
<type 'numpy.nd... | [`np.fill`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.fill.html) modifies the array in-place, and returns `None`. Therefor, if you're assigning the result to a name, it gets a value of `None`.
An alternative is to use an expression which returns `nan`, e.g.:
```
a = np.empty(3) * np.nan
``` |
Best way to initialize and fill an numpy array? | 22,414,152 | 11 | 2014-03-14T19:32:15Z | 22,414,429 | 23 | 2014-03-14T19:47:30Z | [
"python",
"arrays",
"numpy",
"multidimensional-array",
"initialization"
] | I want to initialize and fill a `numpy` array. What is the best way?
This works as I expect:
```
>>> import numpy as np
>>> np.empty(3)
array([ -1.28822975e-231, -1.73060252e-077, 2.23946712e-314])
```
But this doesn't:
```
>>> np.empty(3).fill(np.nan)
>>>
```
Nothing?
```
>>> type(np.empty(3))
<type 'numpy.nd... | You could also try:
```
In [79]: np.full(3, np.nan)
Out[79]: array([ nan, nan, nan])
```
The pertinent doc:
```
Definition: np.full(shape, fill_value, dtype=None, order='C')
Docstring:
Return a new array of given shape and type, filled with `fill_value`.
```
Although I think this might be only available in numpy ... |
Problems with custom LIBFFI Heroku buildpack | 22,415,725 | 4 | 2014-03-14T21:05:49Z | 22,454,916 | 8 | 2014-03-17T12:58:45Z | [
"python",
"heroku",
"cryptography",
"openssl",
"libffi"
] | I'm trying to deploy my app to Heroku. It is using `pyOpenSSL`, which requires `cryptography`, which requires `libffi`. I found a custom buildpack that includes `libffi` here: <https://github.com/mfenniak/heroku-buildpack-python-libffi>. However, `cryptography` cannot seem to find `libffi` even though it's on `LD_LIBRA... | It appears github user kennethjiang had the same problem and forked the [custom libffi buildpack](https://github.com/kennethjiang/heroku-buildpack-python-libffi) with a fix just four days ago.
Here are the relevant changes:
<https://github.com/kennethjiang/heroku-buildpack-python-libffi/compare/3bb5fab8213f41411f515f... |
How do __enter__ and __exit__ work in Python decorator classes? | 22,417,323 | 7 | 2014-03-14T23:02:45Z | 22,417,454 | 16 | 2014-03-14T23:15:31Z | [
"python",
"class",
"count",
"decorator",
"exit"
] | I'm trying to create a decorator class that counts how many times a function is called, but I'm getting an error message that says:
```
"TypeError: __exit__() takes exactly 1 argument (4 given)"
```
and I really don't know how I'm giving it four arguments. My code looks like this:
```
class fcount2(object):
... | the `__exit__()` method should accept information about exceptions that come up in the `with:` block. See [here](http://docs.python.org/2/reference/datamodel.html#object.__exit__).
The following modification of your code works:
```
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
... |
How do I find the intersection of two line segments? | 22,417,842 | 8 | 2014-03-15T00:01:58Z | 22,487,009 | 14 | 2014-03-18T17:42:37Z | [
"python",
"matplotlib"
] | Suppose we have two finite line segments defined each by two points (in two space). I would like to find a way to get the intersection point of those two lines. Eventually, I would like to extend this to work on sets of connected line segments.
I have found a good solution here: [Python - matplotlib: find intersection... | For the sake of completion, I thought I would post the final solution which I used.
Using Shapely (<https://pypi.python.org/pypi/Shapely>) the code can look as simple as this:
```
from shapely.geometry import LineString
line1 = LineString([(0,0), (1,0), (1,1)])
line2 = LineString([(0,1), (1,1)])
print(line1.interse... |
Error Install Pandas for Python on Mac OS X | 22,419,071 | 4 | 2014-03-15T03:12:52Z | 22,419,707 | 8 | 2014-03-15T04:52:59Z | [
"python",
"xcode",
"pandas",
"command",
"pip"
] | I want to install pandas for use in Python
I have the latest release of xcode and command line tool, pip, easy\_install, but installing this keeps giving me the following error, anyone can help?
```
sudo easy_install pandas
> Best match: pandas 0.13.1
>Downloading https://pypi.python.org/packages/source/p/pandas/pan... | As noted in the comments, this is a now common problem caused by changes in Xcode 5.1 and by Apple's choice of build options for the system Python 2.7. You can work around the issue by removing the offending options as suggested [here](http://stackoverflow.com/questions/22313407/clang-error-unknown-argument-mno-fused-m... |
Django and mysql problems on Mavericks | 22,419,210 | 8 | 2014-03-15T03:39:11Z | 29,671,752 | 12 | 2015-04-16T10:18:01Z | [
"python",
"mysql",
"django",
"osx"
] | I'm running Mac OSX 10.9 Mavericks. I'm trying to run django under python 3. Because I'm running Python 3 I have to get the official connector from the mysql devs [here](https://dev.mysql.com/downloads/connector/python/) gave it a quick test in the shell and it works.
I ran `python manage.py runserver` with `"mysql.co... | For python 2.7, 3.3+ there is a driver called [mysqlclient](https://pypi.python.org/pypi/mysqlclient) that works with django 1.8
```
pip install mysqlclient
```
And in your settings
```
DATABASES = {
'default': {
'NAME': '',
'ENGINE': 'django.db.backends.mysql',
'USER': '',
'PASSW... |
what is flask-sqlalchemy where in clause query syntax? | 22,420,598 | 3 | 2014-03-15T06:53:16Z | 22,422,572 | 11 | 2014-03-15T10:31:33Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I`m using flask-sqlalchemy and my problem is where in clause like:
```
select * from table_1 where id in (1,2,3,5)
OR
select * from table_1 where field_1_id in (select id from table_2 where .... )
```
and get\_or\_create like peewee orm
```
Object.get_or_create(.......)
```
how can i generate this sentences with fl... | Try [**.in\_** clause](http://docs.sqlalchemy.org/en/rel_0_7/core/expression_api.html#sqlalchemy.sql.operators.ColumnOperators.in_) in sqlalchemy
```
result = db_session.query(table_1).filter(table_1.id.in_((1,2,3,5))).all()
```
**Note**: here am assuming table\_1 is your model |
Pass a 2d numpy array to c using ctypes | 22,425,921 | 4 | 2014-03-15T15:41:56Z | 27,737,099 | 9 | 2015-01-02T03:37:51Z | [
"python",
"c",
"numpy",
"ctypes"
] | What is the correct way to pass a numpy 2d - array to a c function using ctypes ?
My current approach so far (leads to a segfault):
c code :
```
void test(double **in_array, int N){
int i,j;
for(i = 0; i<N; i++){
for(j = 0; j<N; j++){
printf("%e \t", in_array[i][j]);
}
... | This is probably a late answer, but I finally got it working. All credit goes to Sturla Molden at [this link](http://numpy-discussion.10968.n7.nabble.com/Pass-2d-ndarray-into-C-double-using-ctypes-td39414.html).
The key is, note that `double**` is an array of type `np.uintp`. Therefore, we have
```
xpp = (x.ctypes.da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.