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 |
|---|---|---|---|---|---|---|---|---|---|
Pass keyword argument only to __new__() and never further it to __init__()? | 14,755,754 | 2 | 2013-02-07T16:15:54Z | 14,756,633 | 7 | 2013-02-07T16:58:10Z | [
"python",
"design",
"mocking"
] | # **Part 1**
I have a setup where I have a set of classes that I want to mock, my idea was that in the cases where I want to do this I pass a `mock` keyword argument into the constructor and in `__new__` intercept this and instead pass back a mocked version of that object.
It looks like this (**Edited the keyword loo... | This is a job for `__metaclass__` :-)
The code responsible to call both `__new__` and `__init__` when instantiating a Python new-style object lies in the `__call__`method for the class metaclass. (or the semantically equivalent to that).
In other words - when you do:
`RealObject()` - what is really called is the `Re... |
WebSocket server in Python: 'module' object has no attribute 'AF_INET' | 14,755,963 | 13 | 2013-02-07T16:26:10Z | 14,756,156 | 43 | 2013-02-07T16:34:32Z | [
"python",
"sockets",
"websocket"
] | I am trying to run this simple Python WebSocket, with a couple very minor changes. I am running Python 2.4.3 because I cannot use an newer version, but I'm not sure how much that matters.
Here is the error I'm getting:
```
Traceback (most recent call last):
File "socket.py", line 258, in ?
server = WebSocketSer... | It appears that you've named your own file `socket.py`, so when you `import socket`, you're not getting the system library (it's just re-importing the file you're currently in - which has no `AF_INET` symbol). Try renaming your file something like `mysocket.py`. |
WebSocket server in Python: 'module' object has no attribute 'AF_INET' | 14,755,963 | 13 | 2013-02-07T16:26:10Z | 28,924,666 | 7 | 2015-03-08T08:49:43Z | [
"python",
"sockets",
"websocket"
] | I am trying to run this simple Python WebSocket, with a couple very minor changes. I am running Python 2.4.3 because I cannot use an newer version, but I'm not sure how much that matters.
Here is the error I'm getting:
```
Traceback (most recent call last):
File "socket.py", line 258, in ?
server = WebSocketSer... | Even after changing the file name, if you are running the python from terminal.
(you may get the same error)
Kindly
**rm -rf socket.pyc**
(previously compiled bytecode) |
setattr(object, name, value) vs object.__setattr__(name,value) | 14,756,289 | 6 | 2013-02-07T16:40:47Z | 14,756,407 | 14 | 2013-02-07T16:46:49Z | [
"python",
"coding-style"
] | I was just reading post [How can I assign a new class attribute via \_\_dict\_\_ in python?](http://stackoverflow.com/questions/432786/how-can-i-assign-a-new-class-attribute-via-dict-in-python) and there was one comment from @bruno desthuilliers saying:
> One shouldn't directly call magic methods - they are here as im... | You should always use `setattr()`, the commenter is quite correct.
Not all types implement `__setattr__`, for example, yet `setattr()` will work correctly if the type allows the attribute to be set.
Double-underscore methods are hooks, there to enable your custom classes to implement custom behaviour. The Python APIs... |
Why are uncompiled, repeatedly used regexes so much slower in Python 3? | 14,756,790 | 16 | 2013-02-07T17:04:42Z | 14,757,032 | 23 | 2013-02-07T17:16:59Z | [
"python",
"regex",
"caching"
] | When answering [this question](http://stackoverflow.com/q/14755882/20670) (and having read [this answer](http://stackoverflow.com/a/452143/20670) to a similar question), I thought that I knew how Python caches regexes.
But then I thought I'd test it, comparing two scenarios:
1. a single compilation of a simple regex,... | The code *has* changed.
In Python 2.7, the cache is a simple dictionary; if more than `_MAXCACHE` items are stored in it, the whole the cache is cleared before storing a new item. A cache lookup only takes building a simple key and testing the dictionary, see the [2.7 implementation of `_compile()`](http://hg.python.o... |
Is there a numpy/scipy dot product, calculating only the diagonal entries of the result? | 14,758,283 | 14 | 2013-02-07T18:25:03Z | 14,759,273 | 10 | 2013-02-07T19:22:38Z | [
"python",
"numpy",
"scipy",
"product"
] | Imagine having 2 numpy arrays:
```
> A, A.shape = (n,p)
> B, B.shape = (p,p)
```
Typically p is a smaller number (p <= 200), while n can be arbitrarily large.
I am doing the following:
```
result = np.diag(A.dot(B).dot(A.T))
```
As you can see, I am keeping only the n diagonal entries, however there is an intermed... | I think i got it on my own, but nevertheless will share the solution:
since getting only the diagonals of a matrix multiplication
```
> Z = N.diag(X.dot(Y))
```
is equivalent to the individual sum of the scalar product of rows of X and columns of Y, the previous statement is equivalent to:
```
> Z = (X * Y.T).sum(-... |
Is there a numpy/scipy dot product, calculating only the diagonal entries of the result? | 14,758,283 | 14 | 2013-02-07T18:25:03Z | 14,759,341 | 19 | 2013-02-07T19:26:51Z | [
"python",
"numpy",
"scipy",
"product"
] | Imagine having 2 numpy arrays:
```
> A, A.shape = (n,p)
> B, B.shape = (p,p)
```
Typically p is a smaller number (p <= 200), while n can be arbitrarily large.
I am doing the following:
```
result = np.diag(A.dot(B).dot(A.T))
```
As you can see, I am keeping only the n diagonal entries, however there is an intermed... | You can get almost anything you ever dreamed of with [`numpy.einsum`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html). Until you start getting the hang of it, it basically seems like black voodoo...
```
>>> a = np.arange(15).reshape(5, 3)
>>> b = np.arange(9).reshape(3, 3)
>>> np.diag(np.dot(np... |
Writing XFCE panel plugins in Python? | 14,758,470 | 7 | 2013-02-07T18:36:12Z | 14,776,735 | 7 | 2013-02-08T16:10:45Z | [
"python",
"xfce"
] | I've Googled around a bit, but can't find much. [This](http://pyxfce.xfce.org/) seems rather out of date, and doesn't provide any examples. Is this possible? Should I just shut up and learn C already? | Not done this myself but could get the boilerplate you need from another plugin like.
<http://git.xfce.org/panel-plugins/xfce4-rss-plugin/> |
python 2.7 string.join() with unicode | 14,758,705 | 6 | 2013-02-07T18:50:26Z | 14,758,759 | 11 | 2013-02-07T18:54:00Z | [
"python",
"unicode"
] | I have bunch of byte strings (`str`, not `unicode`, in python 2.7) containing unicode data (in `utf-8` encoding).
I am trying to join them( by `"".join(utf8_strings)` or `u"".join(utf8_strings)`) which throws
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 0: ordinal not in range(128)`
```
I... | Joining byte strings using `''.join()` works just fine; the error you see would *only* appear if you mixed `unicode` and `str` objects:
```
>>> utf8 = [u'\u0123'.encode('utf8'), u'\u0234'.encode('utf8')]
>>> ''.join(utf8)
'\xc4\xa3\xc8\xb4'
>>> u''.join(utf8)
Traceback (most recent call last):
File "<stdin>", line 1... |
Python PIL bytes to Image | 14,759,637 | 11 | 2013-02-07T19:44:00Z | 14,760,096 | 8 | 2013-02-07T20:10:27Z | [
"python",
"image",
"binary",
"python-imaging-library",
"drawtext"
] | ```
import PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import urllib.request
with urllib.request.urlopen('http://pastebin.ca/raw/2311595') as in_file:
hex_data = in_file.read()
print(hex_data)
img = Image.frombuffer('RGB', (320,240), hex_data) #i have tried fromstring
draw = Image... | That image is not formed of raw bytes - rather it is an encoded JPEG file.
Moreover, you are not parsing the ascii HEX representation of the stream into proper bytes:
that is, an "ff" sequence in that file is being passed to PIL as two c letters "f" instead of a byte with the number 255.
So, first, you decode the stri... |
Replacing values with groupby means | 14,760,757 | 6 | 2013-02-07T20:51:01Z | 14,761,803 | 8 | 2013-02-07T21:58:44Z | [
"python",
"pandas"
] | I have a DataFrame with a column that has some bad data with various negative values. I would like to replace values < 0 with the mean of the group that they are in.
For missing values as NAs, I would do:
```
data = df.groupby(['GroupID']).column
data.transform(lambda x: x.fillna(x.mean()))
```
But how to do this op... | Using @AndyHayden's example, you could use `groupby`/`transform` with `replace`:
```
df = pd.DataFrame([[1,1],[1,-1],[2,1],[2,2]], columns=list('ab'))
print(df)
# a b
# 0 1 1
# 1 1 -1
# 2 2 1
# 3 2 2
data = df.groupby(['a'])
def replace(group):
mask = group<0
# Select those values where it is < 0, ... |
Tastypie - Nested resources are updated instead of created on POST | 14,761,093 | 4 | 2013-02-07T21:14:02Z | 16,767,045 | 7 | 2013-05-27T05:51:43Z | [
"python",
"django",
"rest",
"tastypie"
] | I am trying to POST a resource that consists basically of a list of child resources. Here are my resources:
```
class MovementResource(ModelResource):
transactions = fields.ToManyField('stock.api.TransactionResource',
'transaction_set', related_name='movement', full=True)
class Meta:
queryset ... | I got the same issue.
After struggling with it for hours, I found a workaround that forces a POST on the related resource: If you pass a `null` value for the primary key of the nested resource then tastypie POSTs a new one, rather than updating an existing one.
If you POST the following, you should get the behavior t... |
Adding a y-axis label to secondary y-axis in matplotlib | 14,762,181 | 33 | 2013-02-07T22:22:37Z | 14,762,601 | 59 | 2013-02-07T22:52:14Z | [
"python",
"matplotlib"
] | I can add a y label to the left y-axis using `plt.ylabel`, but how can I add it to the secondary y-axis?
```
table = sql.read_frame(query,connection)
table[0].plot(color=colors[0],ylim=(0,100))
table[1].plot(secondary_y=True,color=colors[1])
plt.ylabel('$')
``` | The best way is to interact with the `axes` object directly
```
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='... |
Python datetime strptime() and strftime(): how to preserve the timezone information | 14,762,518 | 37 | 2013-02-07T22:46:13Z | 14,763,274 | 9 | 2013-02-07T23:43:34Z | [
"python",
"datetime",
"python-datetime",
"python-dateutil"
] | See the following code:
```
import datetime
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z'
d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = datetime.datetime.strptime(d_string, fmt)
print d_string
print d2.strftime(fmt)
```
the output is
```
2013-02-07 17:42:31 EST
2013-02-07... | Unfortunately, `strptime()` can only handle the timezone configured by your OS, and then only as a time offset, really. From the [documentation](http://docs.python.org/2/library/time.html#time.strptime):
> Support for the `%Z` directive is based on the values contained in `tzname` and whether `daylight` is true. Becau... |
Python datetime strptime() and strftime(): how to preserve the timezone information | 14,762,518 | 37 | 2013-02-07T22:46:13Z | 14,763,408 | 24 | 2013-02-07T23:55:03Z | [
"python",
"datetime",
"python-datetime",
"python-dateutil"
] | See the following code:
```
import datetime
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z'
d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = datetime.datetime.strptime(d_string, fmt)
print d_string
print d2.strftime(fmt)
```
the output is
```
2013-02-07 17:42:31 EST
2013-02-07... | Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New\_York" to people in North America. This is a limitation in the C time API, and the Python solution isâ¦Â to add full tz features in some future version any day now, if anyone is willi... |
Python modulo on floats | 14,763,722 | 18 | 2013-02-08T00:29:05Z | 14,763,891 | 37 | 2013-02-08T00:44:16Z | [
"python",
"modulo"
] | Can anyone explain how the modulo operator works in Python?
I cannot understand why `3.5 % 0.1 = 0.1`. | Actually, it's not true that `3.5 % 0.1` is `0.1`. You can test this very easily:
```
>>> print(3.5 % 0.1)
0.1
>>> print(3.5 % 0.1 == 0.1)
False
```
In actuality, on most systems, `3.5 % 0.1` is `0.099999999999999811`. But, on some versions of Python, `str(0.099999999999999811)` is `0.1`:
```
>>> 3.5 % 0.1
0.0999999... |
How to encode a long in Base64 in Python? | 14,764,237 | 5 | 2013-02-08T01:22:06Z | 14,764,295 | 7 | 2013-02-08T01:28:32Z | [
"python",
"base64"
] | In Java, I can encode a `BigInteger` as:
```
java.math.BigInteger bi = new java.math.BigInteger("65537L");
String encoded = Base64.encodeBytes(bi.toByteArray(), Base64.ENCODE|Base64.DONT_GUNZIP);
// result: 65537L encodes as "AQAB" in Base64
byte[] decoded = Base64.decode(encoded, Base64.DECODE|Base64.DONT_GUNZIP);
... | Check out this page on [converting integer to base64](http://fuyun.org/2009/10/how-to-convert-an-integer-to-base64-in-python/).
```
import base64
import struct
def encode(n):
data = struct.pack('<Q', n).rstrip('\x00')
if len(data)==0:
data = '\x00'
s = base64.urlsafe_b64encode(data).rstrip('=')
... |
Python and truly concurrent threads | 14,765,071 | 3 | 2013-02-08T03:09:56Z | 14,765,150 | 7 | 2013-02-08T03:20:39Z | [
"python",
"multithreading",
"concurrency",
"gil",
"greenlets"
] | I've been reading for hours now and I can completely figure out how python multi threading is faster than a single thread.
The question really stems from GIL. If there is GIL, and only one thread is really running at any single time, how can multi threading be faster than a single thread?
I read that with some operat... | You are correct - when python is waiting on C code execution the GIL is released, and that is how you can get some speedup. But only one line of python can be executed at a time. Note that this is a CPython (implementation) detail, and not strictly speaking part of the language python itself. For example, [Jython and I... |
What is a relatively simple way to determine the probability that a sentence is in English? | 14,765,632 | 8 | 2013-02-08T04:23:51Z | 14,765,652 | 8 | 2013-02-08T04:25:56Z | [
"python",
"string",
"nlp",
"bayesian"
] | I have a number of strings (collections of characters) that represent sentences in different languages, say:
> > Hello, my name is George.
> >
> > Das brot ist gut.
> >
> > ... etc.
I want to assign each of them scores (from 0 .. 1) indicating the likelihood that they are English sentences. Is there an accepted algor... | A [bayesian classifier](http://en.wikipedia.org/wiki/Baysian_classifier) would be a good choice for this task:
```
>>> from reverend.thomas import Bayes
>>> g = Bayes() # guesser
>>> g.train('french','La souris est rentrée dans son trou.')
>>> g.train('english','my tailor is rich.')
>>> g.train('french','Je ne s... |
Image smoothing in Python | 14,765,891 | 11 | 2013-02-08T04:50:00Z | 14,766,016 | 15 | 2013-02-08T05:04:29Z | [
"python",
"image-processing",
"smoothing"
] | I wanted to try to write a simple function to smooth an inputted image. I was trying to do this using the Image and numpy libraries. I was thinking that using a convolution mask would be an approach to this problem and I know numpy has a convolve function build in.
How can I use the [numpy.convolve](http://docs.scipy.... | You want to look at [`ndimage`](http://docs.scipy.org/doc/scipy/reference/ndimage.html), which is a module in `scipy`. It has a number of filters
all set up as functions, and nice wrappers for convolving arbitrary kernels.
For example,
```
img_gaus = ndimage.filters.gaussian_filter(img, 2, mode='nearest')
```
convol... |
Image smoothing in Python | 14,765,891 | 11 | 2013-02-08T04:50:00Z | 14,766,356 | 14 | 2013-02-08T05:37:21Z | [
"python",
"image-processing",
"smoothing"
] | I wanted to try to write a simple function to smooth an inputted image. I was trying to do this using the Image and numpy libraries. I was thinking that using a convolution mask would be an approach to this problem and I know numpy has a convolve function build in.
How can I use the [numpy.convolve](http://docs.scipy.... | Nice question! **tcaswell** post here is a great suggestion, but you will not learn much this way because scipy is doing all the work for you! Since your question said you wanted to *try and write the function*, I will show you a bit more crude and basic kind of way to do it all manually in the hope that you will bette... |
testing whether a Numpy array contains a given row | 14,766,194 | 27 | 2013-02-08T05:20:34Z | 14,766,816 | 20 | 2013-02-08T06:18:12Z | [
"python",
"numpy"
] | Is there a Pythonic and efficient way to check whether a Numpy array contains at least one instance of a given row? By "efficient" I mean it terminates upon finding the first matching row rather than iterating over the entire array even if a result has already been found.
With Python arrays this can be accomplished ve... | You can use .tolist()
```
>>> a = np.array([[1,2],[10,20],[100,200]])
>>> [1,2] in a.tolist()
True
>>> [1,20] in a.tolist()
False
>>> [1,20] in a.tolist()
False
>>> [1,42] in a.tolist()
False
>>> [42,1] in a.tolist()
False
```
Or use a view:
```
>>> any((a[:]==[1,2]).all(1))
True
>>> any((a[:]==[1,20]).all(1))
False... |
testing whether a Numpy array contains a given row | 14,766,194 | 27 | 2013-02-08T05:20:34Z | 14,772,313 | 16 | 2013-02-08T12:12:57Z | [
"python",
"numpy"
] | Is there a Pythonic and efficient way to check whether a Numpy array contains at least one instance of a given row? By "efficient" I mean it terminates upon finding the first matching row rather than iterating over the entire array even if a result has already been found.
With Python arrays this can be accomplished ve... | Numpys `__contains__` is at the time of writing this `(a == b).any()` which is arguably only correct if `b` is a scalar (it is a bit hairy, but I believe â works like this only in 1.7. or later â this would be the right general method `(a == b).all(np.arange(a.ndim - b.ndim, a.ndim)).any()`, which makes sense for a... |
Why does setattr and getattr allow whitespace? | 14,766,196 | 8 | 2013-02-08T05:20:37Z | 14,766,326 | 7 | 2013-02-08T05:34:00Z | [
"python",
"attributes"
] | Let's say I define this class:
```
class A:
pass
a = A()
```
Now obviously I can set attributes like so:
```
a.x = 5
```
But with `setattr`, I can give `a` attributes which contain whitespace in their names.
```
setattr(a, 'white space', 1)
setattr(a, 'new\nline', None)
```
`dir(a)` contains `'white space'` ... | Object attributes are merely those attributes defined in an object's `__dict__`. If you think of it from that perspective then allowing whitespace (or any other character that can be included in a `str`) in an attribute name makes total sense.
```
>>> class X(object):
... pass
...
>>> x = X()
>>> setattr(x, 'some at... |
how to use custom django templatetag with django template if statement? | 14,767,516 | 3 | 2013-02-08T07:17:00Z | 14,767,556 | 9 | 2013-02-08T07:21:29Z | [
"python",
"django",
"django-templates"
] | I've made a django template tag that counts one of my custom user many-to-many field length:
```
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def unread_messages_count(context):
user = context['request'].user
return len(user.messages_unread.all())
```
an... | The easiest way would be to use an assignment tag..
<https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags>
```
@register.assignment_tag(takes_context=True)
def unread_messages_count(context):
user = context['request'].user
return len(user.messages_unread.all())
{% unread_messages... |
How to detect object on images? | 14,767,594 | 10 | 2013-02-08T07:24:09Z | 14,767,815 | 12 | 2013-02-08T07:39:46Z | [
"python",
"opencv",
"computer-vision"
] | I need python solution.
I have 40-60 images (Happy Holiday set). I need to detect object on all these images.
I don't know object size, form, location on image, I don't have any object template. I know only one thing: this object is present in almost all images. I called it UFO.
Example:
![enter image description he... | When you have the image data as array, you can use built-in numpy function to do this easily and fast:
```
import numpy as np
import PIL
image = PIL.Image.open("14767594_in.png")
image_data = np.asarray(image)
image_data_blue = image_data[:,:,2]
median_blue = np.median(image_data_blue)
non_empty_columns = np.where... |
How to fail a python unittest in setUpClass? | 14,768,135 | 12 | 2013-02-08T08:02:10Z | 14,768,181 | 18 | 2013-02-08T08:05:58Z | [
"python",
"unit-testing",
"python-2.7"
] | I am doing some unittests with python and some pre-test checks in `setUpClass`. How can I throw a `unitest`-`fail` within the `setUpClass`, as the following simple example:
```
class MyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
unittest.TestCase.fail("Test")
def test1(self):
... | `self.fail("test")` put into your setUp instance method fails all the tests
I think the easiest way to do this at the class level is to make a class variable so something like:
```
@classmethod
def setUpClass(cls):
cls.flag = False
def setUp(self):
if self.flag:
self.fail("conditions not met")
```
Hope... |
How to fail a python unittest in setUpClass? | 14,768,135 | 12 | 2013-02-08T08:02:10Z | 14,768,333 | 16 | 2013-02-08T08:16:04Z | [
"python",
"unit-testing",
"python-2.7"
] | I am doing some unittests with python and some pre-test checks in `setUpClass`. How can I throw a `unitest`-`fail` within the `setUpClass`, as the following simple example:
```
class MyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
unittest.TestCase.fail("Test")
def test1(self):
... | Using a simple assert should work
```
assert False, "I mean for this to fail"
``` |
View function did not return a response | 14,770,098 | 7 | 2013-02-08T10:06:50Z | 14,770,234 | 11 | 2013-02-08T10:14:39Z | [
"python",
"sql",
"flask"
] | I want to send a query to mysql and fetch an array. But however I do it I cannot make it work. Here's my code:
```
@app.route('/auth',methods=['GET','POST'])
def auth():
username = request.form['username']
password = request.form['password']
cur = db.cursor()
cur.execute("SELECT * FROM tbl_user WHER... | Flask throws this exception because your `auth` view didn't return anything. Return a response from your `auth` view:
```
return 'Some response'
```
To return the MySQL results, perhaps join the rows together into one string:
```
cur.execute("SELECT * FROM tbl_user WHERE username = '%s' " % username)
return '\n'.joi... |
changing figure size with subplots | 14,770,735 | 30 | 2013-02-08T10:41:57Z | 14,770,827 | 61 | 2013-02-08T10:48:03Z | [
"python",
"matplotlib"
] | I came across this example in the matplotlib website
<http://matplotlib.org/examples/pylab_examples/subplots_demo.html>
and I was wondering if it was possible to increase the figure size.
I tried with
```
f.figsize(15,15)
```
but it does nothing. | If you already have the figure object use:
```
f.set_figheight(15)
f.set_figwidth(15)
```
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
```
f, axs = plt.subplots(2,2,figsize=(15,15))
``` |
Python json.loads doesn't work | 14,771,570 | 7 | 2013-02-08T11:30:09Z | 14,771,593 | 7 | 2013-02-08T11:31:09Z | [
"python",
"json"
] | I've been trying to figure out how to load JSON objects in Python.
```
def do_POST(self):
length = int(self.headers['Content-Length'])
decData = str(self.rfile.read(length))
print decData, type(decData)
"{'name' : 'journal2'}" <type 'str'>
postData = json.loads(decData)
print postData, type(... | Your JSON data is enclosed in extra quotes making it a JSON string, *and* the data contained within that string is *not* JSON.
Print `repr(decData)` instead, you'll get:
```
'"{\'name\' : \'journal2\'}"'
```
and the JSON library is correctly interpreting that as one string with the literal contents `{'name' : 'journ... |
matplotlib axis label format | 14,775,040 | 18 | 2013-02-08T14:45:06Z | 14,775,453 | 18 | 2013-02-08T15:05:51Z | [
"python",
"matplotlib"
] | I am having an issue with the format of the tick labels of an axis. I disabled the offset from the y\_axis:
```
ax1.ticklabel_format(style = 'sci', useOffset=False)
```
and tried to put it a scientific format but all I get is:
```
0.00355872
```
but I expected something like:
```
3.55872...E-2
```
or similar.
wh... | There are a number of ways to do this
You could just tweak the power limits [(doc)](http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.ScalarFormatter.set_powerlimits)
```
ax1.xaxis.get_major_formatter().set_powerlimits((0, 1))
```
which set the powers where `ScalerFormatter` switches to scientific notation... |
matplotlib axis label format | 14,775,040 | 18 | 2013-02-08T14:45:06Z | 19,175,976 | 20 | 2013-10-04T07:47:35Z | [
"python",
"matplotlib"
] | I am having an issue with the format of the tick labels of an axis. I disabled the offset from the y\_axis:
```
ax1.ticklabel_format(style = 'sci', useOffset=False)
```
and tried to put it a scientific format but all I get is:
```
0.00355872
```
but I expected something like:
```
3.55872...E-2
```
or similar.
wh... | You should also specify axis and threshold limits:
```
ax1.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))
```
This would use sci format on *y* axis when figures are out of the `[0.01, 99]` bounds. |
Coloring exceptions from Python on a terminal | 14,775,916 | 5 | 2013-02-08T15:30:30Z | 14,776,693 | 8 | 2013-02-08T16:09:05Z | [
"python",
"exception",
"colors"
] | Is there an easy way to get the *message* of the exception to be colored on the command line? For example
```
def g(): f()
def f(): 1/0
g()
```
Gives the error
```
Traceback (most recent call last):
File "test.py", line 3, in <module>
g()
File "test.py", line 1, in g
def g(): f()
File "test.py... | You can assign a custom function to the [`sys.excepthook` handler](http://docs.python.org/2/library/sys.html#sys.excepthook). The function is called whenever there is a *unhandled* exception (so one that exits the interpreter).
```
import sys
def myexcepthook(type, value, tb):
import traceback
from pygments i... |
How to run custom manage.py in crontab + virtual env? | 14,776,015 | 4 | 2013-02-08T15:35:21Z | 14,776,188 | 11 | 2013-02-08T15:43:03Z | [
"python",
"django",
"virtualenv",
"crontab"
] | How to run in crontab
```
*/1 * * * * /home/user/Desktop/job/dp/ python manage.py statistics
```
with virtual env? I need to activate virtualenv first(Otherwise it does not work)
This is my virtual env:
```
source job/bin/activate
``` | **EDITED**:
Try something like this:
```
*/1 * * * * . /path-to-env/bin/activate && /home/user/Desktop/job/dp/manage.py statistics
```
This should be read as: activate the env and if that was successful, excute the manage.py script. Since manage.py is supposed to have a python shebang and the virtual env sets the co... |
Split a string using an integer as a delimeter | 14,776,127 | 3 | 2013-02-08T15:40:38Z | 14,776,140 | 10 | 2013-02-08T15:41:14Z | [
"python",
"regex"
] | I have a rather long txt file filled with strings of the format `{letter}{number}{letter}`. For instance, the first few lines of my file are:
```
A123E
G234W
R3L
H4562T
```
I am having difficulty finding the correct `regex` pattern to separate each line by alpha and numeric.
For instance, in the first line, I would ... | Split on `\d+`:
```
import re
re.split(r'(\d+)', line)
```
`\d` is the character class matching the digits 0 through to 9, and we want to match at least 1 of them. By putting a capturing group around the `\d+`, [`re.split()` will include the match in the output](http://docs.python.org/2/library/re.html#re.split):
> ... |
Good design pattern(s) for extensible program | 14,776,333 | 7 | 2013-02-08T15:50:54Z | 14,776,427 | 8 | 2013-02-08T15:55:22Z | [
"python",
"design-patterns",
"design",
"architecture",
"factory-pattern"
] | I have a question about how to make a good design for my program. My program is quite simple but I want to have good architecture and make my program easily extensible in the future.
My program need to fetch data from external data sources (XML), extract information from these data and at the end it need to prepare SQ... | If the fetchers all have the same interface, you can use a dictionary:
```
fetcher_dict = {'X':XDataFetcher,'Y':YDataFetcher}
data_source = ...
fetcher = fetcher_dict[data_source]()
```
As far as keeping things flexible -- Just write clean idiomatic code. I tend to like the "You ain't gonna need it" ([YAGNI](http://e... |
Python - How can I pad a string with spaces from the right and left? | 14,776,788 | 21 | 2013-02-08T16:13:51Z | 14,776,800 | 56 | 2013-02-08T16:14:36Z | [
"python",
"string"
] | I have two scenarios where I need to pad a string with whitespaces up to a certain length, in both the left and right directions (in separate cases). For instance, I have the string:
```
TEST
```
but I need to make the string variable
```
_____TEST1
```
so that the actual string variable is 10 characters in length ... | You can look into [`str.ljust` and `str.rjust`](https://docs.python.org/2/library/stdtypes.html#str.ljust) I believe.
The alternative is probably to use the [format](http://docs.python.org/2/library/string.html#format-examples) method:
```
>>> '{:<30}'.format('left aligned')
'left aligned '
>>> '{:>3... |
Is it good practice to depend on python's with...as statement | 14,776,853 | 12 | 2013-02-08T16:16:57Z | 14,776,885 | 17 | 2013-02-08T16:18:34Z | [
"python",
"with-statement",
"contextmanager"
] | I'm curious if it is considered safe or good practice to depend on python's with...as statement. For example when opening a file:
```
with open("myfile","w") as myFile:
#do something
```
So in this example I neglected to explicitly call `myFile.close()` however I can assume it was called when python exited the `w... | This is what context managers are *for*, to rely on *them* to close the file for you. Context managers are called even if there was an exception.
The alternative is to use an `finally` block instead:
```
myFile = open("myfile","w")
try:
# do something with myFile
finally:
myFile.close()
```
but because the b... |
Python - Splitting List That Contains Strings and Integers | 14,776,980 | 4 | 2013-02-08T16:25:00Z | 14,777,046 | 11 | 2013-02-08T16:28:38Z | [
"python",
"string",
"list",
"int"
] | ```
myList = [ 4,'a', 'b', 'c', 1 'd', 3]
```
how to split this list into two list that one contains strings and other contains integers in *elegant/pythonic* way?
output:
```
myStrList = [ 'a', 'b', 'c', 'd' ]
myIntList = [ 4, 1, 3 ]
```
NOTE: didn't implemented such a list, just thought about how to find an eleg... | As others have mentioned in the comments, you should really start thinking about how you can get rid of the list which holds in-homogeneous data in the first place. However, if that really *can't* be done, I'd use a defaultdict:
```
from collections import defaultdict
d = defaultdict(list)
for x in myList:
d[type(x... |
Python - Splitting List That Contains Strings and Integers | 14,776,980 | 4 | 2013-02-08T16:25:00Z | 14,777,089 | 8 | 2013-02-08T16:30:47Z | [
"python",
"string",
"list",
"int"
] | ```
myList = [ 4,'a', 'b', 'c', 1 'd', 3]
```
how to split this list into two list that one contains strings and other contains integers in *elegant/pythonic* way?
output:
```
myStrList = [ 'a', 'b', 'c', 'd' ]
myIntList = [ 4, 1, 3 ]
```
NOTE: didn't implemented such a list, just thought about how to find an eleg... | You can use list comprehension: -
```
>>> myList = [ 4,'a', 'b', 'c', 1, 'd', 3]
>>> myIntList = [x for x in myList if isinstance(x, int)]
>>> myIntList
[4, 1, 3]
>>> myStrList = [x for x in myList if isinstance(x, str)]
>>> myStrList
['a', 'b', 'c', 'd']
``` |
Matplotlib discrete colorbar | 14,777,066 | 24 | 2013-02-08T16:29:47Z | 14,777,392 | 25 | 2013-02-08T16:47:41Z | [
"python",
"matplotlib"
] | I am trying to make a discrete colorbar for a scatterplot in matplotlib
I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.
```
plt.scatter(x, y, c=tag)
```
typically tag will be an integer ranging from 0-20, but the exact range may change
so far I h... | You could follow this [example](http://matplotlib.org/1.2.0/examples/pylab_examples/poormans_contour.html):
```
#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.
Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.... |
Matplotlib discrete colorbar | 14,777,066 | 24 | 2013-02-08T16:29:47Z | 14,779,462 | 39 | 2013-02-08T18:57:42Z | [
"python",
"matplotlib"
] | I am trying to make a discrete colorbar for a scatterplot in matplotlib
I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.
```
plt.scatter(x, y, c=tag)
```
typically tag will be an integer ranging from 0-20, but the exact range may change
so far I h... | You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.
For images i often use the cmap.set\_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get th... |
Matplotlib discrete colorbar | 14,777,066 | 24 | 2013-02-08T16:29:47Z | 14,780,073 | 13 | 2013-02-08T19:38:21Z | [
"python",
"matplotlib"
] | I am trying to make a discrete colorbar for a scatterplot in matplotlib
I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.
```
plt.scatter(x, y, c=tag)
```
typically tag will be an integer ranging from 0-20, but the exact range may change
so far I h... | To set a values above or below the range of the colormap, you'll want to use the `set_over` and `set_under` methods of the colormap. If you want to flag a particular value, mask it (i.e. create a masked array), and use the `set_bad` method. (Have a look at the documentation for the base colormap class: <http://matplotl... |
Matplotlib discrete colorbar | 14,777,066 | 24 | 2013-02-08T16:29:47Z | 28,730,546 | 11 | 2015-02-25T22:04:23Z | [
"python",
"matplotlib"
] | I am trying to make a discrete colorbar for a scatterplot in matplotlib
I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g.
```
plt.scatter(x, y, c=tag)
```
typically tag will be an integer ranging from 0-20, but the exact range may change
so far I h... | The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:
```
import matplotlib.pyplot as plt
import numpy as np
... |
Scrapy crawl from script always blocks script execution after scraping | 14,777,910 | 17 | 2013-02-08T17:18:45Z | 14,802,526 | 27 | 2013-02-10T20:59:35Z | [
"python",
"twisted",
"scrapy"
] | I am following this guide <http://doc.scrapy.org/en/0.16/topics/practices.html#run-scrapy-from-a-script> to run scrapy from my script.
Here is part of my script:
```
crawler = Crawler(Settings(settings))
crawler.configure()
spider = crawler.spiders.create(spider_name)
crawler.crawl(spider)
crawler.... | You will need to stop the reactor when the spider finishes. You can accomplish this by listening for the `spider_closed` signal:
```
from twisted.internet import reactor
from scrapy import log, signals
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy.xlib.pydispatch import dispatche... |
How do I call a model method in django ModelAdmin fieldsets? | 14,777,989 | 9 | 2013-02-08T17:23:38Z | 14,778,274 | 16 | 2013-02-08T17:41:33Z | [
"python",
"django",
"django-models",
"django-admin"
] | I want to display an embedded map on an admin form when data already exists in the db. I have the following code:
models.py
```
class Address(models.Model):
address = models.CharField()
def address_2_html(self):
if self.address:
# Return html for an embedded map using the entered address.... | Like that (from memory):
```
class AddressAdmin(admin.ModelAdmin):
fieldsets = [(label, {'fields': ['address','address_2_html']}),]
readonly_fields = ['address_2_html']
def address_2_html(self, obj):
return obj.address_2_html()
address_2_html.allow_tags = True
address_2_html.short_descript... |
Autoincrementing option for Pandas DataFrame index | 14,778,042 | 7 | 2013-02-08T17:27:14Z | 14,778,334 | 11 | 2013-02-08T17:45:36Z | [
"python",
"indexing",
"append",
"row",
"pandas"
] | Is there a way to set an option for auto-incrementing the index of pandas.DataFrame when adding new rows, or to define a function for managing creation of new indices? | You can set `ignore_index=True` when [`append`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.append.html)-ing:
```
In [1]: df = pd.DataFrame([[1,2],[3,4]])
In [2]: row = pd.Series([5,6])
In [3]: df.append(row, ignore_index=True)
Out[3]:
0 1
0 1 2
1 3 4
2 5 6
``` |
Password hashing: Keccak or not | 14,779,216 | 3 | 2013-02-08T18:40:48Z | 14,862,876 | 18 | 2013-02-13T20:51:21Z | [
"php",
"python",
"blowfish",
"sha-3",
"keccak"
] | The winner of `SHA-3` hashing algorithm contest has been chosen. The winner's algorithm is **Keccak**.
I use Blowfish and really like it, but Keccak is said to be better. Is it worth to use it for storing user's passwords on my website?
If yes, are there any implementations of Keccak for PHP, Python, Ruby or any othe... | *short answer:*
No, and probably never. For password hashing, BCrypt & PBKDF2-HMAC-*xxx* are better choices than any simple SHA-*1/2/3* algorithm. And until SHA-1/2 actual have feasible preimage attacks published, SHA-3 is actually the *worst* choice, specifically *because* of it's speed and low cache footprint.
*lon... |
Curses alternative for windows | 14,779,486 | 21 | 2013-02-08T18:59:01Z | 14,779,649 | 7 | 2013-02-08T19:08:40Z | [
"python",
"curses"
] | Is there any alternative of the curses module for python to use in windows? I looked up in the python documentation, but there its mentioned that its for using in unix. I am not much familiar with these, so is there some way to use curses module in windows or is there some similar module specially for windows?
[I am us... | Then you're out of luck i'm afraid.
There's no real cross-platform version or port of curses/ncurses, there is a "dialogue" port which works, but it's limited in capabilities.
Your best bet is to run CygWin or MinGW32, both are, in "loose terms", a Linux system+terminal emulator which has much of the binaries you need... |
Curses alternative for windows | 14,779,486 | 21 | 2013-02-08T18:59:01Z | 19,851,287 | 53 | 2013-11-08T03:50:21Z | [
"python",
"curses"
] | Is there any alternative of the curses module for python to use in windows? I looked up in the python documentation, but there its mentioned that its for using in unix. I am not much familiar with these, so is there some way to use curses module in windows or is there some similar module specially for windows?
[I am us... | I'm happy to report that there's now a Windows build of Curses available as an extension for Python on Windows, from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses).
You can run the installer, and `import curses` to get curses running. (Verified on 64-bit Windows 7 and Windows 8.)
@ArtOfWarfare points out t... |
Curses alternative for windows | 14,779,486 | 21 | 2013-02-08T18:59:01Z | 32,385,199 | 8 | 2015-09-03T20:50:56Z | [
"python",
"curses"
] | Is there any alternative of the curses module for python to use in windows? I looked up in the python documentation, but there its mentioned that its for using in unix. I am not much familiar with these, so is there some way to use curses module in windows or is there some similar module specially for windows?
[I am us... | The original question was whether there is an *alternative* to curses on Windows.
One answer is to use the [Win32 console API](https://msdn.microsoft.com/en-gb/library/windows/desktop/ms682073(v=vs.85).aspx). You can program this directly in Python using the excellent pywin32 package if you're already familiar with th... |
How to add inline comments to multiline string assignments in python | 14,779,686 | 10 | 2013-02-08T19:10:28Z | 14,779,716 | 11 | 2013-02-08T19:12:31Z | [
"python",
"comments"
] | How to add comments to multiline assignments in python, as is possible in C with the syntax:
```
char sc[] = "\x31\xdb" /* xor %ebx, %ebx */
"\x31\xc9" /* xor %ecx, %ecx */
"\xb8\x46\x00\x00\x00" /* mov $0x46, %eax */
"\xcd\x80... | You can write
```
sc = ("\x31\xdb" # xor %ebx, %ebx
"\x31\xc9" # xor %ecx, %ecx
"â¦")
```
if you want. |
How to compare the modified date of two files in python? | 14,779,775 | 9 | 2013-02-08T19:16:23Z | 14,779,850 | 15 | 2013-02-08T19:21:29Z | [
"python"
] | I am creating a python script that will access each line from a Text file(say File.txt) one by one then search for corresponding '.py' and '.txt' file in the system directory. For example if "COPY"(the first line) is accessed from "File.txt" then search will be done for "COPY.py" and "COPY.txt". If both the files are f... | [`time.ctime()`](http://docs.python.org/2/library/time.html#time.ctime) formats a time as a string, so you're comparing the strings `"Fri Feb 08 16:34:43 2013"` and `"Sat Sep 22 14:19:32 2012"` textually. Just don't do that and compare the `float`s that `getmtime()` gives you directly:
```
pytime = os.path.getmtime(os... |
Python list to Cython | 14,780,007 | 9 | 2013-02-08T19:32:45Z | 14,780,449 | 16 | 2013-02-08T20:03:52Z | [
"python",
"arrays",
"cython"
] | I want to know how to convert normal python list to C list with Cython , process it and return a python list. Like:
Python script:
```
import mymodule
a = [1,2,3,4,5,6]
len = len(a)
print(mymodule.process(a,len))
```
Cython script (mymodule.pyd):
```
cpdef process(a, int len):
cdef float y
for i in range(l... | You'll need to copy the contents of the list to an array explicitly. For example...
```
cimport cython
from libc.stdlib cimport malloc, free
...
def process(a, int len):
cdef int *my_ints
my_ints = <int *>malloc(len(a)*cython.sizeof(int))
if my_ints is NULL:
raise MemoryError()
for i in xr... |
This expression is true in Python: {}.keys().insert(0, "") == None. Why? | 14,780,563 | 3 | 2013-02-08T20:11:25Z | 14,780,592 | 10 | 2013-02-08T20:13:50Z | [
"python"
] | Look to my Python session:
```
>>> {}.keys().insert(0, "") == None
True
```
but:
```
>>> k = {}.keys()
>>> k
[]
>>> k.insert(0, "")
>>> k
['']
```
Why??
**PS**. Thanks for help! Python have very strange design - do not support chaining:
* <http://en.wikipedia.org/wiki/Method_chaining>
That is root of my problem.... | `list.insert` *returns* `None`; when you print `k` you're printing the new state of the list. |
String of bytes into an int | 14,780,869 | 4 | 2013-02-08T20:32:53Z | 14,780,887 | 12 | 2013-02-08T20:34:20Z | [
"python"
] | I want to convert a string like this into an int: `s = 'A0 00 00 00 63'`. What's the easiest/best way to do that?
For example `'20 01'` should become `8193` (2 \* 16^3 + 1 \* 16^0 = 8193). | Use `int()` with either `str.split()`:
```
In [31]: s='20 01'
In [32]: int("".join(s.split()),16)
Out[32]: 8193
```
or `str.replace()` and pass the base as 16:
```
In [34]: int(s.replace(" ",""),16)
Out[34]: 8193
```
Here both `split()` and `replace()` are converting `'20 01'` into `'2001'`:
```
In [35]: '20 01'.... |
numpy matrix trickery - sum of inverse times matrices | 14,783,386 | 11 | 2013-02-09T00:09:05Z | 14,784,037 | 7 | 2013-02-09T01:38:32Z | [
"python",
"numpy",
"scipy",
"linear-algebra"
] | I'm trying to do the following, and repeat until convergence:

where each Xi is `n x p`, and there are `r` of them in an `r x n x p` array called `samples`. `U` is `n x n`, `V` is `p x p`. (I'm getting the MLE of a [matrix normal distribution](http://en.wikipedia.org/wiki/Matrix_nor... | Until someone comes up with a more inspired answer, if I were you, I'd let the fairies cry...
```
r, n, p = 200, 400, 400
X = np.random.rand(r, n, p)
U = np.random.rand(n, n)
In [2]: %timeit np.sum(np.dot(x.T, np.linalg.solve(U, x)) for x in X)
1 loops, best of 3: 9.43 s per loop
In [3]: %timeit np.dot(X[0].T, np.l... |
Encoding error with sqlalchemy and postgresql | 14,783,505 | 9 | 2013-02-09T00:26:15Z | 14,788,796 | 21 | 2013-02-09T13:43:21Z | [
"python",
"postgresql",
"encoding",
"sqlalchemy"
] | I'm using pyramid for a web application with a postgres database, wtforms, sqlalchemy and jinja2 and I'm having this error when the application try to get the issues types from database to fill a select field with wtforms:
```
Error: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)
```
th... | You need to configure Psycopg2's client encoding. See the [SQLAlchemy documentation](http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#unicode):
> By default, the psycopg2 driver uses the `psycopg2.extensions.UNICODE` extension, such that the DBAPI receives and returns all strings as Python Unicode objects... |
Grouping / clustering numbers in Python | 14,783,947 | 6 | 2013-02-09T01:24:59Z | 14,783,998 | 15 | 2013-02-09T01:31:56Z | [
"python",
"numbers",
"iteration"
] | I've googled, I've tested, and this has me at my wits end. I have a list of numbers I need to group by similarity. For instance, in a list of [1, 6, 9, 100, 102, 105, 109, 134, 139], 1 6 9 would be put into a list, 100, 102, 105, and 109 would be put into a list, and 134 and 139. I'm terrible at math, and I've tried an... | There are many ways to do [cluster analysis](https://en.wikipedia.org/wiki/Cluster_analysis). One simple approach is to look at the gap size between successive data elements:
```
def cluster(data, maxgap):
'''Arrange data into groups where successive elements
differ by no more than *maxgap*
>>> clu... |
`make install` with CMake + SWIG + Python | 14,784,134 | 7 | 2013-02-09T01:53:16Z | 14,796,658 | 8 | 2013-02-10T10:14:09Z | [
"c++",
"python",
"makefile",
"cmake",
"swig"
] | I am writing a C++ library which can be used from both C++ and Python on Mac and Linux. So I have decided to use CMake and SWIG for my project.
As well described in the SWIG 2.0 documentation, combination of SWIG and CMake also works fine on my Mac.
<http://www.swig.org/Doc2.0/SWIGDocumentation.html#Introduction_build... | ```
find_package(SWIG REQUIRED)
find_package(PythonLibs REQUIRED)
include(${SWIG_USE_FILE})
set(CMAKE_SWIG_FLAGS "")
include_directories(${PYTHON_INCLUDE_DIRS})
set_source_files_properties(target.i PROPERTIES CPLUSPLUS ON)
set_source_files_properties(target.i PROPERTIES SWIG_FLAGS "-includeall")
swig_add_module(targe... |
Python CSV Error: sequence expected | 14,784,334 | 8 | 2013-02-09T02:33:20Z | 14,784,435 | 11 | 2013-02-09T02:49:00Z | [
"python",
"csv"
] | I am attempting to run the following code in Python, and am getting the error:
```
csv.Error: sequence expected
```
Does anyone have any idea what is wrong with my code? (The file was previously imported into the program).
```
import csv
file = open('/home/btoms/Desktop/TomsBen/2000/01/01/20000101acme.mts', 'r')
v... | `writer.writerow` expects a sequence (a tuple or list) of values to write in a single row, with one value per column in that row. What you have given it instead is a single value. Your code really should look more like:
```
writer.writerow([tmp_STID, tmp_Times, tmp_T, tmp_RH])
```
and it looks to me like most of this... |
How to change index of for loop in Python? | 14,785,495 | 14 | 2013-02-09T06:09:09Z | 14,785,513 | 28 | 2013-02-09T06:12:55Z | [
"python",
"for-loop"
] | Suppose I have a for loop:
```
for i in range(1,10):
if i is 5:
i = 7
```
I want to change `i` if it meets certain condition. I tried this but didn't work.
How do I go about it? | For your particular example, this will work:
```
for i in range(1, 10):
if i in (5, 6):
continue
```
However, you would probably be better off with a `while` loop:
```
i = 1
while i < 10:
if i == 5:
i = 7
# other code
i += 1
```
A `for` loop assigns a variable (in this case `i`) to t... |
Running statements in 'parallel' | 14,785,612 | 8 | 2013-02-09T06:33:14Z | 14,785,624 | 18 | 2013-02-09T06:35:12Z | [
"c++",
"python"
] | In python, I one had to swap values of 2 variables, all you need to do was
```
x,y=y,x
```
One can look at it as if the two statements-(x=y) and (y=x) are executed in parallel and not one after another.
Is there any way to achieve the same effect in c++?
**NOTE/EDIT:**
I am looking to extend this 'parallel effect'... | **Special case: Swapping the value of two variables**
(For the general solution, see below.)
To swap two variable's values in C++, you should always use [`swap`](http://en.cppreference.com/w/cpp/algorithm/swap):
```
using std::swap;
swap(x, y); // Do NOT say: std::swap(x, y) -- Read about Koenig lookup!
```... |
How to change the color of certain words in the tkinter text widget? | 14,786,507 | 7 | 2013-02-09T09:02:27Z | 30,339,009 | 9 | 2015-05-20T01:54:00Z | [
"python",
"python-3.x",
"tkinter"
] | I have a program that i want to be like the python shell and change color of certain words when they are typed any help? | The main idea is to apply *tags* to the parts of text you want to customise. You can create your tags using the method [`tag_configure`](http://effbot.org/tkinterbook/text.htm#Tkinter.Text.tag_config-method), with a specific style, and then you just need to apply this tag to the part of text you want to change using th... |
Confused with getattribute and setattribute in python | 14,787,334 | 8 | 2013-02-09T10:50:28Z | 14,787,522 | 25 | 2013-02-09T11:15:50Z | [
"python"
] | I wan to know that if I have class like this
```
class Test(object):
def __init__(self):
self.a = 20
self.b = 30
```
> obj = Test()
When I do `obj.a`, then which is called first?
`__getattr__` or `getattr` or lookup in `__dict__['a']`
and same with setattr
According to docs
```
object.... | It's a bit complicated. Here's the sequence of checks Python does if you request an attribute of an object.
First, Pyton will check if the object's class has a `__getattribute__` method. If it doesn't have one defined, it will inherit `object.__getattribute__` which implements the other ways of finding the attribute's... |
Plot x-y data if x entry meets condition python | 14,788,459 | 4 | 2013-02-09T13:04:39Z | 14,788,573 | 8 | 2013-02-09T13:16:31Z | [
"python",
"matplotlib"
] | I would like to perform plots/fits for x-y data, provided that the data set's x values meet a condition (i.e. are greater than 10).
My attempt:
```
x_values, y_values = loadtxt(fname, unpack=True, usecols=[1, 0])
for x in x_values:
if x > 10:
(m,b)=polyfit(x_values,y_values,1)
yp = polyval([m,b],... | Sure, just use boolean indexing. You can do things like `y = y[x > 10]`.
E.g.
```
import numpy as np
import matplotlib.pyplot as plt
#-- Generate some data...-------
x = np.linspace(-10, 50, 100)
y = x**2 + 3*x + 8
# Add a lot of noise to part of the data...
y[x < 10] += np.random.random(sum(x < 10)) * 300
# Now l... |
dtypes. Difference between S1 and S2 in Python | 14,790,130 | 4 | 2013-02-09T16:27:24Z | 14,790,178 | 10 | 2013-02-09T16:32:56Z | [
"python",
"numpy"
] | I have two arrays of strings:
```
In [51]: r['Z']
Out[51]:
array(['0', '0', '0', ..., '0', '0', '0'],
dtype='|S1')
In [52]: r['Y']
Out[52]:
array(['X0', 'X0', 'X0', ..., 'X0', 'X1', 'X1'],
d... | See the [`dtypes` documentation](http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html).
The `|S1` and `|S2` strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. The `|` pipe symbol is the [byteorder flag](http://docs.scipy.org/doc/numpy/reference/gener... |
Do Unicode strings in Python 3 still depend on "narrow" / "wide" builds? | 14,790,708 | 7 | 2013-02-09T19:34:32Z | 14,790,983 | 8 | 2013-02-09T20:02:51Z | [
"python",
"unicode",
"python-3.x"
] | Since Python 2.2 and [PEP 261](http://www.python.org/dev/peps/pep-0261/), Python can be built in "narrow" or "wide" mode, which affects the definition of a "character", i.e. "the addressable unit of a Python Unicode string".
Characters in narrow builds look like UTF-16 code units:
```
>>> a = u'\N{MAHJONG TILE GREEN ... | Yes, from 3.0 to 3.2 they do. Windows uses narrow builds while (most) Unix uses wide builds
Using Python 3.2 on Windows:
```
>>> a = '\N{MAHJONG TILE GREEN DRAGON}'
>>> len(a)
2
>>> a
'í ¼í°
'
```
While this behavior is expected on 3.3+ using Windows:
```
>>> a = '\N{MAHJONG TILE GREEN DRAGON}'
>>> len(a)
1
>>> a
'... |
How can I check if key exists in list of dicts in python? | 14,790,980 | 7 | 2013-02-09T20:02:15Z | 14,790,997 | 19 | 2013-02-09T20:04:51Z | [
"python",
"python-2.7"
] | Say I have a list of dicts that looks like this:
```
[{1: "a"}, {2: "b"}]
```
What is the pythonic way to indicate if a certain key is in one of the dicts in the list? | I'd probably write:
```
>>> lod = [{1: "a"}, {2: "b"}]
>>> any(1 in d for d in lod)
True
>>> any(3 in d for d in lod)
False
```
although if there are going to be a lot of dicts in this list you might want to reconsider your data structure.
If you want the index and/or the dictionary where the first match is found, o... |
python flask import error | 14,792,605 | 13 | 2013-02-09T23:01:05Z | 19,470,924 | 44 | 2013-10-19T20:42:15Z | [
"python",
"flask",
"importerror"
] | I am running the following code
```
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
```
and getting the following error
```
Traceback (most recent call last):
File "test.py", line 1, in ... | I ran into this error because I named the test file as flask.py and tried to run it !
It creates namespace conflict with the real flask.py module!
**Delete your local files that you named flask.py flask.pyc**
Hope that helps |
How to use Flask-Security register view? | 14,793,098 | 14 | 2013-02-10T00:05:37Z | 15,049,512 | 23 | 2013-02-24T07:07:53Z | [
"python",
"flask",
"flask-extensions",
"flask-security"
] | Has anyone used `Flask-Security` extension for authentication? How do I get register view to work?
<http://packages.python.org/Flask-Security/customizing.html>
I am referring to link above.
```
@app.route('/register', methods=['GET'])
def register():
return render_template('security/register_user.html')
```
... | You don't need to create the view. A default one is included in Flask-Security.
You just need to enable it in your flask app config:
```
app = Flask(__name__)
app.config['SECURITY_REGISTERABLE'] = True
```
With this, the '/register' route should work.
There is another configuration value to change the URL if desire... |
'str' object has no attribute '_meta' | 14,794,677 | 6 | 2013-02-10T04:19:50Z | 14,794,771 | 8 | 2013-02-10T04:38:27Z | [
"python"
] | ```
def participant_specific(request, participant):
helper = RelayFunctions()
info = helper.participant_specific_donation(participant)
info1 = helper.participant_specific_milestone(participant)
data = { 'participant_specific_donation' : info , 'participant_specific_milestone' : info1 }
json_seriali... | json\_serializer.serialize is supposed to be used with a queryset. More info [here](https://docs.djangoproject.com/en/1.0/topics/serialization/#id2).
You should be able to achieve the same with this:
```
import json
data = json.dumps({ 'participant_specific_donation' : info , 'participant_specific_milestone' : info1 ... |
ImproperlyConfigured("settings.DATABASES is improperly configured. ") error when trying to set up Django | 14,795,824 | 8 | 2013-02-10T07:57:20Z | 15,938,596 | 8 | 2013-04-10T23:58:47Z | [
"python",
"sql",
"django",
"heroku",
"celery"
] | Attempting to follow the instructions [here](https://devcenter.heroku.com/articles/django) to set up a Django instance on Heroku.
Got as far as the installation of Celery, up to the following step:
```
$ python manage.py syncdb
```
when I get the following error:
> raise ImproperlyConfigured("settings.DATABASES is ... | I ran into the same issue. In the Heroku docs at <https://devcenter.heroku.com/articles/django#prerequisites>, it says to add the following to `settings.py`:
```
DATABASES['default'] = dj_database_url.config()
```
You can pass in a parameter of:
```
DATABASES['default'] = dj_database_url.config(default='postgres:/... |
How to get HTTP return code from python urllib's urlopen? | 14,796,153 | 4 | 2013-02-10T09:01:18Z | 14,796,188 | 8 | 2013-02-10T09:06:53Z | [
"python",
"urllib",
"python-2.5"
] | I have the following code:
```
f = urllib.urlopen(url)
html = f.read()
```
I would like to know the HTTP status code (HTTP 200, 404 etc) that comes from opening the url above.
Anybody knows how it can be done?
P.S.
I use python 2.5.
Thanks!!! | You can use the `.getcode()` method of the object returned by `urlopen()`
```
url = urllib.urlopen('http://www.stackoverflow.com/')
code = url.getcode()
``` |
Python syntax for an empty while loop | 14,797,046 | 9 | 2013-02-10T11:06:07Z | 14,797,055 | 17 | 2013-02-10T11:07:23Z | [
"python",
"while-loop"
] | I have written this:
```
while file.readline().startswith("#"):
continue
```
But I suspect the `continue` is unnecessary? What is the correct syntax for what i'm trying to achieve? | ```
while file.readline().startswith("#"):
pass
```
This uses the pass statement :
> The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
<http://www.network-theory.co.uk/docs/pytut/passStatements.html> |
Should I always specify an exception type in `except` statements? | 14,797,375 | 24 | 2013-02-10T11:43:43Z | 14,797,463 | 12 | 2013-02-10T11:54:23Z | [
"python",
"exception"
] | When using PyCharm IDE the use of `except:` without an exception type triggers a reminder from the IDE that this exception clause is `Too broad`.
Should I be ignoring this advice? Or is it Pythonic to always specific the exception type? | You should not be ignoring the advice that the interpreter gives you.
From the [PEP-8](http://www.python.org/dev/peps/pep-0008/) Style Guide for Python :
> When catching exceptions, mention specific exceptions whenever
> possible instead of using a bare except: clause.
>
> For example, use:
```
try:
import pla... |
Should I always specify an exception type in `except` statements? | 14,797,375 | 24 | 2013-02-10T11:43:43Z | 14,797,508 | 24 | 2013-02-10T12:01:51Z | [
"python",
"exception"
] | When using PyCharm IDE the use of `except:` without an exception type triggers a reminder from the IDE that this exception clause is `Too broad`.
Should I be ignoring this advice? Or is it Pythonic to always specific the exception type? | It's almost always better to specify an explicit exception type. If you use a naked `except:` clause, you might end up catching exceptions other than the ones you expect to catch - this can hide bugs or make it harder to debug programs when they aren't doing what you expect.
For example, if you're inserting a row into... |
Sending an existing dict through zmq ipc | 14,797,806 | 7 | 2013-02-10T12:36:59Z | 14,797,974 | 9 | 2013-02-10T12:59:30Z | [
"python",
"zeromq"
] | I'm trying to send an existing dict through zmq ipc socket, I can send a string with this code, but I can't send a dict object
```
import zmq, datetime
d = {0: ('356612022462768', 'EVENT', 0, '2012-12-26 15:50:16', -20.22216, -70.13723, 6.44, 134.0, 1, 2, '18743230', datetime.datetime(2013, 2, 10, 9, 6, 2, 362734))}
... | It is only possible to either send strings or byte arrays through ZeroMq, out-of-the-box. Anything else needs to be serialized before passing it to ZeroMq for transfer on the wire.
You can use whatever you like to serialize it, for example Protocol Buffers, JSON or Message Pack. Note that any recipients needs to be ab... |
Python Custom Iterator: Close a file on StopIteration | 14,797,930 | 6 | 2013-02-10T12:53:32Z | 14,798,115 | 8 | 2013-02-10T13:15:11Z | [
"python",
"file-io",
"iterator"
] | I have written an iterator class that opens a file in it's `__init__`.
```
def __init__(self, path):
self.file = open(path, "r")
```
How do I close that file automatically when the iteration is finished?
Complete class:
```
class Parse(object):
"""A generator that iterates through a CC-CEDICT formatted file... | A better way to write the whole thing would be to keep the opening and the iteration in one place:
```
class Parse(object):
"""A generator that iterates through a CC-CEDICT formatted file, returning
a tuple of parsed results (Traditional, Simplified, Pinyin, English)"""
def __init__(self, path):
se... |
How can I search sub-folders using glob.glob module in Python? | 14,798,220 | 36 | 2013-02-10T13:27:01Z | 14,798,263 | 53 | 2013-02-10T13:31:59Z | [
"python",
"glob"
] | I want to open a series of subfolders in a folder and find some text files and print some lines of the text files. I am using this:
```
configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt")
```
But this cannot access the subfolders as well. Does anyone know how I can use the same command to access subfolders as... | Current versions of `glob.glob()` cannot list files in subdirectories recursively (an [update that will be included in python 3.5 when released](http://bugs.python.org/issue13968) adds a `**` option for arbitrary nested directory traversal).
I'd use [`os.walk()`](http://docs.python.org/2/library/os.html#os.walk) combi... |
How can I search sub-folders using glob.glob module in Python? | 14,798,220 | 36 | 2013-02-10T13:27:01Z | 22,388,582 | 8 | 2014-03-13T19:10:15Z | [
"python",
"glob"
] | I want to open a series of subfolders in a folder and find some text files and print some lines of the text files. I am using this:
```
configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt")
```
But this cannot access the subfolders as well. Does anyone know how I can use the same command to access subfolders as... | The [glob2](https://pypi.python.org/pypi/glob2) package supports wild cards and is reasonably fast
```
code = '''
import glob2
glob2.glob("files/*/**")
'''
timeit.timeit(code, number=1)
```
On my laptop it takes approximately 2 seconds to match [>60,000 file paths](https://github.com/jsdelivr/jsdelivr/tree/master/fil... |
List Mutation on Python | 14,798,676 | 3 | 2013-02-10T14:19:58Z | 14,798,782 | 12 | 2013-02-10T14:32:40Z | [
"python"
] | I tried mutating a list by swapping a common element between the list and another reference list with the first element. The implementation is as shown below:
```
>>> L = [1,2,3,4,5,6,7,8,9]
>>> A = [3]
>>> L[0], L[L.index(A[0])] = L[L.index(A[0])], L[0] #want to swap 3 with 1
>>> L
[1,2,3,4,5,6,7,8,9,] #List L was... | Although in Python, the right-hand side is evaluated *first* when doing multiple assignments, the left-hand assigment *targets*, if they have expressions in them, are evaluated one by one when assigning.
If instead, they'd be evaluated as assignment targets first as you appear to expect, this would of course work.
Th... |
Avoiding boilerplate session handling code in sqlalchemy functions | 14,799,189 | 8 | 2013-02-10T15:16:53Z | 29,805,305 | 7 | 2015-04-22T17:49:33Z | [
"python",
"session",
"sqlalchemy"
] | I have a python application which has lots of small database access functions, using sqlalchemy. I'm trying to avoid having lots of boilerplate session handling code around these functions.
I have numerous functions that look something like this:
```
def get_ticket_history(Session, ticket_id):
s = Session()
t... | The SQLAlchemy docs present a possible way of doing this with context managers.
<http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it>
Copying the code snippet here for completeness:
```
from contextlib import contextmanager
@contextma... |
Django Static Files results in 404 | 14,799,835 | 6 | 2013-02-10T16:26:31Z | 14,800,489 | 11 | 2013-02-10T17:29:39Z | [
"python",
"django"
] | Ive checked over quite a few of the other threads on being unable to serve static content using the static file app within Django but as yet have yet to find a solution.
**settings.py**
```
STATIC_ROOT = '/opt/django/webtools/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
"/home/html/static",
)
STATICFILES... | For local serving of static files, **if you haven't** set up any form of collecting of staticfiles and if you're running Django 1.3+, I believe this is the way your `settings.py` should look like when refering to static files
```
# Absolute path to the directory static files should be collected to.
# Don't put anythin... |
zc.buildout stopped working: ImportError: No module named apport.fileutils | 14,801,416 | 11 | 2013-02-10T19:00:28Z | 14,801,592 | 24 | 2013-02-10T19:18:04Z | [
"python",
"buildout"
] | I've been using buildout for quite a while now without any issue, in fact I did yesterday without any problems.
But as today all my projects fail to buildout. I tried on two different Ubuntu workstations with the same result.
This is the error I get:
```
Initializing zc.buildout
Debug: Downloading http://pypi.python... | 2.0.0 just got released. The old bootstrap.py is not compatible with 2.0.0 but downloads it by default. You can get the v2 bootstrap.py from [here](http://downloads.buildout.org/2/bootstrap.py), or use the code below if you want to stick with the old version.
```
python bootstrap.py -v 1.7.0
```
edit: older versions ... |
tuple pairs, finding minimum, python | 14,802,128 | 8 | 2013-02-10T20:13:55Z | 14,802,198 | 21 | 2013-02-10T20:21:50Z | [
"python",
"tuples",
"min"
] | I have some data which comes as tuple pairs within python, e.g.
```
data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01), (6, 0.5), (7, 0.2), (8, 0.6)]
```
How may I find the min of the dataset by the comparison of the second number only?
i.e. data[0][1] = 7.57, data[1][1] = 2.1.. **min( data ) = (5, 0.01)**
... | ```
In [2]: min(data, key = lambda t: t[1])
Out[2]: (5, 0.01)
```
or:
```
In [3]: import operator
In [4]: min(data, key=operator.itemgetter(1))
Out[4]: (5, 0.01)
``` |
Error when install pylibmc using pip | 14,803,310 | 32 | 2013-02-10T22:25:58Z | 14,969,558 | 28 | 2013-02-19T23:27:49Z | [
"python",
"memcached",
"osx-lion",
"libmemcached"
] | Hello when I attempt to install pylibmc on OSX Lion using pip I get the following error:
```
./_pylibmcmodule.h:42:10: fatal error: 'libmemcached/memcached.h' file not found
#include <libmemcached/memcached.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
```
Any clues at how to s... | It's in the libmemcached package. To install it using macports:
`sudo port install libmemcached`
Then, assuming you're using pip:
`pip install pylibmc --install-option="--with-libmemcached=/opt/local"`
or
`LIBMEMCACHED=/opt/local pip install pylibmc`
as explained in the [pylibmc docs](http://sendapatch.se/project... |
Error when install pylibmc using pip | 14,803,310 | 32 | 2013-02-10T22:25:58Z | 19,432,949 | 65 | 2013-10-17T17:03:11Z | [
"python",
"memcached",
"osx-lion",
"libmemcached"
] | Hello when I attempt to install pylibmc on OSX Lion using pip I get the following error:
```
./_pylibmcmodule.h:42:10: fatal error: 'libmemcached/memcached.h' file not found
#include <libmemcached/memcached.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
```
Any clues at how to s... | libmemcached may also be installed using [Homebrew](http://brew.sh/).
```
brew install libmemcached
```
After that, `pip install pylibmc` worked for me without needing to specify any additional arguments. |
Error when install pylibmc using pip | 14,803,310 | 32 | 2013-02-10T22:25:58Z | 33,663,121 | 16 | 2015-11-12T01:48:39Z | [
"python",
"memcached",
"osx-lion",
"libmemcached"
] | Hello when I attempt to install pylibmc on OSX Lion using pip I get the following error:
```
./_pylibmcmodule.h:42:10: fatal error: 'libmemcached/memcached.h' file not found
#include <libmemcached/memcached.h>
^
1 error generated.
error: command 'clang' failed with exit status 1
```
Any clues at how to s... | I solved this issue by checking where memcached is installed
```
$ which memcached
/usr/local/bin/memcached
```
and then setting LIBMEMCACHED environment variable before pip install:
```
$ export LIBMEMCACHED=/usr/local
$ pip install pylibmc
``` |
Python NameError: name is not defined | 14,804,084 | 24 | 2013-02-10T23:56:13Z | 14,804,107 | 36 | 2013-02-10T23:59:22Z | [
"python",
"python-3.x",
"nameerror"
] | I have a python script and I am receiving the following error:
```
Traceback (most recent call last):
File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module>
s = Something()
NameError: name 'Something' is not defined
```
Here is the code that causes the problem:
```
s = Something()
s.out()
class So... | Define the class before you use it:
```
class Something:
def out(self):
print("it works")
s = Something()
s.out()
```
You need to pass `self` as the first argument to all class methods. |
Opencv integration with wxpython | 14,804,741 | 4 | 2013-02-11T01:33:44Z | 14,818,080 | 7 | 2013-02-11T18:02:15Z | [
"python",
"opencv",
"numpy",
"wxpython",
"python-imaging-library"
] | I just wanted to integrate the opencv video stream from my web cam into a more complex gui than highgui can offer, nothing fancy just a couple of buttons and something else, however it's proven to be not that trivial. I can't find any base example from which I can start designing the gui.
I tried converting this [code]... | The following example code works fine for me under OS X, but I've had tiny surprises with wx across platforms. It is nearly the same code, the difference is that the result from `cvtColor` is reassigned, and a subclass of `wx.Panel` (which is the important part) was added.
```
import wx
import cv, cv2
class ShowCaptu... |
TypeError: 'int' object does not support item assignment | 14,805,306 | 6 | 2013-02-11T03:05:26Z | 14,805,319 | 10 | 2013-02-11T03:07:14Z | [
"python",
"typeerror"
] | Why do I get this error?
```
a[k] = q % b
TypeError: 'int' object does not support item assignment
```
Code:
```
def algorithmone(n,b,a):
assert(b > 1)
q = n
k = 0
while q != 0:
a[k] = q % b
q = q / b
++k
return k
print (algorithmone(5,233,676))
print (algorith... | You're passing an integer to your function as `a`. You then try to assign to it as: `a[k] = ...` but that doesn't work since `a` is a scalar...
It's the same thing as if you had tried:
```
50[42] = 7
```
That statement doesn't make much sense and python would yell at you the same way (presumably).
Also, `++k` isn't... |
Remove null element from mongo array | 14,805,724 | 7 | 2013-02-11T04:05:00Z | 14,805,931 | 17 | 2013-02-11T04:34:37Z | [
"python",
"arrays",
"mongodb",
"pymongo"
] | ```
{
"_id" : 160,
"info" : [
{
'name': 'Serg',
'proff': 'hacker'
},
null,
]
}
```
As you can see I have null element in my array, I need a general solution that will remove null elements from info array.
I tried this:
``... | This should work out for you. In python null is called None.
```
for doc in iter:
people.update({'_id':doc[id]},{'$pull':{'info':None}})
```
[nulls object in Python?](http://stackoverflow.com/questions/3289601/nulls-object-in-python)
Also in mongo shell, this should work out:
```
db.people.update({_... |
check if variable is dataframe | 14,808,945 | 22 | 2013-02-11T09:10:07Z | 14,809,026 | 34 | 2013-02-11T09:15:10Z | [
"python",
"pandas"
] | when my function f is called with a variable I want to check if var is a pandas dataframe:
```
def f(var):
if var == pd.DataFrame():
print "do stuff"
```
I guess the solution might be quite simple but even with
```
def f(var):
if var.values != None:
print "do stuff"
```
I can't get it to work like expected. | Use the built-in isinstance() function.
```
import pandas as pd
def f(var):
if isinstance(var, pd.DataFrame):
print "do stuff"
``` |
check if variable is dataframe | 14,808,945 | 22 | 2013-02-11T09:10:07Z | 14,809,149 | 16 | 2013-02-11T09:23:16Z | [
"python",
"pandas"
] | when my function f is called with a variable I want to check if var is a pandas dataframe:
```
def f(var):
if var == pd.DataFrame():
print "do stuff"
```
I guess the solution might be quite simple but even with
```
def f(var):
if var.values != None:
print "do stuff"
```
I can't get it to work like expected. | [isinstance](http://docs.python.org/2/library/functions.html#isinstance), nothing else.
[PEP8](http://www.python.org/dev/peps/pep-0008/) says explicitly that `isinstance` is the preferred way to check types
```
Yes: if isinstance(obj, int):
No: if type(obj) is type(1):
```
And don't even think about
```
if obj.__c... |
how do I use key word arguments with python multiprocessing pool apply_async | 14,810,014 | 6 | 2013-02-11T10:14:10Z | 14,810,137 | 9 | 2013-02-11T10:21:24Z | [
"python",
"multiprocessing",
"threadpool"
] | I'm trying to get to grips with pythons multiprocessing module, specifically the apply\_async method of `Pool`. I'm trying to call a function with arguments and keyword arguments. If I call the function without kwargs it's fine but when I try to add in a keyword argument I get:
`TypeError: apply_async() got an unexpect... | Pass the keyword args in a dictionary (and the positional arguments in a tuple):
```
pool.apply_async(test, (t,), dict(arg2=5))
``` |
Flask url_for generating http URL instead of https | 14,810,795 | 16 | 2013-02-11T10:56:21Z | 15,111,968 | 20 | 2013-02-27T12:17:54Z | [
"python",
"url-routing",
"flask",
"werkzeug"
] | I an using `url_for` to generate redirect url when a user has logged out.
`return redirect(url_for('.index', _external=True))`
However when I changed the page to a *https* connection, the `url_for` still gives me *http*.
I would like to explicitly ask `url_for` to add *https* at the beginning of an url.
Can you poi... | With Flask 0.10, there will be a much better solution available than wrapping `url_for`. If you look at <https://github.com/mitsuhiko/flask/commit/b5069d07a24a3c3a54fb056aa6f4076a0e7088c7>, a `_scheme` parameter has been added. Which means you can do the following:
```
url_for('secure_thingy', _external=True, _scheme=... |
Flask url_for generating http URL instead of https | 14,810,795 | 16 | 2013-02-11T10:56:21Z | 26,636,880 | 13 | 2014-10-29T17:23:28Z | [
"python",
"url-routing",
"flask",
"werkzeug"
] | I an using `url_for` to generate redirect url when a user has logged out.
`return redirect(url_for('.index', _external=True))`
However when I changed the page to a *https* connection, the `url_for` still gives me *http*.
I would like to explicitly ask `url_for` to add *https* at the beginning of an url.
Can you poi... | I tried the accepted answer with an `url_for` arg but I found it easier to use the [`PREFERRED_URL_SCHEME`](http://flask.pocoo.org/docs/0.10/config/#builtin-configuration-values) config variable and set it to https with:
```
app.config.update(dict(
PREFERRED_URL_SCHEME = 'https'
))
```
since you don't have to add i... |
matplotlib has no attribute 'pyplot' | 14,812,342 | 9 | 2013-02-11T12:52:22Z | 14,812,396 | 13 | 2013-02-11T12:55:13Z | [
"python",
"matplotlib"
] | I can import matplotlib but when I try to run the following:
```
matplotlib.pyplot(x)
```
I get:
```
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
matplotlib.pyplot(x)
AttributeError: 'module' object has no attribute 'pyplot'
``` | [`pyplot`](http://matplotlib.org/api/pyplot_api.html#module-matplotlib.pyplot) is a sub-module of `matplotlib` which doesn't get imported with a simple `import matplotlib`.
```
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.