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 |
|---|---|---|---|---|---|---|---|---|---|
Can I utilize Pyside clicked.connect to connect a function which has a parameter | 23,846,669 | 2 | 2014-05-24T15:20:58Z | 23,846,817 | 7 | 2014-05-24T15:37:25Z | [
"python",
"function",
"pyside",
"qpushbutton",
"click"
] | I want to have a function in main class which has parameters not only self.
```
class Ui_Form(object):
def clearTextEdit(self, x):
self.plainTextEdit.setPlainText(" ")
print("Script in Textbox is Cleaned!",)
```
x will be my additional parameter and I want clearTextEdit to be called by cli... | ## Solution
This is a perfect place to use a lambda:
```
self.pushButton_3.clicked.connect(lambda: self.clearTextEdit(x))
```
Remember, `connect` expects a function of no arguments, so we have to wrap up the function call in another function.
## Explanation
Your original statement
```
self.pushButton_3.clicked.co... |
pygame circle not changing | 23,847,175 | 6 | 2014-05-24T16:14:08Z | 23,866,641 | 38 | 2014-05-26T09:12:17Z | [
"python",
"pygame",
"mouse",
"fill"
] | I finally got the collision down so that when my mouse is hovering over the circles and you click the left mouse button, It fills in. It changes going up, but going down it doesn't.
Here's my code:
```
# Imports a library of functions!
import pygame
import random
# Initializes the game engine
pygame.init()
# Defines ... | Let's assume that the second one is clicked, so
```
filled_1 = False
filled_2 = True
filled_3 = False
filled_4 = False
```
Then you click the third. Thus,
```
filled_1 = False
filled_2 = True
filled_3 = True
filled_4 = False
```
You then have:
```
screen.fill(GREEN)
circle_1 = pygame.draw.circle(screen, BLACK, [2... |
What is the difference between a stack and a frame? | 23,848,391 | 21 | 2014-05-24T18:32:02Z | 23,849,060 | 25 | 2014-05-24T19:55:44Z | [
"python",
"inspect",
"traceback",
"sys"
] | Under what situations would I want to use one over the other?
What is the difference between:
```
>>> import inspect
>>> print(inspect.getouterframes(inspect.currentframe()))
[(<frame object at 0x8fc262c>, '<stdin>', 1, '<module>', None, None)]
```
And:
```
>>> import traceback
>>> traceback.extract_stack()
[('<std... | Alright, since this appears to be more about what stack frames/call stacks are in general, let's go through this:
```
def f():
try:
g()
except:
# WE WILL DO THINGS HERE
def g():
h()
def h():
raise Exception('stuff')
#CALL
f()
```
When we're in `h()`, there are 4 frames on the [call ... |
numpy np.apply_along_axis function speed up? | 23,849,097 | 7 | 2014-05-24T19:58:43Z | 23,849,233 | 12 | 2014-05-24T20:15:34Z | [
"python",
"numpy"
] | The np.apply\_along\_axis() function seems to be *very* slow (no output after 15 mins). Is there a fast way to perform this function on a long array without having to parallelize the operation? I am specifically talking about arrays of the order of size (millions x 1)
Here is an example of what I am trying to do. Plea... | **`np.apply_along_axis` is not for speed**.
There is no way to apply a **pure Python** function to every element of a Numpy array without calling it that many times, short of AST rewriting...
Fortunately, there are solutions:
* **Vectorizing**
Although this is often hard, it's normally the easy solution. Find som... |
Python ducktyping feels clunky is this Pythonic? | 23,850,971 | 2 | 2014-05-25T00:37:30Z | 23,851,015 | 7 | 2014-05-25T00:46:16Z | [
"python",
"python-3.x",
"duck-typing"
] | Python 3
Data might be a string, bytes or an EmailMessage.
Is this the most effective way to get the bytes out of data?
```
while True:
try:
# data is a string
f.write(data.encode('utf-8'))
break
except:
pass
try:
# data is an Em... | ```
if hasattr(data, "encode"):
f.write(data.encode('utf-8'))
elif hasattr(data, "get_bytes"):
f.write(data.get_bytes())
else:
try:
f.write(data)
except TypeError:
self.log.info('Exiting, unknown attachment type')
sys.exit(1)
```
**Edit:**
This is ducktyping - as in "if it quac... |
Different behaviour of ctypes c_char_p? | 23,852,311 | 6 | 2014-05-25T05:24:43Z | 24,061,473 | 11 | 2014-06-05T13:25:26Z | [
"python",
"python-2.7",
"python-3.x",
"ctypes"
] | I am confused with this behaviour of different versions of python and dont understand why ?
```
Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c="hello"
>>> a=ctypes.c_char_p(c)
>... | `c_char_p` is a subclass of `_SimpleCData`, with `_type_ == 'z'`. The `__init__` method calls the type's `setfunc`, which for simple type `'z'` is `z_set`.
In Python 2, the [`z_set` function](http://hg.python.org/cpython/file/f89216059edf/Modules/_ctypes/cfield.c#l1333) (2.7.7) is written to handle both `str` and `uni... |
Python Pandas: How to read only first n rows of CSV files in? | 23,853,553 | 11 | 2014-05-25T08:50:00Z | 23,853,569 | 16 | 2014-05-25T08:52:50Z | [
"python",
"pandas"
] | I have a very large data set and I can't afford to read the entire data set in. So, I'm thinking of reading only one chunk of it to train but I have no idea how to do it. Any thought will be appreciated. | If you only want to read the first 999,999 (non-header) rows:
```
read_csv(..., nrows=999999)
```
If you only want to read rows 1,000,000 ... 1,999,999
```
read_csv(..., skiprows=1000000, nrows=999999)
```
***nrows*** : int, default None Number of rows of file to read. Useful for
reading pieces of large files\*
**... |
Django finds tests but fail to import them | 23,854,677 | 12 | 2014-05-25T11:12:20Z | 23,854,894 | 19 | 2014-05-25T11:44:11Z | [
"python",
"django",
"testing"
] | I am getting weird errors, where a call to `./manage.py test` will find my tests but complain that they cannot be imported.
## Versions
Python 3.4
Django 1.7b4
## My file structure
looks like this (just the relevant bits):
```
inkasso
âââ db.sqlite3
âââ functional_tests
â  âââ base.py
â ... | Yeah... there's a problem with running `./manage.py`, in that it adds the current directory to the PYTHONPATH.
This problem happens when you put an `__init__.py` inside the root folder.
One solution would be, in this case, to never use `manage.py`, but only `django-admin.py <commands> --settings=inkasso.inkasso.setti... |
Middle point of each pair of an numpy.array | 23,855,976 | 5 | 2014-05-25T13:52:16Z | 23,856,065 | 15 | 2014-05-25T14:01:35Z | [
"python",
"numpy",
"mean"
] | I have an array of the form:
`x = np.array([ 1230., 1230., 1227., 1235., 1217., 1153., 1170.])`
and I would like to produce another array where the values are the mean of each pair of values within my original array:
`xm = np.array([ 1230., 1228.5, 1231., 1226., 1185., 1161.5])`
Someone knows the easiest and fast w... | Even shorter, slightly sweeter:
```
(x[1:] + x[:-1]) / 2
```
---
* **This is faster:**
```
>>> python -m timeit -s "import numpy; x = numpy.random.random(1000000)" "x[:-1] + numpy.diff(x)/2"
100 loops, best of 3: 6.03 msec per loop
>>> python -m timeit -s "import numpy; x = numpy.random.random(1000000)" "(... |
How this operation is called? | 23,857,447 | 2 | 2014-05-25T16:22:21Z | 23,857,486 | 8 | 2014-05-25T16:26:58Z | [
"python"
] | I'm trying to solve a problem that I believe is a standard Python task and has already been asked here, but I don't know the proper vocabulary term for it.
Given the structure
```
((['a'], t1), (['a', 'b', 'c'], t2), (['c', 'd'], t3))
```
and I need to get something like this
```
(('a', [t1, t2]), ('b', [t2]), ('c'... | ```
from collections import defaultdict
in_ = ((["a"], "t1"), (["a","b","c"], "t2"), (["c","d"], "t3"))
out = defaultdict(list)
for keys,val in in_:
for key in keys:
out[key].append(val)
```
which gives
```
{
'a': ['t1', 't2'],
'b': ['t2'],
'c': ['t2', 't3'],
'd': ['t3']
}
```
and I wou... |
Using Python to parse a 12GB CSV | 23,858,244 | 5 | 2014-05-25T17:51:42Z | 23,858,323 | 7 | 2014-05-25T17:59:47Z | [
"python",
"csv",
"bigdata"
] | I have a 12 GB CSV file. I'm hoping to extract only some columns from this data and then write a new CSV that hopefully I can load into R for analysis.
The problem is that I'm getting a memory error when trying to load the entire list at once before writing the new CSV file. How can I parse the data row by row and the... | In R, you can use the `fread` function from the popular [**data.table** package](http://cran.us.r-project.org/package=data.table).
You can use the `drop=` argument to specify columns not to be read -- no memory is allocated for them, and they are not read at all. Or `select=` the columns you want to keep, if that is m... |
How do I setup messaging and session middleware in a Django RequestFactory during unit testing | 23,861,157 | 8 | 2014-05-26T00:15:57Z | 23,861,283 | 10 | 2014-05-26T00:36:30Z | [
"python",
"django",
"unit-testing"
] | I have a function I need to test which takes a request as its argument. It is not exposed as a view by URL so I cannot test it with the test client.
I need to pass a request object to it, and the request object needs to have the messaging middleware enabled because messaging middleware is used in the function.
I am u... | This issue [was raised](https://code.djangoproject.com/ticket/17971), so as there said, you can fix your unit tests using that code:
```
from django.contrib.messages.storage.fallback import FallbackStorage
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages... |
Why is it slower to iterate over a small string than a small list? | 23,861,468 | 128 | 2014-05-26T01:09:13Z | 23,861,518 | 31 | 2014-05-26T01:16:49Z | [
"python",
"performance",
"cpython",
"timeit",
"python-internals"
] | I was playing around with timeit and noticed that doing a simple list comprehension over a small string took longer than doing the same operation on a list of small single character strings. Any explanation? It's almost 1.35 times as much time.
```
>>> from timeit import timeit
>>> timeit("[x for x in 'abc']")
2.06910... | When you iterate over most container objects (lists, tuples, dicts, ...), the iterator delivers the objects *in* the container.
But when you iterate over a string, a *new* object has to be created for each character delivered - a string is not "a container" in the same sense a list is a container. The individual chara... |
Why is it slower to iterate over a small string than a small list? | 23,861,468 | 128 | 2014-05-26T01:09:13Z | 23,864,108 | 193 | 2014-05-26T06:37:07Z | [
"python",
"performance",
"cpython",
"timeit",
"python-internals"
] | I was playing around with timeit and noticed that doing a simple list comprehension over a small string took longer than doing the same operation on a list of small single character strings. Any explanation? It's almost 1.35 times as much time.
```
>>> from timeit import timeit
>>> timeit("[x for x in 'abc']")
2.06910... | # TL;DR
* The actual speed difference is closer to 70% (or more) once a lot of the overhead is removed, for Python 2.
* Object creation is **not** at fault. Neither method creates a new object, as one-character strings are cached.
* The difference is unobvious, but is likely created from a greater number of checks on ... |
filter items in a python dictionary where keys contain a specific string | 23,862,406 | 33 | 2014-05-26T03:46:05Z | 23,862,438 | 59 | 2014-05-26T03:49:52Z | [
"python",
"python-2.7",
"dictionary",
"filtering"
] | I'm a C coder developing something in python. I know how to do the following in C (and hence in C-like logic applied to python), but I'm wondering what the 'Python' way of doing it is.
I have a dictionary d, and I'd like to operate on a subset of the items, only those who's key (string) contains a specific substring.
... | How about a [dict comprehension](http://www.python.org/dev/peps/pep-0274/):
```
filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}
```
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only [`dict.... |
filter items in a python dictionary where keys contain a specific string | 23,862,406 | 33 | 2014-05-26T03:46:05Z | 23,862,592 | 8 | 2014-05-26T04:14:40Z | [
"python",
"python-2.7",
"dictionary",
"filtering"
] | I'm a C coder developing something in python. I know how to do the following in C (and hence in C-like logic applied to python), but I'm wondering what the 'Python' way of doing it is.
I have a dictionary d, and I'd like to operate on a subset of the items, only those who's key (string) contains a specific substring.
... | Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:
```
for key, val in d.ite... |
How to write multiple conditions of if-statement in robot framework | 23,863,264 | 5 | 2014-05-26T05:28:01Z | 23,870,640 | 14 | 2014-05-26T12:52:48Z | [
"python",
"python-2.7",
"selenium",
"robotframework"
] | I am having troubles with writing if conditions in robot framework.
I want to execute
```
Run Keyword If '${color}' == 'Red' OR '${color}' == 'Blue' OR '${color}' == 'Pink' Check the quantity
```
I can use this "`Run keyword If`" keyword with one condition, but for more than one conditions, I got this error, `FA... | you should use small caps "or" and "and" instead of OR and AND.
And beware also the spaces/tabs between keywords and arguments (you need at least 2 spaces).
Here is a code sample with your 3 keywords working fine:
Here is the file ts.txt:
```
*** test cases ***
mytest
${color} = set variable Red
Run Key... |
How to implement efficient filtering logic in Python? | 23,866,442 | 7 | 2014-05-26T09:01:04Z | 23,866,627 | 10 | 2014-05-26T09:11:54Z | [
"python",
"filter",
"sqlite3",
"pyqt",
"logic"
] | I am trying to create a program that stores
1. Fruit Name
2. Fruit Type
3. Fruit Color
4. Fruit Size
and show them back to the user upon request. The user will be given pre-defined choices to select from. Something like this:

My database table will... | I'd use [SQLAlchemy](http://www.sqlalchemy.org/) here to handle the database layer, either using it [as an ORM](http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html) or just to [generate the SQL expressions](http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html).
This lets you generate the filters dynamically; y... |
Filter list of strings, ignoring substrings of other items | 23,868,093 | 18 | 2014-05-26T10:28:56Z | 23,868,429 | 8 | 2014-05-26T10:49:12Z | [
"python",
"string",
"algorithm"
] | How can I filter through a list which containing strings and substrings to return only the longest strings. (If any item in the list is a substring of another, return only the longer string.)
I have this function. Is there a faster way?
```
def filterSublist(lst):
uniq = lst
for elem in lst:
uniq = [x... | A simple quadratic time solution would be this:
```
res = []
n = len(lst)
for i in xrange(n):
if not any(i != j and lst[i] in lst[j] for j in xrange(n)):
res.append(lst[i])
```
But we can do much better:
Let `$` be a character that does not appear in any of your strings and has a lower value than all you... |
How to setup Django project in PyCharm | 23,870,365 | 19 | 2014-05-26T12:38:51Z | 23,870,582 | 9 | 2014-05-26T12:50:11Z | [
"python",
"django",
"pycharm"
] | I'm new in this area so I have a question. Recently I started working with Python and Django. I installed PyCharm Community edition as my IDE, but I'm unable create Django project. I looked for some tutorials, and there is option te select "project type", but in latest version this option is missing. Can someone tell m... | If you look at the [features edition comparison matrix](http://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html), you will see that only *Pycharm* *professional* supports the *Django Framework*.
You can setup a project from the command line using the manage.py script and just open it in Pycharm. Then... |
How to setup Django project in PyCharm | 23,870,365 | 19 | 2014-05-26T12:38:51Z | 31,285,942 | 16 | 2015-07-08T07:18:50Z | [
"python",
"django",
"pycharm"
] | I'm new in this area so I have a question. Recently I started working with Python and Django. I installed PyCharm Community edition as my IDE, but I'm unable create Django project. I looked for some tutorials, and there is option te select "project type", but in latest version this option is missing. Can someone tell m... | You can simply go to:
```
In Run -> Edit Configurations create new configuration
Script: path_to/manage.py
Script parameters: runserver
``` |
sklearn and large datasets | 23,872,942 | 10 | 2014-05-26T15:00:08Z | 33,456,225 | 7 | 2015-10-31T20:26:13Z | [
"python",
"bigdata",
"scikit-learn"
] | I have a dataset of 22 GB. I would like to process it on my laptop. Of course I can't load it in memory.
I use a lot sklearn but for much smaller datasets.
In this situations the classical approach should be something like.
Read only part of the data -> Partial train your estimator -> delete the data -> read other p... | I've used several scikit-learn classifiers with out-of-core capabilities to train linear models: Stochastic Gradient, Perceptron and Passive Agressive and also Multinomial Naive Bayes on a Kaggle dataset of over 30Gb. All these classifiers share the partial\_fit method which you mention. Some behave better than others ... |
Force NumPy ndarray to take ownership of its memory in Cython | 23,872,946 | 7 | 2014-05-26T15:00:15Z | 23,873,586 | 10 | 2014-05-26T15:40:08Z | [
"python",
"arrays",
"numpy",
"cython"
] | Following [this answer to "Can I force a numpy ndarray to take ownership of its memory?"](https://stackoverflow.com/a/18312855/396967) I attempted to use the Python C API function `PyArray_ENABLEFLAGS` through Cython's NumPy wrapper and found it is not exposed.
The following attempt to expose it manually (this is just... | You just have some minor errors in the interface definition. The following worked for me:
```
from libc.stdlib cimport malloc
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.int32_t DTYPE_t
cdef extern from "numpy/arrayobject.h":
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
cdef dat... |
How to use const in Cython | 23,873,652 | 4 | 2014-05-26T15:44:08Z | 23,875,037 | 8 | 2014-05-26T17:23:04Z | [
"python",
"const",
"cython"
] | I have read in this link: <https://github.com/cython/cython/wiki/FAQ#id35> that my Cython 0.20.1 should be able to support const.
However my following code does not compile:
```
cdef const double a = 2.5
print(a)
```
During compilation it says
```
test.pyx:5:5: Assignment to const 'a'
Traceback (most recent call la... | `const` works for function arguments, but not for this construct because of how Cython compiles it to C.
```
cdef double a = 2.5
```
becomes
```
double __pyx_v_a;
/* lots of other declarations */
__pyx_v_a = 2.5;
```
and this wouldn't work with a `const` variable. In effect, you cannot use `const` in Cython in all... |
Interpolating a peak for two values of x - Python | 23,874,295 | 5 | 2014-05-26T16:25:35Z | 23,880,302 | 7 | 2014-05-27T02:41:07Z | [
"python",
"numpy",
"interpolation"
] | I want to find two values of `x` that intersect a certain value of `y` on a `x-y` plot of a resonance curve. However, as I have few data points I will need to interpolate to find these values of `x`.
The curve I am looking at can be seen below:

How d... | Prepare curve data:
```
from numpy import *
import pylab as pl
import numpy as np
import scipy as scipy
from scipy import optimize
#Get data
fn = '13AMJ92.txt'
F_values, S_values, P_values = loadtxt(fn, unpack=True, usecols=[1, 2, 3])
#Select Frequency range of peak
lower = 4.995
upper = 5.002
F_values_2 = F_values[... |
Using JSON Type with Flask-sqlalchemy & Postgresql | 23,878,070 | 13 | 2014-05-26T21:39:48Z | 23,881,480 | 10 | 2014-05-27T05:12:26Z | [
"python",
"json",
"postgresql",
"flask",
"flask-sqlalchemy"
] | **Background:** I am building a Flask App and I have stored my data into a postgresql database and within a JSON column type.
**Task:** In my view functions, I would like to order a database query by {Key:Value} from JSON column
**Accomplished**: I have been successful in performing this query at the psql command-lin... | Looking at [the SQLAlchemy documentation for the JSON data type](http://docs.sqlalchemy.org/en/rel_0_9/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON) it appears that you should be able to use the `.cast` method:
```
from sqlalchemy.types import Integer
from app import app, db
from models import Target ... |
Argument Unpacking wastes Stack Frames | 23,879,319 | 26 | 2014-05-27T00:21:46Z | 24,092,157 | 17 | 2014-06-06T23:46:19Z | [
"python",
"recursion",
"cpython",
"python-internals"
] | When a function is called by unpacking arguments, it seems to increase the recursion depth twice. I would like to know *why* this happens.
Normally:
```
depth = 0
def f():
global depth
depth += 1
f()
try:
f()
except RuntimeError:
print(depth)
#>>> 999
```
With an unpacking call:
```
depth = 0... | The exception *message* actually offers you a hint. Compare the non-unpacking option:
```
>>> import sys
>>> sys.setrecursionlimit(4) # to get there faster
>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
File "<stdin>", line 1, in... |
filter a list in Python, then unfilter it | 23,880,076 | 4 | 2014-05-27T02:10:24Z | 23,880,234 | 8 | 2014-05-27T02:31:20Z | [
"python"
] | I have a list of items in Python (v2.7 but a v2/v3 compatible solution would be nice), e.g.:
```
a = [1,6,5,None,5,None,None,1]
```
I'd like to filter out the None values, and then do something with the resulting list, e.g.:
```
b = [x for x in a if x is not None]
c = f(b)
```
Then I'd like to put the None values b... | Here's a simple solution that seems to do the trick:
```
>>> a = [1,6,5,None,5,None,None,1]
>>> b = [x for x in a if x is not None]
>>> c = [2,12,10,10,2] # just an example
>>>
>>> v = iter(c)
>>> [None if x is None else next(v) for x in a]
[2, 12, 10, None, 10, None, None, 2]
``` |
matplotlib hist() autocropping range | 23,887,410 | 6 | 2014-05-27T10:46:38Z | 23,888,091 | 8 | 2014-05-27T11:20:59Z | [
"python",
"matplotlib",
"range",
"histogram"
] | I am trying to make a histgram over a specific range but the matplotlib.pyplot.hist() function keeps cropping the range to the bins with entries in them. A toy example:
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(-100,100,1000)
nbins = 100
xmin = -500
xmax = 500
fig = plt.figure(); ... | Actually, it works if you specify with `range` an interval shorter than `[-100, 100]`. For example, this work :
```
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(-100, 100, 1000)
plt.hist(x, bins=30, range=(-50, 50))
plt.show()
```
If you want to plot the histogram on a range larger than `... |
How to repeat Pandas data frame? | 23,887,881 | 7 | 2014-05-27T11:09:41Z | 23,887,956 | 15 | 2014-05-27T11:13:48Z | [
"python",
"pandas",
"duplicates",
"dataframe",
"repeat"
] | This is my data frame that should be repeated for 5 times:
```
>>> x = pd.DataFrame({'a':1,'b':2},index = range(1))
>>> x
a b
0 1 2
```
I wanna have the result like this:
```
>>> x.append(x).append(x).append(x)
a b
0 1 2
0 1 2
0 1 2
0 1 2
```
But there must be a way smarter than keep appending.. A... | You can use the `concat` function:
```
In [13]: pd.concat([x]*5)
Out[13]:
a b
0 1 2
0 1 2
0 1 2
0 1 2
0 1 2
```
If you only want to repeat the values and not the index, you can do:
```
In [14]: pd.concat([x]*5, ignore_index=True)
Out[14]:
a b
0 1 2
1 1 2
2 1 2
3 1 2
4 1 2
``` |
Catching exceptions based on their abstract base class | 23,890,645 | 7 | 2014-05-27T13:24:11Z | 23,891,850 | 7 | 2014-05-27T14:14:05Z | [
"python",
"exception",
"abstract-base-class"
] | Suppose I've got an exception class with an abstract base class, something like this:
```
class MyExceptions(BaseExeption, metaclass=abc.ABCMeta):
pass
class ProperSubclass(MyExceptions):
pass
MyExceptions.register(ValueError)
```
It appears that I can catch `ProperSubclass` by `MyExceptions`, but not `Valu... | The [documentation](https://docs.python.org/3.4/reference/compound_stmts.html#try) says:
> An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.
Unfortunately, this doesn't say whether virtual base classes shou... |
scrapy item loader return list not single value | 23,894,139 | 6 | 2014-05-27T16:09:41Z | 23,894,270 | 13 | 2014-05-27T16:16:33Z | [
"python",
"python-2.7",
"web-scraping",
"scrapy"
] | I am using scrapy 0.20.
I want to use item loader
this is my code:
```
l = XPathItemLoader(item=MyItemClass(), response=response)
l.add_value('url', response.url)
l.add_xpath('title',"my xpath")
l.add_xpath('developer', "my xpath")
return l.load_item()
```
I got the result in the json file. ... | You need to set an [Input or Output processor](http://doc.scrapy.org/en/latest/topics/loaders.html#declaring-input-and-output-processors). [`TakeFirst`](http://doc.scrapy.org/en/latest/topics/loaders.html#scrapy.contrib.loader.processor.TakeFirst) would work perfectly in your case.
There are multiple places where you ... |
upload file to my dropbox from python script | 23,894,221 | 21 | 2014-05-27T16:14:06Z | 23,895,259 | 36 | 2014-05-27T17:13:58Z | [
"python",
"upload",
"dropbox"
] | I want to upload a file from my python script to my dropbox account automatically. I can't find anyway to do this with just a user/pass. Everything I see in the Dropbox SDK is related to an app having user interaction. I just want to do something like this:
<https://api-content.dropbox.com/1/files_put/>/?user=me&pass=... | Thanks to @smarx for the answer above! I just wanted to clarify for anyone else trying to do this.
1. Make sure you install the dropbox module first of course, `pip install dropbox`.
2. Create an app under your own dropbox account in the "App Console". (<https://www.dropbox.com/developers/apps>)
3. Just for the record... |
Installing M2Crypto 0.20.1 on Python 2.6 on Ubuntu 14.04 | 23,895,210 | 4 | 2014-05-27T17:11:11Z | 23,987,407 | 18 | 2014-06-02T04:35:41Z | [
"python",
"ubuntu"
] | I need to compile and install M2Crypto 0.20.1 from source for Python 2.6 on Ubuntu 14.04. I can't migrate to Python2.7 right now but we're planning so. I installed Python2.6 from <https://launchpad.net/~fkrull/+archive/deadsnakes>. I have installed libssl-dev and python2.6-dev, file /usr/include/x86\_64-linux-gnu/opens... | The path is wrong. Try to do this:
```
cd /usr/include/openssl/
ln -s ../x86_64-linux-gnu/openssl/opensslconf.h .
``` |
Why does seek return None in python? | 23,896,186 | 2 | 2014-05-27T18:10:57Z | 23,896,240 | 8 | 2014-05-27T18:13:07Z | [
"python",
"seek"
] | The [doc](https://docs.python.org/2/library/io.html#io.IOBase.seek) clearly says:
> Return the new absolute position.
However, `seek` appears to return `None` (same behavior also on Linux):
```
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help"... | You are reading the *wrong documentation*. You need to look at [`file.seek()`](https://docs.python.org/2/library/stdtypes.html#file.seek) when using Python 2:
> There is no return value.
Using [`io.open()`](https://docs.python.org/2/library/io.html#io.open) is fine, and if you do, you'll get a *different* object, who... |
Different Results in Go and Pycrypto when using AES-CFB | 23,897,809 | 7 | 2014-05-27T19:54:35Z | 23,899,604 | 8 | 2014-05-27T21:53:57Z | [
"python",
"encryption",
"go",
"pycrypto"
] | I am adding a go application to an already existing python codebase. I've been having trouble dealing with encryption between the languages. This is using go 1.2.1 and Python 2.7.x / PyCrypto 2.7a1.
Here is the Python sample:
```
import Crypto.Cipher
import Crypto.Hash.HMAC
import Crypto.Hash.SHA256
import Crypto.Pub... | Research on the current system has revealed that our python system uses CFB8 (8 bit segments). Go does not support this out of the box, but the source code used in the current CFBDecrypter / CFBEncrypter looks like it can be adapted fairly easily. |
Why does this xpath fail using lxml in python? | 23,900,348 | 4 | 2014-05-27T23:06:17Z | 23,903,927 | 8 | 2014-05-28T06:05:28Z | [
"python",
"xml",
"xpath",
"lxml"
] | Here is an example web page I am trying to get data from.
<http://www.makospearguns.com/product-p/mcffgb.htm>
The xpath was taken from chrome development tools, and firepath in firefox is also able to find it, but using lxml it just returns an empty list for 'text'.
```
from lxml import html
import requests
site_url... | # 1. Browsers frequently change the HTML
Browsers quite frequently change the HTML served to it to make it "valid". For example, if you serve a browser this invalid HTML:
```
<table>
<p>bad paragraph</p>
<tr><td>Note that cells and rows can be unclosed (and valid) in HTML
</table>
```
To render it, the browser i... |
How do I insert a JPEG image into a python Tkinter window? | 23,901,168 | 2 | 2014-05-28T00:38:54Z | 23,905,585 | 7 | 2014-05-28T07:43:32Z | [
"python",
"image",
"tkinter",
"window",
"jpeg"
] | How do I insert a **JPEG** image into a python Tkinter window? This is my code so far.... Please help me! Please fix the code and paste it below! Also, if possible, that would be **awesome** if you could add comments to show what you are doing... Thanks! What is wrong with the following code? (*The image is called Aaro... | Try this:
```
import Tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter ex... |
How can I unpack four variables from a list? | 23,901,266 | 2 | 2014-05-28T00:51:43Z | 23,901,303 | 8 | 2014-05-28T00:57:46Z | [
"python",
"python-2.7"
] | I have this list:
```
varlist = ['1', 'King', 't', '1']
```
I'm trying to unpack these four variables in a `for` loop;
```
for var1, var2, var3, var4 in varlist:
post += len(var1)-len(var3)
post *= len(var2)/len(var4)
```
When I run this loop, I get the following:
```
ValueError: need more than 1 value to ... | Unpacking is different from iteration. You need to do this:
```
var1, var2, var3, var4 = varlist
post += len(var1)-len(var3)
post *= len(var2)/len(var4)
```
No loop is needed here. |
pip install broken (pkg_resources.find_distribution returns empty list in req.py-prepare_files) | 23,901,687 | 7 | 2014-05-28T01:57:52Z | 26,882,153 | 15 | 2014-11-12T08:15:28Z | [
"python",
"install",
"pip"
] | At some point my pip installation broke (I suspect when upgrading to Ubuntu 14.04) and I haven't been able to unbreak it by completely removing it and reinstalling (via synaptic package manager). It doesn't occur for all packages but for a few common ones such as autopep8 and even setuptools itself.
The error I am get... | This fixes the problem:
`pip install --no-use-wheel --upgrade distribute` |
Tornado Get Reference to Instance Variable in RequestHandler | 23,902,532 | 6 | 2014-05-28T03:51:42Z | 23,902,588 | 10 | 2014-05-28T03:57:58Z | [
"python",
"tornado"
] | In writing a tornado Http Server, I am having trouble with accessing an instance variable in my main class, which contains the tornado application object as well as start method, from a separate RequestHandler object. Consider the following crude example,
```
class MyServer(object):
def __init__(self):
se... | When you create your `Application` object, you can pass your `ref_object` instance to `SomeHandler` by placing it in a dict as a third argument to the tuple normally used to define the handler. So, in `MyServer.__init__`:
```
self.application = tornado.web.Application([
(r"/test", SomeHandler, {"ref_object" : self... |
Finding unique tuples | 23,903,819 | 4 | 2014-05-28T05:58:29Z | 23,903,864 | 13 | 2014-05-28T06:01:32Z | [
"python",
"tuples"
] | I want to find unique tuples based upon the following situation:
This is my data:
```
data = [
(1L, u'ASN', u'Mon', u'15:15:00'),
(2L, u'ASN', u'Tue', u'15:15:00'),
(3L, u'ASN', u'Wed', u'15:15:00'),
(5L, u'ASN', u'Fri', u'15:15:00'),
(7L, u'ASN', u'Sun', u'15:15:00'),
(15L, u'ASN', 'Rem... | Put them in a dict, keyed by the parts you want to be unique.
```
uniq = {d[1:]:d for d in data}
uniq = uniq.values()
```
The above will return the last of any data items that are non-unique. If you want the first instead, you can reverse the initial list.
If you only need to use a part of the data after finding the... |
numpy: efficiently summing with index arrays | 23,905,817 | 5 | 2014-05-28T07:56:15Z | 23,914,036 | 8 | 2014-05-28T14:10:45Z | [
"python",
"numpy"
] | Suppose I have 2 matrices M and N (both have > 1 columns). I also have an index matrix I with 2 columns -- 1 for M and one for N. The indices for N are unique, but the indices for M may appear more than once. The operation I would like to perform is,
```
for i,j in w:
M[i] += N[j]
```
Is there a more efficient way ... | For completeness, in numpy >= 1.8 you can also use `np.add`'s `at` method:
```
In [8]: m, n = np.random.rand(2, 10)
In [9]: m_idx, n_idx = np.random.randint(10, size=(2, 20))
In [10]: m0 = m.copy()
In [11]: np.add.at(m, m_idx, n[n_idx])
In [13]: m0 += np.bincount(m_idx, weights=n[n_idx], minlength=len(m))
In [14]... |
Log-log lmplot with seaborn | 23,913,151 | 6 | 2014-05-28T13:34:42Z | 23,918,246 | 15 | 2014-05-28T17:32:58Z | [
"python",
"seaborn"
] | Can the function `lmplot` from Seaborn plot on a log-log scale?
This is lmplot on a normal scale
```
import numpy as np
import pandas as pd
import seaborn as sns
x = 10**arange(1, 10)
y = 10** arange(1,10)*2
df1 = pd.DataFrame( data=y, index=x )
df2 = pd.DataFrame(data = {'x': x, 'y': y})
sns.lmplot('x', 'y', df2)
`... | If you just want to plot a simple regression, it will be easier to use `seaborn.regplot`. This seems to work (although I'm not sure where the y axis minor grid goes)
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
x = 10 ** np.arange(1, 10)
y = x * 2
data = pd.DataFram... |
Python 2.7: making a dictionary object from a specially-formatted list object | 23,914,774 | 4 | 2014-05-28T14:43:52Z | 23,914,855 | 7 | 2014-05-28T14:46:59Z | [
"python",
"list",
"python-2.7",
"dictionary"
] | I have a list type object like:
```
f = [77.0, 'USD', 77.95,
103.9549, 'EUR', 107.3634,
128.1884, 'GBP', 132.3915,
0.7477, 'JPY', 0.777]
```
I want to create a dictionary like below:
```
d =
{'EUR': [103.9549, 107.3634],
'GBP': [128.1884, 132.3915],
'JPY': [0.7477, 0.777],
'USD': [77.0, 77.95]}... | How about:
```
In [5]: {f[i+1]: [f[i], f[i+2]] for i in range(0, len(f), 3)}
Out[5]:
{'EUR': [103.9549, 107.3634],
'GBP': [128.1884, 132.3915],
'JPY': [0.7477, 0.777],
'USD': [77.0, 77.95]}
``` |
python: can't open file 'django-admin.py': [Errno 2] No such file or directory | 23,915,661 | 7 | 2014-05-28T15:20:38Z | 23,915,848 | 18 | 2014-05-28T15:27:44Z | [
"python",
"django"
] | I have a mac and I am starting to work on django. When I try to make a project on the terminal by writing
```
python django-admin.py startproject myproject
```
I get this error
```
python: can't open file 'django-admin.py': [Errno 2] No such file or directory
```
While I was looking around for help, one solution su... | You're confusing two ways of referring to an executable file.
`/usr/local/bin` is in your path, and `django-admin.py` is marked as executable, so you can refer to it without the initial `python`:
```
django-admin.py startproject myproject
```
When you start with `python`, that is saying "start Python with the script... |
Celery parallel distributed task with multiprocessing | 23,916,413 | 28 | 2014-05-28T15:53:27Z | 23,949,584 | 7 | 2014-05-30T07:48:48Z | [
"python",
"django",
"multithreading",
"multiprocessing",
"celery"
] | I have a CPU intensive Celery task. I would like to use all the processing power (cores) across lots of EC2 instances to get this job done faster **(a celery parallel distributed task with multiprocessing - *I think*)**.
The terms, **threading**, **multiprocessing**, **distributed computing**, **distributed parallel p... | Why not use `group` celery task for this?
<http://celery.readthedocs.org/en/latest/userguide/canvas.html#groups>
Basically, you should divide `ids` into chunks (or ranges) and give them to a bunch of tasks in `group`.
For smth more sophisticated, like aggregating results of particular celery tasks, I have successful... |
Celery parallel distributed task with multiprocessing | 23,916,413 | 28 | 2014-05-28T15:53:27Z | 24,019,415 | 50 | 2014-06-03T15:43:50Z | [
"python",
"django",
"multithreading",
"multiprocessing",
"celery"
] | I have a CPU intensive Celery task. I would like to use all the processing power (cores) across lots of EC2 instances to get this job done faster **(a celery parallel distributed task with multiprocessing - *I think*)**.
The terms, **threading**, **multiprocessing**, **distributed computing**, **distributed parallel p... | Your goals are:
1. Distribute your work to many machines (distributed
computing/distributed parallel processing)
2. Distribute the work on a given machine across all CPUs
(multiprocessing/threading)
Celery can do both of these for you fairly easily. The first thing to understand is that each celery worker is [c... |
Clean list of strings that are included on the own strings | 23,916,585 | 3 | 2014-05-28T16:02:35Z | 23,920,049 | 7 | 2014-05-28T19:14:26Z | [
"python",
"string",
"bash",
"list",
"shell"
] | I have a text-file, `lists.txt`, that looks like this:
```
HI family what are u doing ?
HI Family
what are
Channel 5 is very cheap
Channel 5 is
Channel 5 is very
Pokemon
The best Pokemon is Pikachu
```
I want to clean it up, removing any lines that are completely included inside other lines. That is, I want something... | If I understand your question correctly, you want to take a list of strings and remove from it any strings that are substrings of other strings in the list.
In pseudo-code,
```
outer: for string s in l
for string s2 in l
if s substringOf s2
continue outer
print s
```
i.e. loop through the... |
Switching to Python 3 causing UnicodeDecodeError | 23,917,729 | 7 | 2014-05-28T17:02:03Z | 23,917,799 | 18 | 2014-05-28T17:06:23Z | [
"python",
"python-3.x",
"encoding"
] | I've just added Python3 interpreter to Sublime, and the following code stopped working:
```
for directory in directoryList:
fileList = os.listdir(directory)
for filename in fileList:
filename = os.path.join(directory, filename)
currentFile = open(filename, 'rt')
for line in currentFile:... | Python 3 *decodes* text files when reading. The default encoding is taken from [`locale.getpreferredencoding(False)`](https://docs.python.org/3/library/locale.html#locale.getpreferredencoding), which evidently for your setup returns `'ASCII'`. See the [`open()` function documenation](https://docs.python.org/3/library/f... |
How do I get the return value when using Python exec on the code object of a function? | 23,917,776 | 11 | 2014-05-28T17:04:17Z | 23,917,810 | 10 | 2014-05-28T17:07:02Z | [
"python",
"function",
"return",
"exec"
] | For testing purposes I want to directly execute a function defined inside of another function.
I can get to the code object of the child function, through the code (func\_code) of the parent function, but when I exec it, i get no return value.
Is there a way to get the return value from the exec'ed code? | Yes, you need to have the assignment within the `exec` statement:
```
>>> def foo():
... return 5
...
>>> exec("a = foo()")
>>> a
5
```
This probably isn't relevant for your case since its being used in controlled testing, but *be careful with using `exec` with user defined input.* |
Django REST Framework and FileField absolute url | 23,918,619 | 12 | 2014-05-28T17:54:29Z | 23,918,960 | 19 | 2014-05-28T18:14:18Z | [
"python",
"django",
"url",
"filefield"
] | I've defined a simple Django app that includes the following model:
```
class Project(models.Model):
name = models.CharField(max_length=200)
thumbnail = models.FileField(upload_to='media', null=True)
```
(Technically yes, that could have been an ImageField.)
In a template, it's easy enough to include the MED... | Try [SerializerMethodField](http://www.django-rest-framework.org/api-guide/fields#serializermethodfield)
Example (untested):
```
class MySerializer(serializers.ModelSerializer):
thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')
def get_thumbnail_url(self, obj):
return self.contex... |
Django REST Framework and FileField absolute url | 23,918,619 | 12 | 2014-05-28T17:54:29Z | 23,919,612 | 8 | 2014-05-28T18:51:21Z | [
"python",
"django",
"url",
"filefield"
] | I've defined a simple Django app that includes the following model:
```
class Project(models.Model):
name = models.CharField(max_length=200)
thumbnail = models.FileField(upload_to='media', null=True)
```
(Technically yes, that could have been an ImageField.)
In a template, it's easy enough to include the MED... | Thanks, shavenwarthog. Your example and documentation reference helped enormously. My implementation is slightly different, but very close to what you posted:
```
from SomeProject import settings
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
thumbnail_url = serializers.SerializerMethodField('g... |
Cx-Freeze Error - Python 34 | 23,920,073 | 11 | 2014-05-28T19:15:39Z | 23,970,652 | 18 | 2014-05-31T13:34:21Z | [
"python",
"python-3.x",
"cx-freeze"
] | I have a Cx\_Freeze setup file that I am trying to make work. What is terribly frustrating is that it *used* to Freeze appropriately. Now, however, I get the following error:
> > edit. the error that shows up is not a Python exception through the console, but a crash report when attempting to launch the resulting exe ... | You should install cx\_freeze from this [site](http://www.lfd.uci.edu/~gohlke/pythonlibs/#cx_freeze). It contains an important patch that solves the problem (see [this](https://groups.google.com/forum/#!msg/comp.lang.python/Ubagx7NDtJE/_47ZP2Uj-BUJ) discussion for detailed). |
Pillow resize pixelating images - Django/Pillow | 23,921,745 | 2 | 2014-05-28T20:58:43Z | 23,936,340 | 8 | 2014-05-29T14:56:08Z | [
"python",
"django",
"image",
"python-imaging-library",
"pillow"
] | I am developing an image uploader in Django. After the image has been uploaded and saved on disk,
I'm trying to resize the saved image while maintaing it's aspect ratio. I am using Pillow for image processing/resizing. The problem arises when I try to resize the image , it's getting pixelated even though the resized im... | With this code I get this image (Python 2.7, Pillow 2.4.0) which has no pixelating.
```
from PIL import Image
large_size = (1920, 1200)
im = Image.open("babu_980604.jpeg")
image_w, image_h = im.size
aspect_ratio = image_w / float(image_h)
new_height = int(large_size[0] / aspect_ratio)
if new_height < 1200:
fin... |
Draw arrow outside plot in Matplotlib | 23,922,804 | 5 | 2014-05-28T22:17:51Z | 23,923,096 | 8 | 2014-05-28T22:46:05Z | [
"python",
"matplotlib"
] | I have the following gridded plot, and would like to draw an arrow (shown in blue using MS paint). How can I do it through matplotlib? I do not know of any command to do it.
 | ```
import matplotlib.pyplot as plt
fg = plt.figure(1);
fg.clf();
ax = fg.add_subplot(1,1,1)
ax.annotate('', xy=(0, -0.1), xycoords='axes fraction', xytext=(1, -0.1),
arrowprops=dict(arrowstyle="<->", color='b'))
ax.grid(True)
fg.canvas.draw()
```
gives  python | 23,923,496 | 2 | 2014-05-28T23:30:49Z | 23,923,557 | 9 | 2014-05-28T23:38:57Z | [
"python",
"python-2.7"
] | Let's consider a list of large integers, for example one given by:
```
def primesfrom2to(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)... | Look at the types of your results. You are summing a numpy array, which is using numpy datatypes, which can overflow. When you do `sum(a[:20043])`, you get a numpy object back (some sort of `int32` or the like), which overflows when added to another number. When you manually type in the same number, you're creating a P... |
Get the text from multiple elements with the same class in Selenium for Python? | 23,924,008 | 2 | 2014-05-29T00:36:02Z | 23,924,280 | 7 | 2014-05-29T01:14:42Z | [
"python",
"selenium",
"xpath",
"selenium-webdriver",
"webdriver"
] | I'm trying to scrape data from a page with JavaScript loaded content. For example, the content I want is in the following format:
```
<span class="class">text</span>
...
<span class="class">more text</span>
```
I used the `find_element_by_xpath(//span[@class="class"]').text` function but it only returned the first in... | `find_element_by_xpath` returns one element, which has `text` attribute.
`find_elements_by_xpath()` returns all matching elements, which is a list, so you need to loop through and get `text` attribute for each of the element.
```
all_spans = driver.find_elements_by_xpath("//span[@class='class']")
for span in all_span... |
Django: relation "django_site" does not exist | 23,925,726 | 5 | 2014-05-29T04:31:21Z | 34,274,950 | 13 | 2015-12-14T19:21:19Z | [
"python",
"django"
] | I am running a test django server on aws and I just installed django-userena and when I try to signup a user upon clicking submit, I get the following message:
> relation "django\_site" does not exist LINE 1:
> ..."django\_site"."domain", "django\_site"."name" FROM "django\_si...
I am not really sure what went wrong ... | I recently ran into this issue (Django 1.8.7) even with `SITE_ID = 1` in my settings. I had to manually migrate the `sites` app before any other migrations:
```
./manage.py migrate sites
./manage.py migrate
``` |
How to test if a given time-stamp is in seconds or milliseconds? | 23,929,145 | 4 | 2014-05-29T08:39:41Z | 23,982,005 | 17 | 2014-06-01T16:31:48Z | [
"python",
"datetime",
"timestamp",
"unix-timestamp"
] | Assume a given variable, it is containing a `UNIX` time-stamp, but whether it is in seconds or milliseconds format is unknown, I want to assign to a variable which is in seconds format
### For Example:
```
unknown = 1398494489444 # This is millisecond
t = ???
```
Updated: I understand it is not possible to tell with... | If you [convert](http://www.currentmillis.com/) the maximum timestamp values with x digits in millis you get something like this:
* 9999999999999 (13 digits) means Sat Nov 20 2286 17:46:39 UTC
* 999999999999 (12 digits) means Sun Sep 09 2001 01:46:39 UTC
* 99999999999 (11 digits) means Sat Mar 03 1973 09:46:39 UTC
Ca... |
How to test if a given time-stamp is in seconds or milliseconds? | 23,929,145 | 4 | 2014-05-29T08:39:41Z | 24,010,195 | 7 | 2014-06-03T08:14:11Z | [
"python",
"datetime",
"timestamp",
"unix-timestamp"
] | Assume a given variable, it is containing a `UNIX` time-stamp, but whether it is in seconds or milliseconds format is unknown, I want to assign to a variable which is in seconds format
### For Example:
```
unknown = 1398494489444 # This is millisecond
t = ???
```
Updated: I understand it is not possible to tell with... | With your constraints, it is trivial to detect millisecond timestamps. Even timestamps a year into the past are still magnitudes larger than the current timestamp.
Simply test if the number is greater than the current timestamp; if so, you have a timestamp in milliseconds:
```
now = time.mktime(time.gmtime())
if t > ... |
How to test if a given time-stamp is in seconds or milliseconds? | 23,929,145 | 4 | 2014-05-29T08:39:41Z | 24,106,694 | 8 | 2014-06-08T13:36:04Z | [
"python",
"datetime",
"timestamp",
"unix-timestamp"
] | Assume a given variable, it is containing a `UNIX` time-stamp, but whether it is in seconds or milliseconds format is unknown, I want to assign to a variable which is in seconds format
### For Example:
```
unknown = 1398494489444 # This is millisecond
t = ???
```
Updated: I understand it is not possible to tell with... | At the risk of attracting downvotes, I want to go on record as saying DON'T DO IT.
Making assumptions about the units of a physical quantity is a terrible idea - it led to the destruction of the [Mars Meteorological Orbiter](http://www.wired.com/2010/11/1110mars-climate-observer-report/) (the calculated units of thrus... |
How to set the redis timeout waiting for the response with pipeline in redis-py? | 23,930,125 | 3 | 2014-05-29T09:32:43Z | 23,964,854 | 13 | 2014-05-30T23:36:41Z | [
"python",
"redis",
"response",
"pipeline",
"redis-py"
] | In the code below, is the pipeline timeout 2 seconds?
```
client = redis.StrictRedis(host=host, port=port, db=0, socket_timeout=2)
pipe = client.pipeline(transaction=False)
for name in namelist:
key = "%s-%s-%s-%s" % (key_sub1, key_sub2, name, key_sub3)
pipe.smembers(key)
pipe.execute()
```
In the redis, ther... | I asked [andymccurdy](https://github.com/andymccurdy) , the author of redis-py, on github and [the answer](https://github.com/andymccurdy/redis-py/issues/485) is as below:
> If you're using redis-py<=2.9.1, socket\_timeout is both the timeout
> for socket connection and the timeout for reading/writing to the
> socket.... |
Is there a more pythonic, possibly one liner, to iterate over a string within a list? | 23,936,239 | 2 | 2014-05-29T14:51:49Z | 23,936,267 | 7 | 2014-05-29T14:53:02Z | [
"python",
"string",
"list",
"iteration"
] | Strings are iterable.
Lists are iterable.
And with a List of Strings, both the List and the Strings can be iterated through with a nested loop.
For Example:
```
input = [ 'abcdefg', 'hijklmn', 'opqrstu']
for item in input:
for letter in item:
print letter
```
Out:
```
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
... | You can use [`itertools.chain.from_iterable()`](https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable):
```
>>> from itertools import chain
>>> input = ['abcdefg', 'hijklmn', 'opqrstu']
>>>
>>> for letter in chain.from_iterable(input):
... print letter
...
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
... |
Sum lists of variable lengths element-wise | 23,936,958 | 3 | 2014-05-29T15:28:11Z | 23,937,021 | 12 | 2014-05-29T15:30:39Z | [
"python"
] | If I have a list of lists, and each nested list contains numbers, how can I add all of these lists element-wise into a single array?
i.e.
```
listOne = [1, 2, 3]
listTwo = [4, 5, 6]
listThree = [7, 8, 9, 10]
allLists = [listOne, listTwo, listThree]
total = add(allLists)
print total
```
output should be `[12, 15, 18... | Use [`izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest) to remap rows/columns (like `zip` but to the longest element rather than shortest), filling shorter items 0
```
from itertools import izip_longest
total = [sum(x) for x in izip_longest(*allLists, fillvalue=0)]
```
Outputs:
... |
How do i use subprocesses to force python to release memory? | 23,937,189 | 9 | 2014-05-29T15:38:05Z | 24,126,616 | 14 | 2014-06-09T18:33:50Z | [
"python",
"python-2.7",
"memory-management",
"subprocess"
] | I was reading up on [Python Memory Management](http://deeplearning.net/software/theano/tutorial/python-memory-management.html) and would like to reduce the memory footprint of my application. [It was suggested](http://stackoverflow.com/a/1316799) that [subprocesses](https://docs.python.org/2/library/subprocess.html) wo... | The important thing about the optimization suggestion is to make sure that `my_function()` is only invoked in a subprocess. The `deepcopy` and `del` are irrelevant â once you create five million distinct integers in a process, holding onto all of them at the same time, it's game over. Even if you stop referring to th... |
"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl | 23,937,933 | 45 | 2014-05-29T16:15:25Z | 24,051,044 | 131 | 2014-06-05T03:14:46Z | [
"python",
"install",
"pycurl"
] | I'm trying to install pycurl via:
```
sudo pip install pycurl
```
It downloaded fine, but when when it runs setup.py I get the following traceback:
```
Downloading/unpacking pycurl
Running setup.py egg_info for package pycurl
Traceback (most recent call last):
File "<string>", line 16, in <module>
... | On Debian I needed the following package to fix this.
> sudo apt-get install libcurl4-openssl-dev |
"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl | 23,937,933 | 45 | 2014-05-29T16:15:25Z | 27,795,678 | 18 | 2015-01-06T09:28:27Z | [
"python",
"install",
"pycurl"
] | I'm trying to install pycurl via:
```
sudo pip install pycurl
```
It downloaded fine, but when when it runs setup.py I get the following traceback:
```
Downloading/unpacking pycurl
Running setup.py egg_info for package pycurl
Traceback (most recent call last):
File "<string>", line 16, in <module>
... | Similarly with `yum` package manager
```
yum install libcurl-devel
``` |
Swapping the dimensions of a numpy array | 23,943,379 | 3 | 2014-05-29T21:33:05Z | 23,944,468 | 9 | 2014-05-29T23:06:58Z | [
"python",
"arrays",
"optimization",
"numpy",
"dimensions"
] | I would like to do the following:
```
for i in dimension1:
for j in dimension2:
for k in dimension3:
for l in dimension4:
B[k,l,i,j] = A[i,j,k,l]
```
without the use of loops. In the end both A and B contain the same information but indexed
differently.
I must point out that the dimension 1,2,3 a... | The canonical way of doing this in numpy would be to use [`np.transpose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html)'s optional permutation argument. In your case, to go from `ijkl` to `klij`, the permutation is `(2, 3, 0, 1)`, e.g.:
```
In [16]: a = np.empty((2, 3, 4, 5))
In [17]: b = ... |
Installing lxml for Python 3.4 on Windows x 86 (32 bit) with Visual Studio C++ 2010 Express | 23,944,465 | 10 | 2014-05-29T23:06:43Z | 26,839,880 | 8 | 2014-11-10T08:50:19Z | [
"python",
"c++",
"visual-studio-2010",
"lxml"
] | ## Related
Related questions:
* [error: Unable to find vcvarsall.bat](http://stackoverflow.com/q/2817869/1175496)
* [LXML 3.3 with Python 3.3 on windows 7 32-bit](http://stackoverflow.com/q/22981951/1175496)
Related answers:
* <http://stackoverflow.com/a/18045219/1175496>
Related comments:
* [Building lxml for Py... | I also got this problem, but the workarounds provided above are not work for me as well.
Here is my system configuration:
* Win7 64bit
* python3.3
* visual studio 2013
I tried to use the method in the first link in the **Related questions**, but it's fail. This method is to create a system variable for vs2010 use, a... |
TypeError: method() takes 1 positional argument but 2 were given | 23,944,657 | 28 | 2014-05-29T23:27:32Z | 23,944,658 | 52 | 2014-05-29T23:27:32Z | [
"python",
"python-3.x",
"arguments",
"self"
] | If I have a class ...
```
class MyClass:
def method(arg):
print(arg)
```
... which I use to create an object ...
```
my_object = MyClass()
```
... on which I call `method("foo")` like so ...
```
>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeErro... | In Python, this:
```
my_object.method("foo")
```
... is [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar), which the interpreter translates behind the scenes into:
```
MyClass.method(my_object, "foo")
```
... which, as you can see, does indeed have two arguments - it's just that the first one is impli... |
Anaphora resolution example requested with python-nltk | 23,945,336 | 3 | 2014-05-30T00:45:11Z | 23,946,093 | 10 | 2014-05-30T02:26:53Z | [
"python",
"nltk"
] | I have been looking into the howto for [nltk-drt](http://www.nltk.org/howto/drt.html) and into the module definitions for [nltk.sem.drt](http://www.nltk.org/api/nltk.sem.html) but I am having a really hard time trying to understand how to achieve basic functionality using these packages.
An example of a task that I wo... | I don't think DRT (Discourse Representation Theory) deals with [anaphora resolution](http://en.wikipedia.org/wiki/Anaphora_(linguistics)#Nomenclature_and_examples), like what you wanted. It deals with representing the meaning of a sentence in formal logic.
Also, there is a name for your "more realistic test case", whi... |
A faster alternative to Pandas `isin` function | 23,945,493 | 7 | 2014-05-30T01:06:16Z | 23,946,500 | 14 | 2014-05-30T03:21:35Z | [
"python",
"numpy",
"pandas"
] | I have a very large data frame `df` that looks like:
```
ID Value1 Value2
1345 3.2 332
1355 2.2 32
2346 1.0 11
3456 8.9 322
```
And I have a list that contains a subset of IDs `ID_list`. I need to have a subset of `df` for the `ID` contained in `ID_list`.
Currently, I... | It depends on the size of your data but for large datasets [DataFrame.join](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html?highlight=join#pandas.DataFrame.join) seems to be the way to go. This requires your DataFrame index to be your 'ID' and the Series or DataFrame you're joining agai... |
Why is virtualenv necessary? | 23,948,317 | 2 | 2014-05-30T06:21:05Z | 23,948,367 | 9 | 2014-05-30T06:25:22Z | [
"python",
"virtualenv"
] | I am a beginner in Python.
I read *`virtualenv` is preferred during Python project development*.
I couldn't understand this point at all. Why is `virtualenv` preferred? | [Virtualenv](http://virtualenv.readthedocs.org/en/latest/) keeps your Python packages in a virtual environment localized to your project, instead of forcing you to install your packages system-wide.
There are a number of benefits to this,
* the first and principle one is that you can have multiple virtulenvs, so you
... |
How to pass a javascript array to a python script using flask [using flask example] | 23,949,395 | 6 | 2014-05-30T07:35:56Z | 23,956,933 | 10 | 2014-05-30T14:24:55Z | [
"javascript",
"python",
"ajax",
"arrays",
"flask"
] | I am trying to get the [flask/jquery/ajax example](http://flask.pocoo.org/docs/patterns/jquery/) working for my specific case, but I am coming up short every time. I am aware this sort of question has been asked several times, but the answers do not help me (Yes, I am new to this).
The example passes a string from jav... | Here is another way to pass JS Array to python :
JS Side:
```
$.getJSON($SCRIPT_ROOT + '/_array2python', {
wordlist: JSON.stringify(list)
}, function(data){
console.log(data.result)
$( "#result" ).text(data.result);
});
```
Python Side:
```
import json
@app.route('/_array2python')
d... |
Cancel saving model when using pre_save in django | 23,949,709 | 8 | 2014-05-30T07:56:54Z | 23,949,769 | 8 | 2014-05-30T08:00:52Z | [
"python",
"django",
"signals"
] | I have a model:
```
class A(models.Model):
number = models.IntegerField()
```
But when I call A.save(), I want to ensure that number is a prime (or other conditions), or the save instruction should be cancelled.
So how can I cancel the save instruction in the pre\_save signal receiver?
```
@receiver(pre_save, s... | I'm not sure you can cancel the save only using the pre\_save signal. But you can easily achieve this by overriding the save method:
```
def save(self):
if some_condition:
super(A, self).save()
else:
return # cancel the save
``` |
print.__doc__ vs getattr(__builtin__,"print").__doc__ | 23,951,085 | 10 | 2014-05-30T09:21:17Z | 23,951,155 | 9 | 2014-05-30T09:24:57Z | [
"python",
"python-2.x"
] | `print.__doc__` outputs:
```
SyntaxError: invalid syntax
```
where as
```
>>> getattr(__builtin__,"print").__doc__
```
Outputs:
> ```
> print(value, ..., sep=' ', end='\n', file=sys.stdout)
> ```
>
> Prints the values to a stream, or to `sys.stdout` by default. Optional keyword arguments:
>
> file : a file-like ob... | Print isn't globally available as a function in Python 2, so you can't treat it as an object. It's a statement.
In Python 3, or Python 2 with `from __future__ import print_function`, however, `print` is a normal function and you can read the `__doc__` attribute.
See: <https://docs.python.org/2/library/functions.html#... |
print.__doc__ vs getattr(__builtin__,"print").__doc__ | 23,951,085 | 10 | 2014-05-30T09:21:17Z | 23,951,408 | 17 | 2014-05-30T09:38:34Z | [
"python",
"python-2.x"
] | `print.__doc__` outputs:
```
SyntaxError: invalid syntax
```
where as
```
>>> getattr(__builtin__,"print").__doc__
```
Outputs:
> ```
> print(value, ..., sep=' ', end='\n', file=sys.stdout)
> ```
>
> Prints the values to a stream, or to `sys.stdout` by default. Optional keyword arguments:
>
> file : a file-like ob... | In Python 2 (or Python < 2.6 to be very exact) `print` is absolutely nothing like a function, and thus does not have docstring. It doesn't even evaluate all of its arguments before it starts printing:
```
>>> print 42, a
42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is... |
How to convert int to Enum in python? | 23,951,641 | 15 | 2014-05-30T09:50:36Z | 23,951,862 | 34 | 2014-05-30T10:00:35Z | [
"python",
"python-2.7",
"enums",
"int",
"type-conversion"
] | Using the new Enum feature (via [backport enum34](https://pypi.python.org/pypi/enum34)) with python 2.7.6.
Given the following definition, how can I convert an int to the corresponding Enum value?
```
from enum import Enum
class Fruit(Enum):
Apple = 4
Orange = 5
Pear = 6
```
I know I can hand craft a se... | 'Call' the `Enum` class:
```
Fruit(5)
```
to turn `5` into `Fruit.Orange`:
```
>>> from enum import Enum
>>> class Fruit(Enum):
... Apple = 4
... Orange = 5
... Pear = 6
...
>>> Fruit(5)
<Fruit.Orange: 5>
```
From the [Programmatic access to enumeration members and their attributes](https://docs.python... |
TypeError when converting dictionary to JSON array | 23,956,353 | 28 | 2014-05-30T13:57:44Z | 23,956,378 | 72 | 2014-05-30T13:59:04Z | [
"python",
"json",
"dictionary"
] | How do I take a python dictionary where the keys and values are Strings and convert it into a JSON String.
This is what I have right now:
```
import json
def create_simple_meeting(subject, startDate, endDate, location, body):
info = dict()
if(subject != ""):
info["subject"] = subject
if(startDate... | You are trying to serialise the *type* object, `dict`, instead of `info`. Dump the right variable:
```
print(json.dumps(info))
``` |
In Python, what is the difference between f.readlines() and list(f) | 23,958,198 | 8 | 2014-05-30T15:31:09Z | 23,958,277 | 10 | 2014-05-30T15:35:39Z | [
"python",
"list",
"file",
"file-io",
"python-internals"
] | From both [Python2 Tutorial](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) and [Python3 Tutorial](https://docs.python.org/3.4/tutorial/inputoutput.html#methods-of-file-objects), there is a line in the midpoint of *section 7.2.1* saying:
> If you want to read all the lines of a file **in ... | Functionally, there is no difference; both methods result in the exact same list.
Implementation wise, one uses the file object as an [iterator](https://docs.python.org/2/glossary.html#term-iterator) (calls `next(f)` repeatedly until `StopIteration` is raised), the other uses a dedicated method to read the whole file.... |
Notification of key expiration in redis python | 23,964,548 | 10 | 2014-05-30T23:00:03Z | 23,965,234 | 18 | 2014-05-31T00:30:23Z | [
"python",
"python-2.7",
"redis"
] | I would like to be notified when a volatile key expires in my redis store. The redis website provides some description of how this might be achieved in <http://redis.io/topics/notifications>, but I am wondering if it can be done using the python redis api.
After setting:`notify-keyspace-events Ex` in my redis.conf fil... | The surprise (no expiration events seen when time to live for a key reaches zero) is not bound to Python, but rather to the way, Redis is expiring keys.
[Redis doc on Timing of expired events](http://redis.io/topics/notifications)
## Timing of expired events
Keys with a time to live associated are expired by Redis i... |
Slow access to Django's request.body | 23,969,560 | 11 | 2014-05-31T11:33:05Z | 24,039,774 | 8 | 2014-06-04T14:10:23Z | [
"python",
"django",
"performance",
"apache",
"request"
] | Sometimes this line of Django app (hosted using Apache/mod\_wsgi) takes a lot of time to execute (eg. 99% of eg. 6 seconds of request handling, as measured by New Relic), when submitted by some mobile clients:
```
raw_body = request.body
```
(where `request` is an incoming request)
The questions I have:
1. What cou... | Regarding (1), Apache passes control to the mod\_wsgi handler as soon as the request's headers are available, and mod\_wsgi then passes control on to Python. The internal implementation of `request.body` then calls the `read()` method which eventually calls the implementation within mod\_wsgi, which [requests the reque... |
Slow access to Django's request.body | 23,969,560 | 11 | 2014-05-31T11:33:05Z | 24,130,019 | 7 | 2014-06-09T22:25:38Z | [
"python",
"django",
"performance",
"apache",
"request"
] | Sometimes this line of Django app (hosted using Apache/mod\_wsgi) takes a lot of time to execute (eg. 99% of eg. 6 seconds of request handling, as measured by New Relic), when submitted by some mobile clients:
```
raw_body = request.body
```
(where `request` is an incoming request)
The questions I have:
1. What cou... | There are two ways you can fix this in Apache.
You can use [mod\_buffer](http://httpd.apache.org/docs/trunk/mod/mod_buffer.html), available in `>=2.3`, and change `BufferSize` to the maximum expected payload size. This should make Apache hold the request in memory until it's either finished sending, or the buffer is r... |
Plotting with seaborn using the matplotlib object-oriented interface | 23,969,619 | 33 | 2014-05-31T11:39:01Z | 23,973,562 | 66 | 2014-05-31T18:22:14Z | [
"python",
"oop",
"matplotlib",
"seaborn"
] | I strongly prefer using `matplotlib` in OOP style:
```
f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(...)
axarr[1].plot(...)
```
This makes it easier to keep track of multiple figures and subplots.
Question: How to use seaborn this way? Or, how to change [this example](http://www.stanford.edu/~mwaskom/softwa... | It depends a bit on which seaborn function you are using.
The plotting functions in seaborn are broadly divided into two classes
* "Axes-level" functions, including `regplot`, `boxplot`, `kdeplot`, and many others
* "Figure-level" functions, including `lmplot`, `factorplot`, `jointplot` and one or two others
The fir... |
How to stop Python program compiled in py2exe from displaying ImportError: No Module names 'ctypes' | 23,970,240 | 2 | 2014-05-31T12:45:02Z | 24,005,042 | 13 | 2014-06-02T23:50:00Z | [
"python",
"compiler-errors",
"py2exe",
"argparse"
] | I was wondering if this might be a compilation error or if there is something I can do to stop it from displaying. I have made an argparse program for cmd. I compiled it with py2exe and when I run it, it exacutes the program properly but always gives this error before running the code:
```
Traceback (most recent call ... | This is caused by a bug in py2exe, it'll be fixed in next release. [More Info](http://permalink.gmane.org/gmane.comp.python.py2exe/4706)
The solution is to add `ctypes` to `bootstrap_modules` in `C:\Python34\Lib\site-packages\py2exe\runtime.py` file (line 117).
```
...
# modules which are always needed
bootstrap_modu... |
How do I revert to a previous package in Anaconda? | 23,974,217 | 19 | 2014-05-31T20:10:45Z | 23,974,240 | 16 | 2014-05-31T20:16:52Z | [
"python",
"anaconda",
"conda"
] | If I do
```
conda info pandas
```
I can see all of the packages available.
I updated my `pandas` to the latest this morning, but I need to revert to a prior version now. I tried
```
conda update pandas 0.13.1
```
but that didn't work. How do I specify which version to use? | I had to use the `install` function instead:
```
conda install pandas=0.13.1
``` |
How do I revert to a previous package in Anaconda? | 23,974,217 | 19 | 2014-05-31T20:10:45Z | 35,526,770 | 12 | 2016-02-20T17:43:34Z | [
"python",
"anaconda",
"conda"
] | If I do
```
conda info pandas
```
I can see all of the packages available.
I updated my `pandas` to the latest this morning, but I need to revert to a prior version now. I tried
```
conda update pandas 0.13.1
```
but that didn't work. How do I specify which version to use? | You can 'roll back' an installation, downgrading not only the package that was updated but the dependencies as well. To do this:
```
conda list --revisions
conda install --revision [revision number]
```
The first command shows previous installation revisions (with dependencies) and the second reverts to whichever `re... |
Error when check request.method in flask | 23,974,532 | 4 | 2014-05-31T21:04:56Z | 23,974,670 | 10 | 2014-05-31T21:33:37Z | [
"jquery",
"python",
"flask"
] | I am currently learning Flask.
After sending data through `$.ajax()` with jQuery, `type='post'` the server side gives an error when I check `request.method`. The same occurs with `type='get'`.
**error**
```
builtins.ValueError
ValueError: View function did not return a response
Traceback (most recent call last)
F... | You need to make sure you registered your view route with the right methods:
```
@app.route('/login', methods=['GET', 'POST'])
```
to allow both `GET` and `POST` requests, or use:
```
@app.route('/login', methods=['POST'])
```
to allow *only* `POST` for this route.
To test for the request method, use **uppercase**... |
Python - pandas - Append Series into Blank DataFrame | 23,974,802 | 4 | 2014-05-31T21:55:48Z | 23,974,921 | 7 | 2014-05-31T22:11:26Z | [
"python",
"matrix",
"pandas",
"dataframe"
] | Say I have two pandas Series in python:
```
import pandas as pd
h = pd.Series(['g',4,2,1,1])
g = pd.Series([1,6,5,4,"abc"])
```
I can create a DataFrame with just h and then append g to it:
```
df = pd.DataFrame([h])
df1 = df.append(g, ignore_index=True)
```
I get:
```
>>> df1
0 1 2 3 4
0 g 4 2 1 1... | So if you don't pass an empty list to the DataFrame constructor then it works:
```
In [16]:
df = pd.DataFrame()
h = pd.Series(['g',4,2,1,1])
df = df.append(h,ignore_index=True)
df
Out[16]:
0 1 2 3 4
0 g 4 2 1 1
[1 rows x 5 columns]
```
The difference between the two constructor approaches appears to be ... |
C++ - something like with keyword in python | 23,975,082 | 3 | 2014-05-31T22:38:24Z | 23,975,134 | 14 | 2014-05-31T22:45:22Z | [
"python",
"c++"
] | Well i have some abstraction around opengl shaders and i want to use them this way:
```
WITH_SHADER(shader_name) {
// here will be gl commands
}
```
it should automatically bind/unbind that shader from current gl context.
Bind before that compound statement and unbind after that.
Can i construct this macro in C++ s... | The closest thing would be [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization).
Build a class `WithShader` that encapsulates your shader :
* Bind the shader in the constructor
* Unbind it in the destructor
Usage example:
```
{
with_shader ws(shader_name)
// use your shader
}
// binding a... |
Format certain floating dataframe columns into percentage in pandas | 23,981,601 | 5 | 2014-06-01T15:48:33Z | 36,175,424 | 9 | 2016-03-23T10:20:59Z | [
"python",
"pandas",
"formatting",
"ipython-notebook"
] | I am trying to write a paper in IPython notebook, but encountered some issues with display format. Say I have following dataframe `df`, is there any way to format `var1` and `var2` into 2 digit decimals and `var3` into percentages.
```
var1 var2 var3
id ... | The accepted answer suggests to modify the raw data for presentation purposes, something you generally do not want. Imagine you need to make further analyses with these columns and you need the precision you lost with rounding.
You can modify the formatting of individual columns in data frames, in your case:
```
outp... |
Flask WTForms: Difference between DataRequired and InputRequired | 23,982,917 | 9 | 2014-06-01T18:13:47Z | 23,984,389 | 17 | 2014-06-01T20:55:27Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] | What is difference between `DataRequired` and `InputRequired` in `wtforms.valiadators`
I have some fields in my signup form :
```
username
password
password_repeat
submit
```
Should these fields use the `DataRequired` or `InputRequired` validator? | ## Short Answer
**Unless you have a good reason you should use `InputRequired`**
## Why?
Lets look at some notes from the docs/code:
> Note there is a distinction between this and DataRequired in that InputRequired looks that form-input data was provided, and DataRequired looks at the post-coercion data.
and
> **... |
Possible optimizations for calculating squared euclidean distance | 23,983,748 | 3 | 2014-06-01T19:43:26Z | 23,984,007 | 10 | 2014-06-01T20:10:35Z | [
"python",
"c",
"performance",
"numpy"
] | I need to do a few hundred million euclidean distance calculations every day in a Python project.
Here is what I started out with:
```
def euclidean_dist_square(x, y):
diff = np.array(x) - np.array(y)
return np.dot(diff, diff)
```
This is quite fast and I already dropped the sqrt calculation since I need to ... | The fastest way to compute Euclidean distances in NumPy that I know is [the one in scikit-learn](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.euclidean_distances.html), which can be summed up as
```
def squared_distances(X, Y):
"""Return a distance matrix for each pair of rows i, j in ... |
problems importing ttk from tkinter in python 2.7 | 23,984,614 | 10 | 2014-06-01T21:22:00Z | 23,984,633 | 19 | 2014-06-01T21:24:30Z | [
"python",
"tkinter",
"ttk"
] | I'm working with an example file in a tutorial that asks me to first do two imports:
```
from tkinter import *
from tkinter import ttk
```
I get an error. I researched a bit and found that in python 2.7.x I need to capitalize the 't'in tkinter, so I change to:
```
from Tkinter import *
from Tkinter import ttk.
```
... | In python 2.7, ttk is its own package:
```
import Tkinter
import ttk
```
This is documented in the official python documentation: <https://docs.python.org/2/library/ttk.html#module-ttk> |
Expressing IS NOT NULL without causing a PEP8 error | 23,985,501 | 14 | 2014-06-01T23:23:48Z | 23,985,587 | 17 | 2014-06-01T23:39:21Z | [
"python",
"sqlalchemy",
"pep8"
] | At a certain point in my project, I need to query a SQLAlchemy object for columns that are NOT NULL. In my code, I do:
```
session.query(MyModel).filter(MyModel.my_column != None).all()
```
...and it works great. Problem is, whenever I run `pep8` or one of the other linters on the file, it raises an error E711: Compa... | PEP8 isn't meant to be followed to the letter.
You're *recommended* to use `is None` instead of `== None` because `is` cannot be overloaded (unlike `==`):
```
>>> class Bad(object):
... def __eq__(self, other):
... return True
...
>>> instance = Bad()
>>> instance == None
True
>>> instance is None
False
`... |
Python: PyQt QTreeview example - selection | 23,993,895 | 7 | 2014-06-02T11:52:23Z | 24,045,757 | 8 | 2014-06-04T19:17:09Z | [
"python",
"qt",
"tree",
"qtreeview"
] | I'm using Python 2.7 and Qt designer and I'm new to MVC:
I have a View completed within Qt to give me a directory tree list, and the controller in place to run things. My question is:
**Given a Qtree view, how may I obtain a directory once a dir is selected?**
 emmited by the **selectionModel** owned by your tree. This signal is emmited with the **selected** item as first argument and the **deselected** as second, both are instances of [QItemSelection](h... |
replace special characters in a string python | 23,996,118 | 2 | 2014-06-02T13:47:26Z | 23,996,414 | 8 | 2014-06-02T14:01:28Z | [
"python",
"string",
"list",
"replace",
"urllib"
] | I am using urllib to get a string of html from a website and need to put each word in the html document into a list.
Here is the code I have so far. I keep getting an error. I have also copied the error below.
```
import urllib.request
url = input("Please enter a URL: ")
z=urllib.request.urlopen(url)
z=str(z.read()... | One way is to use [re.sub](https://docs.python.org/2/library/re.html#re.RegexObject.sub), that's my preferred way.
```
import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string
```
**Output:**
```
hey there
```
Another way is to use [re.escape](https://docs.python.... |
Installed virtualenv and virtualenvwrapper: Python says no module named virtualenvwrapper | 23,997,403 | 7 | 2014-06-02T14:50:34Z | 25,583,193 | 17 | 2014-08-30T14:03:00Z | [
"python",
"osx",
"virtualenv",
"virtualenvwrapper"
] | Lots of other threads about similar issues, but none that I could find where quite the same case as mine. So, here goes:
**Things I did:**
* Ran: `sudo easy_install pip`
* Ran: `sudo pip install virtualenv`
* Ran: `sudo pip install virtualenvwrapper`
**Current State:**
* .bash\_profile
```
export PATH=/usr/loc... | I've managed to get this working after having the same problem you've described here by editing my **~/.bash\_profile** and adding this:
```
export WORKON_HOME=$HOME/code/.virtualenvs
export PROJECT_HOME=$HOME/code
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin... |
Why isn't this a syntax error in python? | 23,998,026 | 35 | 2014-06-02T15:22:07Z | 23,998,128 | 46 | 2014-06-02T15:27:21Z | [
"python",
"grammar",
"conditional-expressions"
] | Noticed a line in our codebase today which I thought surely would have failed the build with syntax error, but tests were passing so apparently it was actually valid python (in both 2.x and 3).
Whitespace is sometimes not required in the conditional expression:
```
>>> 1if True else 0
1
```
It doesn't work if the LH... | > ### [Whitespace between tokens](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens)
>
> Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.