title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How does str(list) work? | 30,109,030 | 7 | 2015-05-07T18:32:28Z | 30,109,108 | 43 | 2015-05-07T18:37:29Z | [
"python",
"string",
"list",
"eval",
"python-internals"
] | **Why does `str(list)` returns how we see list on the console? How does `str(list)` work? (any reference to the CPython code for `str(list)`)?**
```
>>> x = ['abc', 'def', 'ghi']
>>> str(x)
"['abc', 'def', 'ghi']"
```
To get the original list back from the `str(list)` I have to:
```
>>> from ast import literal_eval
... | Well you have a total of 4 questions, let us go one by one.
> **1. Why does `str(list)` returns how we see `list` on the console? How does `str(list)` work?**
# What is [`str()`](https://docs.python.org/3/library/functions.html#str) and [`__str__()`](https://docs.python.org/3/reference/datamodel.html#object.__str__)?... |
Implement MATLAB's im2col 'sliding' in Python | 30,109,068 | 7 | 2015-05-07T18:34:25Z | 30,110,497 | 10 | 2015-05-07T19:54:33Z | [
"python",
"performance",
"python-2.7",
"image-processing",
"numpy"
] | Q: How to speed this up?
Below is my implementation of Matlab's [im2col](http://www.mathworks.com/help/images/ref/im2col.html) 'sliding' with the additional feature of returning every n'th column. The function takes an image (or any 2 dim array) and slides from left to right, top to bottom, picking off every overlappi... | You could use some [`broadcasting`](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) here to get all the indices of all those sliding windows in one go and thus with indexing achieve a `vectorized solution`. This is inspired by [`Efficient Implementation of im2col and col2im`](http://stackoverflow.com/q/2... |
How to skip `if __name__ == "__main__"` in interactive mode? | 30,109,178 | 2 | 2015-05-07T18:40:41Z | 30,109,210 | 8 | 2015-05-07T18:42:18Z | [
"python",
"python-3.x"
] | Given a simple script like:
```
#!/usr/bin/env python3
if __name__ == "__main__":
print("Hello World")
```
How can I load that into the interactive interpreter without executing the `if __name__ == "__main__":` block? By default it gets executed:
```
$ python3 -i simple-script.py
Hello World
>>> â
``` | Don't pass it as an argument, import it into the interpreter.
```
$ python3
>>> import simple_script
>>>
``` |
What does "SSLError: [SSL] PEM lib (_ssl.c:2532)" mean using the Python ssl library? | 30,109,449 | 5 | 2015-05-07T18:55:31Z | 30,109,730 | 8 | 2015-05-07T19:11:55Z | [
"python",
"python-3.x",
"ssl",
"ssl-certificate",
"python-asyncio"
] | **In case someone had a similar issue:** This question was based on a great misconception of how SSL works. Though the variables are named poorly, the actual problem was the certs that where being used had expired. Generating new ones fixed the problem.
I am trying to use connect to another party using Python 3 asynci... | Assuming that version 3.4 is being used:
See: <https://github.com/python/cpython/blob/3.4/Modules/_ssl.c#L2529-L2535>
```
PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
r = SSL_CTX_check_private_key(self->ctx);
PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
if (r != 1) {
_setSSLError(NULL, 0, __FILE__,... |
Make a new array selectively copying, with varying multiplicity, rows of old array in numpy | 30,111,771 | 2 | 2015-05-07T21:13:45Z | 30,111,862 | 7 | 2015-05-07T21:19:31Z | [
"python",
"numpy"
] | I have a 2D array with n rows in numpy, and an accompanying 1-D array of n elements in which the ith element specifies how many times the ith row of the original array should go into a new array. For example if my 2D array is:
```
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5]... | You could use [np.repeat()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html) to repeat elements of an array.
```
In [174]: x.repeat(np.array([2, 0, 1, 0, 3]), axis=0)
Out[174]:
array([[1, 1, 1],
[1, 1, 1],
[3, 3, 3],
[5, 5, 5],
[5, 5, 5],
[5, 5, 5]])
```
---
D... |
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text' | 30,112,357 | 5 | 2015-05-07T21:55:44Z | 30,112,469 | 10 | 2015-05-07T22:05:09Z | [
"python",
"datetime"
] | I have a variable `testeddate` which has a date in text format like 4/25/2015. I am trying convert it to `%Y-%m-%d %H:%M:%S` as follows:
```
dt_str = datetime.strftime(testeddate,'%Y-%m-%d %H:%M:%S')
```
but I am running into this error:
```
TypeError: descriptor 'strftime' requires a 'datetime.date' object but rece... | You have a `Text` object. The [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) function requires a datetime object. The code below takes an intermediate step of converting your `Text` to a `datetime` using [`strptime`](https://docs.python.org/2/library/time.html#time.strptime)
```
import datetim... |
Continue until all iterators are done Python | 30,113,214 | 7 | 2015-05-07T23:16:36Z | 30,113,331 | 18 | 2015-05-07T23:28:02Z | [
"python",
"generator",
"iterable"
] | **I cannot use itertools**
So the coding seems pretty simple, but I'm having trouble thinking of the algorithm to keep a generator running until all iterations have been processed fully.
The idea of the function is to take 2 iterables as parameters like this ...
`(['a', 'b', 'c', 'd', 'e'], [1,2,5])`
And what it do... | Use a default value of `1` for next so you print the letters at least once:
```
def iteration(letters, numbers):
# create iterator from numbers
it = iter(numbers)
# get every letter
for x in letters:
# either print in range passed or default range of 1
for z in range(next(it, 1)):
... |
How come Python does not include a function to load a pickle from a file name? | 30,113,346 | 6 | 2015-05-07T23:29:35Z | 30,113,466 | 9 | 2015-05-07T23:41:57Z | [
"python",
"pickle"
] | I often include this, or something close to it, in Python scripts and IPython notebooks.
```
import cPickle
def unpickle(filename):
with open(filename) as f:
obj = cPickle.load(f)
return obj
```
This seems like a common enough use case that the standard library should provide a function that does the ... | Most of the serialization libraries in the stdlib and on PyPI have a similar API. I'm pretty sure it was [`marshal`](https://docs.python.org/3/library/marshal.html) that set the standard,\* and `pickle`, `json`, `PyYAML`, etc. have just followed in its footsteps.
So, the question is, why was `marshal` designed that wa... |
Using `split` on columns too slow - how can I get better performance? | 30,113,499 | 2 | 2015-05-07T23:46:01Z | 30,113,715 | 7 | 2015-05-08T00:12:06Z | [
"python",
"performance",
"pandas",
"split"
] | I've a dataset (around 10Gb) of call records. There's column with ip addresses that I want to split into four new columns. I'm trying to use:
```
df['ip'].fillna('0.0.0.0', inplace=True)
df = df.join(df['ip'].apply(lambda x: Series(x.split('.'))))
```
but it's tooooo slow... the `fillna` is fast, like 10s, but then i... | ~~It turns out that the `str.split` in Pandas (in `core/strings.py` as `str_split`) is actually very slow; it isn't any more efficient, and still iterates through using Python, offering no speedup whatsoever.~~
Actually, see below. Pandas performance on this is simply miserable; it's not just Python vs C iteration, as... |
Get the current function name in the Flask template context | 30,114,205 | 3 | 2015-05-08T01:09:43Z | 30,114,380 | 7 | 2015-05-08T01:33:05Z | [
"python",
"flask"
] | What I basically need is something like the following:
```
{{ url_for(current_view) }}
```
in a Jinja2 template, such that if the response came from:
```
@app.route('/')
def index():
return render('index.html')
```
then `current_view` equals to `"index"`, i.e., the actual view name, such that `url_for` works.
... | You can use `request.endpoint`:
```
{{ url_for(request.endpoint) }}
``` |
How to use a WTForms FieldList of FormFields? | 30,121,763 | 5 | 2015-05-08T10:38:49Z | 30,179,649 | 9 | 2015-05-12T00:10:51Z | [
"python",
"forms",
"flask",
"wtforms",
"fieldlist"
] | I'm building a website using [Flask](http://flask.pocoo.org/) in which I use [WTForms](http://wtforms.readthedocs.org/). In a Form I now want to use a FieldList of FormFields as follows:
```
class LocationForm(Form):
location_id = StringField('location_id')
city = StringField('city')
class CompanyForm(Form):
... | For starters, there's an argument for the [FieldList](http://wtforms.readthedocs.org/en/latest/fields.html#wtforms.fields.FieldList) called `min_entries`, that will make space for your data:
```
class CompanyForm(Form):
company_name = StringField('company_name')
locations = FieldList(FormField(LocationForm), m... |
Change Python if input to be case insensitive | 30,123,112 | 3 | 2015-05-08T11:49:18Z | 30,123,141 | 9 | 2015-05-08T11:50:55Z | [
"python"
] | I'm in school, and since we are rather young students, some of my 'colleagues' do not grasp what case sensitivity is. We are making a quiz in Python. Here is the code:
```
score = 0 #this defines variable score, and sets it as zero
print("What is the capital of the UK?")
answer = input ()
if answer == "London":
pr... | You can use `.upper()` or `.lower()`
```
if answer.lower() == 'london':
``` |
How can I make a script to recover my Grooveshark playlists now that the service has been shut down? | 30,124,541 | 4 | 2015-05-08T13:00:14Z | 30,124,542 | 17 | 2015-05-08T13:00:14Z | [
"python",
"backup",
"playlist",
"recovery",
"grooveshark"
] | The Grooveshark music streaming service has been shut down without previous notification. I had many playlists that I would like to recover (playlists I made over several years).
Is there any way I could recover them? A script or something automated would be awesome. | I made a script that will try to find all the playlists made by the user and download them in an output directory as CSV files. It is made in Python.
* You must just pass your username as parameter to the script (i.e. `python pysharkbackup.py "my_user_name"`). Your email address should work as well (the one you used f... |
How to emit websocket message from outside a websocket endpoint? | 30,124,701 | 2 | 2015-05-08T13:09:12Z | 30,125,944 | 8 | 2015-05-08T14:11:50Z | [
"python",
"flask",
"websocket",
"socket.io",
"flask-socketio"
] | I'm building a website using [Flask](http://flask.pocoo.org/) in which I also use Websockets using [Flask-socketIO](https://flask-socketio.readthedocs.org/en/latest/), but there's one thing I don't understand.
I built a chat-functionality. When one user sends a message I use websockets to send that message to the serv... | Quoting from Miguel Grinberg's response on [an open issue page on the Flask-SocketIO GitHub](https://github.com/miguelgrinberg/Flask-SocketIO/issues/40):
> When you want to emit from a regular route you have to use
> socketio.emit(), only socket handlers have the socketio context
> necessary to call the plain emit().
... |
Is it Pythonic to use objects wherever possible? | 30,126,475 | 2 | 2015-05-08T14:37:59Z | 30,126,539 | 7 | 2015-05-08T14:41:49Z | [
"python",
"oop"
] | Newbie Python question here - I am writing a little utility in Python to do disk space calculations when given the attributes of 2 different files.
Should I create a 'file' class with methods appropriate to the conversion and then create each file as an instance of that class? I'm pretty new to Python, but ok with Per... | *Definition nitpicking preface: Everything in Python is technically an object, even functions and numbers. I'm going to assume you mean classes vs. functions in your question.*
Actually I think one of the great things about Python is that it doesn't embrace classes for absolutely everything as some other languages (e.... |
Flask-Admin vs Flask-AppBuilder | 30,126,607 | 3 | 2015-05-08T14:44:31Z | 30,292,629 | 7 | 2015-05-17T22:04:04Z | [
"python",
"flask",
"flask-admin"
] | I am new to Flask and have noticed that there are two plugins that enable CRUD views and authorized login, **Flask-Admin** and **Flask-AppBuilder**.
These two features interest me along with nice **Master-Detail** views for my model, where I can see both the rows of the master table and the relevant details on the sam... | I am the developer of Flask-AppBuilder, so maybe a strong bias here. I will try to give you my most honest view. I do not know Flask-Admin that much, so i will probably make some mistakes.
Flask-Admin and Flask-AppBuilder:
* Will both give you an admin interface for Flask with bootstrap.
* Will both make their best t... |
Best way to install psycopg2 on ubuntu 14.04 | 30,127,224 | 3 | 2015-05-08T15:14:20Z | 30,127,304 | 12 | 2015-05-08T15:18:34Z | [
"python",
"virtualenv"
] | I am having trouble installing a Django app ([Mezzanine](http://mezzanine.jupo.org)) on Ubuntu 14.04. I've installed most necessities using apt-get (except for django-compressor and south -used pip), including psycopg2 for Postgres. However when I go to run python manage.py createdb it gives this error:
```
Error load... | If you need psycopg2 for a system installed program, then install it with the system package manager. If you need it for a program in a virtualenv, install it in that virtualenv.
```
. env/bin/activate
pip install psycopg2
```
Note that on many distros, the development headers needed for compiling against libraries a... |
how find all groups of subsets of set A? Set partitions in Python | 30,130,053 | 3 | 2015-05-08T18:00:26Z | 30,133,157 | 7 | 2015-05-08T21:30:50Z | [
"python",
"algorithm",
"python-3.x",
"set",
"subset"
] | I want to find an algorithm that given a set `A` to find all groups of subsets that satisfy the following condition:
> x ⪠y ⪠.... z = A, where x, y, ... z â Group
and
> â x,y â Group: x â A, y â A, x â© y = â
= {}
and
> â x â Group: x != â
Note: I hope to define it well, I'm not good with ... | Solution:
```
def partitions(A):
if not A:
yield []
else:
a, *R = A
for partition in partitions(R):
yield partition + [[a]]
for i, subset in enumerate(partition):
yield partition[:i] + [subset + [a]] + partition[i+1:]
```
Explanation:
* The empt... |
datetime to string with series in python pandas | 30,132,282 | 5 | 2015-05-08T20:23:11Z | 30,132,313 | 9 | 2015-05-08T20:25:12Z | [
"python",
"datetime",
"pandas"
] | I need to make this simple thing:
```
dates = p.to_datetime(p.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.str
```
But a get an error. How should I transform from datetime to string
Thanks in advance | There is no `str` accessor for datetimes and you can't do `dates.astype(str)` either, you can call `apply` and use `datetime.strftime`:
```
In [73]:
dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0 2001-01-01
1 2001-03-31
dty... |
How can a pointer be passed between Rust and Python? | 30,133,293 | 9 | 2015-05-08T21:41:49Z | 30,134,107 | 9 | 2015-05-08T23:05:39Z | [
"python",
"rust",
"ctypes"
] | I am experimenting with writing a library in Rust that I can call from Python code. I would like to be able to pass a void pointer back to Python so that I can hold state between calls into Rust. However, I get a segfault in Rust when trying to access the pointer again.
Full code samples and crash report: <https://gis... | [eryksun nailed it](http://stackoverflow.com/questions/30133293/how-can-a-pointer-be-passed-between-rust-and-python#comment48377553_30133293):
> On the Python side, you're missing lib.continue\_state.argtypes = (ctypes.c\_void\_p,). Without defining the parameter as a pointer, ctypes uses the default conversion for a ... |
BeautifulSoup invalid syntax in Python 3.4 (after 2to3.py) | 30,140,034 | 3 | 2015-05-09T12:39:41Z | 30,140,054 | 7 | 2015-05-09T12:41:24Z | [
"python",
"python-3.x",
"beautifulsoup",
"python-3.4"
] | I am trying to install Beautiful Soup 4 in Python 3.4. I installed it from the command line, (got the invalid syntax error because I had not converted it), ran the `2to3.py` conversion script to `bs4` and now I get a new invalid syntax error.
```
>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
Fil... | BeautifulSoup 4 does **not** need manual converting to run on Python 3. You are trying to run code only compatible with Python 2 instead; it appears you failed to correctly convert the codebase.
From the [BeautifulSoup 4 homepage](http://www.crummy.com/software/BeautifulSoup/):
> Beautiful Soup 4 works on both Python... |
Sort a list to form the largest possible number | 30,140,796 | 3 | 2015-05-09T13:59:34Z | 30,141,885 | 13 | 2015-05-09T15:40:01Z | [
"python",
"python-2.7"
] | I am trying to write a function that given a list of non negative integers, arranges them such that they form the largest possible number.
For example, given `[50, 2, 1, 9]`, the largest formed number is `95021`.
Here is the code that I have tried to solve the problem:
```
a = [50, 2, 1, 9]
a.sort()
ans = []
for i i... | In Python 2 you can do this with an appropriate comparison function passed to `sort`.
```
#!/usr/bin/env python
''' Sort a list of non-negative integers so that
if the integers were converted to string, concatenated
and converted back to int, the resulting int is the highest
possible for that list
F... |
Computing the correlation coefficient between two multi-dimensional arrays | 30,143,417 | 2 | 2015-05-09T18:12:37Z | 30,143,754 | 7 | 2015-05-09T18:49:00Z | [
"python",
"arrays",
"numpy",
"scipy",
"correlation"
] | I have two arrays that have the shapes `N X T` and `M X T`. I'd like to compute the correlation coefficient across `T` between every possible pair of rows `n` and `m` (from `N` and `M`, respectively).
What's the fastest, most pythonic way to do this? (Looping over `N` and `M` would seem to me to be neither fast nor py... | **Correlation (default 'valid' case) between two 2D arrays:**
You can simply use matrix-multiplication [`np.dot`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) like so -
```
out = np.dot(arr_one,arr_two.T)
```
Correlation with the default `"valid"` case between each pairwise row combinations (r... |
Difference between bytearray and list | 30,145,490 | 4 | 2015-05-09T22:01:50Z | 30,145,560 | 9 | 2015-05-09T22:10:32Z | [
"python",
"python-2.7"
] | What is the difference between `bytearray` and for example, a `list` or `tuple`?
As the name suggests, `bytearray` must be an `array` that carries `byte` objects.
In python, it seems that `bytes` and `str` are treated equally
```
>>> bytes
<type 'str'>
```
So, what is the difference?
Also, if you print a `byte... | You are correct in some way: In Python 2, `bytes` is synonymous with the `str` type. This is because originally, there was no `bytes` object, there was only `str` and `unicode` (the latter being for unicode string, i.e. having multi-byte capabilities). When Python 3 came, they changed the whole string things and made u... |
Plotting 2D Kernel Density Estimation with Python | 30,145,957 | 8 | 2015-05-09T23:04:40Z | 30,146,280 | 14 | 2015-05-09T23:53:02Z | [
"python",
"matplotlib",
"plot",
"kernel",
"seaborn"
] | I would like to plot a 2D kernel density estimation. I find the seaborn package very useful here. However, after searching for a long time, I couldn't figure out how to make the y-axis and x-axis non-transparent. Also, how to show the values of the density on the contour? I would be very appreciated if someone could he... | Here is a solution using `scipy` and `matplotlib` only :
```
import numpy as np
import matplotlib.pyplot as pl
import scipy.stats as st
data = np.random.multivariate_normal((0, 0), [[0.8, 0.05], [0.05, 0.7]], 100)
x = data[:, 0]
y = data[:, 1]
xmin, xmax = -3, 3
ymin, ymax = -3, 3
# Peform the kernel density estimat... |
Why do numbers in a string become "x0n" when a backslash precedes them? | 30,146,891 | 4 | 2015-05-10T01:53:10Z | 30,146,915 | 8 | 2015-05-10T01:59:17Z | [
"python",
"string",
"python-3.x"
] | I was doing a few experiments with escape backslashes in the Python 3.4 shell and noticed something quite strange.
```
>>> string = "\test\test\1\2\3"
>>> string
'\test\test\x01\x02\x03'
>>> string = "5"
>>> string
'5'
>>> string = "5\6\7"
>>> string
'5\x06\x07'
```
As you can see in the above code, I defined a varia... | In Python string literals, the `\` character starts escape sequences. `\n` translates to a newline character, `\t` to a tab, etc. `\xhh` hex sequences let you produce codepoints with hex values instead, `\uhhhh` produce codepoints with 4-digit hex values, and `\Uhhhhhhhh` produce codepoints with 8-digit hex values.
Se... |
Why does assigning to an empty list (e.g. [] = "") raise no error? | 30,147,165 | 100 | 2015-05-10T02:41:15Z | 30,147,177 | 33 | 2015-05-10T02:43:22Z | [
"python",
"string",
"list",
"tuples"
] | In python 3.4, I am typing
```
[] = ""
```
and it works fine, no Exception is raised. Though of course `[]` is not equal to `""` afterwards.
```
[] = ()
```
also works fine.
```
"" = []
```
raises an exception as expected though,
```
() = ""
```
raises an exception as expected though. So, what's going on? | It follows the [*Assignment statements* section](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements) rules from the documentation,
> ```
> assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)
> ```
>
> If the `target list` is a comma-separated list of targets: **The obj... |
Why does assigning to an empty list (e.g. [] = "") raise no error? | 30,147,165 | 100 | 2015-05-10T02:41:15Z | 30,147,179 | 116 | 2015-05-10T02:43:37Z | [
"python",
"string",
"list",
"tuples"
] | In python 3.4, I am typing
```
[] = ""
```
and it works fine, no Exception is raised. Though of course `[]` is not equal to `""` afterwards.
```
[] = ()
```
also works fine.
```
"" = []
```
raises an exception as expected though,
```
() = ""
```
raises an exception as expected though. So, what's going on? | You are not comparing for equality. You are **assigning**.
Python allows you to assign to multiple targets:
```
foo, bar = 1, 2
```
assigns the two values to `foo` and `bar`, respectively. All you need is a *sequence* or *iterable* on the right-hand side, and a list or tuple of names on the left.
When you do:
```
... |
scoping and typing rules in python | 30,148,453 | 3 | 2015-05-10T06:35:29Z | 30,148,460 | 9 | 2015-05-10T06:37:26Z | [
"python"
] | I am a beginner at python programming and I have written the following program in an attempt to understand scoping and typing rules.
```
a = 5 ... | Variables in Python don't have types. They're just names for values. Those values, of course, do have types, but the variables don't care. Just as "John" can be the name for a man in one conversation or for a poodle in another, `a` can be the name for an `int` in one part of your program and a `str` in another part.
-... |
How do I do exponentiation in python? | 30,148,740 | 3 | 2015-05-10T07:20:26Z | 30,148,765 | 12 | 2015-05-10T07:23:29Z | [
"python",
"math",
"operators"
] | ```
def cube(number):
return number^3
print cube(2)
```
I would would expect `cube(2) = 8`, but instead I'm getting `cube(2) = 1`
What am I doing wrong? | `^` is the [xor](http://en.wikipedia.org/wiki/Exclusive_or) operator.
`**` is exponentiation.
`2**3 = 8` |
Redis AUTH command in Python | 30,149,493 | 4 | 2015-05-10T08:51:50Z | 30,153,367 | 7 | 2015-05-10T15:47:25Z | [
"python",
"redis"
] | I'm using [redis-py](https://github.com/andymccurdy/redis-py) binding in Python 2 to connect to my Redis server. The server requires a password. I don't know how to `AUTH` after making the connection in Python.
The following code does not work:
```
import redis
r = redis.StrictRedis()
r.auth('pass')
```
It says:
> ... | Thanks to the hints from the comments. I found the answer from <https://redis-py.readthedocs.org/en/latest/>.
It says
```
class redis.StrictRedis(host='localhost', port=6379, db=0, password=None, socket_timeout=None, connection_pool=None, charset='utf-8', errors='strict', unix_socket_path=None)
```
So `AUTH` is in f... |
IOError: [Errno 2] No such file or directory writing in a file in home directory | 30,151,355 | 2 | 2015-05-10T12:24:06Z | 30,151,425 | 9 | 2015-05-10T12:29:26Z | [
"python"
] | I have this code below to store some text in a file ~/.boto that is in home directory.
But Im getting this error:
```
IOError: [Errno 2] No such file or directory: '~/.boto'
```
This is the code:
```
file = open("~/.boto")
file.write("test")
file.close()
``` | You need to use os.path.expanduser and open for writing with `w`:
```
import os
# with will automatically close your file
with open(os.path.expanduser("~/.boto"),"w") as f:
f.write("test") # write to file
```
**os.path.expanduser(path)**
> On Unix and Windows, return the argument with an initial component of ~... |
json.dumps messes up order | 30,152,688 | 4 | 2015-05-10T14:41:00Z | 30,152,809 | 7 | 2015-05-10T14:51:11Z | [
"python",
"json"
] | I'm working with the [json module](https://docs.python.org/2/library/json.html) creating a `json` file containing entries of the like
```
json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }})
```
However, in the `json`-file created the fields are in the wrong order
```
{"fields": {"... | Like the other answers correctly state, Python dictionaries are *unordered*.
That said, [JSON is also supposed to have *unordered* mappings](http://stackoverflow.com/a/4920304/42973), so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON obje... |
Django, uwsgi and nginx - Internal Server Error | 30,154,364 | 3 | 2015-05-10T17:21:30Z | 30,155,016 | 7 | 2015-05-10T18:20:39Z | [
"python",
"django",
"nginx",
"uwsgi"
] | I am quite new to python and am working on my first django project. I followed [this](http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html) tutorial. I managed to configure all the things but django app itself. It works if I run django server alone, however it does not work when started by uwsgi.... | You are probably lacking a `chdir` line in your `uwsgi_conf.ini`. Or, probably, you have a `chdir` line, but it is wrong.
This is confirmed by your traceback:
```
File "./wsgi.py", line 16, in <module>
```
Here you should see `./api/wsgi.py`, not `./wsgi.py`.
Clearly, the working directory of uWSGI is the `api/` di... |
How can I write asyncio coroutines that optionally act as regular functions? | 30,155,138 | 5 | 2015-05-10T18:31:03Z | 30,163,654 | 10 | 2015-05-11T09:10:53Z | [
"python",
"python-3.x",
"python-asyncio"
] | I'm writing a library that I'd like end-users to be able to optionally use as if its methods and functions were not coroutines.
For example, given this function:
```
@asyncio.coroutine
def blah_getter():
return (yield from http_client.get('http://blahblahblah'))
```
An end user who doesn't care to use any asynch... | You need two functions -- asynchronous coroutine and synchronous regular function:
```
@asyncio.coroutine
def async_gettter():
return (yield from http_client.get('http://example.com'))
def sync_getter()
return asyncio.get_event_loop().run_until_complete(async_getter())
```
`magically_determine_if_being_yield... |
How can I write asyncio coroutines that optionally act as regular functions? | 30,155,138 | 5 | 2015-05-10T18:31:03Z | 30,171,640 | 7 | 2015-05-11T15:24:05Z | [
"python",
"python-3.x",
"python-asyncio"
] | I'm writing a library that I'd like end-users to be able to optionally use as if its methods and functions were not coroutines.
For example, given this function:
```
@asyncio.coroutine
def blah_getter():
return (yield from http_client.get('http://blahblahblah'))
```
An end user who doesn't care to use any asynch... | I agree with Andrew's answer, I just want to add that if you're dealing with objects, rather than top-level functions, you can use a metaclass to add synchronous versions of your asynchronous methods automatically. See this example:
```
import asyncio
import aiohttp
class SyncAdder(type):
""" A metaclass which ad... |
Python in Browser: How to choose between Brython, PyPy.js, Skulpt and Transcrypt? | 30,155,551 | 18 | 2015-05-10T19:08:35Z | 30,155,677 | 8 | 2015-05-10T19:20:10Z | [
"python",
"browser",
"brython",
"skulpt",
"transcrypt"
] | *EDIT: Please note I'm **NOT** asking for a (subjective) product recommendation. I am asking for **objective** information -- that I can then use to make my own decision.*
I'm very excited to see that it is now possible to code Python inside a browser page. The main candidates appear to be:
<http://www.brython.info/>... | <https://brythonista.wordpress.com/2015/03/28/comparing-the-speed-of-cpython-brython-skulpt-and-pypy-js/>
This page benchmarks the three candidates. Brython emerges as a clear winner.
Despite the 'help' explaining that S.O. is not good for this kind of question, it appears that a concise answer is in this case possib... |
Python in Browser: How to choose between Brython, PyPy.js, Skulpt and Transcrypt? | 30,155,551 | 18 | 2015-05-10T19:08:35Z | 30,517,812 | 9 | 2015-05-28T22:01:19Z | [
"python",
"browser",
"brython",
"skulpt",
"transcrypt"
] | *EDIT: Please note I'm **NOT** asking for a (subjective) product recommendation. I am asking for **objective** information -- that I can then use to make my own decision.*
I'm very excited to see that it is now possible to code Python inside a browser page. The main candidates appear to be:
<http://www.brython.info/>... | This might be helpful too:
<http://stromberg.dnsalias.org/~strombrg/pybrowser/python-browser.html>
It compares several Python-in-the-browser technologies. |
Python in Browser: How to choose between Brython, PyPy.js, Skulpt and Transcrypt? | 30,155,551 | 18 | 2015-05-10T19:08:35Z | 38,564,424 | 9 | 2016-07-25T09:43:56Z | [
"python",
"browser",
"brython",
"skulpt",
"transcrypt"
] | *EDIT: Please note I'm **NOT** asking for a (subjective) product recommendation. I am asking for **objective** information -- that I can then use to make my own decision.*
I'm very excited to see that it is now possible to code Python inside a browser page. The main candidates appear to be:
<http://www.brython.info/>... | Here's some info on Brython vs Transcrypt (July 2016, since Transcrypt was added as an option on this question by the OP), gleaned by starting off a project with Brython a few months ago and moving to Transcrypt (completed moving last week). I like Brython and Transcrypt and can see uses for both of them.
For people t... |
Virtualenv in source control | 30,156,152 | 5 | 2015-05-10T20:10:09Z | 30,156,162 | 8 | 2015-05-10T20:10:55Z | [
"python",
"virtualenv"
] | Perhaps this is more an opinion-based question, but I was wondering whether the contents of a `virtualenv` should be included in a GitHub repository. Why should it or should it not be included? | No, anything that can be generated should not be included.
Dependencies should be managed with something like pip, and the requirements.txt file can be included.
The only files under source control should be files you absolutely need to get you development environment going. So it can included boot strapping of some ... |
matplotlib installation issue python 3 | 30,156,965 | 5 | 2015-05-10T21:41:45Z | 31,403,604 | 7 | 2015-07-14T10:06:24Z | [
"python",
"ubuntu",
"matplotlib",
"install"
] | I am trying to install metaplotlib on ubuntu 14.04 within pycharm and get the following error:
> TypeError: unorderable types: str() < int()
ubuntu 14.04 64bits
pycharm running python 3
The traceback is:
```
DEPRECATION: --no-install, --no-download, --build, and --no-clean are deprecated. Downloading/unpacking mat... | I was getting the same error and was able to solve it by installing libfreetype6-dev and libpng12-dev.
`sudo apt-get install libfreetype6-dev libpng12-dev`
Thanks to @koukouviou for pointing the upstream bug report, which considerably sped up the solution finding process. |
Does python os.fork uses the same python interpreter? | 30,157,895 | 7 | 2015-05-11T00:01:32Z | 30,157,929 | 8 | 2015-05-11T00:06:56Z | [
"python",
"multiprocessing"
] | I understand that threads in Python use the same instance of Python interpreter. My question is it the same with process created by `os.fork`? Or does each process created by `os.fork` has its own interpreter? | `os.fork()` is equivalent to the `fork()` syscall in many UNIC(es). So **yes** your sub-process(es) will be separate from the parent and have a different interpreter (*as such*).
[`man fork`](http://linux.die.net/man/2/fork):
> FORK(2)
>
> NAME
> fork - create a child process
>
> SYNOPSIS
> #include
>
> ```
> pid_... |
Does python os.fork uses the same python interpreter? | 30,157,895 | 7 | 2015-05-11T00:01:32Z | 30,157,933 | 9 | 2015-05-11T00:07:39Z | [
"python",
"multiprocessing"
] | I understand that threads in Python use the same instance of Python interpreter. My question is it the same with process created by `os.fork`? Or does each process created by `os.fork` has its own interpreter? | Whenever you fork, the entire Python process is duplicated in memory (*including* the Python interpreter, your code and any libraries, current stack etc.) to create a second process - one reason why forking a process is much more expensive than creating a thread.
This creates a **new copy** of the python interpreter.
... |
Does python os.fork uses the same python interpreter? | 30,157,895 | 7 | 2015-05-11T00:01:32Z | 30,158,020 | 9 | 2015-05-11T00:21:05Z | [
"python",
"multiprocessing"
] | I understand that threads in Python use the same instance of Python interpreter. My question is it the same with process created by `os.fork`? Or does each process created by `os.fork` has its own interpreter? | While `fork` does indeed create a copy of the current Python interpreter rather than running with the same one, it usually isn't what you want, at least not on its own. Among other problems:
* There can be problems forking multi-threaded processes on some platforms. And some libraries (most famously Apple's Cocoa/Core... |
Removing backslashes from string | 30,158,002 | 9 | 2015-05-11T00:18:29Z | 30,158,037 | 11 | 2015-05-11T00:23:10Z | [
"python"
] | I answered a question earlier where the OP asked how he can remove backslashes from a string. This is how the backslashes looked like in the OP's string:
```
"I don\'t know why I don\'t have the right answer"
```
This was my answer:
```
a = "I don\'t know why I don\'t have the right answer"
b = a.strip("/")
print b
... | Well, there are no slashes, nor backslashes, in the string. The backslashes escape `'`, although they don't have to because the string is delimited with `""`.
```
print("I don\'t know why I don\'t have the right answer")
print("I don't know why I don't have the right answer")
```
Produces:
```
I don't know why I don... |
Removing backslashes from string | 30,158,002 | 9 | 2015-05-11T00:18:29Z | 30,158,063 | 15 | 2015-05-11T00:28:43Z | [
"python"
] | I answered a question earlier where the OP asked how he can remove backslashes from a string. This is how the backslashes looked like in the OP's string:
```
"I don\'t know why I don\'t have the right answer"
```
This was my answer:
```
a = "I don\'t know why I don\'t have the right answer"
b = a.strip("/")
print b
... | ```
a = "I don\'t know why I don\'t have the right answer"
b = a.strip("/")
print b
```
1. Slash (`/`) and backslash (`\`) are not the same character. There are no slashes anywhere in the string, so what you're doing will have no effect.
2. Even if you used a backslash, there are no backslashes in `a` anyway; `\'` in ... |
display an octal value as it's string representation | 30,160,270 | 2 | 2015-05-11T05:34:14Z | 30,160,301 | 13 | 2015-05-11T05:36:56Z | [
"python",
"format",
"octal"
] | I've got a problem when convert an octal to string
```
p = 01212
k = str(p)
print k
```
The result is `650` but I need `01212`. How can I do this? Thanks in advance | Your number `p` is the actual *value* rather than the *representation* of that value. So it's actually `65010`, `12128` and `28a16`, *all at the same time.*
If you want to see it as octal, just use:
```
print oct(p)
```
as per the following transcript:
```
>>> p = 01212
>>> print p
650
>>> print oct(p)
01212
```
T... |
How to move files between two Amazon S3 Buckets using boto? | 30,161,700 | 3 | 2015-05-11T07:17:31Z | 30,162,265 | 7 | 2015-05-11T07:52:17Z | [
"python",
"amazon-s3",
"boto"
] | I have to move files between one bucket to another with Pyhton Boto API. (I need it to "Cut" the file from the first Bucket and "Paste" it in the second one).
What is the best way to do that?
\*\* Note: Is that matter if I have two different ACCESS KEYS and SECRET KEYS? | I think the boto S3 documentation answers your question.
<https://github.com/boto/boto/blob/develop/docs/source/s3_tut.rst>
Moving files from one bucket to another via boto is effectively a copy of the keys from source to destination than removing the key from source.
You can get access to the buckets:
```
import b... |
Is there a faster way to clean out control characters in a file? | 30,169,613 | 13 | 2015-05-11T13:56:41Z | 30,347,354 | 7 | 2015-05-20T10:44:24Z | [
"python",
"regex",
"unicode",
"io",
"control-characters"
] | [Previously](http://www.uni-koeln.de/~mzampier/papers/bucc2014.pdf), I had been cleaning out data using the [code snippet](http://pastebin.com/1aR1ivaR) below
```
import unicodedata, re, io
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(c for c in all_chars if unicodedata.category(c)[0] == ... | found a solution working character by charater, I bench marked it using a 100K file:
```
import unicodedata, re, io
from time import time
# This is to generate randomly a file to test the script
from string import lowercase
from random import random
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ... |
How to run Spyder in virtual environment? | 30,170,468 | 9 | 2015-05-11T14:33:47Z | 30,170,469 | 10 | 2015-05-11T14:33:47Z | [
"python",
"python-3.x",
"virtualenv",
"anaconda",
"spyder"
] | I have been using Spyder installed with with Anaconda distribution which uses Python 2.7 as default. Currently I need to set up a development virtual environment with Python 3.4.
Top two suggestions after research online are:
1. to set up virtual environment first and to point change the preferences of Spyder , e.g [... | There is an option to [create virtual environments in Anaconda](http://conda.pydata.org/docs/faq.html#creating-new-environments) with required Python version.
```
conda create -n myenv python=3.4 anaconda
```
This will create virtual environment to `virtualenv`.
To activate it :
```
source activate myenv # (in lin... |
Python asyncio task got bad yield | 30,172,821 | 8 | 2015-05-11T16:23:30Z | 30,174,350 | 7 | 2015-05-11T17:50:31Z | [
"python",
"asynchronous",
"python-asyncio"
] | I am confused about how to play around with the `asyncio` module in Python 3.4. I have a `searching` API for a search engine, and want to each search request to be run either parallel, or asynchronously, so that I don't have to wait for one search finish to start another.
Here is my high-level searching API to build s... | The problem is that you can't just call existing synchronous code as if it was an `asyncio.coroutine` and get asynchronous behavior. When you call `yield from searching(...)`, you're only going to get asynchronous behavior if `searching` itself is actually an `asyncio.coroutine`, or at least returns an `asyncio.Future`... |
String vs list membership check | 30,175,674 | 10 | 2015-05-11T19:05:43Z | 30,175,729 | 9 | 2015-05-11T19:09:09Z | [
"python",
"string",
"list"
] | So i'm wondering why this:
```
'alpha' in 'alphanumeric'
```
is `True`, but
```
list('alpha') in list('alphanumeric')
```
is `False`.
Why does `x in s` succeed when `x` is a substring of `s`, but `x in l` doesn't when `x` is a sub*list* of `l`? | When you use `list` function with any iterable, a new list object will be created with all the elements from the iterable as individual elements in the list.
In your case, strings are valid Python iterables, so
```
>>> list('alpha')
['a', 'l', 'p', 'h', 'a']
>>> list('alphanumeric')
['a', 'l', 'p', 'h', 'a', 'n', 'u'... |
How to pass tuple1 if ... else tuple2 to str.format? | 30,185,316 | 10 | 2015-05-12T08:15:25Z | 30,185,360 | 8 | 2015-05-12T08:17:43Z | [
"python",
"tuples",
"string-formatting"
] | Put simply, why do I get the following error?
```
>>> yes = True
>>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " "))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
```
I use python 2.6. | Use the `*` operator, which takes an iterable of parameters and supplies each one as a positional argument to the function:
```
In [3]: 'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))
Out[3]: 'no [ ] yes [x]'
``` |
How to pass tuple1 if ... else tuple2 to str.format? | 30,185,316 | 10 | 2015-05-12T08:15:25Z | 30,185,365 | 15 | 2015-05-12T08:17:57Z | [
"python",
"tuples",
"string-formatting"
] | Put simply, why do I get the following error?
```
>>> yes = True
>>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " "))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
```
I use python 2.6. | â Indexing option:
When accessing argumentsâ items in format string, you should use index to call the value:
```
yes = True
print 'no [{0[0]}] yes [{0[1]}]'.format((" ", "x") if yes else ("x", " "))
```
`{0[0]}` in format string equals `(" ", "x")[0]` in calling index of tulple
`{0[1]}` in format string equals ... |
Obtain a list containing string elements excluding elements prefixed with any other element from initial list | 30,186,869 | 13 | 2015-05-12T09:30:55Z | 30,188,818 | 8 | 2015-05-12T10:57:40Z | [
"python",
"string",
"list",
"python-2.7",
"filtering"
] | I have some trouble with filtering a list of strings. I found a similar question [here](http://stackoverflow.com/questions/22221878/python-delete-substrings-from-list-of-strings) but is not what i need.
The input list is:
```
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
```
and the expected result is
... | You can group the items by first letter and just search the sublists, no string can start with a substring unless it has at least the same first letter:
```
from collections import defaultdict
def find(l):
d = defaultdict(list)
# group by first letter
for ele in l:
d[ele[0]].append(ele)
for va... |
Obtain a list containing string elements excluding elements prefixed with any other element from initial list | 30,186,869 | 13 | 2015-05-12T09:30:55Z | 30,250,865 | 12 | 2015-05-15T03:03:46Z | [
"python",
"string",
"list",
"python-2.7",
"filtering"
] | I have some trouble with filtering a list of strings. I found a similar question [here](http://stackoverflow.com/questions/22221878/python-delete-substrings-from-list-of-strings) but is not what i need.
The input list is:
```
l = ['ab', 'xc', 'abb', 'abed', 'sdfdg', 'abfdsdg', 'xccc']
```
and the expected result is
... | This algorithm completes the task in 0.97 second on my computer, with [the input file submitted by the author (154MB)](http://soft2u.ro/out.txt):
```
l.sort()
last_str = l[0]
filtered = [last_str]
app = filtered.append
for str in l:
if not str.startswith(last_str):
last_str = str
app(str)
#... |
"yield from iterable" vs "return iter(iterable)" | 30,187,598 | 12 | 2015-05-12T10:03:43Z | 30,188,263 | 9 | 2015-05-12T10:32:29Z | [
"python",
"python-3.x",
"iterable",
"yield-from"
] | When wrapping an (internal) iterator one often has to reroute the `__iter__` method to the underlying iterable. Consider the following example:
```
class FancyNewClass(collections.Iterable):
def __init__(self):
self._internal_iterable = [1,2,3,4,5]
# ...
# variant A
def __iter__(self):
... | The only significant difference is what happens when an exception is raised from within the iterable. Using `return iter()` your `FancyNewClass` will not appear on the exception traceback, whereas with `yield from` it will. It is generally a good thing to have as much information on the traceback as possible, although ... |
How can I use super() with one argument in python | 30,190,185 | 13 | 2015-05-12T11:57:02Z | 30,190,341 | 11 | 2015-05-12T12:04:08Z | [
"python",
"super"
] | While reading about the [`super()` object](https://docs.python.org/2/library/functions.html#super) in Python, I read the following statement:
> If the second argument is omitted, the super object returned is unbound
What does this exactly mean and how do I use `super()` with one argument in code? | Python function objects are [descriptors](https://docs.python.org/2/howto/descriptor.html), and Python uses the descriptor protocol to *bind* functions to an instance. This process produces a *bound method*.
Binding is what makes the 'magic' `self` argument appear when you call a method, and what makes a `property` ob... |
Coroutine in python between 3.4 and 3.5, How can I keep backwords compatibility? | 30,191,556 | 8 | 2015-05-12T12:56:07Z | 30,195,047 | 11 | 2015-05-12T15:16:46Z | [
"python",
"python-3.x",
"asynchronous",
"python-asyncio"
] | I'm on developing python chatting bot framework with `asyncio`. But I watch [PEP-492](https://www.python.org/dev/peps/pep-0492) and there is new syntax, `async`/`await` and finally it accepted.
I like `async`/`await` syntax and I want to use it. but I worry about 3.4 backwords compatibility.
If I use new syntax in my... | If you need to support Python 3.4 in your code, you'll need to use the old `@asyncio.coroutine`/`yield from` style syntax. There's no way to support the `async`/`await` syntax without running 3.5; you'll get a `SyntaxError` at compilation time on 3.4 or lower.
The only thing that takes advantage of the new features yo... |
Python: apply list of functions to each element in list | 30,193,522 | 2 | 2015-05-12T14:14:42Z | 30,193,577 | 8 | 2015-05-12T14:17:13Z | [
"python",
"python-2.7",
"lambda"
] | Say I have list with elements `content = ['121\n', '12\n', '2\n', '322\n']` and list with functions `fnl = [str.strip, int]`.
So I need to apply each function from `fnl` to each element from `content` sequentially.
I can do this by several calls `map`.
Another way:
```
xl = lambda func, content: map(func, content)
f... | You could use the [`reduce()` function](https://docs.python.org/2/library/functions.html#reduce) in a list comprehension here:
```
[reduce(lambda v, f: f(v), fnl, element) for element in content]
```
Demo:
```
>>> content = ['121\n', '12\n', '2\n', '322\n']
>>> fnl = [str.strip, int]
>>> [reduce(lambda v, f: f(v), f... |
How to multiply functions in python? | 30,195,045 | 25 | 2015-05-12T15:16:32Z | 30,196,480 | 16 | 2015-05-12T16:22:09Z | [
"python",
"function",
"monkeypatching",
"function-composition"
] | ```
def sub3(n):
return n - 3
def square(n):
return n * n
```
It's dead easy to compose functions in python:
```
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [square(sub3(n)) for n in my_list]
[9, 4, 1, 0, 1, 4, 9, 16, 25, 36]
```
Unfortunately, when wanting to use the composition as a *key*, it's kind of... | You can use your hack class as a decorator pretty much as it's written, though you'd likely want to choose a more appropriate name for the class.
Like this:
```
class Composable(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
return self.fun... |
How to save Python NLTK alignment models for later use? | 30,195,287 | 13 | 2015-05-12T15:25:51Z | 30,214,539 | 7 | 2015-05-13T12:18:28Z | [
"python",
"io",
"nlp",
"nltk",
"machine-translation"
] | In Python, I'm using [`NLTK's alignment module`](http://www.nltk.org/api/nltk.align.html) to create word alignments between parallel texts. Aligning bitexts can be a time-consuming process, especially when done over considerable corpora. It would be nice to do alignments in batch one day and use those alignments later ... | The immediate answer is to pickle it, see <https://wiki.python.org/moin/UsingPickle>
But because IBMModel1 returns a lambda function, it's not possible to pickle it with the default `pickle` / `cPickle` (see <https://github.com/nltk/nltk/blob/develop/nltk/align/ibm1.py#L74> and <https://github.com/nltk/nltk/blob/devel... |
Why is my Fortran code wrapped with f2py using so much memory? | 30,197,773 | 7 | 2015-05-12T17:32:34Z | 30,198,584 | 7 | 2015-05-12T18:18:39Z | [
"python",
"memory-management",
"fortran",
"out-of-memory",
"f2py"
] | I am trying to calculate all the distances between approximately a hundred thousand points. I have the following code written in Fortran and compiled using `f2py`:
```
C 1 2 3 4 5 6 7
C123456789012345678901234567890123456789012345678901234567890123456789012
... | You are feeding double precision arrays to the Fortran subroutine. Each element in double precision requires 8 Byte of memory. For `N=30,000` that makes
```
coor(n,3) => 30,000*3*8 ~ 0.7 MB
dist(n,n) => 30,000^2*8 ~ 6.7 GB
```
Since the half precision floats are additionally required for Python, that accounts for ano... |
Nest a flat list based on an arbitrary criterion | 30,198,235 | 10 | 2015-05-12T17:59:02Z | 30,198,305 | 9 | 2015-05-12T18:03:37Z | [
"python",
"list"
] | I have a flat list of unique objects, some of which may share a given attribute with others. I wish to create a nested list-of-lists, with objects grouped by the given attribute. As a minimal example, given the following list:
```
>>> flat = ["Shoes", "pants", "shirt", "tie", "jacket", "hat"]
```
I might want to grou... | A common idiom for an existing list is to use [groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby) in itertools:
```
from itertools import groupby
flat = ["Shoes", "pants", "shirt", "tie", "jacket", "hat"]
result=[]
for k, g in groupby(sorted(flat, key=len), key=len):
result.append(list(... |
What's the pythonic idiom for making a simple list out of a list of instances? | 30,198,638 | 2 | 2015-05-12T18:21:16Z | 30,198,704 | 8 | 2015-05-12T18:24:21Z | [
"python",
"sqlalchemy",
"list-comprehension"
] | I have a list of record instances returned by SQLAlchemy.
While the instances have many attributes, I want a new list with only one of the attributes. The java coder in me says:
```
my_records = query.all()
names = []
for my_record in my_records:
names.append(my_record.name)
```
...which works, of course. But Wh... | You are looking for what is called a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
names = [my_record.name for my_record in query.all()]
```
The above is a concise equivalent to the for-loop in your example.
---
In addition, you should be aware that there are ... |
Python how to index multidimensional array with string key, like a dict | 30,198,973 | 5 | 2015-05-12T18:39:41Z | 30,200,037 | 7 | 2015-05-12T19:42:26Z | [
"python",
"numpy",
"dictionary",
"indexing",
"pandas"
] | I would like to combine the functionality of numpy's `array` with native python's `dict`, namely creating a multidimensional array that can be indexed with strings.
For example, I could do this:
```
dict_2d = {'a': {'x': 1, 'y': 2},
'b': {'x': 3, 'y': 4}}
print dict_2d['a','y'] # returns 2
```
I know I c... | You may be looking for [pandas](http://pandas.pydata.org/), which provides handy datatypes that wrap numpy arrays, allowing you do access rows and columns by name instead of just by number. |
Expanding a block of numbers in Python | 30,201,119 | 7 | 2015-05-12T20:47:54Z | 30,201,202 | 9 | 2015-05-12T20:52:36Z | [
"python",
"list",
"python-2.7",
"variable-expansion"
] | Before I asked, I did some googling, and was unable to find an answer.
The scenario I have is this:
A list of numbers are passed to the script, either \n-delimited via a file, or comma-delimited via a command line arg. The numbers can be singular, or in blocks, like so:
File:
```
1
2
3
7-10
15
20-25
```
Command Lin... | So let's say you're given the list:
```
L = ['1','2','3','7-10','15','20-25']
```
and you want to expand out all the ranges contained therein:
```
answer = []
for elem in L:
if '-' not in elem:
answer.append(elem)
continue
start, end = elem.split('-')
answer.extend(map(str, range(int(star... |
Why are the programming languages limits precision of 22/7 equally? | 30,201,855 | 4 | 2015-05-12T21:36:57Z | 30,202,144 | 16 | 2015-05-12T21:58:06Z | [
"python",
"ruby",
"haskell",
"floating-point",
"erlang"
] | I tried
```
Erlang
$ erl
1> Pi = 22/7.
3.142857142857143
Haskell
$ ghci
Prelude> 22/7
3.142857142857143
Python
$ python
>>> 22/7.0
3.142857142857143
Ruby
$ irb
2.1.6 :001 > 22 / 7.0
=> 3.142857142857143
```
The results are the same. Why? | This happens because all the languages are using the same numerical representation for non-integer numbers: [IEEE 754 floating point numbers](http://en.wikipedia.org/wiki/IEEE_floating_point) with, most likely, the same level of precision. (Either 32-bit "floats" or 64-bit "doubles", depending on how your system and la... |
'NoneType' object has no attribute '_app_data' in scrapy\twisted\openssl | 30,202,669 | 8 | 2015-05-12T22:41:08Z | 31,423,708 | 21 | 2015-07-15T07:11:12Z | [
"python",
"openssl",
"scrapy",
"twisted",
"pyopenssl"
] | During the scraping process using scrapy one error appears in my logs from time to time.
It doesnt seem to be anywhere in my code, and looks like it something inside twisted\openssl.
Any ideas what caused this and how to get rid of it?
Stacktrace here:
```
[Launcher,27487/stderr] Error during info_callback
Traceb... | I was able to solve this problem by installing the `service_identity` package:
`pip install service_identity` |
Unprint a line on the console in Python? | 30,203,228 | 2 | 2015-05-12T23:38:32Z | 30,203,416 | 7 | 2015-05-13T00:01:53Z | [
"python",
"printing"
] | Is it possible to manipulate lines of text that have already been printed to the console?
For example,
```
import time
for k in range(1,100):
print(str(k)+"/"+"100")
time.sleep(0.03)
#>> Clear the most recent line printed to the console
print("ready or not here I come!")
```
I've seen some things for ... | What you're looking for is:
```
print("{}/100".format(k), "\r", end="")
```
`\r` is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. `end=""` is to prevent `\n` after printing (to stay on the same line).
In [Python 2](htt... |
running a python package after compiling and uploading to pypicloud server | 30,205,298 | 12 | 2015-05-13T03:44:21Z | 30,271,399 | 9 | 2015-05-16T03:01:26Z | [
"python",
"pypi"
] | Folks,
After building and deploying a package called `myShtuff` to a local pypicloud server, I am able to install it into a separate virtual env.
Everything seems to work, except for the path of the executable...
```
(venv)[ec2-user@ip-10-0-1-118 ~]$ pip freeze
Fabric==1.10.1
boto==2.38.0
myShtuff==0.1
ecdsa==0.13
pa... | You need a `__main__.py` in your package, and an entry point defined in setup.py.
See [here](https://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation) and [here](https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/) but in short, your `__main__.py` runs what... |
Optimize Double loop in python | 30,211,336 | 7 | 2015-05-13T09:53:15Z | 30,215,273 | 7 | 2015-05-13T12:48:12Z | [
"python",
"performance",
"loops",
"numpy",
"numba"
] | I am trying to optimize the following loop :
```
def numpy(nx, nz, c, rho):
for ix in range(2, nx-3):
for iz in range(2, nz-3):
a[ix, iz] = sum(c*rho[ix-1:ix+3, iz])
b[ix, iz] = sum(c*rho[ix-2:ix+2, iz])
return a, b
```
I tried different solutions and found using numba to cal... | You are basically performing 2D convolution there, with a small modification that your kernel is not reversing as the usual [`convolution`](http://en.wikipedia.org/wiki/Convolution) operation does.
So, basically, there are two things we need to do here to use [`signal.convolve2d`](http://docs.scipy.org/doc/scipy-0.15.1... |
What is the difference between pandas.qcut and pandas.cut? | 30,211,923 | 9 | 2015-05-13T10:18:25Z | 30,214,901 | 13 | 2015-05-13T12:33:00Z | [
"python",
"pandas"
] | The documentation says:
<http://pandas.pydata.org/pandas-docs/dev/basics.html>
"Continuous values can be discretized using the cut (bins based on values) and qcut (bins based on sample quantiles) functions"
Sounds very abstract to me... I can see the differences in the example below but **what does qcut (sample quan... | To begin, note that quantiles is just the most general term for things like percentiles, quartiles, and medians. You specified five bins in your example, so you are asking `qcut` for quintiles.
So, when you ask for quintiles with `qcut`, the bins will be chosen so that you have the same number of records in each bin. ... |
Sort two lists in python? | 30,212,452 | 3 | 2015-05-13T10:40:56Z | 30,212,576 | 7 | 2015-05-13T10:46:17Z | [
"python",
"list",
"sorting"
] | I am counting some occurrences of words in a text, and I have two lists : the first contains the words, the second contains the occurrences.
So at the end of the analysis I have something like
```
listWords : ["go", "make", "do", "some", "lot"]
listOccurrences: [2, 4, 8, 1, 5]
```
And I want to sort those two lists ... | ```
>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listTmp = zip(listOccurrences, listWords)
>>> listTmp
[(2, 'go'), (4, 'make'), (8, 'do'), (1, 'some'), (5, 'lot')]
>>> listTmp.sort(reverse=True)
>>> listTmp
[(8, 'do'), (5, 'lot'), (4, 'make'), (2, 'go'), (1, 'some')]
>>>... |
How do I compare two Python Pandas Series of different lengths? | 30,214,328 | 6 | 2015-05-13T12:07:34Z | 30,214,389 | 10 | 2015-05-13T12:10:24Z | [
"python",
"pandas"
] | I have two Series of different lengths, and I want to get the indices for which **both the indices *and* the amount** are the same in both series.
Here are the Series:
```
ipdb> s1
s1
000007720 2000.00
group1 -3732.05
group t3 2432.12
group2 -38147.87
FSHLAJ -36711.09... | You want to use [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html#pandas.Series.isin):
```
In [121]:
s2[s2.isin(s1)]
Out[121]:
000007720
group1 -3732.05
group2 -38147.87
FSHLAJ -36711.09
Name: 2000.00, dtype: float64
```
I don't know which way round you wanted to perform t... |
Basics of recursion in Python | 30,214,531 | 13 | 2015-05-13T12:18:00Z | 30,214,677 | 44 | 2015-05-13T12:24:12Z | [
"python",
"list",
"python-2.7",
"recursion"
] | > "Write a recursive function, "listSum" that takes a list of integers and returns the sum of all integers in the list".
Example:
```
>>>> listSum([1,3,4,5,6])
19
```
I know how to do this another way but not in the recursive way.
```
def listSum(ls):
i = 0
s = 0
while i < len(ls):
s = s + ls[i]... | Whenever you face a problem like this, try to express the result of the function with the same function.
In your case, you can get the result by adding the first number with the result of calling the same function with rest of the elements in the list.
For example,
```
listSum([1, 3, 4, 5, 6]) = 1 + listSum([3, 4, 5... |
Errata (erasures+errors) Berlekamp-Massey for Reed-Solomon decoding | 30,215,337 | 23 | 2015-05-13T12:50:39Z | 30,468,399 | 12 | 2015-05-26T20:35:24Z | [
"python",
"math",
"error-correction",
"galois-field",
"reed-solomon"
] | I am trying to implement a Reed-Solomon encoder-decoder in Python supporting the decoding of both erasures and errors, and that's driving me crazy.
The implementation currently supports decoding only errors or only erasures, but not both at the same time (even if it's below the theoretical bound of 2\*errors+erasures ... | After reading lots and lots of research papers and books, the only place where I have found the answer is in the book ([readable online on Google Books](https://books.google.fr/books?id=eQs2i-R9-oYC&lpg=PR11&ots=atCPQJm3OJ&dq=%22Algebraic%20codes%20for%20data%20transmission%22%2C%20Blahut%2C%20Richard%20E.%2C%202003%2C... |
Why is [] faster than list()? | 30,216,000 | 472 | 2015-05-13T13:16:22Z | 30,216,145 | 65 | 2015-05-13T13:21:38Z | [
"python",
"performance",
"list",
"instantiation",
"literals"
] | I recently compared the processing speeds of `[]` and `list()` and was surprised to discover that `[]` runs *more than three times faster* than `list()`. I ran the same test with `{}` and `dict()` and the results were practically identical: `[]` and `{}` both took around 0.128sec / million cycles, while `list()` and `d... | Because `list` is a [function](https://docs.python.org/2/library/functions.html#list) to convert say a string to a list object, while `[]` is used to create a list off the bat. Try this (might make more sense to you):
```
x = "wham bam"
a = list(x)
>>> a
["w", "h", "a", "m", ...]
```
While
```
y = ["wham bam"]
>>> y... |
Why is [] faster than list()? | 30,216,000 | 472 | 2015-05-13T13:16:22Z | 30,216,156 | 539 | 2015-05-13T13:21:57Z | [
"python",
"performance",
"list",
"instantiation",
"literals"
] | I recently compared the processing speeds of `[]` and `list()` and was surprised to discover that `[]` runs *more than three times faster* than `list()`. I ran the same test with `{}` and `dict()` and the results were practically identical: `[]` and `{}` both took around 0.128sec / million cycles, while `list()` and `d... | Because `[]` and `{}` are *literal syntax*. Python can create bytecode just to create the list or dictionary objects:
```
>>> import dis
>>> dis.dis(compile('[]', '', 'eval'))
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(compile('{}', '', 'eval'))
1 0 BUILD_MA... |
Why is [] faster than list()? | 30,216,000 | 472 | 2015-05-13T13:16:22Z | 30,216,174 | 111 | 2015-05-13T13:22:44Z | [
"python",
"performance",
"list",
"instantiation",
"literals"
] | I recently compared the processing speeds of `[]` and `list()` and was surprised to discover that `[]` runs *more than three times faster* than `list()`. I ran the same test with `{}` and `dict()` and the results were practically identical: `[]` and `{}` both took around 0.128sec / million cycles, while `list()` and `d... | `list()` requires a global lookup and a function call but `[]` compiles to a single instruction. See:
```
Python 2.7.3
>>> import dis
>>> print dis.dis(lambda: list())
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
None
>>> print dis.di... |
Python argparse, provide different arguments based on parent argument value | 30,216,662 | 3 | 2015-05-13T13:40:57Z | 30,217,387 | 7 | 2015-05-13T14:09:22Z | [
"python",
"dynamic",
"argparse",
"subparsers"
] | here is what i would like to do :
A command that looks like git command behavior. You don't get the same options whether you typed git commit or git checkout.
But in my case i want to provide different arguments based on an argument value (a file name) like this :
```
>cmd file.a -h
usage: cmd filename [-opt1] [-opt2]... | When you take a look at [`parse_args()` implementation](https://github.com/python/cpython/blob/3.2/Lib/argparse.py) you'll notice that it parses all arguments at once (it doesn't use `yield` to continuously generate state) so you have to prepare your structure before and not after half of the arguments would be parsed.... |
How to create non-blocking continuous reading from `stdin`? | 30,217,916 | 6 | 2015-05-13T14:30:55Z | 30,218,069 | 7 | 2015-05-13T14:36:50Z | [
"python",
"python-3.x",
"subprocess",
"stdin",
"nonblocking"
] | I have a single process, which has been created like this:
```
p = subprocess.Popen(args = './myapp',
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
universal_newlines=True)
```
Later on, I'm trying to write to `p`'s `stdin`:
```
p.stdin.write('my... | ```
p = subprocess.Popen(args = './myapp',
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
universal_newlines=True)
while p.poll() is None:
data = p.stdout.readline()
```
This will create a non-blocking read of your process until the process exi... |
Get parent of current directory from Python script | 30,218,802 | 7 | 2015-05-13T15:07:34Z | 30,218,825 | 11 | 2015-05-13T15:08:45Z | [
"python",
"sys",
"sys.path"
] | I want to get the parent of current directory from Python script. For example I launch the script from `/home/kristina/desire-directory/scripts` the desire path in this case is `/home/kristina/desire-directory`
I know `sys.path[0]` from `sys`. But I don't want to parse `sys.path[0]` resulting string. Is there any anot... | ### Using os.path
To *get the parent directory of the directory containing the script* (regardless of the current working directory), you'll need to use `__file__`.
Inside the script use [`os.path.abspath(__file__)`](https://docs.python.org/3/library/os.path.html#os.path.abspath) to obtain the absolute path of the sc... |
Different slicing behaviors on left/right hand side of assignment operator | 30,220,736 | 2 | 2015-05-13T16:42:39Z | 30,221,031 | 7 | 2015-05-13T16:58:12Z | [
"python",
"python-3.x",
"operators",
"slice",
"deep-copy"
] | As a Python newbie coming from the C++ background, the slicing operator in Python (3.4.x) looks ridiculous to me. I just don't get the design philosophy behind the "special rule". Let me explain why I say it's "special".
On the one hand, according to the Stack Overflow answer [here](http://stackoverflow.com/questions/... | Python operators are best considered as syntactic sugar for *"magic"* methods; for example, `x + y` is evaluated as `x.__add__(y)`. In the same way that:
* `foo = bar.baz` becomes `foo = bar.__getattr__(baz)`; whereas
* `bar.baz = foo` becomes `bar.__setattr__(baz, foo)`;
the Python *"slicing operator"* \* `a[b]` is ... |
Create a day-of-week column in a Pandas dataframe using Python | 30,222,533 | 5 | 2015-05-13T18:24:11Z | 30,222,759 | 12 | 2015-05-13T18:36:36Z | [
"python",
"datetime",
"pandas"
] | Create a day-of-week column in a Pandas dataframe using Python
Iâd like to read a csv file into a pandas dataframe, parse a column of dates from string format to a date object, and then generate a new column that indicates the day of the week.
This is what Iâm trying:
What Iâd like to do is something like:
``... | EDIT:
As user jezrael points out below, `dt.weekday_name` was added in version 0.18.1
---
Use this:
<http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html>
See this:
[Get weekday/day-of-week for Datetime column of DataFrame](http://stackoverflow.com/questions/28009370/get-weekday-f... |
matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot? | 30,223,161 | 21 | 2015-05-13T18:58:38Z | 30,333,984 | 15 | 2015-05-19T18:59:47Z | [
"python",
"matplotlib"
] | I have this so far:
```
x,y,z = data.nonzero()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, zdir='z', c= 'red')
plt.savefig("plot.png")
```
Which creates:

What I'd like to do is stretch this out to make the Z... | The code example below provides a way to scale each axis relative to the others. However, to do so you need to modify the Axes3D.get\_proj function. Below is an example based on the example provided by matplot lib: <http://matplotlib.org/1.4.0/mpl_toolkits/mplot3d/tutorial.html#line-plots>
(There is a shorter version ... |
How to speed up the code - searching through a dataframe takes hours | 30,224,143 | 6 | 2015-05-13T20:00:06Z | 30,224,634 | 7 | 2015-05-13T20:30:23Z | [
"python",
"csv",
"python-3.x",
"pandas"
] | I've got a CSV file containing the distance between centroids in a GIS-model in the next format:
```
InputID,TargetID,Distance
1,2,3050.01327866
1,7,3334.99565217
1,5,3390.99115304
1,3,3613.77046864
1,4,4182.29900892
...
...
3330,3322,955927.582933
```
It is sorted on origin (`InputID`) and then on the nearest destin... | IIUC, all you need is `pivot`. If you start from a frame like this:
```
df = pd.DataFrame(columns="InputID,TargetID,Distance".split(","))
df["InputID"] = np.arange(36)//6 + 1
df["TargetID"] = np.arange(36) % 6 + 1
df["Distance"] = np.random.uniform(0, 100, len(df))
df = df[df.InputID != df.TargetID]
df = df.sort(["Inp... |
Reproduce a C function pointer array in Python | 30,225,067 | 6 | 2015-05-13T20:58:45Z | 30,225,178 | 7 | 2015-05-13T21:05:02Z | [
"python",
"c"
] | I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions.
The thing is that I would like to avoid doing a lot of `if` and `else if`. Usually in C to avoid this situation I use a function pointer array that I travel with a `while`... | In Python you use a [***dictionary***](https://docs.python.org/2/tutorial/datastructures.html#dictionaries).
Example:
```
keyword2func = {
"word1": function_word1,
"word2": function_word2,
}
word = input("")
keyword2func[word]()
``` |
How to make an Python subclass uncallable | 30,225,477 | 18 | 2015-05-13T21:27:45Z | 30,225,611 | 14 | 2015-05-13T21:37:32Z | [
"python"
] | How do you "disable" the `__call__` method on a subclass so the following would be true:
```
class Parent(object):
def __call__(self):
return
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
object.__setattr__(self, '__call__', None)
>>> c = Child()
>>> callable(... | You can't. As jonrsharpe points out, there's no way to make `Child` appear to not have the attribute, and that's what `callable(Child())` relies on to produce its answer. Even making it a descriptor that raises `AttributeError` won't work, per this bug report: <https://bugs.python.org/issue23990> . A python 2 example:
... |
Loop for each item in a list | 30,228,015 | 8 | 2015-05-14T01:49:43Z | 30,228,035 | 12 | 2015-05-14T01:52:00Z | [
"python",
"dictionary",
"cartesian-product"
] | I have a dictionary:
```
mydict = {'item1':[1,2,3],'item2':[10,20,30]}
```
I want to create the cartesian product of the two so that I get a tuple of each possible pair.
```
output: [(1,10),(1,20),(1,30),
(2,10),(2,20),(2,30),
(3,10),(3,20),(3,30)]
```
It seems like there would be a simple way to ... | The [`itertools.product()`](https://docs.python.org/2/library/itertools.html#itertools.product) function will do this:
```
>>> import itertools
>>> mydict = {'item1':[1,2,3],'item2':[10,20,30]}
>>> list(itertools.product(*mydict.values()))
[(10, 1), (10, 2), (10, 3), (20, 1), (20, 2), (20, 3), (30, 1), (30, 2), (30, 3... |
Django custom command error: unrecognized arguments | 30,230,490 | 10 | 2015-05-14T06:12:15Z | 30,230,675 | 20 | 2015-05-14T06:25:11Z | [
"python",
"django",
"django-admin"
] | I'm trying to create a command similar to `createsuperuser` which will take two arguments (username and password)
Its working fine in django 1.7 but not in 1.8. (I'm also using python3.4)
this is the code I wrote
**myapp/management/commands/createmysuperuser.py**
```
from django.core.management.base import BaseComm... | In django 1.8 you should [add arguments](https://docs.djangoproject.com/en/1.8/releases/1.8/#extending-management-command-arguments-through-command-option-list) to you command:
```
class Command(BaseCommand):
...
def add_arguments(self, parser):
parser.add_argument('username')
parser.add_argume... |
Raise error if a Python dict comprehension overwrites a key | 30,238,783 | 17 | 2015-05-14T13:34:57Z | 30,238,855 | 15 | 2015-05-14T13:38:31Z | [
"python"
] | Is there a way to get a dict comprehension to raise an exception if it would override a key?
For example, I would like the following to error because there are two values for the key `'a'`:
```
>>> {k:v for k, v in ('a1', 'a2', 'b3')}
{'a': '2', 'b': '3'}
```
I realise this can be done with a `for` loop. Is there a ... | You can use a generator with a helper function:
```
class DuplicateKeyError(ValueError): pass
def dict_no_dupl(it):
d = {}
for k, v in it:
if k in d: raise DuplicateKeyError(k)
d[k] = v
return d
dict_no_dupl((k, v) for k, v in ('a1', 'a2', 'b3'))
```
This does add a helper function, but ... |
Raise error if a Python dict comprehension overwrites a key | 30,238,783 | 17 | 2015-05-14T13:34:57Z | 30,238,926 | 9 | 2015-05-14T13:42:14Z | [
"python"
] | Is there a way to get a dict comprehension to raise an exception if it would override a key?
For example, I would like the following to error because there are two values for the key `'a'`:
```
>>> {k:v for k, v in ('a1', 'a2', 'b3')}
{'a': '2', 'b': '3'}
```
I realise this can be done with a `for` loop. Is there a ... | If you don't care about which key caused a collision:
Check that the generated dict has the appropriate size with `len()`. |
Splitting lists by short numbers | 30,241,068 | 4 | 2015-05-14T15:22:00Z | 30,241,768 | 7 | 2015-05-14T15:54:52Z | [
"python",
"python-3.x",
"numpy",
"split"
] | I'm using NumPy to find intersections on a graph, but `isClose` returns multiple values per intersection
So, I'm going to try to find their averages. But first, I want to isolate the similar values. This is also a useful skill I feel.
I have a list of the x values for the intersection called `idx` that looks like thi... | Considering you have a numpy array, you can use [np.split](http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html), splitting where the difference is > `.5`:
```
import numpy as np
x = np.array([-8.67735471, -8.63727455, -8.59719439, -5.5511022, -5.51102204, -5.47094188,
-5.43086172, -2.4248497, -2.... |
boost python threading segmentation fault | 30,241,980 | 3 | 2015-05-14T16:05:53Z | 30,251,481 | 7 | 2015-05-15T04:23:22Z | [
"python",
"c++",
"boost-python"
] | Consider the following straightforward python extension. When `start()-ed`, `Foo` will just add the next sequential integer to a `py::list`, once a second:
```
#include <boost/python.hpp>
#include <thread>
#include <atomic>
namespace py = boost::python;
struct Foo {
Foo() : running(false) { }
~Foo() { stop(... | In short, there is a mutex around the CPython interpreter known as the [Global Interpreter Lock](http://wiki.python.org/moin/GlobalInterpreterLock) (GIL). This mutex prevents parallel operations to be performed on Python objects. Thus, at any point in time, a max of one thread, the one that has acquired the GIL, is all... |
NumPy slice notation in a dictionary | 30,244,731 | 7 | 2015-05-14T18:33:02Z | 30,244,830 | 9 | 2015-05-14T18:38:31Z | [
"python",
"python-2.7",
"numpy",
"slice"
] | I wonder if it is possible to store numpy slice notation in a python dictionary. Something like:
```
lookup = {0:[:540],
30:[540:1080],
60:[1080:]}
```
It is possible to use native python slice syntax, e.g. `slice(0,10,2)`, but I have not been able to store more complex slices. For example, someth... | The syntax `[:, :2, :, :540]` is turned into a tuple of `slice` objects by Python:
```
(slice(None, None, None),
slice(None, 2, None),
slice(None, None, None),
slice(None, 540, None))
```
A convenient way to generate this tuple is to use the special function\* [`np.s_`](http://docs.scipy.org/doc/numpy/reference/ge... |
Python Pandas Create New Column with Groupby().Sum() | 30,244,952 | 4 | 2015-05-14T18:44:39Z | 30,244,979 | 20 | 2015-05-14T18:46:07Z | [
"python",
"pandas"
] | Trying to create a new column with the groupby calculation. In the code below, I get the correct calculated values for each date (see group below) but when I try to create a new column (df['Data4']) with it I get NaN. So I am trying to create a new column in the dataframe with the sum of 'Data3' for the all dates and a... | You want to use [`transform`](http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation) this will return a Series with the index aligned to the df so you can then add it as a new column:
```
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015... |
Python - efficiently find where something would land in a sorted list? | 30,245,090 | 4 | 2015-05-14T18:52:19Z | 30,245,136 | 9 | 2015-05-14T18:54:58Z | [
"python",
"sorting"
] | I have a list:
```
x = ['c', 'a', 'e']
```
I can sort this list:
```
x_sorted = sorted(x)
```
`x_sorted` is now `['a', 'c', 'e']`
Now let's say I have a new variable `y = 'd'`
I want to find out where in `x_sorted` this new variable would fall. In this example the new variable `y` contains the string `'d'` so it ... | You can use [bisect](https://docs.python.org/2/library/bisect.html)
```
from bisect import bisect
l = ['a', 'c', 'e']
print(bisect(l,"d"))
2
```
To add it to the list:
```
from bisect import insort
l = ['a',"b", 'c', 'e']
insort(l, "d")
print(l)
insort(l, "f")
print(l)
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c',... |
python plot horizontal line for a range of values | 30,246,807 | 4 | 2015-05-14T20:32:37Z | 30,247,026 | 7 | 2015-05-14T20:45:40Z | [
"python",
"matplotlib"
] | I am really new to python and trying to plot speed as a constant value for the distince from its current startpointinmeters to the next startpointinmeters, so speed is constant from the start to the end (next start).
For example, speed should be 13 for distance 0 to 27.82 and 15 from 27.82 to 40.12 and so on.
Any ide... | This can be done with the [step](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.step) function of Matplotlib:
```
import matplotlib.pyplot as plt
x = [0., 27.82, 40.12, 75.33, 172.77, 208.64, 253., 335.21, 351.16,
590.38, 779.37, 968.35, 1220.66, 1299.17, 1318.32, 1352.7]
v = [13., 15., 14., 14., 17... |
Listing contents of a bucket with boto3 | 30,249,069 | 13 | 2015-05-14T23:22:55Z | 30,249,553 | 19 | 2015-05-15T00:17:48Z | [
"python",
"amazon-s3",
"boto",
"boto3"
] | How can I see what's inside a bucket in S3 with `boto3`? (i.e. do an `"ls"`)?
Doing the following:
```
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('some/path/')
```
returns:
```
s3.Bucket(name='some/path/')
```
How do I see its contents? | One way to see the contents would be:
```
for object in mybucket.objects.all():
print(object)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.