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
Python TypeError: coercing to Unicode: need string or buffer, tuple found
28,826,241
4
2015-03-03T07:25:30Z
28,828,537
9
2015-03-03T09:45:04Z
[ "python", "operating-system", "tuples", "typeerror" ]
``` #!/usr/bin/env python import sys import os print "Scan a file for ""ErrorScatter"" payload" print "Drag the suspicious file here then press enter." filepath = raw_input("File Location: ") fixpath = filepath , "/Contents/MacOS/ErrorScatter" scan = os.path.exists(fixpath) ``` So i am making a program to check if a ...
, operator in Python is used to create tuples, for example ``` 1, 2, 3 ``` makes 3-element tuple ``` (1, 2, 3) ``` and ``` "blah", "bleh" ``` means 2-element tuple ``` ("blah", "bleh") ``` To concatenate strings, you could use `+` as [Gaurav already suggested](http://stackoverflow.com/questions/28826241/python-...
Is it possible to ignore one single specific line with pylint?
28,829,236
11
2015-03-03T10:18:33Z
29,562,085
14
2015-04-10T12:57:39Z
[ "python", "pylint" ]
I have the following line in my header: ``` import config.logging_settings ``` This actually changes my python logging settings, but pylint thinks it is an unused import. I do not want to remove `unused-import` warnings in general so is it possible to just ignore this one specific line? I wouldn't mind having a `.py...
Pylint message control is documented in [the Pylint manual](https://pylint.readthedocs.io/en/latest/faq.html#message-control): > ### Is it possible to locally disable a particular message? > > Yes, this feature has been added in Pylint 0.11. This may be done by adding > `#pylint: disable=some-message,another-one` ...
Build Boost with multiple Python versions
28,830,653
7
2015-03-03T11:26:34Z
28,893,295
8
2015-03-06T06:15:51Z
[ "python", "boost", "compilation", "boost-python" ]
I use several versions of Python on my computer : `2.6.6`, `2.7.6` and `2.7.9`. When I compile Boost with boost-python, I have to give the Python to use in argument. If I want compatibility, **have I to compile Boost for each Python version ?** (it's quite huge !) Or is there a way to use only one build of Boost with s...
The official Python [development cycle](https://docs.python.org/devguide/devcycle.html) does not describe the stability of the application binary interface (ABI) between releases. For releases before Python 3.2, there is no guarantee for ABI compatibility. For 3.2 and beyond, [PEP 384](https://www.python.org/dev/peps/p...
Python List generation: Force new Object
28,831,766
2
2015-03-03T12:23:59Z
28,831,813
8
2015-03-03T12:26:14Z
[ "python", "list" ]
Is there a way in Python to force to generate a new object when creating a list? Assume I have a class `Test` of which I want to store 5 objects in a list. I use the following code to generate the list: ``` myList = [Test()] * 5 ``` With this code python creates only 1 Object which is stored 5 times. Of course I ...
Use a [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) to execute an expression more than once: ``` myList = [Test() for _ in range(5)] ``` Since this would ignore the `range()`-produced index, I named the `for` loop target `_` to [signal the variable is ignored](https:...
List to nested dictionary in python
28,832,166
3
2015-03-03T12:45:18Z
28,832,516
8
2015-03-03T13:02:20Z
[ "python", "list", "python-2.7", "dictionary" ]
I have a list as follows ``` ['item1', 'item2', 'item3', 'item4'] ``` I want to construct a dictionary from the above list as follows ``` { "item1": { "item2": { "item3": "item4" } } } ``` The number of items in the list is dynamic. The dictionary will be a nested dictionary till...
Simple one-liner: ``` a = ['item1', 'item2', 'item3','item4'] print reduce(lambda x, y: {y: x}, reversed(a)) ``` For better understanding the above code can be expanded to: ``` def nest_me(x, y): """ Take two arguments and return a one element dict with first argument as a value and second as a key "...
Check if any item in Python list is None (but include zero)
28,836,378
2
2015-03-03T16:05:31Z
28,836,394
9
2015-03-03T16:06:14Z
[ "python" ]
I'm trying to do a simple test that returns `True` if any of the results of a list are `None`. However, I want `0` and `''` to not cause a return of `True`. ``` list_1 = [0, 1, None, 4] list_2 = [0, 1, 3, 4] any(list_1) is None >>>False any(list_2) is None >>>False ``` As you can see, the `any()` function as it is i...
For `list` objects can simply use a membership test: ``` None in list_1 ``` Like `any()`, the membership test on a `list` will scan all elements but short-circuit by returning as soon as a match is found. `any()` returns `True` or `False`, never `None`, so your `any(list_1) is None` test is certainly not going anywh...
How to send requests with JSONs in unit tests
28,836,893
20
2015-03-03T16:29:51Z
28,840,457
41
2015-03-03T19:37:19Z
[ "python", "json", "flask", "python-unittest" ]
I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so: ``` Request = request.get_json() ``` This has been working fine, however I am trying to create unit tests using Python's unittest module and I'm having difficulty finding a way to send a JSON with the request...
Changing the post to ``` response=self.app.post('/test_function', data=json.dumps(dict(foo='bar')), content_type='application/json') ``` fixed it. Thanks to user3012759.
Representing rings of algebraic integers
28,840,685
18
2015-03-03T19:49:18Z
30,111,607
7
2015-05-07T21:04:26Z
[ "python", "sympy" ]
I'm trying to represent the ring; ![enter image description here](http://i.stack.imgur.com/z2hjb.png) where theta is the root of a monic irreducible polynomial f with integer coefficients of degree d. This ring is a subring of the algebraic integers, which itself is a subring of the field; ![enter image description...
I suspect that may not be a feature in `sympy` for these reasons: **First**, if theta is *not algebraic* over the integers, then adjoining theta to a polynomial ring over the integers, is isomorphic. For example, pi is not algebraic over the integers, because there are no integer coefficients that, combined with pi a...
Python regex match middle of string
28,840,903
3
2015-03-03T20:01:38Z
28,840,954
8
2015-03-03T20:03:53Z
[ "python", "regex" ]
I have a python string, that I'm trying to extract. I have a interesting issue: ``` >>> s="SKU 9780136058281, (ASIN B00A2KNZ2S, (binding Merchant: 'paperback' / 'hardcover'))" >>> print(re.match('ASIN', s)) None >>> print(re.match('SKU', s)) <_sre.SRE_Match object; span=(0, 3), match='SKU'> ``` I'm trying to mach a t...
You need to use `re.search` and [grouping](https://docs.python.org/2/library/re.html#re.MatchObject.group),and *Note* that `re.match` match the pattern from beginning of the string : ``` >>> s="SKU 9780136058281, (ASIN B00A2KNZ2S, (binding Merchant: 'paperback' / 'hardcover'))" >>> import re >>> re.search(r'SKU (\d+)'...
Is there an official or common knowledge standard minimal interface for a "list-like" object?
28,841,735
42
2015-03-03T20:56:57Z
28,841,805
10
2015-03-03T21:01:44Z
[ "python", "list" ]
I keep seeing functions and documentation like [this](https://plot.ly/python/overview/#out%5B1%5D) and [this](http://code.activestate.com/recipes/67671-a-function-to-unzip-simple-list-like-objects/) *(to name a few)* which operate on or refer to *list-like objects*. I'm quite aware of what exactly an actual list is (`...
The technical term for a "list-like object" is **sequence**. At the very least it supports ordering (i.e. two objects with the same elements but different order are not equal), indexing (`foo[bar]` such that `bar` is an integer less than the length of the sequence), and containment checking (`in`), and has a given leng...
Is there an official or common knowledge standard minimal interface for a "list-like" object?
28,841,735
42
2015-03-03T20:56:57Z
28,842,065
8
2015-03-03T21:18:14Z
[ "python", "list" ]
I keep seeing functions and documentation like [this](https://plot.ly/python/overview/#out%5B1%5D) and [this](http://code.activestate.com/recipes/67671-a-function-to-unzip-simple-list-like-objects/) *(to name a few)* which operate on or refer to *list-like objects*. I'm quite aware of what exactly an actual list is (`...
Pretty much any time you see "-like object" in Python documentation the author is being deliberately vague. The author has decided that enumerating all the required interfaces would be too much trouble, and is only saying that some of its interfaces are required. An object that implemented all the interfaces is guarant...
Is there an official or common knowledge standard minimal interface for a "list-like" object?
28,841,735
42
2015-03-03T20:56:57Z
28,842,190
40
2015-03-03T21:25:26Z
[ "python", "list" ]
I keep seeing functions and documentation like [this](https://plot.ly/python/overview/#out%5B1%5D) and [this](http://code.activestate.com/recipes/67671-a-function-to-unzip-simple-list-like-objects/) *(to name a few)* which operate on or refer to *list-like objects*. I'm quite aware of what exactly an actual list is (`...
See the [`collections.abc`](https://docs.python.org/3/library/collections.abc.html) module. Of the abstract base classes listed there, `list` in Python implements `Iterable`, `Container`, `Sized`, `Sequence` and `MutableSequence`. Now, of these, `Iterable`, `Sequence` and `MutableSequence` could be casually called *lis...
add vs update in set operations in python
28,845,284
11
2015-03-04T01:40:24Z
28,845,301
7
2015-03-04T01:42:28Z
[ "python", "set" ]
What is the difference between add and update operations in python if i just want to add a single value to the set. ``` a = set() a.update([1]) #works a.add(1) #works a.update([1,2])#works a.add([1,2])#fails ``` Can someone explain why is this so.
`add` is faster for a single element because it is exactly for that purpose, adding a single element: ``` In [5]: timeit a.update([1]) 10000000 loops, best of 3: 191 ns per loop In [6]: timeit a.add(1) 10000000 loops, best of 3: 69.9 ns per loop ``` `update` expects an iterable or iterables so if you have a single ...
add vs update in set operations in python
28,845,284
11
2015-03-04T01:40:24Z
28,845,328
22
2015-03-04T01:45:44Z
[ "python", "set" ]
What is the difference between add and update operations in python if i just want to add a single value to the set. ``` a = set() a.update([1]) #works a.add(1) #works a.update([1,2])#works a.add([1,2])#fails ``` Can someone explain why is this so.
**[`set.add`](https://docs.python.org/2/library/stdtypes.html#set.add)** `set.add` adds an individual element to the set. So, ``` >>> a = set() >>> a.add(1) >>> a set([1]) ``` works, but it cannot work with an iterable, unless it is hashable. That is the reason why `a.add([1, 2])` fails. ``` >>> a.add([1, 2]) Trace...
Traversing a list of lists by index within a loop, to reformat strings
28,845,886
16
2015-03-04T02:54:14Z
28,845,960
13
2015-03-04T03:02:42Z
[ "python", "list", "loops" ]
I have a list of lists that looks like this, that was pulled in from a poorly formatted csv file: ``` DF = [['Customer Number: 001 '], ['Notes: Bought a ton of stuff and was easy to deal with'], ['Customer Number: 666 '], ['Notes: acted and looked like Chris Farley on that hidden decaf skit from SNL'], ['Customer ...
Just keep track of when we find a new customer: ``` from pprint import pprint as pp out = [] for sub in DF: if sub[0].startswith("Customer Number"): cust = sub[0] else: out.append(cust + sub[0]) pp(out) ``` Output: ``` ['Customer Number: 001 Notes: Bought a ton of stuff and was easy to deal ...
import matplotlib.pyplot gives ImportError: dlopen(…) Library not loaded libpng15.15.dylib
28,848,270
21
2015-03-04T06:53:53Z
31,892,421
20
2015-08-08T11:03:06Z
[ "python", "osx", "matplotlib" ]
[I am aware that this exact same question has been asked before.](http://stackoverflow.com/questions/27281943/import-matplotlib-pyplot-gives-importerror-dlopen-library-not-loaded-libpn) I did follow the instructions given in the answer there, and it didn't solve my problem (and I don't have enough reputation to just co...
Some python packages link dynamically against native c libraries. After an update of one of those libraries, links can break and give you weird error messages about missing dynamic libraries, as seen in the error message in the question. Basically, after an update of a native library sometimes you also have to rebuild...
Install Anaconda on Ubuntu 12.04 via command line
28,852,841
4
2015-03-04T11:04:23Z
28,853,163
7
2015-03-04T11:21:44Z
[ "python", "ssh", "server" ]
I would like to install [Anaconda](https://store.continuum.io/cshop/anaconda/) on a remote server. The server is running Ubuntu 12.04. I only have access to this server via SSH. How can I install Anaconda via the command line?
Something along the lines of: wget <http://09c8d0b2229f813c1b93-c95ac804525aac4b6dba79b00b39d1d3.r79.cf1.rackcdn.com/Anaconda-2.1.0-Linux-x86_64.sh> to get the installer for 64 bit linux followed by: bash Anaconda-2.x.x-Linux-x86[\_64].sh
Pip install: can't open file pip, or Parent module '' not loaded
28,864,307
3
2015-03-04T20:31:40Z
31,971,858
9
2015-08-12T17:33:55Z
[ "python", "django", "python-3.x", "install", "pip" ]
Thanks for reading this in the first place. I'm trying to install Django. So here's what I do in the command line: ``` C:\>python34 pip install Django ``` And here's what I get: ``` C:\Python34\python.exe: can't open file 'pip': [Errno 2] No such file or directory ``` If I do the same from the site-packages direct...
Assuming you have pip installed and you want to do this through python as opposed to the standalone pip client, you can also do ``` python -m pip install SomePackage ```
Equivalent of j in Numpy
28,872,862
6
2015-03-05T08:08:15Z
28,873,083
9
2015-03-05T08:21:00Z
[ "python", "numpy" ]
Please let me know the Equivalent of Octave j in Numpy or rather how do use 'j' in Python: ``` octave:1> j ans = 0 + 1i octave:1> j*pi/4 ans = 0.00000 + 0.78540i octave:2> ``` But in Python: ``` >>> import numpy as np >>> np.imag <function imag at 0x2368140> >>> np.imag(3) array(0) >>> np.imag(3,2) Traceback (most...
In Python, `1j` or `0+1j` is a literal of complex type. You can broadcast that into an array using expressions, for example ``` In [17]: 1j * np.arange(5) Out[17]: array([ 0.+0.j, 0.+1.j, 0.+2.j, 0.+3.j, 0.+4.j]) ``` Create an array from literals: ``` In [18]: np.array([1j]) Out[18]: array([ 0.+1.j]) ``` Note t...
Taking a JSON string, unmarshaling it into a map[string]interface{}, editing, and marshaling it into a []byte seems more complicated then it should be
28,877,512
2
2015-03-05T12:05:54Z
28,878,037
8
2015-03-05T12:37:22Z
[ "python", "json", "dictionary", "go" ]
I'm doing very basic JSON manipulation to learn some Go, and it works, except one thing seems off, I have to write allot of `.(map[string]interface{})` and `.([]interface{})` to access entries in the JSON, especially if they are children of children of children, etc. See here (also on Go Playground: <https://play.gola...
The cleanest way would be to create predefined types (structures `struct`) that model your JSON, and unmarshal to a value of that type, and you can simply refer to elements using [Selectors](http://golang.org/ref/spec#Selectors) (for `struct` types) and [Index expressions](http://golang.org/ref/spec#Index_expressions) ...
Unable to start appengine application after updating it via Google Cloud SDK
28,879,485
15
2015-03-05T13:54:49Z
28,883,237
13
2015-03-05T16:49:05Z
[ "python", "windows", "google-app-engine", "google-cloud-platform", "gcloud" ]
Recently I have updated google appengine from 1.9.17 to 1.9.18 via [Google Cloud SDK](https://cloud.google.com/sdk/) by using command `gcloud components update` in Windows 7 64 bit. After that I couldn't able to start any of the project in appengine launcher. Getting this error: ``` Traceback (most recent call last): ...
This has happened to me today to reinstall the app engine sdk. I could not run my code in the launcher. I remember reading that is not used pip app engine, but now I have solved the problem. In short what I did was: 1. Install pip the footsteps of <https://pip.pypa.io/en/latest/installing.html> (this also correctly ...
Unable to start appengine application after updating it via Google Cloud SDK
28,879,485
15
2015-03-05T13:54:49Z
28,883,931
8
2015-03-05T17:24:22Z
[ "python", "windows", "google-app-engine", "google-cloud-platform", "gcloud" ]
Recently I have updated google appengine from 1.9.17 to 1.9.18 via [Google Cloud SDK](https://cloud.google.com/sdk/) by using command `gcloud components update` in Windows 7 64 bit. After that I couldn't able to start any of the project in appengine launcher. Getting this error: ``` Traceback (most recent call last): ...
This is currently an issue with the dev\_appserver bundled in the Cloud SDK. A fix will be out soon. In the meanwhile, your options are: 1) Use `gcloud preview app run` to run your app when using the Cloud SDK 2) Install the standalone AppEngine SDK (which you already mentioned in your question)
What does a plain yield keyword do in Python?
28,880,095
8
2015-03-05T14:24:14Z
28,880,312
8
2015-03-05T14:33:27Z
[ "python", "yield" ]
According to [the Python documentation](https://docs.python.org/2/reference/expressions.html#grammar-token-yield_expression) the yield keyword **can** take an "[expression\_list](https://docs.python.org/2/reference/expressions.html#grammar-token-expression_list)", but it is optional: ``` yield_expression ::= "yield" ...
Although they're almost always used as simple generators, `yield` enables fully-fledged **[coroutines](https://stackoverflow.com/a/21541902/1595865)**. Besides receiving values, you can also **send values into the method that yields**. Thus, you don't need `expression_list` if you only want to send such values. Here'...
Convert test client data to JSON
28,882,226
4
2015-03-05T15:59:52Z
28,883,182
8
2015-03-05T16:46:02Z
[ "python", "json", "testing", "flask" ]
I'm building an app and I want to make some tests. I need to convert the response data from the test client to JSON. The app: ``` tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, ...
You need to get the response data as text, but the default is bytes. The response object provides the method [`get_data`](http://werkzeug.pocoo.org/docs/0.10/wrappers/#werkzeug.wrappers.BaseRequest.get_data) to control this. ``` data = json.loads(response.get_data(as_text=True)) ```
Python semicolon does make a difference
28,883,858
8
2015-03-05T17:19:38Z
28,883,978
7
2015-03-05T17:27:00Z
[ "python" ]
Why does use of a colon make difference to the result? And what should be the correct result? ``` # Not stored in a different location. >>> id('123 4')== id('123 4') True # Also returns true >>> x = '123 4'; y ='123 4'; id(x) == id(y) True ``` # But this same thing returns false. ``` >>> x = '123 4' >>> y = '123 4'...
``` >>> x="123 4";y="123 4" ``` Python is smart enough to recognize both variables get the same value (since they are interpreted in the same line) and so stores that value in the same memory location (that is, `id(x) == id(y)`). However ``` >>> x="123 4" >>> y="123 4" ``` Python is not smart enough to realize they...
Why is 'x' in ('x',) faster than 'x' == 'x'?
28,885,132
237
2015-03-05T18:29:58Z
28,885,213
176
2015-03-05T18:35:06Z
[ "python", "performance", "python-3.x", "python-internals" ]
``` >>> timeit.timeit("'x' in ('x',)") 0.04869917374131205 >>> timeit.timeit("'x' == 'x'") 0.06144205736110564 ``` Also works for tuples with multiple elements, both versions seem to grow linearly: ``` >>> timeit.timeit("'x' in ('x', 'y')") 0.04866674801541748 >>> timeit.timeit("'x' == 'x' or 'x' == 'y'") 0.065657828...
There are three factors at play here which, combined, produce this surprising behavior. First: the `in` operator takes a shortcut and checks identity (`x is y`) before it checks equality (`x == y`): ``` >>> n = float('nan') >>> n in (n, ) True >>> n == n False >>> n is n True ``` Second: because of Python's string i...
Why is 'x' in ('x',) faster than 'x' == 'x'?
28,885,132
237
2015-03-05T18:29:58Z
28,889,838
213
2015-03-05T23:29:11Z
[ "python", "performance", "python-3.x", "python-internals" ]
``` >>> timeit.timeit("'x' in ('x',)") 0.04869917374131205 >>> timeit.timeit("'x' == 'x'") 0.06144205736110564 ``` Also works for tuples with multiple elements, both versions seem to grow linearly: ``` >>> timeit.timeit("'x' in ('x', 'y')") 0.04866674801541748 >>> timeit.timeit("'x' == 'x' or 'x' == 'y'") 0.065657828...
As I mentioned to David Wolever, there's more to this than meets the eye; both methods dispatch to `is`; you can prove this by doing ``` min(Timer("x == x", setup="x = 'a' * 1000000").repeat(10, 10000)) #>>> 0.00045456900261342525 min(Timer("x == y", setup="x = 'a' * 1000000; y = 'a' * 1000000").repeat(10, 10000)) #>...
Tricks to get reverse-order cumulative histogram in matplotlib
28,889,845
5
2015-03-05T23:30:08Z
28,889,994
7
2015-03-05T23:45:27Z
[ "python", "matplotlib", "histogram", "cumulative-frequency" ]
I am wondering if there is a (better) trick to reverse a cumulative histogram in matplotlib. Let's say I have some scores in the range of 0.0 to 1.0 where 1.0 is the best score. Now, I am interested to plot how many samples are **above** a certain score threshold. ``` import numpy as np import matplotlib.pyplot as pl...
Pretty sure you can just use `cumulative=-1` in your function call: ``` plt.hist(d, 50, histtype="stepfilled", alpha=.7, cumulative=-1) ``` From the matplotlib hist() docs: > If cumulative evaluates to less than 0 (e.g., -1), the direction of accumulation is reversed. Take a look at the third example image [here](h...
Error Installing scikit-learn
28,890,418
3
2015-03-06T00:30:59Z
28,890,449
11
2015-03-06T00:34:54Z
[ "python", "pip", "scikit-learn" ]
When trying to install scikit-learn, I get the following error: ``` Exception: Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-6.0.8-py2.7.egg/pip/basecommand.py", line 232, in main status = s...
Are you the root user? Do you have admin privileges? One way you be to do: ``` $ sudo pip install scikit-learn ``` You will need to type your password and then it should work.
Ignoring existing table when ./manage.py migrate
28,891,780
3
2015-03-06T03:11:36Z
28,891,799
7
2015-03-06T03:15:09Z
[ "python", "django", "database", "migrate", "manage.py" ]
I have a question about Django's migration feature when there is an existing table. ``` ContentData ContentType Faq UserLog TB_TEAM_INF ``` When I try to do "./manage.py migrate" so it can create the 5 tables above from models.py, I got an error message because there is an existing table, TB\_TEAM\_INF. Since TB\_TE...
Add the [`managed`](https://docs.djangoproject.com/en/1.7/ref/models/options/#django.db.models.Options.managed) option to your model definition: ``` class TB_TEAM_INF(models.Model): ... class Meta: managed = False ``` Excerpt from the documentation: > If False, no database table creation or deletion ...
Why does "%-d", or "%-e" remove the leading space or zero?
28,894,172
7
2015-03-06T07:41:11Z
28,916,983
8
2015-03-07T16:18:23Z
[ "python", "python-2.7", "datetime", "strftime" ]
On SO question [904928 (Python strftime - date without leading 0?)](http://stackoverflow.com/questions/904928/python-strftime-date-without-leading-0) Ryan answered: > Actually I had the same problem and I realised that, if you add a > hyphen between the % and the letter, you can remove the leading zero. > > For exampl...
[Python `datetime.strftime()` delegates to C `strftime()` function that is platform-dependent](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior): > The full set of format codes supported varies across platforms, > because Python calls the platform C library’s strftime() function, and > plat...
How to make a line break on the Python ternary operator?
28,897,010
6
2015-03-06T10:37:51Z
28,897,053
14
2015-03-06T10:40:54Z
[ "python", "line-breaks" ]
Sometimes a line containing a ternary operator in Python gets too long: ``` answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel." ``` Is there a recommended way to make a line break at 79 characters with a ternary operator? I did not find it in [PEP 8](https...
PEP8 says the [preferred way of breaking long lines is using parentheses](https://www.python.org/dev/peps/pep-0008/#maximum-line-length): > The preferred way of wrapping long lines is by using Python's implied > line continuation inside parentheses, brackets and braces. Long lines > can be broken over multiple lines b...
django-allauth social account connect to existing account on login
28,897,220
4
2015-03-06T10:51:38Z
28,911,917
8
2015-03-07T06:01:40Z
[ "python", "django", "django-allauth" ]
I have a custom user model and I am using django-allauth for social registration and login. I am trying to connect existing user to new social account when a user login using a social account who already has registered using email. I found this [link](https://github.com/pennersr/django-allauth/issues/418#issuecomment-3...
I managed to get this working by changing the code for adapter a little bit. adapter.py ``` from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user i...
How to generate a valid sample token with stripe?
28,898,536
4
2015-03-06T12:12:16Z
28,898,754
9
2015-03-06T12:25:33Z
[ "python", "django", "stripe-payments" ]
Currently I'm integrating [stripe](https://stripe.com/) payments into may django-based backed app - [here](https://stripe.com/docs/tutorials/charges) is how it can be done with python. I've some integration tests done with `APIClient` and after payments were introduced I need to generate a sample token (normally receiv...
You can just create the token with [stripe.Token.create()](https://stripe.com/docs/api?lang=python#create_card_token): ``` import stripe stripe.api_key = "sk_test_asdfkljasblahblah123" token = stripe.Token.create( card={ "number": '4242424242424242', "exp_month": 12, "exp_year": 2016, ...
Why are exceptions within a Python generator not caught?
28,899,992
20
2015-03-06T13:39:44Z
28,900,339
13
2015-03-06T13:56:57Z
[ "python", "python-3.x", "generator" ]
I have the following experimental code whose function is similar to the `zip` built-in. What it tries to do should have been simple and clear, trying to return the zipped tuples one at a time until an `IndexError` occurs when we stop the generator. ``` def my_zip(*args): i = 0 while True: try: ...
The `yield` yields a generator object everytime and when the generators were created there was no problem at all. That is why `try...except` in `my_zip` is not catching anything. The third time when you executed it, ``` list(arg[2] for arg in args) ``` this is how it got reduced to (over simplified for our understand...
Faster convolution of probability density functions in Python
28,901,221
5
2015-03-06T14:45:43Z
29,236,193
8
2015-03-24T15:10:51Z
[ "python", "numpy", "vectorization", "convolution", "probability-density" ]
Suppose the convolution of a general number of discrete probability density functions needs to be calculated. For the example below there are four distributions which take on values 0,1,2 with the specified probabilities: ``` import numpy as np pdfs = np.array([[0.6,0.3,0.1],[0.5,0.4,0.1],[0.3,0.7,0.0],[1.0,0.0,0.0]])...
You can compute the convolution of all your PDFs efficiently using fast fourier transforms (FFTs): the key fact is that the [FFT of the convolution](http://en.wikipedia.org/wiki/Discrete-time_Fourier_transform#Convolution) is the product of the FFTs of the individual probability density functions. So transform each PDF...
Numpy: find index of elements in one array that occur in another array
28,901,311
3
2015-03-06T14:50:47Z
28,901,411
8
2015-03-06T14:55:50Z
[ "python", "arrays", "numpy" ]
I have two 1D arrays and I want to find out if an element in one array occurs in another array or not. For example: ``` import numpy as np A = np.array([ 1, 48, 50, 78, 85, 97]) B = np.array([38, 43, 50, 62, 78, 85]) ``` I want: ``` C = [2,3,4] # since 50 in second array occurs in first array at index 2, ...
You could use `np.where` and `np.in1d`: ``` >>> np.where(np.in1d(A, B))[0] array([2, 3, 4]) ``` `np.in1d(A, B)` returns a boolean array indicating whether each value of `A` is found in `B`. `np.where` returns the indices of the `True` values. (This will also work if your arrays are not sorted.)
pandas get rows which are NOT in other dataframe
28,901,683
10
2015-03-06T15:10:28Z
28,902,170
8
2015-03-06T15:35:38Z
[ "python", "pandas" ]
I've two pandas data frames which have some rows in common. Suppose dataframe2 is a subset of dataframe1. **How can I get the rows of dataframe1 which are not in dataframe2?** ``` df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14]}) df2 = pandas.DataFrame(data = {'col1' : [1, 2, ...
One method would be to store the result of an inner merge form both dfs, then we can simply select the rows when one column's values are not in this common: ``` In [119]: common = df1.merge(df2,on=['col1','col2']) print(common) df1[(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))] col1 col2 0 1 ...
Script skips second for loop when reading a file
28,901,909
2
2015-03-06T15:22:45Z
28,901,944
7
2015-03-06T15:24:23Z
[ "python", "python-2.7", "for-loop" ]
I am trying to read a log file and compare certain values against preset thresholds. My code manages to log the raw data from with the first `for` loop in my function. I have added print statements to try and figure out what was going on and I've managed to deduce that my second for loop never "happens". This is my c...
It is not skipping your second loop. You need to `seek` the position back. This is because after reading the file, the file offset will be placed at the end of the file, so you will need to put it back at the start. This can be done easily by adding a line ``` datafile.seek(0); ``` Before the second loop. Ref: [Docu...
How to unpack a tuple into more values than the tuple has?
28,905,822
3
2015-03-06T19:02:52Z
28,905,894
9
2015-03-06T19:06:59Z
[ "python", "python-3.x", "tuples", "iterable-unpacking" ]
I have a list of tuples, each of which contains between 1 to 5 elements. I'd like to unpack these tuples into five values but that won't work for tuples of less than five elements: ``` >>> t = (1,2) # or (1) or (1,2,3) or ... >>> a,b,c,d,e = (t) Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
You can add the remaining elements with: ``` a, b, c, d, e = t + (None,) * (5 - len(t)) ``` Demo: ``` >>> t = (1, 2) >>> a, b, c, d, e = t + (None,) * (5 - len(t)) >>> a, b, c, d, e (1, 2, None, None, None) ```
'module' has no attribute 'urlencode'
28,906,859
13
2015-03-06T20:13:04Z
28,906,913
33
2015-03-06T20:16:51Z
[ "python", "python-3.x", "urllib" ]
When i try to follow python wiki page example related to URL encoding: ``` >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) >>> print f.read() ``` An error is raised on the second line: ``` Traceback (most rece...
`urllib` has been split up in Python 3. The `urllib.urlencode()` function is now [`urllib.parse.urlencode()`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode), and the `urllib.urlopen()` function is now [`urllib.request.urlopen()`](https://docs.python.org/3/library/urllib.request.html#urllib....
Pandas scalar value getting and setting: ix or iat?
28,909,034
7
2015-03-06T22:51:06Z
28,980,433
9
2015-03-11T07:03:06Z
[ "python", "indexing", "pandas" ]
I'm trying to figure out when to use different selecting methods in pandas DataFrame. In particular, I'm looking for accessing scalar values. I often hear `ix` being generally recommended. But in [pandas documentation](http://pandas.pydata.org/pandas-docs/dev/indexing.html#fast-scalar-value-getting-and-setting) it's re...
Pandas does some pretty interesting things with the [indexing classes](https://github.com/pydata/pandas/blob/077b99e17a090901636844612cec581282607ae7/pandas/core/indexing.py). I don't think I am capable of describing a simple way to know which to use but I can give some insight on the implementation. [`DataFrame#ix`](...
Image foveation in Python
28,910,285
4
2015-03-07T01:14:16Z
28,912,368
7
2015-03-07T07:06:06Z
[ "python", "opencv", "image-processing", "numpy", "computer-vision" ]
I would like to be able to foveate an image with focal point at the center of the image in Python. My input image can be represented as a 2D Numpy array. I'd like to get an output image with high resolution at the center, but blurry at the sides. I found an OpenCV function called `logplar_interp` for this purpose, but ...
Here's my attempt at recreating this using OpenCV Python. It's a rather hack-ish solution that is a bit computationally intensive, but it certainly gets the job done. First, create a mask where pixels that are **zero** correspond to those pixels you want to keep at high resolution and pixels that are **one** correspon...
Python Pandas - Changing some column types to categories
28,910,851
3
2015-03-07T02:51:43Z
28,910,914
10
2015-03-07T03:01:38Z
[ "python", "numpy", "pandas", "multiple-columns", "categories" ]
I have fed the following CSV file into iPython Notebook: ``` public = pd.read_csv("categories.csv") public ``` I've also imported pandas as pd, numpy as np and matplotlib.pyplot as plt. The following data types are present (the below is a summary - there are about 100 columns) ``` In [36]: public.dtypes Out[37]: ...
Sometimes, you just have to use a for-loop: ``` for col in ['parks', 'playgrounds', 'sports', 'roading']: public[col] = public[col].astype('category') ```
Accessing elements in the shadow DOM
28,911,799
8
2015-03-07T05:41:23Z
29,022,010
8
2015-03-12T23:06:01Z
[ "python", "selenium", "selenium-webdriver", "shadow-dom" ]
Is it possible to *find elements inside the Shadow DOM* with python-selenium? **Example use case:** I have this `input` with `type="date"`: ``` <input type="date"> ``` And I'd like to click *the date picker button* on the right and choose a date from the calendar. If you would inspect the element in Chrome Develop...
There's no way to access the shadow root of native HTML 5 elements. Not useful in this case, but with Chrome it's possible to access a custom created shadow root: ``` var root = document.querySelector("#test_button").createShadowRoot(); root.innerHTML = "<button id='inner_button'>Button in button</button" ``` ``` <...
Can the cumsum function in NumPy decay while adding?
28,915,088
8
2015-03-07T12:55:05Z
28,915,275
7
2015-03-07T13:19:26Z
[ "python", "arrays", "numpy", "cumsum" ]
I have an array of values `a = (2,3,0,0,4,3)` ``` y=0 for x in a: y = (y+x)*.95 ``` Is there any way to use `cumsum` in `numpy` and apply the .95 decay to each row before adding the next value?
You're asking for a simple [IIR Filter](https://en.wikipedia.org/wiki/Infinite_impulse_response). Scipy's [lfilter()](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.lfilter.html) is made for that: ``` import numpy as np from scipy.signal import lfilter data = np.array([2, 3, 0, 0, 4, 3], dtype=float...
Pip broken on Ubuntu 14.4 after package upgrade
28,917,534
6
2015-03-07T17:06:42Z
28,919,613
7
2015-03-07T20:25:42Z
[ "python", "ubuntu", "pip" ]
I was trying to upgrade the python requests package on an EC2 ubuntu 14.4 instance. after doing this, which did not throw an error I ran ``` pip freeze ``` and got: ``` ubuntu@ip-172-31-28-196:~$ pip freeze Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> load_entry_point('pip==1.5.4...
`apt-get` installs a much older version of pip which can lead to problems, completely remove `python-pip` with: ``` apt-get remove --purge python-pip ``` then: ``` curl https://bootstrap.pypa.io/get-pip.py | sudo python ``` using sudo **if** required
Concatenate two big pandas.HDFStore HDF5 files
28,918,851
6
2015-03-07T19:08:47Z
28,919,117
9
2015-03-07T19:39:32Z
[ "python", "pandas", "hdf5", "pytables" ]
This question is somehow related to ["Concatenate a large number of HDF5 files"](https://stackoverflow.com/questions/5346589/concatenate-a-large-number-of-hdf5-files). I have several huge HDF5 files (~20GB compressed), which could not fit the RAM. Each of them stores several `pandas.DataFrame`s of identical format and...
see docs [here](http://odo.readthedocs.org/en/latest/hdf5.html) for the `odo` project (formerly `into`). Note if you use the `into` library, then the argument order has been switched (that was the motivation for changing the name, to avoid confusion!) You can basically do: ``` from odo import odo odo('hdfstore://path...
Installed Python 3 on Mac OS X but its still Python 2.7
28,921,333
4
2015-03-07T23:32:58Z
28,921,336
8
2015-03-07T23:33:26Z
[ "python", "python-2.7", "python-3.x", "osx-yosemite" ]
I am currently running OS X Yosemite (10.10.2) on my MacBook Pro... By default, Apple ships Python 2.7.6 on Yosemite. Just downloaded and ran this installer for Python 3: `python-3.4.3-macosx10.6.pkg` When I opened up my Terminal and typed in `python`, this is what came up: ``` Python 2.7.6 (default, Sep 9 2014, 15...
Try typing `python3` instead of just `python`.
Python -- how to force enumerate to start at 1 -- or workaround?
28,921,405
2
2015-03-07T23:41:21Z
28,921,432
13
2015-03-07T23:44:19Z
[ "python", "for-loop", "enumeration", "modulus" ]
I have a simple for loop: ``` for index, (key, value) in enumerate(self.addArgs["khzObj"].nodes.items()): ``` and I want to start a new wx horizontal boxsizer after every 3rd item to create a panel with 3 nodes each and going on for as many as are in nodes. The obvious solution is to do: ``` if index % 3 == 0: add a...
Since Python 2.6, `enumerate()` takes an optional `start` parameter to indicate where to start the enumeration. See [the documentation for `enumerate`](https://docs.python.org/2/library/functions.html#enumerate).
Improving line-wise I/O operations in D
28,922,323
12
2015-03-08T03:07:57Z
29,153,508
13
2015-03-19T19:38:35Z
[ "python", "io", "d" ]
I need to process lots of medium to large files (a few hundred MB to GBs) in a linewise manner, so I'm interested in standard D approaches for iterating over lines. The `foreach(line; file.byLine())` idiom seems to fit the bill and is pleasantly terse and readable, however performance seems to be less than ideal. For ...
EDIT AND TL;DR: This problem has been solved in <https://github.com/D-Programming-Language/phobos/pull/3089>. The improved `File.byLine` performance will be available starting with D 2.068. I tried your code on a text file with 575247 lines. The Python baseline takes about 0.125 seconds. Here's my codebase with timing...
python json dict iterate {key: value} are the same
28,923,518
2
2015-03-08T05:46:47Z
28,923,527
7
2015-03-08T05:49:10Z
[ "python", "json", "dictionary" ]
i have a json file I am reading in; looks similar to: ``` [ { "Destination_IP": "8.8.4.4", "ID": 0, "Packet": 105277 }, { "Destination_IP": "9.9.4.4", "ID": 0, "Packet": 105278 } ] ``` when i parse the json via: ``` for json_dict in data: for key,value in json_dict.iteritems(): ...
Change your string formats **index**: ``` for json_dict in data: for key,value in json_dict.iteritems(): print("key: {0} | value: {1}".format(key, value)) ``` Or without using index: ``` for json_dict in data: for key,value in json_dict.iteritems(): print("key: {} | value: {}".format(key, val...
Python 3.4.3 subprocess.Popen get output of command without piping?
28,924,910
4
2015-03-08T09:20:30Z
28,925,252
9
2015-03-08T10:08:13Z
[ "python", "linux", "bash", "subprocess", "popen" ]
I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unformatted text as output if it is being piped, but it gives color formatted text if it is being run from the terminal. I need to get this color for...
Using [pexpect](https://pexpect.readthedocs.org/en/latest/install.html): 2.py: ``` import sys if sys.stdout.isatty(): print('hello') else: print('goodbye') ``` subprocess: ``` import subprocess p = subprocess.Popen( ['python3.4', '2.py'], stdout=subprocess.PIPE ) print(p.stdout.read()) --output:...
Scroll down to bottom of infinite page with PhantomJS in Python
28,928,068
10
2015-03-08T15:17:54Z
28,928,684
13
2015-03-08T16:10:58Z
[ "python", "selenium-webdriver", "phantomjs" ]
I have succeeded in getting Python with Selenium and PhantomJS to reload a dynamically loading infinite scrolling page, like in the example below. But how could this be modified so that instead of setting a number of reloads manually, the program stopped when reaching rock bottom? ``` reloads = 100000 #set the number ...
You can check whether the scroll did anything in every step. ``` lastHeight = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(pause) newHeight = driver.execute_script("return document.body.scrollHeigh...
How to properly generate a variable string pattern in Python
28,929,979
3
2015-03-08T18:05:27Z
28,929,991
8
2015-03-08T18:06:09Z
[ "python" ]
I have managed to code a little snippet in Python which generates a character strip whose length equals the length of another string like so: ``` title = "This is a string" concat_str = "" for i in range (0,len(title)): #len(title) == 16 concat_str += '-' # resulting string print(concat_str) # ---------------- ``` ...
The most pythonic way would be: ``` concat_str = '-' * len(title) ``` --- P.S. You do not need to specify `0` as the start for range: `range(len(title))` is more Pythonic.
What is the difference between flatten and ravel functions in numpy?
28,930,465
64
2015-03-08T18:49:44Z
28,930,580
88
2015-03-08T19:00:12Z
[ "python", "numpy" ]
``` import numpy as np y = np.array(((1,2,3),(4,5,6),(7,8,9))) OUTPUT: print(y.flatten()) [1 2 3 4 5 6 7 8 9] print(y.ravel()) [1 2 3 4 5 6 7 8 9] ``` Both function return the same list. Then what is the need of two different functions performing same job.
The difference is that flatten always returns a copy and ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten thi...
Adding value labels on a matplotlib bar chart
28,931,224
12
2015-03-08T20:00:53Z
28,931,750
22
2015-03-08T20:52:34Z
[ "python", "python-2.7", "pandas", "matplotlib", "data-visualization" ]
I got stuck on something that feels like should be relatively easy. The code I bring below is a sample based on a larger project I'm working on. I saw no reason to post all the details, so please accept the data structures I bring as is. Basically, I'm creating a bar chart, and I just can figure out how to add value l...
Firstly `freq_series.plot` returns an axis *not* a figure so to make my answer a little more clear I've changed your given code to refer to it as `ax` rather than `fig` to be more consistent with other code examples. You can get the list of the bars produced in the plot from the `ax.patches` member. Then you can use t...
How to get a list of sub tuple if given some indexes of tuple in python?
28,937,293
3
2015-03-09T07:53:00Z
28,937,316
8
2015-03-09T07:54:28Z
[ "python", "list", "tuples" ]
There is a list of tuple like ``` l = [(1, 2, 'a', 'b'), (3, 4, 'c', 'd'), (5, 6, 'e', 'f')] ``` I can use ``` [(i[0], i[2], i[3]) for i in l] ``` to get the result ``` [(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')] ``` But if given a variable list such as `[0, 2, 3]`, how to get the similar result?
Use [`operator.itemgetter`](https://docs.python.org/3/library/operator.html#operator.itemgetter), like this ``` >>> from operator import itemgetter >>> getter = itemgetter(0, 2, 3) >>> [getter(item) for item in l] [(1, 'a', 'b'), (3, 'c', 'd'), (5, 'e', 'f')] ``` If you have a list of indices, then you can [unpack th...
Intellij/Pycharm can't debug Python modules
28,955,520
7
2015-03-10T03:09:52Z
31,667,307
8
2015-07-28T04:20:35Z
[ "python", "debugging", "intellij-idea", "pycharm", "python-module" ]
I use **PyCharm**/**IntelliJ** community editions from a wile to write and debug Python scripts, but now I'm trying to debug a **Python module**, and PyCharm does a wrong command line instruction parsing, causing an execution error, or maybe I'm making a bad configuration. This is my run/debug configuration: ![Intell...
There is another way to make it work.You can write a python script to run your module.Then just configure PyCharm to run **this script**. ``` import sys import os import runpy path = os.path.dirname(sys.modules[__name__].__file__) path = os.path.join(path, '..') sys.path.insert(0, path) runpy.run_module('<your module ...
How to locate the median in a (seaborn) KDE plot?
28,956,622
5
2015-03-10T05:17:26Z
28,958,609
9
2015-03-10T07:58:18Z
[ "python", "matplotlib", "plot", "seaborn" ]
I am trying to do a [Kernel Density Estimation (KDE) plot](http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.kdeplot.html) with seaborn and locate the median. The code looks something like this: ``` import seaborn as sns import numpy as np import matplotlib.pyplot as plt sns.set_palette("hls", 1) data =...
You need to: 1. Extract the data of the kde line 2. Integrate it to calculate the cumulative distribution function (CDF) 3. Find the value that makes CDF equal 1/2, that is the median ``` import numpy as np import scipy import seaborn as sns import matplotlib.pyplot as plt sns.set_palette("hls", 1) data = np.random....
Overriding Django REST ViewSet with custom post method and model
28,957,912
5
2015-03-10T07:08:23Z
28,967,154
7
2015-03-10T15:03:53Z
[ "python", "django", "django-rest-framework" ]
I have a a `ModelViewSet` in Django's REST Framework that gives me the ability to do a POST and GET through the following address: `api/v1/users` These Users have a a reverse relation to a Comments table and I'd like to be able to access these Comments through the URL: `api/v1/users/<username>/comments` I was able ...
I figured it out. For those looking for an answer as well, the solution was to explicitly define the actions that occur when `request.method == 'POST'` and pass a the object into the serializer. ``` @detail_route(methods=['post','get']) def comment(self, request, **kwargs): user = self.get_object() ...
Ansible write variables into YAML file
28,963,751
5
2015-03-10T12:27:53Z
28,969,144
7
2015-03-10T16:32:09Z
[ "python", "yaml", "jinja2", "ansible" ]
I have a specific ansible variable structure that I want to get from the vault into a yaml file on my hosts. Lets assume a structure like this: ``` secrets: psp1: username: this password: that secret_key: 123 ... ``` I need something like a "generic" template to output whatever "secrets" contains a...
1. As jwodder said, it's valid. 2. If you're using `to_yaml` (instead of `to_nice_yaml`) you have fairly old install of ansible, it's time to upgrade. 3. Use `to_nice_yaml` 4. It's possible to pass your own kwargs to filter functions, which usually pass them on to underlying python module call. Like [this one](https://...
Arff Loader : AttributeError: 'dict' object has no attribute 'data'
28,966,434
8
2015-03-10T14:31:34Z
28,967,268
12
2015-03-10T15:08:29Z
[ "python", "attributes", "runtime-error", "arff" ]
I am trying to load a .arff file into a numpy array using liac-arff library. (<https://github.com/renatopp/liac-arff>) This is my code. ``` import arff, numpy as np dataset = arff.load(open('mydataset.arff', 'rb')) data = np.array(dataset.data) ``` when executing, I am getting the error. ``` ArffLoader.py", line 8,...
## Short version `dataset` is a `dict`. For a `dict`, you access the values using the python indexing notation, `dataset[key]`, where `key` could be a string, integer, float, tuple, or any other immutable data type (it is a bit more complicated than that, more below if you are interested). In your case, the key is in...
Attribute Error Installing with pip
28,967,785
9
2015-03-10T15:33:30Z
30,310,206
19
2015-05-18T18:15:59Z
[ "python", "osx", "pip" ]
This is a head stumper so I am posting this question AFTER having examined and read all of the prior posts on this issue. Running OSX 10.9 Python 2.7 no virtualenv ``` pip install awssh Downloading/unpacking awssh Downloading awssh-0.1.tar.gz Cleaning up... Exception: Traceback (most recent call last): File "/...
This error is caused by the presence of an outdated version of `pkg_resources`. In order to get rid of the error, do the following: 1. Start a python session, import `pkg_resources`, and view the file from which it is loaded: ``` In [1]: import pkg_resources In [2]: pkg_resources.__file__ Out[2]: '/usr/l...
How to convert a pymongo.cursor.Cursor into a dict?
28,968,660
6
2015-03-10T16:10:55Z
28,970,776
9
2015-03-10T17:56:34Z
[ "python", "mongodb", "dictionary", "mongodb-query", "pymongo" ]
I am using pymongo to query for all items in a region (actually it is to query for all venues in a region on a map). I used `db.command(SON())` before to search in a spherical region, which can return me a dictionary and in the dictionary there is a key called `results` which contains the venues. Now I need to search i...
The [`find`](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find) method returns a returns a [`Cursor`](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor) instance, which allows you to iterate over all matching documents. To get the fir...
Inter segment distance using numba jit, Python
28,970,883
8
2015-03-10T18:01:46Z
28,977,230
9
2015-03-11T01:47:47Z
[ "python", "numpy", "jit", "numba" ]
I have been asking related questions on this stack for the past week to try to isolate things I didn't understand about using the @jit decorator with Numba in Python. However, I'm hitting the wall, so I'll just write the whole problem. The issue at hand is to calculate the minimal distance between pairs of a **large**...
Here's my version of your code which is significantly faster: ``` @jit(nopython=True) def dot(a,b): res = a[0]*b[0]+a[1]*b[1]+a[2]*b[2] return res @jit def compute_stuff2(array_to_compute): N = array_to_compute.shape[0] con_mat = np.zeros((N,N)) p0 = np.zeros(3) p1 = np.zeros(3) q0 = np.z...
Crawling through pages with PostBack data javascript Python Scrapy
28,974,838
3
2015-03-10T21:55:45Z
28,976,674
7
2015-03-11T00:45:37Z
[ "javascript", "python", "asp.net", "web-scraping", "scrapy" ]
I'm crawling through some directories with ASP.NET programming via Scrapy. The pages to crawl through are encoded as such: `javascript:__doPostBack('ctl00$MainContent$List','Page$X')` where X is an int between 1 and 180. The MainContent argument is always the same. I have no idea how to crawl into these. I would lov...
This kind of pagination is not that trivial as it may seem. It was an interesting challenge to solve it. There are several important notes about the solution provided below: * the idea here is to follow the pagination page by page passing around the current page in the [`Request.meta` dictionary](http://doc.scrapy.org...
elif block not executing in Python
28,975,495
2
2015-03-10T22:46:14Z
28,975,525
12
2015-03-10T22:49:10Z
[ "python", "if-statement" ]
What is wrong here? Upon entering 3 (<=5), the output should be, I think, "Phew, ..." but it stays as "Awesome, ..." ``` weather = raw_input('How is the weather today, from 0 to 10? ') answer = raw_input ('Are you in mood to go out? ') if weather >= 5: if answer == 'Yes': print 'Awesome, I will go out!' ...
`raw_input` returns a string not an integer, e.g. `'3'` instead of `3`. In Python 2, strings always compare greater than integers so `weather >= 5` is always true. To fix this, cast `weather` to an integer: ``` weather = int(raw_input('How is the weather today, from 0 to 10? ')) ```
pip doesn't see setuptools
28,980,160
7
2015-03-11T06:43:08Z
30,308,437
10
2015-05-18T16:29:27Z
[ "python", "python-3.x", "pip", "virtualenv" ]
I am migrating from python2 to python3. I created a virtualenv with `python3 -m venv py3` and am trying to `pip install -r requirements.txt` but it says ``` Collecting mock==1.0.1 (from -r requirements.txt (line 8)) Using cached mock-1.0.1.tar.gz setuptools must be installed to install from a source distribution ...
This is not an answer to your questions, but for me it was easier to reinstall the virtual environment than trying to solve the issue. After setting up a new virtualenv, I had no problem installing or updating packages again.
Collection object is not callable error with PyMongo
28,981,718
27
2015-03-11T08:31:14Z
28,982,131
10
2015-03-11T08:55:45Z
[ "python", "mongodb", "pymongo" ]
Following along the PyMongo [tutorial](http://api.mongodb.org/python/current/tutorial.html) and am getting an error when calling the `insert_one` method on a collection. ``` In [1]: import pymongo In [2]: from pymongo import MongoClient In [3]: client = MongoClient() In [4]: db = client.new_db In [5]: db Out[5]: D...
The problem is that you are following the tutorial from the current release documentation but actually have PyMongo 2.8 installed. The [`insert_one()`](http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one) method is new in PyMongo 3.0 now backported in [PyMongo 2.9...
Collection object is not callable error with PyMongo
28,981,718
27
2015-03-11T08:31:14Z
28,982,139
42
2015-03-11T08:56:07Z
[ "python", "mongodb", "pymongo" ]
Following along the PyMongo [tutorial](http://api.mongodb.org/python/current/tutorial.html) and am getting an error when calling the `insert_one` method on a collection. ``` In [1]: import pymongo In [2]: from pymongo import MongoClient In [3]: client = MongoClient() In [4]: db = client.new_db In [5]: db Out[5]: D...
It is a clear question but the problem here seems to be that you are reading from the ["beta"](http://api.mongodb.org/python/current/tutorial.html) release documentation but in all likelihood you actually at most have "pymongo" 2.8 installed rather than the "3.0b" referred to in the link you quote. The [2.8 release tu...
Flask app logger not working when running within gunicorn
28,982,106
9
2015-03-11T08:54:37Z
34,437,443
8
2015-12-23T14:07:37Z
[ "python", "logging", "flask", "gunicorn" ]
I'm trying to save application log messages from a very simple flask app in a log file. While this works flawlessly when I'm running the app with the embedded Flask server, it is not working at all when running within gUnicorn, basically, no application output is redirected neither the log file (the one specified in my...
You answered your question yourself here. Though I'll add my answer in hope that it would help someone else having similar issue. Since your question has 2 parts, of which the first part is solved, ill mark my response for each part: PART 1: No logging happening if instead of directly running the app via python, you ...
How to check if a sequence could be turned into a palindrome
28,989,262
3
2015-03-11T14:27:00Z
28,989,976
7
2015-03-11T14:56:22Z
[ "python", "sorting", "python-3.x", "palindrome" ]
I have to find if a list can be a palindrome. The first part of my program sorts the list. ``` A = [0, 99, 97, 97, 99, 100, 100, 0] # sorted: B = [0, 0, 97, 97, 99, 99, 100, 100] ``` This list can be a palindrome because it can be reordered to: ``` [0, 97, 99, 100, 100, 99, 97, 0] ``` I wrote the following code to ...
Count the occurrences of each value. Then check that the number of odd counts is zero or one. There is no need to sort the list. This will work for any list of values. ``` from collections import Counter def can_be_palindrome(data): odd = (c % 2 for c in Counter(data).values()) any(odd) # skip first odd, if ...
How to check if a sequence could be turned into a palindrome
28,989,262
3
2015-03-11T14:27:00Z
28,990,005
9
2015-03-11T14:57:22Z
[ "python", "sorting", "python-3.x", "palindrome" ]
I have to find if a list can be a palindrome. The first part of my program sorts the list. ``` A = [0, 99, 97, 97, 99, 100, 100, 0] # sorted: B = [0, 0, 97, 97, 99, 99, 100, 100] ``` This list can be a palindrome because it can be reordered to: ``` [0, 97, 99, 100, 100, 99, 97, 0] ``` I wrote the following code to ...
As we traverse `B`, we can use a set to keep track of what elements have an odd number so far (using a set here is much faster than a list): ``` odds = set() for i in B: if i in odds: odds.remove(i) else: odds.add(i) ``` Then if the length of `odds` is 0 or 1, print `True`. Otherwise print `Fa...
How to check if a sequence could be turned into a palindrome
28,989,262
3
2015-03-11T14:27:00Z
28,991,331
7
2015-03-11T15:52:21Z
[ "python", "sorting", "python-3.x", "palindrome" ]
I have to find if a list can be a palindrome. The first part of my program sorts the list. ``` A = [0, 99, 97, 97, 99, 100, 100, 0] # sorted: B = [0, 0, 97, 97, 99, 99, 100, 100] ``` This list can be a palindrome because it can be reordered to: ``` [0, 97, 99, 100, 100, 99, 97, 0] ``` I wrote the following code to ...
A fast one (or so I thought): uses a dictionary to calculate `odd` values. Stores the values as keys in dictionary, with values being `True` if the key occurred odd times, `False` for even. Finally return True that the `.values()` only has 0 or 1 `True` element (a.k.a. there was only 0 or 1 elements occurring odd numbe...
Creating a shell command line application with Python and Click
28,990,497
6
2015-03-11T15:18:43Z
28,995,530
9
2015-03-11T19:22:20Z
[ "python", "command-line-interface", "python-click" ]
I'm using click (<http://click.pocoo.org/3/>) to create a command line application, but I don't know how to create a shell for this application. Suppose I'm writing a program called *test* and I have commands called *subtest1* and *subtest2* I was able to make it work from terminal like: ``` $ test subtest1 $ test ...
This is not impossible with click, but there's no built-in support for that either. The first you would have to do is making your group callback invokable without a subcommand by passing `invoke_without_command=True` into the group decorator (as described [here](http://click.pocoo.org/3/commands/#group-invocation-witho...
Python3 project remove __pycache__ folders and .pyc files
28,991,015
15
2015-03-11T15:39:05Z
28,991,449
7
2015-03-11T15:56:42Z
[ "python", "python-3.x", "python-3.4", "delete-file" ]
What is the BEST way to clear out all the `__pycache__` folders and `.pyc/.pyo` files from a python3 project. I have seen multiple users suggest the `pyclean` script bundled with Debian, but this does not remove the folders. I want a simple way to clean up the project before pushing the files to my DVS.
I found the answer myself when I mistyped pyclean as pycclean: ``` No command 'pycclean' found, did you mean: Command 'py3clean' from package 'python3-minimal' (main) Command 'pyclean' from package 'python-minimal' (main) pycclean: command not found ``` Running `py3clean .` cleaned it up very nicely...
Python3 project remove __pycache__ folders and .pyc files
28,991,015
15
2015-03-11T15:39:05Z
30,659,970
27
2015-06-05T06:41:05Z
[ "python", "python-3.x", "python-3.4", "delete-file" ]
What is the BEST way to clear out all the `__pycache__` folders and `.pyc/.pyo` files from a python3 project. I have seen multiple users suggest the `pyclean` script bundled with Debian, but this does not remove the folders. I want a simple way to clean up the project before pushing the files to my DVS.
You can do it manually with the next command: ``` find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf ``` This will remove all **\*.pyc** files and **\_\_pycache\_\_** directories recursively in the current directory.
supervisor - how to run multiple commands
28,994,647
6
2015-03-11T18:32:31Z
28,994,845
9
2015-03-11T18:43:54Z
[ "python", "celery", "supervisor" ]
I'm managing a Celery worker that processes queue via Supervisor. Here's my /etc/supervisor/celery.conf: ``` [program:celery] command = /var/worker/venv/bin/celery worker -A a_report_tasks -Q a_report_process --loglevel=INFO directory=/var/worker user=nobody numprocs=1 autostart=true autorestart=true startsecs=10 sto...
Add a second section with a *different task name*. If two tasks have the same task name, the latter overwrites the former. ``` [program:celeryb] command = /var/worker/venv/bin/celery worker -A b_report_tasks -Q b_report_process --loglevel=INFO directory=/var/worker user=nobody numprocs=1 autostart=true autorestart=tru...
Creating a simple prime sieve in Python
28,994,651
6
2015-03-11T18:32:41Z
28,995,321
7
2015-03-11T19:10:54Z
[ "python" ]
I wrote a simple prime sieve (an unbounded sieve of Eratosthenes) using Python, but for some reason, it isn't working correctly. Here is the sieve: ``` from itertools import count def sieve(): nums = count(2) while True: n = next(nums) nums = filter(lambda k: k%n != 0, nums) yield n ``...
The problem is that the `lambda` is always referring to the *latest* value of `n`, not the one used when `lambda` was created. The simplest way around it is to capture the value explicitly using a keyword argument: ``` from itertools import count def sieve(): nums = count(2) while True: n = next(nums)...
Return True if all characters in a string are in another string
28,997,056
3
2015-03-11T20:49:03Z
28,997,088
8
2015-03-11T20:50:29Z
[ "python", "string", "boolean" ]
Alright so for this problem I am meant to be writing a function that returns True if a given string contains only characters from another given string. So if I input "bird" as the first string and "irbd" as the second, it would return True, but if I used "birds" as the first string and "irdb" as the second it would ret...
This is a perfect use case of [sets](https://docs.python.org/2/tutorial/datastructures.html#sets). The following code will solve your problem: ``` def only_uses_letters_from(string1, string2): """Check if the first string only contains characters also in the second string.""" return set(string1) <= set(string2) ...
how to show integer, not float, with hover tooltip in bokeh
28,999,411
8
2015-03-11T23:35:19Z
28,999,752
7
2015-03-12T00:09:26Z
[ "python", "bokeh" ]
I have a simple graph of X-Y data points. I want my Bokeh figure to show me the integer value of each datapoint when I hover over it. I am close to getting what I want but when I hover over the data point, it shows a float and then higher up, it uses scientific notation. Is there a way to have the hover tool only retur...
Aha! Using @ instead of $ works. ``` hover.tooltips = [ ("Days", "@x"), ("Return", "@y"), ] ```
how to show integer, not float, with hover tooltip in bokeh
28,999,411
8
2015-03-11T23:35:19Z
32,115,916
10
2015-08-20T10:34:37Z
[ "python", "bokeh" ]
I have a simple graph of X-Y data points. I want my Bokeh figure to show me the integer value of each datapoint when I hover over it. I am close to getting what I want but when I hover over the data point, it shows a float and then higher up, it uses scientific notation. Is there a way to have the hover tool only retur...
Adding my two cents. I figured out by you can control the decimal points by using the following code: ``` hover.tooltips = [ ("Days", "@x{int}"), # this will show integer, even if x is float ("Return", "@y{1.11}"), # this will format as 2-decimal float ] ``` Hope this helps.
How to convert a DataFrame back to normal RDD in pyspark?
29,000,514
21
2015-03-12T01:36:30Z
29,128,946
40
2015-03-18T17:36:16Z
[ "python", "apache-spark", "pyspark" ]
I need to use the ``` (rdd.)partitionBy(npartitions, custom_partitioner) ``` method that is not available on the DataFrame. All of the DataFrame methods refer only to DataFrame results. So then how to create an RDD from the DataFrame data? Note: this is a change (in 1.3.0) from 1.2.0. **Update** from the answer fro...
Use the method `.rdd` like this: ``` rdd = df.rdd ```
How to convert a DataFrame back to normal RDD in pyspark?
29,000,514
21
2015-03-12T01:36:30Z
37,286,339
7
2016-05-17T21:13:31Z
[ "python", "apache-spark", "pyspark" ]
I need to use the ``` (rdd.)partitionBy(npartitions, custom_partitioner) ``` method that is not available on the DataFrame. All of the DataFrame methods refer only to DataFrame results. So then how to create an RDD from the DataFrame data? Note: this is a change (in 1.3.0) from 1.2.0. **Update** from the answer fro...
@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format. Try this: ``` rdd = df.rdd.map(tuple) ``` or ``` rdd = df.rdd.map(list) ```
Is there any example of cv2.KalmanFilter implementation?
29,012,038
9
2015-03-12T14:09:54Z
29,013,648
11
2015-03-12T15:19:27Z
[ "python", "opencv", "kalman-filter" ]
I'm trying to build a veeery simple tracker for 2D objects using python wrapper for OpenCV (cv2). I've only noticed 3 functions: * KalmanFilter (constructor) * .predict() * .correct(measurement) My idea is to create a code to check if kalman is working like this: ``` kf = cv2.KalmanFilter(...) # set initial positio...
if you're using opencv2.4, then it's bad news: the KalmanFilter is unusable, since you cannot set the transition (or any other) Matrix. for opencv3.0 it works correctly, like this: ``` import cv2, numpy as np meas=[] pred=[] frame = np.zeros((400,400,3), np.uint8) # drawing canvas mp = np.array((2,1), np.float32) # ...
What is Python's interpreter printing something in "a ++ 1" and why?
29,015,868
2
2015-03-12T16:59:32Z
29,015,908
8
2015-03-12T17:00:59Z
[ "python" ]
Here's something strange I noticed about my Python interpreter: ``` $ python Python 2.7.8 (default, Nov 10 2014, 08:19:18) [GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 1 >>> for i in range(3): ... for j in range(3): ... a ++ 1 .....
`a ++ 1` is just doing a single addition. As jonrsharpe mentions in the comments, this value is printed in the loop because it returns a value other than `None`. ``` a = 1 a ++ 1 == a + (+1) # True a +- 1 == 0 # True ```
Deleting rows based on multiple conditions Python Pandas
29,017,525
4
2015-03-12T18:26:24Z
29,017,731
9
2015-03-12T18:37:52Z
[ "python", "pandas" ]
I want to delete rows when a few conditions are met: For instance, a random DataFrame is generated: ``` import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), columns=['one', 'two', 'three', 'four']) print df ``` one instance of table is shown as below: ``` one two three ...
[For reasons that aren't 100% clear to me](http://pandas.pydata.org/pandas-docs/dev/gotchas.html#bitwise-boolean), `pandas` plays nice with the bitwise logical operators `|` and `&`, but not the boolean ones `or` and `and`. Try this instead: ``` df = df[(df.one > 0) | (df.two > 0) | (df.three > 0) & (df.four < 1)] ``...
Python Tuple Unpacking
29,019,817
7
2015-03-12T20:43:06Z
29,019,852
11
2015-03-12T20:45:24Z
[ "python", "list-comprehension", "iterable-unpacking" ]
If I have ``` nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')] ``` and would like ``` nums = [1, 2, 3] words= ['one', 'two', 'three'] ``` How would I do that in a Pythonic way? It took me a minute to realize why the following doesn't work ``` nums, words = [(el[0], el[1]) for el in nums_and_words] ``` I'm...
Use [`zip`](https://docs.python.org/2/library/functions.html#zip), then unpack: ``` nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')] nums, words = zip(*nums_and_words) ``` Actually, this "unpacks" twice: First, when you pass the list of lists to `zip` with `*`, then when you distribute the result to the two va...
Geany - How to execute code in terminal pane instead of external terminal
29,022,464
7
2015-03-12T23:49:24Z
29,022,510
11
2015-03-12T23:54:54Z
[ "python", "ide", "geany" ]
I really like Geany for writing Python code. When I click F5, it opens system's default terminal window and executes the code there. There is also a terminal inside Geany window, the bottom pane and the last tab. What I want is the code to be executed there. Is it possible? ![Geany with terminal pane](http://i.stack....
After fiddling with the options, I found the way: 1. Right-click on terminal area and select "Preferences". It opens the general preferences window with Terminal tab opened. 2. There is an option: "Execute programs in the VTE". Checking this option does what I want.
What to use in replacement of an interface/protocol in python
29,022,766
3
2015-03-13T00:23:59Z
29,022,807
7
2015-03-13T00:28:27Z
[ "python", "interface", "protocols" ]
I am making a chess game and wanted to make a standard piece interface/protocol. Python does not have those in the language, so what am I supposed to use? I read a bit about factories, but I'm not sure how they would help. Thanks in advance!
In short, you probably don't need to worry about it at all. Since Python uses [duck typing](https://docs.python.org/2/glossary.html#term-duck-typing) - see also the [Wikipedia article](http://en.wikipedia.org/wiki/Duck_typing) for a broader definition - if an object has the right methods, it will simply work, otherwise...
Using Qt threads in pyside
29,027,813
3
2015-03-13T08:32:23Z
29,206,902
8
2015-03-23T09:33:36Z
[ "python", "pyside" ]
I don't understand the output of the sample code below [found here](http://stackoverflow.com/questions/24165877/pyside-widget-run-with-threading-thread-class). Current thread and worker thread have the same address, how is that possible? ``` from PySide import QtCore class Master(QtCore.QObject): command = QtCore...
There's no "wrapper getting reused", just that the old wrapper object (that was deleted) happens to reside at the same memory address with the new wrapper object. PySide uses `shiboken` library to wrap the `QObject`s into Python objects. The [shiboken documentation](https://github.com/PySide/shiboken-docs/blob/master/...
PyCharm 4.0.5 hangs on 'scanning files to index' background task
29,030,682
7
2015-03-13T11:08:16Z
34,977,724
7
2016-01-24T15:42:23Z
[ "python", "django", "pycharm" ]
my spec: Intel Core i5-3470 3,2 GHz / 4 GB Ram / I'm using Windows 64 bit. PyCharm 4.0.5 When I launch PyCharm it starts 'scanning files to index' background task and hangs for ~1 hour/forever. From time to time it finishes and proceeds with Updating indices task. It lasts for ~ 3 hours/forever. While this processes a...
My project contained a folder that had like 100k files/folders inside. This was making indexing way too slow. To fix this, exclude the folder from Project structure in PyCharm. ``` File - Settings - Project: yourprojectname - Project Structure - Right click on folder and press "Excluded" ```
Apply function on cumulative values of pandas series
29,033,198
3
2015-03-13T13:15:27Z
29,033,268
7
2015-03-13T13:18:53Z
[ "python", "pandas" ]
Is there an equivalent of `rolling_apply` in pandas that applies function to the cumulative values of a series rather than the rolling values? I realize `cumsum`, `cumprod`, `cummax`, and `cummin` exist, but I'd like to apply a custom function.
You can use [`pd.expanding_apply`](http://pandas.pydata.org/pandas-docs/dev/computation.html#expanding-window-moment-functions). Below is a simple example which only really does a cumulative sum, but you could write whatever function you wanted for it. ``` import pandas as pd df = pd.DataFrame({'data':[10*i for i in ...
Pandas convert a column of list to dummies
29,034,928
4
2015-03-13T14:33:00Z
29,036,042
11
2015-03-13T15:23:29Z
[ "python", "pandas" ]
I have a dataframe where one column is a list of groups each of my users belongs to. Something like: ``` index groups 0 ['a','b','c'] 1 ['c'] 2 ['b','c','e'] 3 ['a','c'] 4 ['b','e'] ``` And what I would like to do is create a series of dummy columns to identify which groups each user belongs to ...
Using `s` for your `df['groups']`: ``` In [21]: s = pd.Series({0: ['a', 'b', 'c'], 1:['c'], 2: ['b', 'c', 'e'], 3: ['a', 'c'], 4: ['b', 'e'] }) In [22]: s Out[22]: 0 [a, b, c] 1 [c] 2 [b, c, e] 3 [a, c] 4 [b, e] dtype: object ``` This is a possible solution: ``` In [23]: pd.get_dummies(s....
How can I include package_data without a MANIFEST.in file?
29,036,937
9
2015-03-13T16:07:42Z
29,071,634
13
2015-03-16T07:30:40Z
[ "python", "manifest", "packaging", "setuptools", "setup.py" ]
How can I include `package_data` for `sdist` without a MANIFEST.in file? My setup.py looks like this: ``` import setuptools setuptools.setup( name='foo', version='2015.3', license='commercial', packages=setuptools.find_packages(), package_data={'': ['foo/bar.txt']}, ) ``` Versions: ``` user@ho...
**TL;DR**: The keys in the `package_data` dictionaries are **packages**; the values are lists of globs. `''` is not a valid name for any Python package. If you want to have `bar.txt` be installed next to the `__init__.py` of package `foo`, use ``` package_data={'foo': ['bar.txt']} ``` --- I have the layout: ``` f...
How do I add a kernel on a remote machine in IPython (Jupyter) Notebook?
29,037,211
11
2015-03-13T16:22:37Z
30,670,602
9
2015-06-05T15:41:02Z
[ "python", "ipython", "ipython-notebook", "ipython-parallel", "jupyter" ]
Dropdown menu in the top-right of the UI on a local machine (PC): ``` Kernel-> Change kernel-> Python 2 (on a local PC) Python 3 (on a local PC) My new kernel (on a remote PC) ```
The IPython notebook talks to the kernels over predefined ports. To talk to a remote kernel, you just need to forward the ports to the remote machine as part of the kernel initialisation, the notebook doesn't care where the kernel is as long as it can talk to it. You could either set up a wrapper script that gets call...
Split a string with list of numbers
29,038,159
3
2015-03-13T17:10:43Z
29,038,310
7
2015-03-13T17:19:38Z
[ "python", "list", "split" ]
I'm trying to split a string by the positions given from a list, and add the parts to a new list. I start with: ``` seq = 'ATCGATCGATCG' seq_new = [] seq_cut = [2, 8 , 10] ``` I would like to get: ``` seq_new = ['AT', 'CGATCG', 'AT', 'CG'] ``` The list with the positions is variable in size and values. How can I pr...
Use [`zip`](https://docs.python.org/3.3/library/functions.html#zip) to create indexes for [slicing](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation): ``` seq_new = [seq[start:end] for start, end in zip([None] + seq_cut, seq_cut + [None])] ``` This zips together `[None, 2, 8 , 10]` and `[2, 8,...
pip fails with AttributeError: 'module' object has no attribute 'wraps'
29,038,889
11
2015-03-13T17:57:06Z
29,040,109
8
2015-03-13T19:07:10Z
[ "python", "python-2.7", "pip", "fedora-21" ]
I'm on Fedora. I recently upgraded my system from F20 to F21. Pip was working fine on F20 but after the upgrade to F21 something must have gone wrong. Pip stopped working, every time I enter the command `pip <anything>` the error below occurs: ``` Traceback (most recent call last): File "/usr/bin/pip", line 7, in <m...
Okay after trying out all the solutions I could google with no result in sight. I tried to risk and play a little bit. This might not be the safest solution but it worked fine for me. Seeing that `python get-pip.py` resulted in: ``` Requirement already up-to-date: pip in /usr/lib/python2.7/site-packages ``` even when...
Heap's algorithm permutation generator
29,042,819
5
2015-03-13T22:10:05Z
29,044,942
15
2015-03-14T02:58:33Z
[ "python", "algorithm", "permutation" ]
I need to iterate over permutations of a tuple of integers. The order has to be generated by swapping a pair of elements at each step. I found the Wikipedia article (<http://en.wikipedia.org/wiki/Heap%27s_algorithm>) for Heap's algorithm, which is supposed to do this. The pseudocode is: ``` procedure generate(n : int...
### Historical prologue *The [Wikipedia article on Heap's algorithm](http://en.wikipedia.org/wiki/Heap%27s_algorithm) has been corrected since this answer was written but you can see the version referred to by the question and answer in [Wikipedia's change history](https://en.wikipedia.org/w/index.php?title=Heap%27s_a...