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 |
|---|---|---|---|---|---|---|---|---|---|
NumPy and SciPy - Difference between .todense() and .toarray() | 30,416,695 | 7 | 2015-05-23T19:23:44Z | 30,416,739 | 10 | 2015-05-23T19:28:23Z | [
"python",
"numpy",
"scipy"
] | I am wondering if there is any difference (advantage/disadvantage) of using `.toarray()` vs. `.todense()` on sparse NumPy arrays. E.g.,
```
import scipy as sp
import numpy as np
sparse_m = sp.sparse.bsr_matrix(np.array([[1,0,0,0,1], [1,0,0,0,1]]))
%timeit sparse_m.toarray()
1000 loops, best of 3: 299 µs per loop
%t... | `toarray` returns an ndarray; `todense` returns a matrix. If you want a matrix, use `todense`; otherwise, use `toarray`. |
What is the Time Complexity of finding the max k integers? | 30,418,082 | 2 | 2015-05-23T22:13:01Z | 30,418,168 | 8 | 2015-05-23T22:25:34Z | [
"python",
"algorithm",
"dictionary",
"big-o",
"time-complexity"
] | ```
def max_k_sort(k, nums):
# sort nums first using timsort
# add O(n*log(n)) time complexity
sorted_nums = sorted(nums)
return sorted_nums[-1*k:len(nums)]
def max_k(k, nums):
# build initial max number list
max_nums = {}
# add O(k) time complexity?
i = 0
while i < k:
max... | ```
for n in nums:
if n > least_max:
max_nums[least_max_key] = n
least_max_key = min(max_nums, key=max_nums.get) # this is O(k)
least_max = max_nums[least_max_key]
```
You're doing an O(k) operation *n* times, so the complexity of your second function is O(n\*k).
Assuming y... |
Error " 'dict' object has no attribute 'iteritems' " when trying to use NetworkX's write_shp() | 30,418,481 | 55 | 2015-05-23T23:14:54Z | 30,418,498 | 107 | 2015-05-23T23:17:28Z | [
"python",
"dictionary",
"networkx"
] | I'm trying to use NetworkX to read a Shapefile and use the function write\_shp() to generate the Shapefiles that will contain the nodes and edges (following this example - <https://networkx.github.io/documentation/latest/reference/readwrite.nx_shp.html>), but when I try to run the code it gives me the following error:
... | As you are in python3 , use `dict.items()` instead of `dict.iteritems()`
`iteritems()` was removed in python3, so you can't use this method anymore.
Take a look at Python Wiki ([Link](https://wiki.python.org/moin/Python3.0))
In **Built-in Changes** part, it is stated that
> Removed dict.iteritems(), dict.iterkeys()... |
Why increase a value in this way in python? | 30,420,633 | 3 | 2015-05-24T06:13:00Z | 30,420,641 | 7 | 2015-05-24T06:14:18Z | [
"python"
] | I've found an example of a code in python, and I understand the code but there is one line that I don't know why is wrote that way:
```
c = 1
c = (c + 1) & 255
```
I know it increments the value of the variable C in one, but I don't understand the `& 255`
can anyone explain it to me? | What this code does is reset `c` to zero when it reaches 256, so the sequence goes:
```
1 -> 2 -> 3 -> ... -> 254 -> 255 -> 0 -> 1 -> ...
```
It is another way to write:
```
c = (c + 1) % 256
```
One way to think about this is that the `% 256` restricts the range of the result to `0`..`255`.
Note that the `& 255` ... |
What does In [*] in IPython Notebook mean and how to turn it off? | 30,421,373 | 8 | 2015-05-24T08:12:14Z | 30,421,412 | 10 | 2015-05-24T08:16:10Z | [
"python",
"ipython",
"jupyter"
] | I use Windows 7, Python 2.7.9 plus latest version of IPython 3.1.
I ran `%python` inside an IPython Notebook and ran the cell, instead of returning the Python version, it did not run and jumped to a new line and printed a `In [*]` instead of a line number. Now no line is running in ipython everything is ignored when I... | The kernel is busy. Go to the menu `Kernel` and click `Interrupt`. If this does not work click `Restart`. You need to go in a new cell and press `Shift + Enter` to see if it worked. |
How is it possible to evaluate +5 in Python? | 30,422,301 | 6 | 2015-05-24T10:09:33Z | 30,422,348 | 7 | 2015-05-24T10:14:30Z | [
"python",
"operators",
"addition"
] | How does evaluating `+ 5` work (spoiler alert: result is 5)?
Isn't the `+` working by calling the `__add__` method on something? 5 would be "`other`" in:
```
>>> other = 5
>>> x = 1
>>> x.__add__(other)
6
```
So what is the "void" that allows adding 5?
`void.__add__(5)`
Another clue is that:
```
/ 5
```
throws t... | The `+` in this case calls the unary magic method [`__pos__`](https://docs.python.org/2/reference/datamodel.html#object.__pos__) rather than [`__add__`](https://docs.python.org/2/reference/datamodel.html#object.__add__):
```
>>> class A(int):
def __pos__(self):
print '__pos__ called'
return self
..... |
How is it possible to evaluate +5 in Python? | 30,422,301 | 6 | 2015-05-24T10:09:33Z | 30,422,355 | 7 | 2015-05-24T10:15:26Z | [
"python",
"operators",
"addition"
] | How does evaluating `+ 5` work (spoiler alert: result is 5)?
Isn't the `+` working by calling the `__add__` method on something? 5 would be "`other`" in:
```
>>> other = 5
>>> x = 1
>>> x.__add__(other)
6
```
So what is the "void" that allows adding 5?
`void.__add__(5)`
Another clue is that:
```
/ 5
```
throws t... | It looks like you've found one of the three [unary operators](https://docs.python.org/2.7/reference/expressions.html#unary-arithmetic-and-bitwise-operations):
* The unary plus operation `+x` calls the **\_\_pos\_\_()** method.
* The unary negation operation `-x` calls the **\_\_neg\_\_()** method.
* The unary not (or ... |
Automate the Boring Stuff With Python, Chapter 4 Exercise | 30,424,355 | 2 | 2015-05-24T14:01:56Z | 30,424,469 | 8 | 2015-05-24T14:14:27Z | [
"python",
"list"
] | I'm newbie and doing Al Sweigar's book at the moment. In chapter 4's exercise, he asks the following,
Say you have a list of lists where each value in the inner lists is a one-character string, like this:
```
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O... | ```
>>> print('\n'.join(map(''.join, zip(*grid))))
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
```
The `zip(*grid)` effectively transposes the matrix (flip it on the main diagonal), then each row is joined into one string, then the rows are joined with newlines so the whole thing can be printed at once... |
What is the difference between creating db tables using alembic and defining models in SQLAlchemy? | 30,425,214 | 5 | 2015-05-24T15:30:02Z | 30,425,438 | 8 | 2015-05-24T15:54:36Z | [
"python",
"flask",
"sqlalchemy",
"alembic"
] | I could create tables using the command `alembic revision -m 'table_name'` and then defining the versions and migrate using `alembic upgrade head`.
Also, I could create tables in a database by defining a class in `models.py` (SQLAlchemy).
What is the difference between the two? I'm very confused. Have I messed up the... | Yes, you are thinking about it in the wrong way.
Let's say you don't use Alembic or any other migration framework. In that case you create a new database for your application with the following steps:
1. Write your model classes
2. Create and configure a brand new database
3. Run `db.create_all()`, which looks at you... |
On Finding the Maximum Depth of an Arbitrarily Nested List | 30,427,268 | 6 | 2015-05-24T19:09:21Z | 30,427,698 | 7 | 2015-05-24T19:52:27Z | [
"python",
"recursion"
] | I'm currently working with a recursive function in Python, and I've run into a wall. As titled, the problem is to return the maximum depth of an arbitrarily nested list.
Here is what I have so far:
```
def depthCount(lst):
'takes an arbitrarily nested list as a parameter and returns the maximum depth to which the... | **If they are just nested lists**, e.g., `[[[], []], [], [[]]]`, here's a nice solution:
```
def depthCount(lst):
return 1 + max(map(depthCount, lst), default=0)
```
Here's a slight variation you could use if you don't use Python 3.4, where the `default` argument was introduced:
```
def depthCount(lst):
retu... |
Fixing an almost valid JSON file | 30,429,496 | 2 | 2015-05-24T23:41:11Z | 30,429,538 | 7 | 2015-05-24T23:47:44Z | [
"python",
"json"
] | I have the following JSON data.(It is not a fully valid data.But it is almost valid)
```
{
u'Category': u'Exp',
u'Severity': u'warn',
u'EventName': u'TimeExceeded',
u'EventTimestamp': u'1432510367083',
u'Message': u'details: {
"Message": "long (2567 ms : ATime: 5 ms, BTime: 1237 ms, CTime: ... | Although they look similar, this is actually not JSON, but Python's representation of a dict if you print it.
There are two reasons this is invalid:
1. The `u` which represents `unicode` in front of each string
2. You need double-quotes around your keys and values in JSON, not single-quotes.
Assuming you have a repr... |
Dependency Algorithm - find a minimum set of packages to install | 30,429,786 | 10 | 2015-05-25T00:30:03Z | 30,543,429 | 7 | 2015-05-30T07:14:16Z | [
"java",
"python",
"algorithm",
"mathematical-optimization",
"minimization"
] | I'm working on an algorithm which goal is to find a minimum set of packages to install package "X".
I'll explain better with an example:
```
X depends on A and (E or C)
A depends on E and (H or Y)
E depends on B and (Z or Y)
C depends on (A or K)
H depends on nothing
Y depends on nothing
Z depends on nothing
K depend... | Unfortunately, there is little hope to find an algorithm which is much better than brute-force, considering that the problem is actually [NP-hard](http://en.wikipedia.org/wiki/NP-hard) (but not even [NP-complete](http://en.wikipedia.org/wiki/NP-complete)).
A proof of NP-hardness of this problem is that the minimum [ve... |
Decorator to time specific lines of the code instead of whole method? | 30,433,910 | 7 | 2015-05-25T08:17:01Z | 30,434,166 | 7 | 2015-05-25T08:34:51Z | [
"python"
] | Lets assume a simple method :
```
def test_method():
a = 1
b = 10000
c = 20000
sum1 = sum(range(a,b))
sum2 = sum(range(b,c))
return (sum1,sum2)
```
To time this method using a decorator, a simple decorator would be :
```
from functools import wraps
def timed_decorator(f):
@wraps(f)
de... | You can use a context manager.
```
import contextlib
@contextlib.contextmanager
def time_measure(ident):
tstart = time.time()
yield
elapsed = time.time() - tstart
logger.debug("{0}: {1} ms".format(ident, elapsed))
```
In your code, you use it like
```
with time_measure('test_method:sum1'):
sum1 ... |
How do I fix UnsupportedCharsetException in Eclipse Kepler/Luna with Jython/PyDev? | 30,443,537 | 3 | 2015-05-25T17:48:03Z | 33,827,262 | 7 | 2015-11-20T12:55:08Z | [
"java",
"python",
"eclipse",
"pydev",
"jython"
] | Example code:
```
from java.lang import System
if __name__ == '__main__':
[System.out.print(x) for x in "Python-powered Java Hello World from within a List-Comprehension."]
```
Annoying output:
```
console: Failed to install 'org.python.util.JLineConsole': java.nio.charset.UnsupportedCharsetException: cp0.
cons... | I've fixed this issue following the advice mentioned in the bug report you referred to (<http://bugs.jython.org/issue2222>), adding
-Dpython.console.encoding=UTF-8 as a VM argument to the run configuration for my program. Setting the same value as an
environment variable for the Jython interpreter didn't work in my cas... |
How to avoid a redundant and verbose if-else-structure? | 30,443,558 | 2 | 2015-05-25T17:48:58Z | 30,443,610 | 7 | 2015-05-25T17:52:23Z | [
"python"
] | Is there a simpler and more efficient way to writing this code? It is a calculator on how much it costs to smoke.
There must be a way of skipping all the `if` and `elif` tags, and make it into a loop and save a few minutes of typing the code, and there may be even a "standard" in how to type code like this that I have... | You can use a dictionary and a predefined function:
```
mappings = {'D': 1, 'W': 7, 'Y': 365, 'DE': 3650}
def calculate_cigarettes(arg):
cost = cost_st * how_many * mappings[arg]
print('It will cost', cost, 'kr total.')
``` |
Install Vim via Homebrew with Python AND Python3 Support | 30,443,836 | 2 | 2015-05-25T18:09:15Z | 30,516,109 | 8 | 2015-05-28T20:04:24Z | [
"python",
"python-3.x",
"vim",
"homebrew"
] | I would like to enable Python auto-completion in Vim so maybe this is a non-issue. This is what I've observed:
First, [Virtual Environments](https://github.com/kennethreitz/python-guide/blob/master/docs/dev/virtualenvs.rst) provides the ability to assign an interpreter on a per-project basis. The assumption being both... | Vim compiled with both, or with 'dynamic' is only available on Windows versions. Mac/\*nix/etc can only use one version of Python.
My way around this was to compile two different vims, one with each Python version, and then create a version check in my .vimrc to be co-compatible with the two of them.
```
if has('pyth... |
VIM: Use python3 interpreter in python-mode | 30,444,890 | 3 | 2015-05-25T19:31:14Z | 30,449,124 | 12 | 2015-05-26T03:48:18Z | [
"python",
"vim",
"ubuntu-14.04",
"python-3.4",
"python-mode"
] | I have recently switched to vim and configured it for Python-programming using [this](http://unlogic.co.uk/2013/02/08/vim-as-a-python-ide/) tutorial. Before, I have made sure that vim supports python3 (vim --version shows +python/dyn and +python3/dyn) using [this](http://askubuntu.com/questions/585237/whats-the-easiest... | Try adding this to your .vimrc file
```
let g:pymode_python = 'python3'
```
I found this in the help docs. In vim type:
```
:help python-mode
```
By default, vim is not compiled with python3 support, so when I tried this, I got all kinds of errors... Which tells me it's trying to use python3. But if your `vim --ver... |
Python, Pandas : Return only those rows which have missing values | 30,447,083 | 3 | 2015-05-25T23:03:24Z | 30,447,205 | 8 | 2015-05-25T23:18:46Z | [
"python",
"pandas",
"missing-data"
] | While working in Pandas in Python...
I'm working with a dataset that contains some missing values, and I'd like to return a dataframe which contains only those rows which have missing data. Is there a nice way to do this?
(My current method to do this is an inefficient "look to see what index isn't in the dataframe w... | I believe this should do it:
```
null_data = df[df.isnull().any(axis=1)]
``` |
python fuzzy text search | 30,449,452 | 5 | 2015-05-26T04:25:56Z | 30,450,439 | 16 | 2015-05-26T05:51:08Z | [
"python",
"elasticsearch",
"full-text-search",
"fuzzy-search",
"whoosh"
] | I am wondering if there has any Python library can conduct fuzzy text search. For example:
* I have three key words `"letter", "stamp", and "mail"`.
* I would like to have a function to check if those three words are within
the same paragraph (or certain distances, one page).
* In addition, those words have to maint... | **{1}**
You can do this in `Whoosh 2.7`. It has fuzzy search by adding the plugin `whoosh.qparser.FuzzyTermPlugin`:
> `whoosh.qparser.FuzzyTermPlugin` lets you search for âfuzzyâ terms, that is, terms that donât have to match exactly. The fuzzy term will match any similar term within a certain number of âedits... |
How to declare accented variables in Python | 30,450,276 | 7 | 2015-05-26T03:57:57Z | 30,450,277 | 9 | 2015-05-26T04:18:52Z | [
"python",
"character-encoding",
"unicode"
] | I need to write **few basic scripts** for students in **Python**, like this one:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
mia_età = 31
print mia_etÃ
```
But apparently I cannot use accented characters while declaring variables. Is there any way out?
*("mia\_età " means "my\_age" in Italian and I would like t... | Python 1 and 2 only support ASCII alphanumeric characters and `_` in [identifiers](https://docs.python.org/2/reference/lexical_analysis.html#identifiers).
Python 3 supports all Unicode letters and certain marks in [identifiers](https://docs.python.org/3/reference/lexical_analysis.html#identifiers).
```
#!/usr/bin/pyt... |
Python: installed selenium package not detected | 30,450,388 | 4 | 2015-05-26T05:48:05Z | 30,470,288 | 7 | 2015-05-26T22:50:01Z | [
"python",
"selenium",
"pip",
"anaconda"
] | I am using the [Anaconda](http://continuum.io/downloads) python distribution and would like to use the [selenium](http://selenium.googlecode.com/svn/trunk/docs/api/py/index.html) package. Unfortunately the distribution does not have selenium included in it so I installed it using the recommended:
```
pip install -U se... | Following the advice of a comment in [this](http://stackoverflow.com/questions/18640305/how-to-keep-track-of-pip-installed-packages-in-an-anaconda-conda-env?rq=1) question I installed Selenium using the `pip` installed with the distribution.
```
~/anaconda/bin/pip install -U selenium
```
I did not know about this bef... |
Print 5 items in a row on separate lines for a list? | 30,451,252 | 9 | 2015-05-26T06:42:03Z | 30,451,349 | 13 | 2015-05-26T06:46:54Z | [
"python"
] | I have a list of unknown number of items, let's say 26.
let's say
```
list=['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
```
How to print like this:
```
abcde
fghij
klmno
pqrst
uvwxy
z
```
?
Thank you very much.
Attempt:
```
start = 0
for it... | You can simple do this by list comprehension: `"\n".join(["".join(lst[i:i+5]) for i in xrange(0,len(lst),5)])` the [`xrange(start, end, interval)`](https://docs.python.org/2/library/functions.html#xrange) here would give a list of integers which are equally spaced at a distance of `5`, then we slice the given list in t... |
Print 5 items in a row on separate lines for a list? | 30,451,252 | 9 | 2015-05-26T06:42:03Z | 30,451,938 | 11 | 2015-05-26T07:16:53Z | [
"python"
] | I have a list of unknown number of items, let's say 26.
let's say
```
list=['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
```
How to print like this:
```
abcde
fghij
klmno
pqrst
uvwxy
z
```
?
Thank you very much.
Attempt:
```
start = 0
for it... | ```
for i, a in enumerate(A):
print a,
if i % 5 == 4:
print "\n"
```
Another alternative, the comma after the print means there is no newline character |
Why does this Python boolean comparison return a triple? | 30,453,403 | 2 | 2015-05-26T08:30:25Z | 30,453,445 | 8 | 2015-05-26T08:32:16Z | [
"python",
"boolean",
"behavior"
] | I was playing around on the command-line for Python 2.7.8, where I encountered this behavior:
```
>>> "902".isdigit() == True
True
>>> "902".isdigit(), "2".isdigit() == True
(True, True)
>>> "902".isdigit(), "2".isdigit() == True,True
(True, True, True)
>>> ("902".isdigit(), "2".isdigit()) == (True,True)
```
I found ... | Because:
```
"902".isdigit(), "2".isdigit() == True,True
```
is interpreted as:
```
("902".isdigit(), ("2".isdigit() == True), True)
```
Note that you shouldn't test booleans with `==`; a more pythonic way to write the test is:
```
"902".isdigit() and "2".isdigit()
``` |
filling an array with a loop in python | 30,459,166 | 2 | 2015-05-26T12:53:07Z | 30,459,268 | 7 | 2015-05-26T12:57:58Z | [
"python"
] | my problem is as follows, i have an array named `crave=['word1','word2','word3'....'wordx']` and i want to transform into `ITEM=[['word1','word2','word3'],['word4','word5','word6'] etc]`
i used the following code
```
buff=[['none','none','none']]
n=10
ITEM=[]
i=0
while 1>0 :
buff[0][0]=crave[i]
buff[0][1]=crave[i+... | You can easily do this by using list comprehension.
`xrange(0, len(crave), 3)` is used to iterate from 0 to len(crave) with an interval of 3. and then we use [list slicing](https://docs.python.org/2/tutorial/introduction.html) `crave[i:i+3]` to extract the required data.
```
crave=['word1','word2','word3','word4','wor... |
disable default certificate verification in python 2.7.9 | 30,461,969 | 3 | 2015-05-26T14:50:40Z | 30,467,956 | 10 | 2015-05-26T20:08:44Z | [
"python",
"ssl"
] | I try to make a local HTTPS connection to a XMLRPC api. Since I upgrade to python 2.7.9 that [enable by default certificates verification](https://www.python.org/dev/peps/pep-0476/), I got a CERTIFICATE\_VERIFY\_FAILED error when I use my API
```
>>> test=xmlrpclib.ServerProxy('https://admin:bz15h9v9n@localhost:9999/A... | You have to provide an unverified SSL context, constructed by hand or using the private function \_create\_unverified\_context() from ssl module:
```
import xmlrpclib
import ssl
test = xmlrpclib.ServerProxy('https://admin:bz15h9v9n@localhost:9999/API',
verbose=False, use_datetime=True,
... |
What is this syntax "..." (ellipsis)? | 30,462,352 | 5 | 2015-05-26T15:07:24Z | 30,462,383 | 13 | 2015-05-26T15:08:30Z | [
"python"
] | I was looking at [the source code](https://github.com/sambler/myblenderaddons/blob/master/io_scene_fbx/import_fbx.py) of a Blender add-on and I saw a new syntax:
```
def elem_name_ensure_class(elem, clss=...):
elem_name, elem_class = elem_split_name_class(elem)
if clss is not ...:
assert(elem_class == ... | `...` is a literal syntax for the Python [`Elipsis` object](https://docs.python.org/3/library/stdtypes.html#the-ellipsis-object):
```
>>> ...
Ellipsis
```
It is mostly used by NumPy; see [What does the Python Ellipsis object do?](http://stackoverflow.com/questions/772124/what-does-the-python-ellipsis-object-do)
The ... |
Why does the Python regex ".*PATTERN*" match "XXPATTERXX"? | 30,463,189 | 3 | 2015-05-26T15:46:03Z | 30,463,219 | 9 | 2015-05-26T15:47:12Z | [
"python",
"regex"
] | Suppose I want to find `"PATTERN"` in a string, where `"PATTERN"` could be anywhere in the string. My first try was `*PATTERN*`, but this generates an error saying that there is "nothing to repeat", which I can accept so I tried `.*PATTERN*`. This regex does however not give the expected result, see below
```
import r... | Your pattern matches 0 or more `N` characters at the end, but doesn't say anything about what comes after those `N` characters.
You could add `$` to the pattern to anchor to the end of the input string to disallow the `XX`:
```
>>> import re
>>> re.compile(".*PATTERN*$")
<_sre.SRE_Pattern object at 0x10029fb90>
>>> i... |
Functional Breadth First Search | 30,464,163 | 21 | 2015-05-26T16:32:26Z | 30,464,615 | 11 | 2015-05-26T16:56:36Z | [
"python",
"haskell",
"functional-programming",
"ocaml",
"sml"
] | Functional depth first search is lovely in directed acyclic graphs.
In graphs with cycles however, how do we avoid infinite recursion? In a procedural language I would mark nodes as I hit them, but let's say I can't do that.
A list of visited nodes is possible, but will be slow because using one will result in a line... | You have to keep track of the nodes you visit. Lists are not king in the ML family, they're just one of the oligarchs. You should just use a set (tree based) to track the visited nodes. This will add a log factor compared to mutating the node state, but is so much cleaner it's not funny. If you know more about your nod... |
Functional Breadth First Search | 30,464,163 | 21 | 2015-05-26T16:32:26Z | 30,469,287 | 45 | 2015-05-26T21:29:45Z | [
"python",
"haskell",
"functional-programming",
"ocaml",
"sml"
] | Functional depth first search is lovely in directed acyclic graphs.
In graphs with cycles however, how do we avoid infinite recursion? In a procedural language I would mark nodes as I hit them, but let's say I can't do that.
A list of visited nodes is possible, but will be slow because using one will result in a line... | One option is to use **inductive graphs**, which are a functional way of representing and working with arbitrary graph structures. They are provided by Haskell's **[fgl](https://hackage.haskell.org/package/fgl)** library and described in ["Inductive Graphs and Funtional Graph Algorithms"](http://web.engr.oregonstate.ed... |
pythonic way to filter list for elements with unique length | 30,469,776 | 4 | 2015-05-26T22:07:55Z | 30,469,833 | 10 | 2015-05-26T22:13:20Z | [
"python",
"filtering"
] | I want to filter a list, leaving only first elements with unique length.
I wrote a function for it, but I believe there should be a simpler way of doing it:
```
def uniq_len(_list):
from itertools import groupby
uniq_lens = list(set([x for x, g in groupby(_list, len)]))
all_goods = []
for elem in _list... | If you just want any arbitrary string for each length, in arbitrary order, the easy way to do this is to first convert to a dict mapping lengths to strings, then just read off the values:
```
>>> {len(s): s for s in jones}.values()
dict_values(['jon', 'bill', 'jamie'])
```
If you want the *first* for each length, and... |
Is MATLAB faster than Python (little simple experiment) | 30,475,410 | 5 | 2015-05-27T07:06:36Z | 30,475,540 | 11 | 2015-05-27T07:13:03Z | [
"python",
"matlab",
"performance-testing"
] | I have read this ( [Is MATLAB faster than Python?](http://stackoverflow.com/questions/2133031/is-matlab-faster-than-python) ) and I find it has lots of ifs.
I have tried this little experiment on an old computer that still runs on Windows XP.
In MATLAB R2010b I have copied and pasted the following code in the Command... | First, using `time` is not a good way to test code like this. But let's ignore that.
---
When you have code that does a lot of looping and repeating very similar work each time through the loop, [PyPy](http://pypy.org)'s JIT will do a great job. When that code does the *exact same* thing every time, to constant value... |
Padding or truncating a Python list | 30,475,558 | 16 | 2015-05-27T07:13:58Z | 30,475,648 | 20 | 2015-05-27T07:18:31Z | [
"python",
"list",
"python-2.7"
] | I'd like to truncate or pad a list. E.g. for size 4:
```
[1,2,3] -> [1,2,3,0]
[1,2,3,4,5] -> [1,2,3,4]
```
I can see a couple of ways:
```
def trp(l, n):
""" Truncate or pad a list """
r = l[:n]
if len(r) < n:
r.extend([0] * (n - len(r)))
return r
```
Or a shorter, but less efficient:
```
m... | You can use `itertools` module to make it completely lazy, like this
```
>>> from itertools import repeat, chain, islice
>>> def trimmer(seq, size, filler=0):
... return islice(chain(seq, repeat(filler)), size)
...
>>> list(trimmer([1, 2, 3], 4))
[1, 2, 3, 0]
>>> list(trimmer([1, 2, 3, 4, 5], 4))
[1, 2, 3, 4]
```... |
Padding or truncating a Python list | 30,475,558 | 16 | 2015-05-27T07:13:58Z | 30,475,725 | 18 | 2015-05-27T07:22:43Z | [
"python",
"list",
"python-2.7"
] | I'd like to truncate or pad a list. E.g. for size 4:
```
[1,2,3] -> [1,2,3,0]
[1,2,3,4,5] -> [1,2,3,4]
```
I can see a couple of ways:
```
def trp(l, n):
""" Truncate or pad a list """
r = l[:n]
if len(r) < n:
r.extend([0] * (n - len(r)))
return r
```
Or a shorter, but less efficient:
```
m... | Slicing using an index greater than the length of a list just returns the entire list.
Multiplying a list by a negative value returns an empty list.
That means the function can be written as:
```
def trp(l, n):
return l[:n] + [0]*(n-len(l))
trp([], 4)
[0, 0, 0, 0]
trp([1,2,3,4], 4)
[1, 2, 3, 4]
trp([1,2,3,4,5... |
List comprehension and in place methods | 30,478,083 | 3 | 2015-05-27T09:15:46Z | 30,478,128 | 7 | 2015-05-27T09:18:19Z | [
"python",
"list",
"list-comprehension"
] | I am just trying to understand what happens during list comprehension. Some methods which work on lists 'in-place' don't seem to work when applied in a list comprehension:
```
a = [[1, 2, 3], [4, 5, 6]]
i1 = id(a[0])
for i in a: i.reverse()
>>> [[3, 2, 1], [6, 5, 4] # Works
print i1 == id(a[0]) # True, same memory ... | `i.reverse()` reverses the array in place and doesn't return anything, meaning it returns `None` type. That way you obtain `[None, None]` from list comprehension and previous arrays' elements are reversed at the same time.
These two shouldn't be mixed, either use a `for` and `x.reverse()`, or use `reversed(x)` or `x[:... |
Python command line arguments linux | 30,482,106 | 2 | 2015-05-27T12:13:38Z | 30,482,127 | 9 | 2015-05-27T12:14:27Z | [
"python",
"linux",
"command-line",
"terminal",
"arguments"
] | I have this little program(I know there is a lot of errors):
```
#!/usr/bin/python
import os.path
import sys
filearg = sys.argv[0]
if (filearg == ""):
filearg = input("")
else:
if (os.path.isfile(filearg)):
print "File exist"
else:
print"No file"
print filearg
print "w... | It should be `sys.argv[1]` not `sys.argv[0]`:
```
filearg = sys.argv[1]
```
From the [docs](https://docs.python.org/2/library/sys.html#sys.argv):
> The list of command line arguments passed to a Python script. **argv[0] is the script name** (it is operating system dependent whether this is a full pathname or not). I... |
How to check if a python module has been imported? | 30,483,246 | 5 | 2015-05-27T12:59:53Z | 30,483,269 | 10 | 2015-05-27T13:00:55Z | [
"python",
"python-import"
] | How do I check if I imported a module somewhere in the code?
```
if not has_imported("sys"):
print 'you have not imported sys'
```
The reason that i would like to check if i already imported a module is because i have a module that i don't want to import because sometimes it messes up my program. | Test for the module name in the [`sys.modules` dictionary](https://docs.python.org/2/library/sys.html#sys.modules):
```
import sys
modulename = 'datetime'
if modulename not in sys.modules:
print 'You have not imported the {} module'.format(modulename)
```
From the documenation:
> This is a dictionary that maps ... |
Python: openpyxl how to read a cell font color | 30,483,649 | 15 | 2015-05-27T13:17:04Z | 30,682,271 | 8 | 2015-06-06T11:28:47Z | [
"python",
"openpyxl"
] | I have tried to print `some_cell.font.color.rgb` and got various results.
For some I got what I want (like "`FF000000`"), but for others it gives me `Value must be type 'basetring'`. I assume that the latter is because I haven't actually defined the font color for these cells.
I'm using openpyxl 2.2.2 | I think this is a bug in openpyxl and I think you should report it [here](https://bitbucket.org/openpyxl/openpyxl/issues).
Debugging the following code (with [trepan](https://pypi.python.org/pypi/trepan/0.4.8) of course):
```
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
c = ws['A4'] # cell gets creat... |
Is it possible to modify the behavior of len()? | 30,483,752 | 11 | 2015-05-27T13:21:14Z | 30,483,797 | 19 | 2015-05-27T13:23:06Z | [
"python",
"python-3.x"
] | I'm aware of creating a custom `__repr__` or `__add__` method (and so on), to modify the behavior of operators and functions. Is there a method override for `len`?
For example:
```
class Foo:
def __repr__(self):
return "A wild Foo Class in its natural habitat."
foo = Foo()
print(foo) # A wild Fo... | Yes, implement the [`__len__` method](https://docs.python.org/3/reference/datamodel.html#object.__len__):
```
def __len__(self):
return 42
```
Demo:
```
>>> class Foo(object):
... def __len__(self):
... return 42
...
>>> len(Foo())
42
```
From the documentation:
> Called to implement the built-in ... |
Is it possible to modify the behavior of len()? | 30,483,752 | 11 | 2015-05-27T13:21:14Z | 30,483,807 | 7 | 2015-05-27T13:23:23Z | [
"python",
"python-3.x"
] | I'm aware of creating a custom `__repr__` or `__add__` method (and so on), to modify the behavior of operators and functions. Is there a method override for `len`?
For example:
```
class Foo:
def __repr__(self):
return "A wild Foo Class in its natural habitat."
foo = Foo()
print(foo) # A wild Fo... | Yes, just as you have already discovered that you can override the behaviour of a `repr()` function call by implementing the `__repr__` magic method, you can specify the behaviour from a [`len()`](https://docs.python.org/3/library/functions.html#len) function call by implementing (surprise surprise) then [`__len__`](ht... |
python - fill cells with colors using openpyxl | 30,484,220 | 10 | 2015-05-27T13:39:23Z | 30,486,164 | 12 | 2015-05-27T14:57:58Z | [
"python",
"openpyxl"
] | I am currently using openpyxl v2.2.2 for Python 2.7 and i wanted to set colors to cells. I have used the following imports
```
import openpyxl,
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
```
and the follo... | Why are you trying to assign a fill to a style?
`ws['A1'].fill = redFill` should work fine. |
Check if argparse optional argument is set or not | 30,487,767 | 13 | 2015-05-27T16:08:23Z | 30,488,411 | 24 | 2015-05-27T16:39:55Z | [
"python",
"argparse"
] | I would like to check whether an optional argparse argument has been set by the user or not.
Can I safely check using isset?
Something like this:
```
if(isset(args.myArg)):
#do something
else:
#do something else
```
Does this work the same for float / int / string type arguments?
I could set a default para... | I think that optional arguments (specified with `--`) are initialized to `None` if they are not supplied. So you can test with `is not None`. Try the example below:
```
import argparse as ap
def main():
parser = ap.ArgumentParser(description="My Script")
parser.add_argument("--myArg")
args, leftovers = pa... |
Check if argparse optional argument is set or not | 30,487,767 | 13 | 2015-05-27T16:08:23Z | 30,491,369 | 9 | 2015-05-27T19:22:45Z | [
"python",
"argparse"
] | I would like to check whether an optional argparse argument has been set by the user or not.
Can I safely check using isset?
Something like this:
```
if(isset(args.myArg)):
#do something
else:
#do something else
```
Does this work the same for float / int / string type arguments?
I could set a default para... | As @Honza notes `is None` is a good test. It's the default `default`, and the user can't give you a string that duplicates it.
You can specify another `default='mydefaultvalue`, and test for that. But what if the user specifies that string? Does that count as setting or not?
You can also specify `default=argparse.SUP... |
Fill zero values of 1d numpy array with last non-zero values | 30,488,961 | 3 | 2015-05-27T17:07:46Z | 30,489,294 | 7 | 2015-05-27T17:26:28Z | [
"python",
"numpy"
] | Let's say we have a 1d numpy array filled with some `int` values. And let's say that some of them are `0`.
Is there any way, using `numpy` array's power, to fill all the `0` values with the last non-zero values found?
for example:
```
arr = np.array([1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2])
fill_zeros_with_last(arr)
... | Here's a solution using `np.maximum.accumulate`:
```
def fill_zeros_with_last(arr):
prev = np.arange(len(arr))
prev[arr == 0] = 0
prev = np.maximum.accumulate(prev)
return arr[prev]
```
We construct an array `prev` which has the same length as `arr`, and such that `prev[i]` is the index of the last no... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 30,492,913 | 127 | 2015-05-27T20:52:56Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | The idea here is to install multiple `ipython` kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added [instructions](http://stackoverflow.com/a/34464003/2272172) using pure virtualenvs.
## Anaconda 4.1.0
Since version 4.1.0, anaconda includes a special package `nb_conda_kernels` ... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 30,493,051 | 13 | 2015-05-27T21:00:39Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.
Requirements:
* MacPorts is installed in the usual /opt directory
* python 2.7 is installed through macports
* python 3.4 is installed through macports
* Ipython is installed for python 2.7
* Ipython is inst... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 30,493,155 | 22 | 2015-05-27T21:06:46Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | With a current version of the Notebook/Jupyter, you can create a [Python3 kernel](http://jupyter.cs.brynmawr.edu/hub/dblank/public/Jupyter%20Help.ipynb#1.4.2-Enable-Python-3-kernel). After starting a new notebook application from the command line with Python 2 you should see an entry âPython 3â in the dropdown menu... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 33,016,661 | 8 | 2015-10-08T13:01:41Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | From my Linux installation I did:
`sudo ipython2 kernelspec install-self`
And now my python 2 is back on the list.
**Reference:**
<http://ipython.readthedocs.org/en/latest/install/kernel_install.html>
---
**UPDATE:**
The method above is now deprecated and will be dropped in the future. The new method should be:
... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 34,464,003 | 14 | 2015-12-25T15:18:22Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | These instructions explain how to install a python2 and python3 kernel in separate virtual environments for non-anaconda users. If you are using anaconda, please find my [other answer](http://stackoverflow.com/a/30492913/2272172) for a solution directly tailored to anaconda.
I assume that you already have `jupyter not... |
Using both Python 2.x and Python 3.x in IPython Notebook | 30,492,623 | 78 | 2015-05-27T20:34:41Z | 37,857,536 | 15 | 2016-06-16T11:14:49Z | [
"python",
"python-2.7",
"python-3.x",
"ipython",
"ipython-notebook"
] | I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.
I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uni... | If youâre running [Jupyter](http://jupyter.org) on Python 3, you can set up a Python 2 kernel like this:
```
python2 -m pip install ipykernel
python2 -m ipykernel install --user
```
<http://ipython.readthedocs.io/en/stable/install/kernel_install.html> |
404 Error in "Writing your first Django App" tutorial | 30,493,018 | 6 | 2015-05-27T20:58:29Z | 30,493,133 | 7 | 2015-05-27T21:05:26Z | [
"python",
"django"
] | I am new to programming and have been working through the "Writing your first Django App" Tutorial for version 1.8. I'm stuck with an error.
```
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/polls
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:... | The root urls should be at `mysite\mysite\urls.py`, not `mysite\urls.py` as you have it. |
Installing lxml, libxml2, libxslt on Windows 8.1 | 30,493,031 | 13 | 2015-05-27T20:59:24Z | 30,494,745 | 41 | 2015-05-27T23:20:08Z | [
"python",
"windows",
"module",
"installation",
"lxml"
] | ## After additional exploration, I found a solution to installing lxml with pip and wheel. Additional comments on approach welcomed.
I'm finding the existing Python documentation for Linux distributions excellent. For Windows... not so much. I've configured my Linux system fine but I need some help getting a Windows 8... | I was able to fix the installation with the following steps. I hope others find this helpful.
My installation of "pip" was working fine before the problem. I went to the Windows command line and made sure that "wheel" was installed.
```
C:\Python34>python -m pip install wheel
Requirement already satisfied (use --upgr... |
Django 1.8, Multiple Custom User Types | 30,495,979 | 8 | 2015-05-28T01:59:06Z | 31,103,029 | 8 | 2015-06-28T18:03:46Z | [
"python",
"django",
"authentication",
"user"
] | I am creating a Django site that will have 4 types of users;
* Super Admin: Essentially manages all types of users
* UserTypeA: Can login to site and basically will have a CRUD interface for some arbitrary model. Also has extra attributes (specific info that only pertains to TypeA users)
* UserTypeB: Can login to site... | First of all, you cannot make multiple authentication user base for a project. So you have to use the Django user authentication provided and fork it for multiple types of users. The Django user has some default values you need to provide during registration (try creating a user in Django Admin). What you can do is cre... |
Turning string with embedded brackets into a dictionary | 30,498,520 | 11 | 2015-05-28T06:12:14Z | 30,498,722 | 18 | 2015-05-28T06:25:01Z | [
"python",
"regex",
"dictionary"
] | What's the best way to build a dictionary from a string like the one below:
```
"{key1 value1} {key2 value2} {key3 {value with spaces}}"
```
So the key is always a string with no spaces but the value is either a string or a string in curly brackets (it has spaces)?
How would you dict it into:
```
{'key1': 'value1',... | ```
import re
x="{key1 value1} {key2 value2} {key3 {value with spaces}}"
print dict(re.findall(r"\{(\S+)\s+\{*(.*?)\}+",x))
```
You can try this.
Output:
```
{'key3': 'value with spaces', 'key2': 'value2', 'key1': 'value1'}
```
Here with `re.findall` we extract `key` and its `value`.`re.findall` returns a list with... |
range(n)[x:y:z] | 30,498,719 | 7 | 2015-05-28T06:24:56Z | 30,498,874 | 7 | 2015-05-28T06:33:55Z | [
"python",
"range",
"python-2.x"
] | Not sure what the arguments inside the `[ ]` really do after the `range()` function.
Exp: `print ( range(5)[::-2])`
Output: `[4, 2, 0]`
But if `[x:y:z]` stands for `[start:stop:step]`, then when I put `print(range(5)[4:-2:-2])`, the output list is `[4]` instead of `[4, 2, 0]`, not sure how that works. | Youâre right, itâs `[start:stop:step]`. Note that negative starts and stops are defined to start at the end of the sequence. So for a range that ends with the values `2, 3, 4`, the stop `-2` refers to the `3` (-1 is the last, -2 is the second to last, etc.).
So in your case, the range has a length of 5, starting a... |
range(n)[x:y:z] | 30,498,719 | 7 | 2015-05-28T06:24:56Z | 30,498,902 | 8 | 2015-05-28T06:35:13Z | [
"python",
"range",
"python-2.x"
] | Not sure what the arguments inside the `[ ]` really do after the `range()` function.
Exp: `print ( range(5)[::-2])`
Output: `[4, 2, 0]`
But if `[x:y:z]` stands for `[start:stop:step]`, then when I put `print(range(5)[4:-2:-2])`, the output list is `[4]` instead of `[4, 2, 0]`, not sure how that works. | In Python 3, `range()` creates a special `range` object. In Python 2, it creates a `list`.
```
List element: 0 1 2 3 4
Index: 0 1 2 3 4
Backwards index: -5 -4 -3 -2 -1
```
So, going from index `4` to index `-2` really goes from list element `4` to list element `3`. Since you're skipping every o... |
Efficient algorithm perl or python | 30,502,426 | 7 | 2015-05-28T09:24:56Z | 30,502,643 | 8 | 2015-05-28T09:34:16Z | [
"python",
"algorithm",
"perl"
] | Interviewer asked a question in an interview to write fast & efficient algorithm for below function,
Problem: Write a function to parse a given string for below given rules & produce final parsed string as output
write a function which will accepts string as input, string length will be in between [0..2000000000]
> ... | You can repeat substitution while it matches transformation rules,
```
my %h = (
'AB' => 'AA',
'AC' => 'AA',
'AA' => 'A',
'CC' => 'C',
'BC' => 'BB',
'BB' => 'B',
);
my $s = 'ABCAAB';
1 while $s =~ s/(AB|AC|AA|CC|BC|BB)/$h{$1}/; # also without /g switch
print $s;
```
output
```
A
``` |
Efficient algorithm perl or python | 30,502,426 | 7 | 2015-05-28T09:24:56Z | 30,502,806 | 15 | 2015-05-28T09:40:23Z | [
"python",
"algorithm",
"perl"
] | Interviewer asked a question in an interview to write fast & efficient algorithm for below function,
Problem: Write a function to parse a given string for below given rules & produce final parsed string as output
write a function which will accepts string as input, string length will be in between [0..2000000000]
> ... | Rules 1 to 3 will discard any character following an A.
Rules 5 and 6 will discard any B and C following a B.
Rule 4 will discard any C following a C. The order of the substitutions does not matter.
So after processing the string will be one of C, CB, CA, CBA, B, BA, A.
A single scan of the string will suffice. I... |
open cv error: (-215) scn == 3 || scn == 4 in function cvtColor | 30,506,126 | 12 | 2015-05-28T12:06:00Z | 32,598,876 | 13 | 2015-09-16T02:42:05Z | [
"python",
"opencv",
"photo"
] | I'm currently in Ubuntu 14.04, using python 2.7 and cv2.
When I run this code:
```
import numpy as np
import cv2
img = cv2.imread('2015-05-27-191152.jpg',0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
it returns:
```
File "face_detection.py", line 11, in <module>
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GR... | Give the full path of image with forward slash..it solved the error for me. eg.
```
import numpy as np
import cv2
img = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
also if you give 0 in second parameter while loading image using cv2.imread than no need to c... |
Returning a String from Rust function to Python | 30,510,764 | 13 | 2015-05-28T15:22:32Z | 30,511,235 | 9 | 2015-05-28T15:42:28Z | [
"python",
"rust"
] | I'm very new to Rust. How would I return a `String` from a Rust function that can be used in Python?
Here is my Rust implementation:
```
use std::ffi::CString;
#[no_mangle]
pub extern fn query() -> CString {
let s = CString::new("Hello!").unwrap();
return s;
}
```
And the Python code that calls it:
```
fro... | The most direct version would be this:
```
use libc::c_char;
use std::ffi::CString;
use std::mem;
#[no_mangle]
pub extern fn query() -> *mut c_char {
let s = CString::new("Hello!").unwrap();
s.into_raw()
}
```
Here we return a pointer to a zero-terminated sequence of `char`s which can be passed to Python's `... |
What is the g object in this Flask code? | 30,514,749 | 3 | 2015-05-28T18:46:19Z | 30,514,815 | 11 | 2015-05-28T18:49:27Z | [
"python",
"flask"
] | I found this code that times each response, but I'm not sure where `g` is supposed to come from. What is `g`?
```
@app.before_request
def before_request():
g.start = time.time()
@app.teardown_request
def teardown_request(exception=None):
diff = time.time() - g.start
print diff
``` | [`g`](http://flask.pocoo.org/docs/dev/api/#flask.g) is an object provided by Flask. It is a global namespace for holding any data you want during a single app context.
```
from flask import g
```
---
Note that the dev server and any web server will output timing information in the logs already. If you really want to... |
Split string into list in jinja? | 30,515,456 | 15 | 2015-05-28T19:25:46Z | 30,517,735 | 24 | 2015-05-28T21:55:27Z | [
"python",
"jinja2"
] | I have some variables in a jinja2 template which are strings seperated by a ';'.
I need to use these strings separately in the code.
i.e. the variable is variable1 = "green;blue"
```
{% list1 = {{ variable1 }}.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
```
I can split them up before ren... | It works with:
```
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
``` |
Pandas error - invalid value encountered | 30,519,487 | 19 | 2015-05-29T00:59:50Z | 31,257,931 | 23 | 2015-07-07T00:34:15Z | [
"python",
"pandas",
"python-3.4",
"anaconda"
] | New to Pandas. I downloaded and installed [Anaconda](http://continuum.io/downloads). Then I tried running the following code via the Spyder app
```
import pandas as pd
import numpy as np
train = pd.read_csv('/Users/Ben/Documents/Kaggle/Titanic/train.csv')
train
```
Although this prints the dataframe as I expected, i... | I have the same error and have decided that it is a bug. It seems to be caused by the presence of NaN values in a DataFrame in Spyder. I have uninstalled and reinstalled all packages and nothing has effected it. NaN values are supported and are completely valid in DataFrames especially if they have a DateTime index.
I... |
Take multiple lists into dataframe | 30,522,724 | 8 | 2015-05-29T06:37:49Z | 30,522,778 | 14 | 2015-05-29T06:40:18Z | [
"python",
"numpy",
"pandas"
] | How do I take multiple lists and put them as different columns in a python dataframe? I tried following [Read lists into columns of pandas DataFrame](http://stackoverflow.com/questions/29014618/read-lists-into-columns-of-pandas-dataframe) but had some trouble.
Attempt 1:
* Have three lists, and zip them together and ... | I think you're almost there, try removing the extra square brackets around the lst's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):
```
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
{'lst1Tite': lst1,
'lst2Tite'... |
List with many dictionaries VS dictionary with few lists? | 30,522,982 | 28 | 2015-05-29T06:51:57Z | 30,523,225 | 7 | 2015-05-29T07:05:49Z | [
"python",
"pandas",
"dataset"
] | I am doing some exercises with datasets like so:
**List with many dictionaries**
```
users = [
{"id": 0, "name": "Ashley"},
{"id": 1, "name": "Ben"},
{"id": 2, "name": "Conrad"},
{"id": 3, "name": "Doug"},
{"id": 4, "name": "Evin"},
{"id": 5, "name": "Florian"},
{"id": 6, "name": "Gerald"}... | **Users**
1. When you need to append some new user just make a new list of all user details and append it
2. Easily sortable as @StevenRumbalski suggested
3. Searching will be easy
4. This is more compact and easily manageable as record grows (for some very high number of records I think we will need something better ... |
List with many dictionaries VS dictionary with few lists? | 30,522,982 | 28 | 2015-05-29T06:51:57Z | 30,525,128 | 23 | 2015-05-29T08:46:39Z | [
"python",
"pandas",
"dataset"
] | I am doing some exercises with datasets like so:
**List with many dictionaries**
```
users = [
{"id": 0, "name": "Ashley"},
{"id": 1, "name": "Ben"},
{"id": 2, "name": "Conrad"},
{"id": 3, "name": "Doug"},
{"id": 4, "name": "Evin"},
{"id": 5, "name": "Florian"},
{"id": 6, "name": "Gerald"}... | This relates to [column oriented databases](https://en.wikipedia.org/wiki/Column-oriented_DBMS) versus row oriented. Your first example is a row oriented data structure, and the second is column oriented. In the particular case of Python, the first could be made notably more efficient using [slots](https://docs.python.... |
Python dictionary as html table in ipython notebook | 30,523,735 | 14 | 2015-05-29T07:31:35Z | 30,523,907 | 10 | 2015-05-29T07:41:53Z | [
"python",
"ipython-notebook"
] | Is there any (existing) way to display a python dictionary as html table in an ipython notebook. Say I have a dictionary
```
d = {'a': 2, 'b': 3}
```
then i run
```
magic_ipython_function(d)
```
to give me something like
 | You're probably looking for something like [ipy\_table](https://pypi.python.org/pypi/ipy_table).
A different way would be to use [pandas](http://pandas.pydata.org/) for a dataframe, but that might be an overkill. |
Python dictionary as html table in ipython notebook | 30,523,735 | 14 | 2015-05-29T07:31:35Z | 30,525,061 | 8 | 2015-05-29T08:42:52Z | [
"python",
"ipython-notebook"
] | Is there any (existing) way to display a python dictionary as html table in an ipython notebook. Say I have a dictionary
```
d = {'a': 2, 'b': 3}
```
then i run
```
magic_ipython_function(d)
```
to give me something like
 | You can write a custom function to override the default `_repr_html_` function.
```
class DictTable(dict):
# Overridden dict class which takes a dict in the form {'a': 2, 'b': 3},
# and renders an HTML Table in IPython Notebook.
def _repr_html_(self):
html = ["<table width=100%>"]
for key, ... |
Python NumPy: How to fill a matrix using an equation | 30,528,689 | 9 | 2015-05-29T11:41:03Z | 30,528,883 | 10 | 2015-05-29T11:50:38Z | [
"python",
"numpy",
"matrix",
"scipy"
] | I wish to initialise a matrix `A`, using the equation `A_i,j = f(i,j)` for some `f` (It's not important what this is).
How can I do so concisely avoiding a situation where I have two for loops? | [numpy.fromfunction](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfunction.html#numpy.fromfunction) fits the bill here.
Example from doc:
```
>>> import numpy as np
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
``` |
numpy: difference between NaN and masked array | 30,528,852 | 7 | 2015-05-29T11:49:04Z | 30,529,713 | 7 | 2015-05-29T12:31:51Z | [
"python",
"numpy",
null
] | In numpy there are two ways to mark missing values: I can either use a `NaN` or a `masked array`. I understand that using NaNs is (potentially) faster while masked array offers more functionality (which?).
I guess my question is if/ when should I use one over the other?
What is the use case of `np.NaN` in a `regular a... | The difference resides in the data held by the two structures.
Using a [regular array with `np.nan`](http://docs.scipy.org/doc/numpy/user/misc.html), there is no data behind invalid values.
Using a [masked array](http://docs.scipy.org/doc/numpy/reference/maskedarray.html), you can initialize a full array, and then ap... |
Python pandas time series interpolation and regularization | 30,530,001 | 6 | 2015-05-29T12:45:51Z | 30,530,329 | 11 | 2015-05-29T13:00:57Z | [
"python",
"pandas",
"time-series",
"interpolation",
"regularized"
] | I am using Python Pandas for the first time. I have 5-min lag traffic data in csv format:
```
...
2015-01-04 08:29:05,271238
2015-01-04 08:34:05,329285
2015-01-04 08:39:05,-1
2015-01-04 08:44:05,260260
2015-01-04 08:49:05,263711
...
```
There are several issues:
* for some timestamps there's missing data (-1)
* miss... | Change the `-1`s to NaNs:
```
ts[ts==-1] = np.nan
```
Then resample the data to have a 5 minute frequency.
```
ts = ts.resample('5T')
```
Note that, by default, if two measurements fall within the same 5 minute period, `resample` averages the values together.
Finally, you could linearly interpolate the time series... |
Python: cycle through elements in list reversing when the end is reached | 30,530,131 | 3 | 2015-05-29T12:51:43Z | 30,530,279 | 10 | 2015-05-29T12:59:02Z | [
"python",
"list",
"cycle"
] | I have a list that looks like:
```
a = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
```
I need to cycle through this list one element at a time but when the end of the list is reached, the cycle needs to be *reversed*.
For example, using [itertools.cycle](https://docs.python.org/2/library/itertools.h... | You can [`cycle`](https://docs.python.org/2/library/itertools.html#itertools.cycle) the [`chain`](https://docs.python.org/2/library/itertools.html#itertools.chain) of your `a` and [`reversed`](https://docs.python.org/2/library/functions.html?#reversed) `a`, eg:
```
from itertools import cycle, islice, chain
a = range... |
How to "select distinct" across multiple data frame columns in pandas? | 30,530,663 | 8 | 2015-05-29T13:17:32Z | 30,531,939 | 25 | 2015-05-29T14:18:00Z | [
"python",
"pandas"
] | I'm looking for a way to do the equivalent to the sql
> "SELECT DISTINCT col1, col2 FROM dataframe\_table"
The pandas sql comparison doesn't have anything about "distinct"
.unique() only works for a single column, so I suppose I could concat the columns, or put them in a list/tuple and compare that way, but this see... | You can use the [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html) method to get the unique rows in a DataFrame:
```
In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})
In [30]: df
Out[30]:
a b
0 1 3
1 2 4
2 1 3
3 2 5
In [32]: df.drop_d... |
Float must be a string or a number? | 30,531,766 | 4 | 2015-05-29T14:08:50Z | 30,531,872 | 7 | 2015-05-29T14:13:53Z | [
"python",
"type-conversion",
"text-files"
] | I have a very simple program. The code:
```
money = open("money.txt", "r")
moneyx = float(money)
print(moneyx)
```
The text file, money.txt, contains only this:
```
0.00
```
The error message I receive is:
```
TypeError: float() argument must be a string or a number
```
It is most likely a simple mistake. Any adv... | `money` is a [`file` object](https://docs.python.org/2/library/stdtypes.html#bltin-file-objects), *not* the content of the file. To get the content, you have to `read` the file. If the entire file contains just that one number, then [`read()`](https://docs.python.org/2/library/stdtypes.html#file.read) is all you need.
... |
What's the logic behind Python's hash function order? | 30,537,090 | 4 | 2015-05-29T18:56:30Z | 30,537,091 | 9 | 2015-05-29T18:56:30Z | [
"python",
"python-2.7",
"python-3.x",
"hashtable"
] | As we know, Some of Python's data structures use **hash tables** for storing items like `set` or `dictionary`. So there is no order in these objects. But it seems that, for some sequences of numbers that's not true.
For example consider the following examples :
```
>>> set([7,2,5,3,6])
set([2, 3, 5, 6, 7])
>>> set([... | Although there are a lot of questions in SO about `hash` and its order,but no one of them explains the algorithm of hash function.
So all you need here is know that how python calculate the indices in hash table.
If you go through the [`hashtable.c`](https://hg.python.org/cpython/file/661cdbd617b8/Modules/hashtable.c... |
How do you check if the client for a MongoDB instance is valid? | 30,539,183 | 6 | 2015-05-29T21:15:12Z | 30,539,401 | 10 | 2015-05-29T21:31:58Z | [
"python",
"mongodb",
"pymongo"
] | In particular, I am currently trying to check if a connection to a client is valid using the following function:
```
def mongodb_connect(client_uri):
try:
return pymongo.MongoClient(client_uri)
except pymongo.errors.ConnectionFailure:
print "Failed to connect to server {}".format(client_uri)
`... | The `serverSelectionTimeoutMS` keyword parameter of [`pymongo.mongo_client.MongoClient`](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient) controls how long the driver will try to connect to a server. The default value is 30s.
Set it to a very low value compatible wi... |
zsh: no matches found: requests[security] | 30,539,798 | 2 | 2015-05-29T22:06:32Z | 30,539,963 | 9 | 2015-05-29T22:23:08Z | [
"python",
"security",
"python-2.7",
"ssl",
"python-requests"
] | I am trying to run a python urllib2 script and getting this error:
> InsecurePlatformWarning: A true SSLContext object is not available.
> This prevents urllib3 from configuring SSL appropriately and may cause
> certain SSL connections to fail. For more information, see <https://urllib3.readthedocs.org/en/latest/secur... | `zsh` uses [square brackets for globbing / pattern matching](http://zsh.sourceforge.net/Guide/zshguide05.html#l137).
That means that if you need to pass literal square brackets as an argument to a command, you either need to escape them or quote the argument like this:
```
pip install 'requests[security]'
```
If you... |
What's the deal with Python 3.4, Unicode, different languages and Windows? | 30,539,882 | 20 | 2015-05-29T22:14:17Z | 30,540,470 | 9 | 2015-05-29T23:19:25Z | [
"python",
"unicode"
] | Happy examples:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
czech = u'LeoÅ¡ JanáÄek'.encode("utf-8")
print(czech)
pl = u'ZdzisÅaw BeksiÅski'.encode("utf-8")
print(pl)
jp = u'ãªã³ã° å±±æ è²å'.encode("utf-8")
print(jp)
chinese = u'äºè¡'.encode("utf-8")
print(chinese)
MIR = u'ÐаÑина Ð´Ð»Ñ ... | The problem is with the Windows console, which supports an ANSI character set appropriate for the region targeted by your version of Windows. Python throws an exception by default when unsupported characters are output.
Python can read an [environment variable](https://docs.python.org/3.4/using/cmdline.html#envvar-PYT... |
What's the deal with Python 3.4, Unicode, different languages and Windows? | 30,539,882 | 20 | 2015-05-29T22:14:17Z | 30,551,552 | 10 | 2015-05-30T21:26:51Z | [
"python",
"unicode"
] | Happy examples:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
czech = u'LeoÅ¡ JanáÄek'.encode("utf-8")
print(czech)
pl = u'ZdzisÅaw BeksiÅski'.encode("utf-8")
print(pl)
jp = u'ãªã³ã° å±±æ è²å'.encode("utf-8")
print(jp)
chinese = u'äºè¡'.encode("utf-8")
print(chinese)
MIR = u'ÐаÑина Ð´Ð»Ñ ... | **Update:** [Since Python 3.6, the code example that prints Unicode strings directly should just work now (even without `py -mrun`)](http://stackoverflow.com/a/32176732/4279).
---
Python can print text in multiple languages in Windows console whatever `chcp` says:
```
T:\> py -mpip install win-unicode-console
T:\> p... |
Combine List with List of Tuples | 30,542,214 | 3 | 2015-05-30T04:21:22Z | 30,542,266 | 7 | 2015-05-30T04:29:04Z | [
"python",
"list"
] | ```
l1 = [1, 2, 3, 4]
l2 = [(10, 20), (30, 40), (50, 60), (70, 80)]
>>> print(list(zip(l1, l2)))
[(1, (10, 20)), (2, (30, 40)), (3, (50, 60)), (4, (70, 80))]
```
However, I want it to be just a list of four tuples likes this:
```
[(1, 10, 20), (2, 30, 40), (3, 50, 60), (4, 70, 80)]
```
I've also tried:
```
>>> pr... | A more generic way to approach this problem is to consider that both the lists should be scaled up/down to the same dimension as and when required
```
>>> [(a, ) + b for a, b in zip(l1, l2)]
[(1, 10, 20), (2, 30, 40), (3, 50, 60), (4, 70, 80)]
```
As in your example, the second list has an extra dimension in contrast... |
Replace in string based on function ouput | 30,544,912 | 8 | 2015-05-30T10:19:45Z | 30,545,050 | 7 | 2015-05-30T10:35:15Z | [
"python",
"regex"
] | So, for input:
```
accessibility,random good bye
```
I want output:
```
a11y,r4m g2d bye
```
So, basically, I have to abbreviate all words of length greater than or equal to 4 in the following format: `first_letter + length_of_all_letters_in_between + last_letter`
I try to do this:
```
re.sub(r"([A-Za-z])([A-Za-z... | What you are doing in JavaScript is certainly right, you are passing an anonymous function. What you do in Python is to pass a constant expression ("\12\3", since `len(r"\2")` is evaluated before the function call), it is not a function that can be evaluated for each match!
While anonymous functions in Python aren't q... |
"Firefox quit unexpectedly." when running basic Selenium script in Python | 30,549,426 | 13 | 2015-05-30T17:50:43Z | 30,631,120 | 7 | 2015-06-03T21:30:08Z | [
"python",
"html",
"firefox",
"selenium",
"selenium-webdriver"
] | I'm trying to scrape and print the HTML of a page using `Selenium` in `Python`, but every time I run it I get the error message
```
Firefox quit unexpectedly.
```
I'm new to Selenium, so any help would be greatly appreciated. I'm hoping for the simplest fix possible. Thank you!
My code:
```
import selenium
from sel... | My experience since the upgrade to Firefox 38.x on Windows a couple of weeks back has been that it has a problem with Selenium 2.45.x. When invoking the browser it produces a "Firefox has stopped working" error which I have to close manually, at which point the test runs. [Others have reported similar issues](https://g... |
Expanding tuples in list comprehension generator | 30,551,955 | 5 | 2015-05-30T22:22:44Z | 30,551,962 | 7 | 2015-05-30T22:24:26Z | [
"python",
"list",
"tuples",
"list-comprehension"
] | I am using this function
```
def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
return [(getattr(obj, field) for field in fields)
for obj in listobj]
```
My desired output which I want should be
```
[('2am', '5am', 'john'), ('3am', '5am', 'john1'), ('3am', '5am', 'john2') ]
```
The ... | Typecast the gen-exp to a `tuple`
```
def convert_tuple(self, listobj, fields=['start', 'end', 'user']):
return [tuple(getattr(obj, field) for field in fields)
for obj in listobj]
``` |
How do I find and remove white specks from an image using SciPy/NumPy? | 30,551,987 | 5 | 2015-05-30T22:27:53Z | 30,552,076 | 7 | 2015-05-30T22:42:16Z | [
"python",
"image-processing",
"numpy",
"scipy"
] | I have a series of images which serve as my raw data which I am trying to prepare for publication. These images have a series of white specks randomly throughout which I would like to replace with the average of some surrounding pixels.
I cannot post images, but the following code should produce a PNG that approximate... | You could simply try a median filter with a small kernel size,
```
from scipy.ndimage import median_filter
filtered_array = median_filter(random_array, size=3)
```
which will remove the specks without noticeably changing the original image.
A median filter is well suited for such tasks since it will better preserve... |
Is there a way to define list(obj) method on a user defined class in python? | 30,554,643 | 4 | 2015-05-31T06:45:08Z | 30,554,680 | 14 | 2015-05-31T06:51:37Z | [
"python",
"python-3.x"
] | One can can implement the method `__str__(self)` to return a string. Is there an `__list__(self)` counterpart? (`__list__` doesn't work!)
Is .toList() the way to go? | There is no direct counterpart, but `list()` is implemented by iterating over the argument. So implement either [the iterator protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) (`__iter__()`) or [bound indexing](https://docs.python.org/2/reference/datamodel.html#emulating-container-types) (`__len... |
Can't connect to Flask web service, connection refused | 30,554,702 | 5 | 2015-05-31T06:53:47Z | 30,554,831 | 22 | 2015-05-31T07:13:45Z | [
"python",
"flask"
] | I'm trying to run a simple web server on a Raspberry Pi with Flask. When I run my Flask app, it says:
> running on <http://127.0.0.1:5000/>
But when I enter this address on my laptop's in Chrome, I get
> ERR\_CONNECTION\_REFUSED
I can open 127.0.0.1:5000 on the Raspberry Pi's browser. What do I need to do to connec... | Run your app like this:
```
if __name__ == '__main__':
app.run(host='0.0.0.0')
```
It will make the server [externally visible](http://flask.pocoo.org/docs/0.10/quickstart/#public-server). If the IP address of the machine is `192.168.X.X` then, from the same network you can access it in 5000 port. Like, <http://1... |
How can this datetime variable be converted to the string equivalent of this format in python? | 30,557,810 | 3 | 2015-05-31T13:10:46Z | 30,557,844 | 7 | 2015-05-31T13:13:13Z | [
"python",
"python-2.7",
"datetime",
"datetime-format"
] | I am using python 2.7.10
I have a datetime variable which contains `2015-03-31 21:02:36.452000`. I want to convert this datetime variable into a string which looks like `31-Mar-2015 21:02:36`.
How can this be done in python 2.7? | Use strptime to create a datetime object then use strftime to format it they way you want:
```
from datetime import datetime
s= "2015-05-31 21:02:36.452000"
print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S.%f").strftime("%d-%b-%Y %H:%m:%S"))
31-May-2015 21:05:36
```
The format string is the following:
```
%Y Year wit... |
sys_platform is not defined x64 Windows | 30,559,230 | 16 | 2015-05-31T15:35:22Z | 31,061,131 | 7 | 2015-06-25T21:30:10Z | [
"python",
"pip"
] | This has been bugging me for a little while. I recently upgraded to x64 Python, and I started getting this error (example pip install).
```
C:\Users\<uname>\distribute-0.6.35>pip install python-qt
Collecting python-qt
Downloading python-qt-0.50.tar.gz
Building wheels for collected packages: python-qt
Running setup... | 1. Might be a bug. Check out: <https://bugs.python.org/>
2. You can manually check the markers.py file and try to fix it. I think there would a reference to `sys_platform` that has to be changed to `sys.platform`
3. Regarding markerlib, you can try this out-
```
import markerlib
marker = markerlib.compile("sy... |
Multivariate Normal CDF in Python using scipy | 30,560,176 | 5 | 2015-05-31T17:09:19Z | 30,567,633 | 10 | 2015-06-01T07:10:59Z | [
"python",
"scipy",
"normal-distribution",
"cdf"
] | In order to calculate the CDF of a multivariate normal, I followed [this](http://stackoverflow.com/questions/809362/cumulative-normal-distribution-in-python) example (for the univariate case) but cannot interpret the output produced by scipy:
```
from scipy.stats import norm
import numpy as np
mean = np.array([1,5])
c... | After searching a lot, I think [this](http://www.nhsilbert.net/source/2014/04/multivariate-normal-cdf-values-in-python/) blog entry by Noah H. Silbert describes the only readymade code from a standard library that can be used for computing the cdf for a multivariate normal in Python. Scipy has a way to do it but as men... |
how to compare two strings ignoring few characters | 30,562,147 | 2 | 2015-05-31T20:08:12Z | 30,562,224 | 10 | 2015-05-31T20:16:56Z | [
"python"
] | I want to compare two strings in python ignoring some characters, like if the string is:
```
"http://localhost:13555/ChessBoard_x16_y20.bmp"
```
I want to ignore the values `"16"` and `"20"` in the string; no matter what these values are, if the rest of the string is same as this string is then I should get the resul... | Use [regular expressions](https://en.wikipedia.org/wiki/Regular_expression). Here it is for your case. A dot matches any symbol. A \d matches a digit. Some special symbols have to be escaped.
```
import re
if re.match(r'http://localhost:13555/ChessBoard_x\d\d_y\d\d\.bmp', URL):
print("TRUE")
else:
print("FALSE... |
How to call a function from a list? | 30,562,723 | 2 | 2015-05-31T21:09:09Z | 30,562,742 | 8 | 2015-05-31T21:11:59Z | [
"python",
"function"
] | For example, I have the following list:
```
method = [fun1, fun2, fun3, fun4]
```
Then I show a menu where the user must select a number from 1-4 (`len(method)`). If the user selects `i`, I have to use the function `funi`. How can I do that?
Eg.
```
A=['hello','bye','goodbye']
def hello(n):
print n**2
def bye(n):
... | Let's see...
You call a function fn by using parens () as in `fn()`
You access an item from a list by the indexing operator [] as in `lst[idx]`
So, by combining the two `lst[idx](*args)`
EDIT
Python list indices are zero-based, so for the first item is 0, the second 1, etc... If the user selects 1-4, you'll have t... |
How to check if a value is present in any of given sets | 30,571,285 | 14 | 2015-06-01T10:34:52Z | 30,571,340 | 12 | 2015-06-01T10:37:44Z | [
"python",
"set"
] | Say I have different sets (they have to be different, I cannot join them as per the kind of data I am working with):
```
r = set([1,2,3])
s = set([4,5,6])
t = set([7,8,9])
```
What is the best way to check if a given variable is present in either of them?
I am using:
```
if myvar in r \
or myvar in s \
or myv... | You can use builtin [any](https://docs.python.org/2/library/functions.html#any):
```
r = set([1,2,3])
s = set([4,5,6])
t = set([7,8,9])
if any(myvar in x for x in [r,s,t]):
print "I'm in one of them"
```
`any` will short circuit on the first condition that returns `True` so you can get around constructing a poten... |
How to check if a value is present in any of given sets | 30,571,285 | 14 | 2015-06-01T10:34:52Z | 30,571,351 | 12 | 2015-06-01T10:38:05Z | [
"python",
"set"
] | Say I have different sets (they have to be different, I cannot join them as per the kind of data I am working with):
```
r = set([1,2,3])
s = set([4,5,6])
t = set([7,8,9])
```
What is the best way to check if a given variable is present in either of them?
I am using:
```
if myvar in r \
or myvar in s \
or myv... | Just use any:
```
if any(myvar in x for x in (r,s,t))
```
set lookups are `0(1)` so creating a union to check if the variable is in any set is totally unnecessary instead of simply checking using `in` with `any` which will short circuit as soon as a match is found and does not create a new set.
*And I am also wonde... |
get playing wav audio level as output | 30,571,955 | 14 | 2015-06-01T06:27:09Z | 30,672,376 | 7 | 2015-06-05T17:23:32Z | [
"python",
"audio",
"raspberry-pi"
] | I want to make a speaking mouth which moves or emits light or something when a playing wav file emits sound. So I need to detect when a wav file is speaking or when it is in a silence between words. Currently I'm using a pygame script that I have found
```
import pygame
pygame.mixer.init()
pygame.mixer.music.load("my_... | You'll need to inspect the WAV file to work out when the voice is present. The simplest way to do this is look for loud and quiet periods. Because sound works with waves, when it's quiet the values in the wave file won't change very much, and when it's loud they'll be changing a lot.
One way of estimating loudness is ... |
How to train Word2vec on very large datasets? | 30,573,873 | 9 | 2015-06-01T12:46:10Z | 30,655,911 | 19 | 2015-06-04T23:30:18Z | [
"python",
"c",
"machine-learning",
"word2vec"
] | I am thinking of training word2vec on huge large scale data of more than 10 TB+ in size on web crawl dump.
I personally trained c implementation GoogleNews-2012 dump (1.5gb) on my iMac took about 3 hours to train and generate vectors (impressed with speed). I did not try python implementation though :( I read somewher... | There are a number of opportunities to create Word2Vec models at scale. As you pointed out, candidate solutions are distributed (and/or multi-threaded) or GPU. This is not an exhaustive list but hopefully you get some ideas as to how to proceed.
Distributed / Multi-threading options:
* [Gensim](https://radimrehurek.c... |
Find objects with date and time less then 24 hours from now | 30,574,915 | 12 | 2015-06-01T13:31:14Z | 31,477,041 | 11 | 2015-07-17T13:31:39Z | [
"python",
"django",
"django-models",
"django-orm"
] | I have model with two fields:
```
class Event(models.Model):
date = models.DateField(_(u'Date'))
time = models.TimeField(_(u'Time'))
```
I need to find all objects where date&time is in 24 hours from now.
I am able to do this when using DateTime field, but I am not sure how to achieve this when fields are se... | For the simple case (not sure if all are simple cases though...), this should do the trick:
```
import datetime
today = datetime.datetime.now()
tomorrow = today + datetime.timedelta(days=1)
qs_today = queryset.filter(
date=today.date(),
time__gte=today.time(),
)
qs_tomorrow = queryset.filter(
date=tomorr... |
Find objects with date and time less then 24 hours from now | 30,574,915 | 12 | 2015-06-01T13:31:14Z | 31,499,709 | 8 | 2015-07-19T09:19:56Z | [
"python",
"django",
"django-models",
"django-orm"
] | I have model with two fields:
```
class Event(models.Model):
date = models.DateField(_(u'Date'))
time = models.TimeField(_(u'Time'))
```
I need to find all objects where date&time is in 24 hours from now.
I am able to do this when using DateTime field, but I am not sure how to achieve this when fields are se... | As you state you can do what you want with a `DateTimeField`, but now with the separate fields, I understand your issue is how to combine them.
[Looking at the docs for DateField](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.DateField) - your `date` variable is a `datetime.date` instance a... |
Have numpy argsort return an array of 2d indices? | 30,577,375 | 3 | 2015-06-01T15:28:18Z | 30,577,520 | 7 | 2015-06-01T15:34:19Z | [
"python",
"arrays",
"numpy"
] | If we have a 1d array
```
arr = np.random.randint(7, size=(5))
# [3 1 4 6 2]
print np.argsort(arr)
# [1 4 0 2 3] <= The indices in the sorted order
```
If we have a 2d array
```
arr = np.random.randint(7, size=(3, 3))
# [[5 2 4]
# [3 3 3]
# [6 1 2]]
print np.argsort(arr)
# [[1 2 0]
# [0 1 2]
# [1 2 0]] <= It sorts e... | Apply `numpy.argsort` on flattened array and then unravel the indices back to (3, 3) shape:
```
>>> arr = np.array([[5, 2, 4],
[3, 3, 3],
[6, 1, 2]])
>>> np.dstack(np.unravel_index(np.argsort(arr.ravel()), (3, 3)))
array([[[2, 1],
[0, 1],
[2, 2],
[1, 0],
[1, 1],
[1, 2],
... |
Select pandas frame rows based on two columns' values | 30,582,375 | 6 | 2015-06-01T20:11:01Z | 30,582,747 | 8 | 2015-06-01T20:31:45Z | [
"python",
"arrays",
"numpy",
"pandas",
"dataframe"
] | I wish to select some specific rows based on two column values. For example:
```
d = {'user' : [1., 2., 3., 4] ,'item' : [5., 6., 7., 8.],'f1' : [9., 16., 17., 18.], 'f2':[4,5,6,5], 'f3':[4,5,5,8]}
df = pd.DataFrame(d)
print df
Out:
f1 f2 f3 item user
0 9 4 4 5 1
1 16 5 5 6 2
2 17 ... | If you make `samples` a DataFrame with columns `user` and `item`, then you can obtain the desired values with an [inner join](http://pandas.pydata.org/pandas-docs/stable/merging.html#brief-primer-on-merge-methods-relational-algebra). By default, `pd.merge` merges on all columns of `samples` and `df` shared in common --... |
Using coverage, how do I test this line? | 30,582,815 | 15 | 2015-06-01T20:35:56Z | 30,653,523 | 13 | 2015-06-04T20:27:57Z | [
"python",
"django",
"django-testing"
] | I have a simple test:
```
class ModelTests(TestCase):
def test_method(self):
instance = Activity(title="Test")
self.assertEqual(instance.get_approved_member_count(), 0)
```
My problem is that coverage still shows `get_approved_member_count` line as NOT tested:
. But it also shows that it was never defined (line 75 is red).
This is a classic problem of starting coverage too late. The simplest way to fix this is to use coverage to run your test runner, instead of using the test runner to run coverage:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.