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 |
|---|---|---|---|---|---|---|---|---|---|
Cannot import a python module that is definitely installed (mechanize) | 14,295,680 | 21 | 2013-01-12T17:07:14Z | 16,377,297 | 23 | 2013-05-04T17:55:33Z | [
"python",
"mechanize",
"ubuntu-12.04",
"python-module"
] | On-going woes with the python (2.7.3) installation on my Ubuntu 12.04 machine and importing modules.
Here I am having an issue where I have definitely installed mechanize both on my machine and in various virtual environments.
I have tried installing from pip, easy\_install and via `python setup.py install` from this... | in my case it is permission problem. The package was somehow installed with root rw permission only, other user just cannot rw to it! |
Bottle file upload and process | 14,296,438 | 7 | 2013-01-12T18:15:55Z | 14,296,741 | 14 | 2013-01-12T18:45:55Z | [
"python",
"file-upload",
"bottle"
] | I am using Bottle for uploading rather large files. The idea is that when the file is uploaded, the web app run (and forget) a system command with the uploaded file-path as an argument. Except for starting the system command with the correct file-path as an argument I do not need to save the file, but I need to be cert... | Ok, let's break this down.
The full code is:
### HTML:
```
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="file" name="data" />
</form>
```
## PYTHON CODE:
```
from bottle import route, request
@route('/upload', method='POST')
def do_upload():
... |
What does "error: option --single-version-externally-managed not recognized" indicate? | 14,296,531 | 46 | 2013-01-12T18:24:33Z | 15,258,644 | 12 | 2013-03-06T21:41:47Z | [
"python",
"pip",
"distribute"
] | I seem to have suddenly started encounter the error `error: option --single-version-externally-managed not recognized` when `pip install`ing varions packages (including `PyObjC` and `astropy`). I've never seen this error before, but it's now also showing up on travis-ci builds for which nothing has changed.
Does this ... | `--single-version-externally-managed` is an option used for Python packages instructing the setuptools module to create a Python package which can be easily managed by the host's package manager if needed, like Yum or Apt.
If you're seeing this message, you may have an old version of setuptools or Python. Try using Di... |
What does "error: option --single-version-externally-managed not recognized" indicate? | 14,296,531 | 46 | 2013-01-12T18:24:33Z | 19,697,682 | 86 | 2013-10-31T02:54:15Z | [
"python",
"pip",
"distribute"
] | I seem to have suddenly started encounter the error `error: option --single-version-externally-managed not recognized` when `pip install`ing varions packages (including `PyObjC` and `astropy`). I've never seen this error before, but it's now also showing up on travis-ci builds for which nothing has changed.
Does this ... | Add `--egg` option
```
pip install --egg SCons
```
I use `pip` version 1.4.1 |
What does "error: option --single-version-externally-managed not recognized" indicate? | 14,296,531 | 46 | 2013-01-12T18:24:33Z | 36,207,872 | 12 | 2016-03-24T18:50:54Z | [
"python",
"pip",
"distribute"
] | I seem to have suddenly started encounter the error `error: option --single-version-externally-managed not recognized` when `pip install`ing varions packages (including `PyObjC` and `astropy`). I've never seen this error before, but it's now also showing up on travis-ci builds for which nothing has changed.
Does this ... | Installing `wheel` resolved this issue with recent `pip` (I used 8.1.2):
```
pip install wheel
``` |
Estimate Autocorrelation using Python | 14,297,012 | 18 | 2013-01-12T19:19:24Z | 14,298,647 | 20 | 2013-01-12T22:33:20Z | [
"python",
"numpy",
"signal-processing"
] | I would like to perform Autocorrelation on the signal shown below. The time between two consecutive points is 2.5ms (or a repetition rate of 400Hz).

This is the equation for estimating autoacrrelation that I would like to use (Taken from <http://en.w... | I don't think there is a NumPy function for this particular calculation. Here is how I would write it:
```
def estimated_autocorrelation(x):
"""
http://stackoverflow.com/q/14297012/190597
http://en.wikipedia.org/wiki/Autocorrelation#Estimation
"""
n = len(x)
variance = x.var()
x = x-x.mean(... |
Estimate Autocorrelation using Python | 14,297,012 | 18 | 2013-01-12T19:19:24Z | 16,324,067 | 9 | 2013-05-01T18:28:32Z | [
"python",
"numpy",
"signal-processing"
] | I would like to perform Autocorrelation on the signal shown below. The time between two consecutive points is 2.5ms (or a repetition rate of 400Hz).

This is the equation for estimating autoacrrelation that I would like to use (Taken from <http://en.w... | The statsmodels package adds a autocorrelation function that internally uses `np.correlate` (according to the `statsmodels` documentation).
See:
<http://statsmodels.sourceforge.net/stable/generated/statsmodels.tsa.stattools.acf.html#statsmodels.tsa.stattools.acf> |
Estimate Autocorrelation using Python | 14,297,012 | 18 | 2013-01-12T19:19:24Z | 20,463,466 | 11 | 2013-12-09T04:58:33Z | [
"python",
"numpy",
"signal-processing"
] | I would like to perform Autocorrelation on the signal shown below. The time between two consecutive points is 2.5ms (or a repetition rate of 400Hz).

This is the equation for estimating autoacrrelation that I would like to use (Taken from <http://en.w... | I took a part of code from pandas autocorrelation\_plot() function. I checked the answers with R and the values are matching exactly.
```
import numpy
def acf(series):
n = len(series)
data = numpy.asarray(series)
mean = numpy.mean(data)
c0 = numpy.sum((data - mean) ** 2) / float(n)
def r(h):
... |
SQL like joins in pandas | 14,298,401 | 9 | 2013-01-12T22:03:47Z | 14,309,050 | 11 | 2013-01-13T22:41:47Z | [
"python",
"pandas"
] | I have two dataframes, the first is of the form (note that the dates are datetime objects):
```
df = DataFrame('key': [0,1,2,3,4,5],
'date': [date0,date1, date2, date3, date4, date5],
'value': [0,10,20,30,40,50])
```
And a second which is of the form:
```
df2 = DataFrame('key': [0,1,2,3... | Currently, you can do this in a few steps with the built-in [`pandas.merge()`](http://pandas.pydata.org/pandas-docs/stable/merging.html?highlight=sql#database-style-dataframe-joining-merging) and [boolean indexing](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing).
```
merged = df.merge(df2, ... |
Convert data to the quantile bin | 14,298,433 | 10 | 2013-01-12T22:08:44Z | 14,298,661 | 9 | 2013-01-12T22:34:53Z | [
"python",
"pandas"
] | I have a dataframe with numerical columns. For each column I would like calculate quantile information and assign each row to one of them. I tried to use the [`qcut()` method](http://pandas.pydata.org/pandas-docs/dev/groupby.html?highlight=qcut) to return a list of bins but instead ended up calculating the bins individ... | I think using the `labels` stored inside the `Categorical` object returned by `qcut` can make this a lot simpler. For example:
```
>>> import pandas as pd
>>> import numpy as np
>>> np.random.seed(1001)
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=['A', 'B'])
>>> df
A B
0 -1.086446 -0.896065... |
method objects vs function objects , Python class instances vs class | 14,298,844 | 13 | 2013-01-12T22:57:07Z | 14,298,870 | 11 | 2013-01-12T23:01:12Z | [
"python",
"class",
"methods",
"instance"
] | I am trying to verify the difference between instance attributes and class attributes as laid out by the Python tutorial release 2.7.3 dated Nov 01, 2012, chapter 9: Classes, Page 66 last line ([*source*](https://docs.python.org/2/tutorial/classes.html#instance-objects)):
> Valid method names of an instance object dep... | The tutorial is indeed wrong; both `class.functionname` and `instance.functionname` return a method object.
What goes on is that a function is a [descriptor](http://docs.python.org/2/reference/datamodel.html#descriptors) and their `__get__` method is invoked, returning a method. Methods have a `__func__` attribute poi... |
method objects vs function objects , Python class instances vs class | 14,298,844 | 13 | 2013-01-12T22:57:07Z | 14,298,889 | 18 | 2013-01-12T23:04:06Z | [
"python",
"class",
"methods",
"instance"
] | I am trying to verify the difference between instance attributes and class attributes as laid out by the Python tutorial release 2.7.3 dated Nov 01, 2012, chapter 9: Classes, Page 66 last line ([*source*](https://docs.python.org/2/tutorial/classes.html#instance-objects)):
> Valid method names of an instance object dep... | # *Bound* vs *Unbound* Methods - an explanation.
### ... or why Python has the behaviour you point out.
So, first off, a note that this is different in 3.x. In 3.x, you will get `MyClass.f` being a function, and `x.f` as a method - as expected. This behaviour is essentially a poor design decision that has later been ... |
What is special about deleting an empty list? | 14,299,104 | 10 | 2013-01-12T23:35:52Z | 14,299,161 | 13 | 2013-01-12T23:45:55Z | [
"python"
] | Consider the following...
```
In [1]: del []
In [2]: del {}
File "<ipython-input-2-24ce3265f213>", line 1
SyntaxError: can't delete literal
In [3]: del ""
File "<ipython-input-3-95fcb133aa75>", line 1
SyntaxError: can't delete literal
In [4]: del ["A"]
File "<ipython-input-5-d41e712d0c77>", line 1
SyntaxError... | The [`del` statement syntax](http://docs.python.org/3/reference/simple_stmts.html#the-del-statement) allows for a [`target_list`](http://docs.python.org/3/reference/simple_stmts.html#grammar-token-target_list), and that includes a list or tuple of variable names.
It is intended for deleting several names at once:
```... |
Sorting by multiple conditions in python | 14,299,448 | 7 | 2013-01-13T00:32:17Z | 14,299,498 | 10 | 2013-01-13T00:39:39Z | [
"python",
"sorting"
] | I am new to programming and right now i'm writing a league table in python. I would like to sort my league by first points, and if there are two teams with the same points I would like to sort them by goal difference, and if they have the same goal difference i would like to sort by name.
The first condition is pretty... | Have the `key` function return a tuple, with items in decreasing order of priority:
```
table.sort(reverse=True, key=lambda team: (Team.getPoints(team),
Team.getGoalDifference(team),
Team.getName(team))
```
Alternately, you could re... |
How to use lxml to find an element by text? | 14,299,978 | 17 | 2013-01-13T02:10:24Z | 14,300,008 | 21 | 2013-01-13T02:14:37Z | [
"python",
"html",
"lxml"
] | Assume we have the following html:
```
<html>
<body>
<a href="/1234.html">TEXT A</a>
<a href="/3243.html">TEXT B</a>
<a href="/7445.html">TEXT C</a>
<body>
</html>
```
How do I make it find the element "a", which contains "TEXT A"?
So far I've got:
```
root = lxml.hmtl.document_froms... | You are very close. Use `text()=` rather than `@text` (which indicates an attribute).
```
e = root.xpath('.//a[text()="TEXT A"]')
```
Or, if you know only that the text contains "TEXT A",
```
e = root.xpath('.//a[contains(text(),"TEXT A")]')
```
Or, if you know only that text starts with "TEXT A",
```
e = root.xpa... |
making matplotlib scatter plots from dataframes in Python's pandas | 14,300,137 | 41 | 2013-01-13T02:38:30Z | 14,306,902 | 61 | 2013-01-13T18:48:58Z | [
"python",
"matplotlib",
"plot",
"dataframe",
"pandas"
] | What is the best way to make a series of scatter plots using `matplotlib` from a `pandas` dataframe in Python?
For example, if I have a dataframe `df` that has some columns of interest, I find myself typically converting everything to arrays:
```
import matplotlib.pylab as plt
# df is a DataFrame: fetch col1 and col2... | Try passing columns of the `DataFrame` directly to matplotlib, as in the examples below, instead of extracting them as numpy arrays.
```
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
In [5]: df
Out[5]:
col1 col2 col3
0 -1.000075 -0.75991... |
pandas rolling computation with window based on values instead of counts | 14,300,768 | 13 | 2013-01-13T04:50:56Z | 14,307,460 | 8 | 2013-01-13T19:49:12Z | [
"python",
"pandas"
] | I'm looking for a way to do something like the various `rolling_*` functions of `pandas`, but I want the window of the rolling computation to be defined by a range of values (say, a range of values of a column of the DataFrame), not by the number of rows in the window.
As an example, suppose I have this data:
```
>>>... | I think this does what you want:
```
In [1]: df
Out[1]:
RollBasis ToRoll
0 1 1
1 1 4
2 1 -5
3 2 2
4 3 -4
5 5 -2
6 8 0
7 10 -13
8 12 -2
9 13 -5
In [2]: def f(x):
...: s... |
pandas rolling computation with window based on values instead of counts | 14,300,768 | 13 | 2013-01-13T04:50:56Z | 14,307,961 | 10 | 2013-01-13T20:46:14Z | [
"python",
"pandas"
] | I'm looking for a way to do something like the various `rolling_*` functions of `pandas`, but I want the window of the rolling computation to be defined by a range of values (say, a range of values of a column of the DataFrame), not by the number of rows in the window.
As an example, suppose I have this data:
```
>>>... | Based on Zelazny7's answer, I created this more general solution:
```
def rollBy(what, basis, window, func):
def applyToWindow(val):
chunk = what[(val<=basis) & (basis<val+window)]
return func(chunk)
return basis.apply(applyToWindow)
>>> rollBy(d.ToRoll, d.RollBasis, 5, sum)
0 -4
1 -4
2 ... |
pandas rolling computation with window based on values instead of counts | 14,300,768 | 13 | 2013-01-13T04:50:56Z | 21,189,441 | 9 | 2014-01-17T15:22:13Z | [
"python",
"pandas"
] | I'm looking for a way to do something like the various `rolling_*` functions of `pandas`, but I want the window of the rolling computation to be defined by a range of values (say, a range of values of a column of the DataFrame), not by the number of rows in the window.
As an example, suppose I have this data:
```
>>>... | Based on BrenBarns's answer, but speeded up by using label based indexing rather than boolean based indexing:
```
def rollBy(what,basis,window,func,*args,**kwargs):
#note that basis must be sorted in order for this to work properly
indexed_what = pd.Series(what.values,index=basis.values)
def applyToWi... |
Group by multiple time units in pandas data frame | 14,301,004 | 8 | 2013-01-13T05:40:50Z | 14,306,366 | 16 | 2013-01-13T17:52:51Z | [
"python",
"pandas"
] | I have a data frame that consists of a time series data with 15-second intervals:
```
date_time value
2012-12-28 11:11:00 103.2
2012-12-28 11:11:15 103.1
2012-12-28 11:11:30 103.4
2012-12-28 11:11:45 103.5
2012-12-28 11:12:00 103.3
```
The data spans many years. I would like to group by both... | In case `date_time` is not your index, a `date_time`-indexed DataFrame could be created with:
```
dfts = df.set_index('date_time')
```
From there you can group by intervals using
```
dfts.groupby(lambda x : x.month).mean()
```
to see mean values for each month. Similarly, you can do
```
dfts.groupby(lambda x : x.y... |
Concatenating lists in Python 3 | 14,301,056 | 3 | 2013-01-13T05:52:54Z | 14,301,097 | 7 | 2013-01-13T06:02:53Z | [
"python",
"python-3.x"
] | I'm reading [Dive into Python 3](http://getpython3.com/diveintopython3/native-datatypes.html) and at the section of lists, the author states that you can concatenate lists with the "+" operator or calling the extend() method. Are these the same just two different ways to do the operation? Any reason I should be using o... | `a_list.extend(b_list)` modifies `a_list` in place. `a_list = a_list + b_list` creates a new list, then saves it to the name `a_list`. Note that `a_list += b_list` should be exactly the same as the `extend` version.
Using `extend` or `+=` is probably slightly faster, since it doesn't need to create a new object, but i... |
Convert pandas group by object to multi-indexed Dataframe | 14,301,913 | 9 | 2013-01-13T08:36:21Z | 14,306,921 | 11 | 2013-01-13T18:51:30Z | [
"python",
"group-by",
"dataframe",
"pandas",
"multi-index"
] | If I have the following Dataframe
```
>>> df = pd.DataFrame({'Name': ['Bob'] * 3 + ['Alice'] * 3, \
'Destination': ['Athens', 'Rome'] * 3, 'Length': np.random.randint(1, 6, 6)})
>>> df
Destination Length Name
0 Athens 3 Bob
1 Rome 5 Bob
2 Athens 2 Bob
3 Rome... | Since you're not aggregating similarly indexed rows, try setting the index with a list of column names.
```
In [2]: df.set_index(['Name', 'Destination'])
Out[2]:
Length
Name Destination
Bob Athens 3
Rome 5
Athens 2
Alice Rome 1
... |
Python bare asterisk in function argument | 14,301,967 | 44 | 2013-01-13T08:43:12Z | 14,302,007 | 47 | 2013-01-13T08:50:58Z | [
"python",
"python-3.x",
"parameter-passing"
] | What does a bare asterisk in the arguments of a function do?
When I looked at the pickle module, I see this: (http://docs.python.org/3.3/library/pickle.html#pickle.dump)
```
pickle.dump(obj, file, protocol=None, *, fix_imports=True)
```
I know about a single and double asterisks preceding arguments (for variable num... | Bare `*` is used to force the caller to use named arguments - so you cannot define a function with `*` as an argument when you have no following keyword arguments.
See [this answer](http://stackoverflow.com/a/14298976/180174) or [Python 3 documentation](http://docs.python.org/3/reference/compound_stmts.html#function-d... |
dictionary update sequence element #0 has length 3; 2 is required | 14,302,248 | 21 | 2013-01-13T09:27:20Z | 14,313,394 | 29 | 2013-01-14T04:38:16Z | [
"python",
"openerp"
] | I want to add lines to the object `account.bank.statement.line` through other object but I get this error: `"dictionary update sequence element #0 has length 3; 2 is required"`
```
def action_account_line_create(self, cr, uid, ids):
res = False
cash_id = self.pool.get('account.bank.statement.line')
for exp... | This error raised up because you trying to update `dict` object by using a wrong sequence (`list` or `tuple`) structure.
`cash_id.create(cr, uid, lines,context=None)` trying to convert `lines` into dict object:
```
(0, 0, {
'name': l.name,
'date': l.date,
'amount': l.am... |
truncate and pad using format specification mini language | 14,302,815 | 5 | 2013-01-13T11:02:06Z | 14,302,858 | 11 | 2013-01-13T11:09:08Z | [
"python",
"string-formatting"
] | I'm currently writing code which pads a string with spaces, using Python's [format specification mini language](http://docs.python.org/2/library/string.html#formatspec):
```
print('''{user:<10}, you're welcome!'''.format(user='John Doe'))
```
The output is:
```
John Doe , you're welcome!
```
However, if user's nam... | From the page you linked to:
> For non-number types [precision]
> indicates the maximum field size - in other words, how many characters
> will be used from the field content. The precision is not allowed for
> integer values.
Precision is introduced by a period
> `format_spec ::= [[fill]align][sign][#][0][width][,]... |
Calling Python code within Haskell | 14,304,734 | 4 | 2013-01-13T15:07:15Z | 14,304,814 | 8 | 2013-01-13T15:16:48Z | [
"python",
"haskell"
] | I have a bunch (or will have a bunch) of Python code that uses the OpenCV libraries, as well as SimpleCV. I also have a bunch of Haskell code that does some other stuff, but wants to call one function that I define in the Python. This one function returns a three-tuple of doubles.
What's the best way to go about calli... | You can use [Thrift](http://thrift.apache.org/). It's for scalable cross-language services development, combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, **Python**, PHP, Ruby, Erlang, Perl, **Haskell**, C#, Cocoa, JavaScript, Node.js, Smal... |
Run setUp only once | 14,305,941 | 13 | 2013-01-13T17:11:02Z | 14,306,074 | 35 | 2013-01-13T17:21:48Z | [
"python",
"unit-testing",
"selenium"
] | My Python version is 2.6.
I would like execute the setUp method only once since I'm doing there things which are needed for every test.
My idea was to create a boolean var which will be set to 'true' after the first execution.
```
class mySelTest(unittest.TestCase):
  setup_done = False
  def setUp(self):
Â... | You can use [`setUpClass`](http://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass) to define methods that only run once per testsuite. |
Run setUp only once | 14,305,941 | 13 | 2013-01-13T17:11:02Z | 34,065,561 | 8 | 2015-12-03T12:01:04Z | [
"python",
"unit-testing",
"selenium"
] | My Python version is 2.6.
I would like execute the setUp method only once since I'm doing there things which are needed for every test.
My idea was to create a boolean var which will be set to 'true' after the first execution.
```
class mySelTest(unittest.TestCase):
  setup_done = False
  def setUp(self):
Â... | Daniel's answer is correct but better with an example to avoid some common mistakes I found, like not calling super in setUpClass.
The documentation [setUpClass](https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass) don't states the need to call super and you will get an error if you don't, sol... |
How do I modify the width of a TextCtrl in wxPython? | 14,306,852 | 4 | 2013-01-13T18:41:18Z | 14,306,869 | 8 | 2013-01-13T18:43:43Z | [
"python",
"wxpython"
] | I'm trying to create a text control that has the default height but a custom width. This is my current code:
```
tc = wx.TextCtrl(self, -1)
tc.Size.SetWidth(300)
```
The width of the text control remains unchanged though. I've also tried calling `tc.Layout()` after changing the width with no results. I don't want to ... | I just noticed that I can pass `(300, -1)` as the size of the text control:
```
wx.TextCtrl(self, -1, size=(300, -1))
```
Which results in the text control using the default height. This solves my problem but doesn't technically answer my question, so I'm holding out for a better answer.
---
Edit: This answer plus ... |
Updating row in SqlAlchemy ORM | 14,307,238 | 6 | 2013-01-13T19:25:47Z | 14,323,227 | 10 | 2013-01-14T17:11:46Z | [
"python",
"sqlalchemy"
] | I am trying to obtain a row from DB, modify that row and save it again.
Everything by using SqlAlchemy
My code
```
from sqlalchemy import Column, DateTime, Integer, String, Table, MetaData
from sqlalchemy.orm import mapper
from sqlalchemy import create_engine, orm
metadata = MetaData()
product = Table('product', ... | I assume that your intention is to use [Object-Relational API](http://mapfish.org/doc/tutorials/sqlalchemy.html#object-relational-api).
So to update row in db you'll need to do this by loading mapped object from the table record and updating object's property.
Please see code example below.
Please note I've added exam... |
Python: Module Error with pprint, no error with print | 14,310,298 | 6 | 2013-01-14T01:31:11Z | 14,310,327 | 19 | 2013-01-14T01:35:06Z | [
"python",
"python-3.x"
] | So I have this function that creates a dictionary called `a()` and takes parameters `params`. I want to print that dictionary, so I used pprint:
```
dict=a(params)
pprint(dict)
```
pprint gives me this error:
```
TypeError: 'module' object is not callable
```
but print works fine! | How did you import `pprint`? If you didn't specify what to import from `pprint` you need to use the module name when calling.
```
import pprint
pprint.pprint(...)
```
Or you can import a specific method.
```
from pprint import pprint
pprint(...)
``` |
Event signal is emmitted twice every time | 14,311,578 | 3 | 2013-01-14T02:20:11Z | 14,313,847 | 9 | 2013-01-14T05:51:58Z | [
"python",
"python-2.7",
"pyqt"
] | I am working on GUI appplication. From main window I open new popup window Dialog=myDialog()
(so both are now open). If i press button on that new popup window, and catch signal with this code:
```
class Ui_DialogCalibration(object):
def setupUi(self, DialogCalibration):
DialogCalibration.setObjectName(_fromUtf8("... | Quoting from the [docs](http://www.riverbankcomputing.com/static/Docs/PyQt4/html/new_style_signals_slots.html#connecting-slots-by-name):
> [Connecting the both variations of the signal] also happens with signals that take optional arguments. Qt
> implements this using multiple signals. For example,
> `QtGui.QAbstractB... |
Importing Libraries Issue - "ImportError: No Module named ____" | 14,311,601 | 6 | 2013-01-14T02:23:15Z | 14,311,690 | 12 | 2013-01-14T02:40:33Z | [
"python",
"numpy",
"libraries",
"pip",
"nltk"
] | I've looked through a lot of the other question/answers for this topic but no avail.
I downloaded numpy and nltk using pip, and based on the messages I know the install location is:
`Requirement already satisfied (use --upgrade to upgrade): nltk in /usr/local/lib/python2.7/site-packages`, so it looks like it's install... | Try changing the `PYTHONPATH`environment variable. If you are using BASH the below should work. Other Linux shells will be slightly different in how they assign environment variables.
```
export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages
``` |
Importing Libraries Issue - "ImportError: No Module named ____" | 14,311,601 | 6 | 2013-01-14T02:23:15Z | 14,359,226 | 8 | 2013-01-16T13:08:58Z | [
"python",
"numpy",
"libraries",
"pip",
"nltk"
] | I've looked through a lot of the other question/answers for this topic but no avail.
I downloaded numpy and nltk using pip, and based on the messages I know the install location is:
`Requirement already satisfied (use --upgrade to upgrade): nltk in /usr/local/lib/python2.7/site-packages`, so it looks like it's install... | The problem is that `/usr/local/lib/python2.7/site-packages` is not in your default path list. In order to verify this, run the following commands:
```
import sys
for pth in sys.path:
print pth
```
You will get a list of the directories searched for modules. As you probably will not have `/usr/local/lib/python2.7... |
Python - Why call methods during __init__() | 14,313,446 | 2 | 2013-01-14T04:48:16Z | 14,313,487 | 12 | 2013-01-14T04:56:35Z | [
"python",
"qt"
] | I've been looking at some tutorials for some PyQt4 stuff and It Is Good, but I don't quite understand why the syntax when creating an object is such:
```
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
... | Sometimes code is separated into functions for readability purposes.
If your object initialization requires three steps, then logically it would make sense to break it into three functions. The names of those functions could describe which portion of the initialization they handle.
Another reason you might see an "in... |
Why isn't Queue.qsize accurate? | 14,313,814 | 2 | 2013-01-14T05:48:06Z | 14,313,879 | 9 | 2013-01-14T05:55:28Z | [
"python",
"queue"
] | According to the [Python 2.7](http://docs.python.org/2/library/queue.html#Queue.Queue.qsize) docs, `Queue.qsize` isn't dependable, and `help(Queue.Queue.qsize)` says that it isn't reliable. Is there a particular implementation issue I am not aware of?
P.S. I am aware that `Queue.Queue.qsize` uses mutexes, and that the... | `Queue.Queue.qsize` works fine in a single-threaded application (and even in a multi-threaded application for many applications of its purpose). You simply can't use it to reliably determine whether a call to `put` or `get` will block.
Note that if you don't need concurrency, [`collections.deque`](http://docs.python.o... |
How can i put authentication on class views in django | 14,314,456 | 4 | 2013-01-14T07:06:25Z | 14,314,664 | 11 | 2013-01-14T07:33:22Z | [
"python",
"django"
] | IN the Django docs they say this <https://docs.djangoproject.com/en/dev/topics/auth/default/#user-objects>
```
from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def my_view(request):
```
But how can i use login\_required on class based view
```
@login_required
c... | You can do that in many ways like
<https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views>
1. Either this
> ```
> urlpatterns = patterns('',
> (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
> (r'^vote/', permission_required('pol... |
How to filter numbers that contain unique digits? | 14,317,055 | 8 | 2013-01-14T10:50:44Z | 14,317,304 | 7 | 2013-01-14T11:07:36Z | [
"python",
"algorithm"
] | You have a list of numbers and you want to filter out those numbers that contain unique digits, i.e. each digit may only occur once in the number.
Positive examples:
* 985
* 58293.6
* 0.1246
Negative examples:
* 9585 (5 occurs twice)
* 58293.666 (6 occurs three times)
* 0.12461 (1 occurs twice)
How would you do th... | > Is there a way to do it without converting the integers to strings
> first and then convert them back?
Yes, you could use `divmod` to find the digits base 10, but this is not faster than the method you posted:
```
def uniques2(numbers):
for number in numbers:
seen = set()
quotient = number
... |
Boto - Uploading file to a specific location on Amazon S3 | 14,317,243 | 28 | 2013-01-14T11:03:25Z | 14,319,596 | 47 | 2013-01-14T13:45:58Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto"
] | This is the code I'm working from
```
import sys
import boto
import boto.s3
# AWS ACCESS DETAILS
AWS_ACCESS_KEY_ID = ''
AWS_SECRET_ACCESS_KEY = ''
bucket_name = AWS_ACCESS_KEY_ID.lower() + '-mah-bucket' conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(bucket_name, location... | All you should have to do is prepend the virtual directory path to the key name prior to uploading. For example:
```
key_name = 'my test file'
path = 'images/holiday'
full_key_name = os.path.join(path, key_name)
k = bucket.new_key(full_key_name)
k.set_contents_from_filename(...)
```
You may have to change that a bit ... |
Matplotlib imshow: Data rotated? | 14,320,159 | 12 | 2013-01-14T14:17:37Z | 14,320,227 | 22 | 2013-01-14T14:22:25Z | [
"python",
"matplotlib"
] | I was trying to plot some data with scatter. My code is
```
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy.interpolate import griddata
data = np.loadtxt('file1.txt')
x = data[:,0]
y = data[:,1]
z = data[:,2]
plt.scatter(x, y, c=z, s=100, cmap=mpl.cm.spectral)
cbar=plt.colorbar()... | Look at the keyword arguments of `imshow`. There is `origin`. The default is "upper", but you want "lower".
The default makes sense for plotting images, that usually start at the top-left corner. For most matrix-plotting, you'll want `origin="lower"` |
Testing Python C libraries - get build path | 14,320,220 | 9 | 2013-01-14T14:21:49Z | 14,369,968 | 10 | 2013-01-16T23:47:35Z | [
"python",
"setuptools",
"distutils"
] | When using setuptools/distutils to build C libraries in Python
```
$ python setup.py build
```
the `*.so/*.pyd` files are placed in `build/lib.win32-2.7` (or equivalent).
I'd like to test these files in my test suite, but I'd rather not hard code the `build/lib*` path. Does anyone know how to pull this path from dis... | You must get the platform that you are running on and the version of python you are running on and then assemble the name yourself.
To get the current platform, use `sysconfig.get_platform()`. To get the python version, use `sys.version_info` (specifically the first three elements of the returned tuple). On my system ... |
efficiently checking that string consists of one character in Python | 14,320,909 | 49 | 2013-01-14T15:02:08Z | 14,320,929 | 11 | 2013-01-14T15:03:00Z | [
"python",
"string"
] | What is an efficient way to check that a string `s` in Python consists of just one character, say `'A'`? Something like `all_equal(s, 'A')` which would behave like this:
```
all_equal("AAAAA", "A") = True
all_equal("AAAAAAAAAAA", "A") = True
all_equal("AAAAAfAAAAA", "A") = False
```
Two seemingly inefficient ways w... | Try using the built-in function [`all`](http://docs.python.org/2/library/functions.html#all):
```
all(c == 'A' for c in s)
``` |
efficiently checking that string consists of one character in Python | 14,320,909 | 49 | 2013-01-14T15:02:08Z | 14,320,935 | 12 | 2013-01-14T15:03:25Z | [
"python",
"string"
] | What is an efficient way to check that a string `s` in Python consists of just one character, say `'A'`? Something like `all_equal(s, 'A')` which would behave like this:
```
all_equal("AAAAA", "A") = True
all_equal("AAAAAAAAAAA", "A") = True
all_equal("AAAAAfAAAAA", "A") = False
```
Two seemingly inefficient ways w... | You could convert to a set and check there is only one member:
```
len(set("AAAAAAAA"))
``` |
efficiently checking that string consists of one character in Python | 14,320,909 | 49 | 2013-01-14T15:02:08Z | 14,320,949 | 39 | 2013-01-14T15:04:01Z | [
"python",
"string"
] | What is an efficient way to check that a string `s` in Python consists of just one character, say `'A'`? Something like `all_equal(s, 'A')` which would behave like this:
```
all_equal("AAAAA", "A") = True
all_equal("AAAAAAAAAAA", "A") = True
all_equal("AAAAAfAAAAA", "A") = False
```
Two seemingly inefficient ways w... | ```
>>> s = 'AAAAAAAAAAAAAAAAAAA'
>>> s.count(s[0]) == len(s)
True
```
This doesn't short circuit. A version which does short-circuit would be:
```
>>> all(x == s[0] for x in s)
True
```
However, I have a feeling that due the the optimized C implementation, the non-short circuiting version will probably perform bett... |
efficiently checking that string consists of one character in Python | 14,320,909 | 49 | 2013-01-14T15:02:08Z | 14,321,721 | 86 | 2013-01-14T15:46:49Z | [
"python",
"string"
] | What is an efficient way to check that a string `s` in Python consists of just one character, say `'A'`? Something like `all_equal(s, 'A')` which would behave like this:
```
all_equal("AAAAA", "A") = True
all_equal("AAAAAAAAAAA", "A") = True
all_equal("AAAAAfAAAAA", "A") = False
```
Two seemingly inefficient ways w... | This is by far the fastest, several times faster than even `count()`, just time it with that excellent [mgilson's timing suite](http://stackoverflow.com/a/14320949/866022):
```
s == len(s) * s[0]
```
Here all the checking is done inside the Python C code which just:
* allocates len(s) characters;
* fills the space w... |
Lucas Kanade python numpy implementation uses enormous amount of memory | 14,321,092 | 9 | 2013-01-14T15:11:56Z | 14,325,821 | 8 | 2013-01-14T20:06:29Z | [
"python",
"numpy",
"opticalflow"
] | I was working on Optical Flow script using Lucas Kanade method, as University project. While it works well, there is something I can't figure out. It uses few MB of memory at start, but that amount increases rapidly every second. By the time it computes OF for 1 frame of 480p movie, it uses about 1GB. When it reaches 1... | While it doesn't explain your memory issues, your implementation is, to put it mildly, suboptimal. Not only are you not using numpy to its fullest capabilities, but the flow of your algorithm is also not very good at avoiding repeated calculations. I think you are simply running your system out of resources, not becaus... |
Sum between pairs of indices in 2d array | 14,321,390 | 10 | 2013-01-14T15:28:00Z | 14,323,604 | 11 | 2013-01-14T17:36:18Z | [
"python",
"numpy",
"sum",
"multidimensional-array"
] | Sorry, I do not know the protocol for re-asking a question if it doesn't get an answer. This question was asked a few months ago here: [Numpy sum between pairs of indices in 2d array](http://stackoverflow.com/questions/13476450/numpy-sum-between-pairs-of-indices-in-2d-array)
I have a 2-d numpy array (MxN) and two more... | **EDIT** Added timing results for all answers so far, including the OP's code following @seberg's comment below, and the OP's method is the fastest:
```
def sliced_sum_op(a, b, c) :
d = np.empty(a.shape[0])
for i in xrange(a.shape[0]):
d[i] = np.sum(a[i, b[i]:c[i]])
return d
```
---
You can stil... |
scipy.io.wavfile gives "WavFileWarning: chunk not understood" error | 14,321,627 | 5 | 2013-01-14T15:41:52Z | 18,958,665 | 11 | 2013-09-23T11:57:46Z | [
"python",
"osx",
"numpy",
"scipy"
] | I'm trying to read a .wav file using scipy. I do this:
```
from scipy.io import wavfile
filename = "myWavFile.wav"
print "Processing " + filename
samples = wavfile.read(filename)
```
And I get this ugly error:
```
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scipy/io/wavfile.py:121... | The files is no longer available (not surprising after 9 months!), but for future reference the most likely cause is that it had extra metadata which scipy can't parse.
In my case, it was default metadata (copyright, track name etc) which was added by Audacity- you can open the file in Audacity and use File ... Open M... |
Checking if a key exists and its value is not an empty string in a Python dictionary | 14,323,045 | 12 | 2013-01-14T17:01:33Z | 14,323,136 | 16 | 2013-01-14T17:06:44Z | [
"python",
"dictionary",
"string"
] | Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:
* If the key is present
* If the key's value is not an empty string
And otherwise assigning a default value to the variable.
I would like to use `dict.get`:
```
my_value = dict.get(key, my_default)
```
But this as... | Maybe you mean something like:
```
a.get('foo',my_default) or my_default
```
which I think should be equivalent to the `if-else` conditional you have
e.g.
```
>>> a = {'foo':''}
>>> a.get('foo','bar') or 'bar'
'bar'
>>> a['foo'] = 'baz'
>>> a.get('foo','bar') or 'bar'
'baz'
>>> a.get('qux','bar') or 'bar'
'bar'
```... |
Checking if a key exists and its value is not an empty string in a Python dictionary | 14,323,045 | 12 | 2013-01-14T17:01:33Z | 14,323,377 | 9 | 2013-01-14T17:20:58Z | [
"python",
"dictionary",
"string"
] | Is there a clear best practice for assigning a variable from a key/value pair in a Python dictionary:
* If the key is present
* If the key's value is not an empty string
And otherwise assigning a default value to the variable.
I would like to use `dict.get`:
```
my_value = dict.get(key, my_default)
```
But this as... | The simplest way to do what you want:
```
my_value = dict.get(key) or my_default
```
The `or` will deliver the first value if it evaluates non-false, otherwise the second one. Unlike other languages Python doesn't force the result to be boolean, quite a useful property sometimes. |
Get root's attributes - elementtree | 14,323,335 | 5 | 2013-01-14T17:18:23Z | 14,323,382 | 8 | 2013-01-14T17:21:27Z | [
"python",
"xml",
"elementtree",
"xmlroot"
] | I've an XML `<root>` element with several attributes. I've been using the `ElementTree` package.
After I've parsed a tree from an xml file, I'm getting the document root, but how can I get the requested attribute, or even the entire list of attributes. I have
```
<root a="1" b="2" c="3">
</blablabla>
</root>
``` | Each `Element` has an attribute `.attrib` that is a dictionary; simply use it's [mapping methods](http://docs.python.org/2/library/stdtypes.html#mapping-types-dict) to ask it for it's keys or values:
```
for name, value in root.attrib.items():
print '{0}="{1}"'.format(name, value)
```
or
```
for name in root.att... |
Matplotlib custom marker/symbol | 14,324,270 | 12 | 2013-01-14T18:24:19Z | 14,413,913 | 26 | 2013-01-19T11:37:13Z | [
"python",
"matplotlib"
] | So there is this guide:
<http://matplotlib.org/examples/pylab_examples/scatter_symbol.html>

```
# http://matplotlib.org/examples/pylab_examples/scatter_symbol.html
from matplotlib import pyplot as plt
import numpy as np
import matplotlib
x = np.arang... | So found out that it was just using mathtext symbols and not referring to any sepecial vector based marker stored in the matplotlib module..
```
from matplotlib import pyplot as plt
import numpy as np
from numpy.random import randint
import matplotlib
x = np.arange(0.0, 100.0, 2.0)
y = x ** 1.3 + np.random.rand(*x.sh... |
random boolean by percentage | 14,324,472 | 3 | 2013-01-14T18:38:19Z | 14,324,497 | 10 | 2013-01-14T18:40:18Z | [
"python",
"random",
"python-2.7"
] | I'm trying to get a get a random boolean but with a weighted percentage. For instance, I want the user to pass in a percentage (i.e. 60) and the generator will randomly select true 60% of the time.
What I have is this:
```
def reset(percent=50):
prob = random.randrange(0,100)
if prob > percent:
return... | Just return the test:
```
def reset(percent=50):
return random.randrange(100) < percent
```
because the result of a `<` lower than operator is already a boolean. You do not need to give a starting value either.
Note that you need to use *lower than* if you want `True` to be returned for a given percentage; if `p... |
Bold font weight for LaTeX axes label in matplotlib | 14,324,477 | 17 | 2013-01-14T18:38:39Z | 14,324,826 | 14 | 2013-01-14T19:01:59Z | [
"python",
"matplotlib",
"latex"
] | In [`matplotlib`](http://matplotlib.org/) you can make the text of an axis label bold by
```
plt.xlabel('foo',fontweight='bold')
```
You can also use LaTeX with the right backend
```
plt.xlabel(r'$\phi$')
```
When you combine them however, the math text is not bold anymore
```
plt.xlabel(r'$\phi$',fontweight='bold... | Unfortunately you can't bold symbols using the bold font, see [this question](http://tex.stackexchange.com/questions/595/how-can-i-get-bold-math-symbols) on tex.stackexchange.
As the answer suggests, you could use `\boldsymbol` to bold phi:
```
r'$\boldsymbol{\phi}$'
```
You'll need to load `amsmath` into the TeX pr... |
Bold font weight for LaTeX axes label in matplotlib | 14,324,477 | 17 | 2013-01-14T18:38:39Z | 16,019,418 | 11 | 2013-04-15T15:46:40Z | [
"python",
"matplotlib",
"latex"
] | In [`matplotlib`](http://matplotlib.org/) you can make the text of an axis label bold by
```
plt.xlabel('foo',fontweight='bold')
```
You can also use LaTeX with the right backend
```
plt.xlabel(r'$\phi$')
```
When you combine them however, the math text is not bold anymore
```
plt.xlabel(r'$\phi$',fontweight='bold... | If you intend to have consistently bolded fonts throughout the plot, the best way may be to enable latex and add `\boldmath` to your preamble:
```
# Optionally set font to Computer Modern to avoid common missing font errors
matplotlib.rc('font', family='serif', serif='cm10')
matplotlib.rc('text', usetex=True)
matplot... |
How to change marker border width and hatch width? | 14,325,773 | 14 | 2013-01-14T20:03:16Z | 14,329,557 | 21 | 2013-01-15T01:02:05Z | [
"python",
"matplotlib"
] | In this example of a marker from my scatter plot I have set the color to green, and edge color to black, and hatch to "|". For the hatch pattern to show up at all I must set the edgecolor, however when I do, I get a very thick border around the marker. Two questions:
1) How can I to set the size of this border (prefer... | 1. You just need to set the `linewidth` to control the marker border thickness.
2. You can increase the density of hatching, by repeating symbols (in the example below, the `'|'` is repeated in the R/H pane; note that to obtain NW->SE diagonal lines the symbol must be escaped so needs twice as many characters to really... |
Scipy's fftpack dct and idct | 14,325,795 | 4 | 2013-01-14T20:04:42Z | 14,326,289 | 7 | 2013-01-14T20:42:17Z | [
"python",
"scipy",
"dct",
"fftpack"
] | Let say you use the dct function, then do no manipulation of the data and use the invert transform; wouldn't the inverted data be the same as the pre-transformed data? Why the floating point issue? Is it a reported issue or is it a normal behavior?
```
In [21]: a = [1.2, 3.4, 5.1, 2.3, 4.5]
In [22]: b = dct(a)
In [2... | It looks like dct and idct do not normalize by default. define `dct` to call `fftpack.dct` in the following manner. Do the same for `idct`.
```
In [13]: dct = lambda x: fftpack.dct(x, norm='ortho')
In [14]: idct = lambda x: fftpack.idct(x, norm='ortho')
```
Once done, you will get back the original answers after per... |
Create a reference inside a class to his own type | 14,326,144 | 3 | 2013-01-14T20:31:27Z | 14,326,182 | 7 | 2013-01-14T20:33:22Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I really didn't know how to write the title for this problem :P
So in google app engine I want to create a class that can have 'sons' of the same type:
```
class Chapter(db.Model):
title = db.StringProperty(required=True)
note = db.TextProperty()
father = db.ReferenceProperty(Chapter, collection_name='son... | You need to use [SelfReferenceProperty](https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#SelfReferenceProperty)
```
class Chapter(db.Model):
title = db.StringProperty(required=True)
note = db.TextProperty()
father = db.SelfReferenceProperty(collection_name='sons')
o... |
Count vs len on a Django QuerySet | 14,327,036 | 36 | 2013-01-14T21:29:25Z | 14,327,086 | 56 | 2013-01-14T21:32:31Z | [
"python",
"django",
"performance"
] | In Django, given that I have a QuerySet that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs) or qs.count()?
(Also given that counting the objects in the same iteration is not an option) | Although the [Django docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/) recommend using `count` rather than `len`:
> Note: Don't use `len()` on QuerySets if all you want to do is determine the number of records in the set. It's much more efficient to handle a count at the database level, using SQL's `S... |
Count vs len on a Django QuerySet | 14,327,036 | 36 | 2013-01-14T21:29:25Z | 14,327,315 | 16 | 2013-01-14T21:46:13Z | [
"python",
"django",
"performance"
] | In Django, given that I have a QuerySet that I am going to iterate over and print the results of, what is the best option for counting the objects? len(qs) or qs.count()?
(Also given that counting the objects in the same iteration is not an option) | I think using `len(qs)` makes more sense here as you need to iterate over the results. `qs.count()` is a better option if all that you want to do it print the count and not iterate over the results.
`len(qs)` will hit the database with `select * from table` whereas `qs.count()` will hit the db with `select count(*) fr... |
Invalid syntax on VERY SIMPLE Python if ... else statement | 14,327,195 | 4 | 2013-01-14T21:38:08Z | 14,327,232 | 8 | 2013-01-14T21:40:52Z | [
"python",
"python-3.x"
] | Can someone explain why I am getting an invalid syntax error from Python's interpretor while formulating this simple if...else statement? I don't add any tabs myself I simply type the text then press enter after typing. When I type an enter after "else:" I get the error. "Else" is highlighted by the interpreter. What's... | That's because your `else` part is empty and also not properly indented with the `if`.
```
if 3 > 0:
print "voila"
else:
pass
```
In python `pass` is equivalent to `{}` used in other languages like C. |
How to create dictionary from two lists without losing duplicate values? | 14,327,247 | 2 | 2013-01-14T21:41:50Z | 14,327,280 | 9 | 2013-01-14T21:43:42Z | [
"python",
"list",
"dictionary"
] | I have two lists:
```
pin_list = ['in0', 'in1', 'in2', 'y']
delvt_list = ['0.399', '0.1995', '0.1995', '0.399']
```
I use the code:
temp = dict(zip(delvt\_list,pin\_list)) but I get the following:
```
temp = {'0.1995': 'in2', '0.399': 'y'}
```
What python code do I need to write to get:
```
temp = {'0.1995': {'i... | Use [`collections.defaultdict`](http://docs.python.org/2/library/collections.html#collections.defaultdict):
```
temp = defaultdict(set)
for delvt, pin in zip(delvt_list, pin_list):
temp[delvt].add(pin)
```
This creates a `defaultdict` where the default value is a set, then loop and add the values for each key.
... |
Can't get Fabric's detached screen session example to work | 14,327,649 | 8 | 2013-01-14T22:07:48Z | 14,460,261 | 11 | 2013-01-22T13:57:32Z | [
"python",
"fabric"
] | I am trying to execute a script on a remote host using a detached screen session. I tried out the [example Fabric gives](http://fabric.readthedocs.org/en/0.9.1/faq.html#why-can-t-i-run-programs-in-the-background-with-it-makes-fabric-hang) and unfortunately couldn't get it to work.
```
from fabric.api import run
def y... | `run('screen -d -m yes; sleep 1')` works.
Not sure if Fabric or screen are to blame for this behaviour though. |
Tool to convert Python code to be PEP8 compliant | 14,328,406 | 55 | 2013-01-14T23:01:31Z | 14,328,499 | 101 | 2013-01-14T23:09:23Z | [
"python",
"coding-style",
"pep8"
] | I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both [an online service](http://pep8online.com/) and [a python module](https://github.com/jcrocholl/pep8/).
However, I cannot find a service or module which can *convert* my Python file to a self-contained, PEP8... | You can use [autopep8](http://pypi.python.org/pypi/autopep8)! Whilst you make yourself a cup of coffee this tool happily removes all those pesky PEP8 violations which don't change the *meaning* of the code.
Install it via pip:
```
pip install autopep8
```
Apply this to a specific file:
```
autopep8 py_file --in-pla... |
Tool to convert Python code to be PEP8 compliant | 14,328,406 | 55 | 2013-01-14T23:01:31Z | 22,655,399 | 15 | 2014-03-26T08:38:10Z | [
"python",
"coding-style",
"pep8"
] | I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both [an online service](http://pep8online.com/) and [a python module](https://github.com/jcrocholl/pep8/).
However, I cannot find a service or module which can *convert* my Python file to a self-contained, PEP8... | Unfortunately "pep8 storming" (the entire project) has several negative side-effects:
* lots of merge-conflicts
* break git blame
* make code review difficult
As an alternative (and thanks to [@y-p for the idea](https://github.com/pydata/pandas/issues/6248)), I wrote a small package which autopep8s only those lines w... |
If Python is interpreted, why do you need a compiler for setup.py | 14,328,690 | 3 | 2013-01-14T23:27:06Z | 14,328,701 | 14 | 2013-01-14T23:28:27Z | [
"python",
"installation"
] | There's a lot about python that I just don't understand, so forgive me if this is an overly basic question.
I run python 2.7 on windows and when installing a package using setuptools' setup.py, I often run in to the following error: `error: Unable to find vcvarsall.bat` which is an issue discussed all over the place, ... | Python is interpreted, but many libraries use compiled C extensions. The error you are seeing occurs when the auto-installer is unable to compile the C extensions for a given package. |
Get size of integer in Python | 14,329,794 | 5 | 2013-01-15T01:31:38Z | 14,329,864 | 12 | 2013-01-15T01:38:37Z | [
"python",
"numbers",
"byte"
] | How can I find out the number of Bytes a certain number takes up to store e.g. for \x00 - \xFF I'm looking to get 1 (Byte), \x100 - \xffff would give me 2 (Bytes) and so on... any clue?
Thank you
Ron | Unless you're dealing with an `array.array` or a `numpy.array` - the size always has object overhead. And since Python deals with BigInts naturally, it's really, really hard to tell...
```
>>> i = 5
>>> import sys
>>> sys.getsizeof(i)
24
```
So on a 64bit platform it requires 24 bytes to store what could be stored in... |
sublime text2 python error message /usr/bin/python: can't find '__main__' module in '' | 14,330,411 | 32 | 2013-01-15T02:51:52Z | 14,330,557 | 48 | 2013-01-15T03:09:02Z | [
"python"
] | I installed sublime text 2 to OSX 10.8.2.
In my Mac, python 2.7.3 is installed.
In sublime text2, I just type
```
print 'Hello'
```
but error occurred like below.
```
/usr/bin/python: can't find '__main__' module in ''
[Finished in 0.2s with exit code 1]
```
How can I fix it? | I got the same error as I didn't save the script before executing it. Check to see if you have saved it! |
sublime text2 python error message /usr/bin/python: can't find '__main__' module in '' | 14,330,411 | 32 | 2013-01-15T02:51:52Z | 17,100,701 | 26 | 2013-06-14T03:37:22Z | [
"python"
] | I installed sublime text 2 to OSX 10.8.2.
In my Mac, python 2.7.3 is installed.
In sublime text2, I just type
```
print 'Hello'
```
but error occurred like below.
```
/usr/bin/python: can't find '__main__' module in ''
[Finished in 0.2s with exit code 1]
```
How can I fix it? | Note to anyone else:
If you have a directory like so, you can add a `__main__.py` file to tell the interpreter what to execute if you call the module directly.
```
my_module
|
| __init__.py
| my_cool_file.py # print "Hello World"
| __main__.py # import my_cool_file
```
`$ python my_module # Hello World` |
sublime text2 python error message /usr/bin/python: can't find '__main__' module in '' | 14,330,411 | 32 | 2013-01-15T02:51:52Z | 23,190,658 | 10 | 2014-04-21T04:08:03Z | [
"python"
] | I installed sublime text 2 to OSX 10.8.2.
In my Mac, python 2.7.3 is installed.
In sublime text2, I just type
```
print 'Hello'
```
but error occurred like below.
```
/usr/bin/python: can't find '__main__' module in ''
[Finished in 0.2s with exit code 1]
```
How can I fix it? | You need to SAVE your code file with the ".py" extension. Then, on the 'Tools/Build System' menu, make sure your build system is set to either 'auto' or 'Python'. What that message is telling you is there is no valid Python file to 'build' (or, in this case just run). |
How do I achieve consistent highlighting of QListWidget items across widget states? | 14,330,642 | 6 | 2013-01-15T03:20:39Z | 14,333,537 | 7 | 2013-01-15T08:13:59Z | [
"python",
"qt",
"pyqt",
"pyside"
] | I am using PyQT 4.8.3 to create a dialog with two QListWidgets both allowing multiple selection.
1. I find that if these QListWidgets are enabled, the selected items are highlighted in blue only when the QListWidget has focus, without focus the highlight is light-grey.
2. I also find that if the QListWidgets are disab... | I would use stylesheets here. In this example, the selected items in this `QListWidget` will he highlighted in blue, and when the `QListWidget` is disabled or without focus they will turn gray:
```
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui
class myWindow(QtGui.QWidget):
def __i... |
how to install libmemcached for django framework in ubuntu 10.04 | 14,332,451 | 3 | 2013-01-15T06:48:22Z | 14,332,736 | 14 | 2013-01-15T07:11:04Z | [
"python",
"django",
"libmemcached"
] | I installed libmemcached 0,37 and ln -s /usr/local/lib/libmemcached.so.2 /usr/lib/libmemcached.so.2
but when I run manage.py
it still return
import \_pylibmc
RuntimeError: pylibmc requires >= libmemcached 0.32, was compiled with 0.31
I try to install newer libmemcached,but they donot have the file libmemcached.so.2 | You just need to install these dependencies before installing `pylibmc`
```
sudo apt-get install -y libmemcached-dev zlib1g-dev libssl-dev python-dev build-essential
pip install pylibmc
```
[Here](https://gist.github.com/2203961) is gist on Github that helps you. |
awscli getting started error | 14,333,310 | 11 | 2013-01-15T07:56:07Z | 27,884,718 | 15 | 2015-01-11T06:52:50Z | [
"python",
"amazon-web-services",
"python-2.7"
] | I'd already asked this on the AWS official forum on Jan-2 but not any reply. So, I m posting it here again so that I can get the error fixed.
---
I installed awscli as stated in this page <http://docs.amazonwebservices.com/cli/latest/userguide/cli-chap-getting-started.html>
And the following is the installation deta... | Try this command
```
sudo pip install awscli --force-reinstall --upgrade
``` |
Print confusion | 14,335,556 | 5 | 2013-01-15T10:20:51Z | 14,335,652 | 11 | 2013-01-15T10:26:11Z | [
"python",
"python-2.7"
] | I am new to python when i try to print "\20%" that is
```
>>>"\20%"
```
why is the shell printing '\x10%' that is, it is showing
```
'\x10%'
```
the same is happening with join also when is do
```
>>>l = ['test','case']
>>>"\20%".join(l)
```
it shows
```
'test\x10%case'
```
I am using python 2.7.3 | `'\20'` is an octal literal, and the same as `chr(2 * 8 + 0) == chr(16)`.
What the Python shell displays by default is *not* the output of print, but the `repr`esentation of the given value, which is the hexadecimal `'\x10'`.
If you want the string `\20%`, you have to either escape the backaslash (`'\\20%'`) or use a... |
Configparser and string with % | 14,340,366 | 3 | 2013-01-15T14:55:37Z | 14,340,509 | 11 | 2013-01-15T15:02:07Z | [
"python"
] | Stupid question with (for sure) simple answer...
I am using configparser to read some strings from a file. When the string has the '%' symbol ($%& for example) it complains:
ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: "%&'"
Anybody familiar with this?
Thanks! | If you don't want environment variable substitution, then use RawConfigParser, not ConfigParser. |
Python: possible to call static method from within class without qualifying the name | 14,340,679 | 10 | 2013-01-15T15:11:14Z | 14,340,708 | 9 | 2013-01-15T15:12:33Z | [
"python",
"class",
"namespaces"
] | This is annoying:
```
class MyClass:
@staticmethod
def foo():
print "hi"
@staticmethod
def bar():
MyClass.foo()
```
Is there a way to make this work without naming MyClass in the call? i.e. so I can just say `foo()` on the last line? | There is no way to use `foo` and get what you want. There is no implicit class scope, so `foo` is either a local or a global, neither of which you want.
You might find classmethods more useful:
```
class MyClass:
@classmethod
def foo(cls):
print "hi"
@classmethod
def bar(cls):
cls.foo... |
Pass bash argument to python script | 14,340,822 | 5 | 2013-01-15T15:17:41Z | 14,340,879 | 17 | 2013-01-15T15:20:45Z | [
"python",
"linux",
"bash",
"shell",
"debian"
] | I am trying to create a bash script which passes its own argument onto a python script. I want it to work like this.
If I run it as this:
```
script.sh latest
```
Then within the bash script it runs a python script with the "latest" argument like this:
```
python script.py latest
```
Likewise if the bash script is... | In this case the trick is to pass however many arguments you have, including the case where there are none, and to preserve any grouping that existed on the original command line.
So, you want these three cases to work:
```
script.sh # no args
script.sh how now # some number
script... |
Passing a set of NumPy arrays into C function for input and output | 14,341,549 | 12 | 2013-01-15T15:54:39Z | 14,356,142 | 7 | 2013-01-16T10:23:35Z | [
"python",
"c",
"numpy",
"ctypes",
"ffi"
] | Let's assume we have a C function that takes a set of one or more input arrays, processes them, and writes its output into a set of output arrays. The signature looks as follows (with `count` representing the number of array elements to be processed):
```
void compute (int count, float** input, float** output)
```
I ... | To do this specifically with Numpy arrays, you could use:
```
import numpy as np
import ctypes
count = 5
size = 1000
#create some arrays
arrays = [np.arange(size,dtype="float32") for ii in range(count)]
#get ctypes handles
ctypes_arrays = [np.ctypeslib.as_ctypes(array) for array in arrays]
#Pack into pointer arra... |
How to mock using patch relative paths? | 14,341,689 | 10 | 2013-01-15T16:00:44Z | 17,324,911 | 9 | 2013-06-26T15:56:04Z | [
"python",
"unit-testing",
"mocking"
] | I have something like this in a python test file:
```
from mock import patch,
from ..monkey import ook
[...]
@patch('monkey.ook', Mock(return_value=None))
def test_run_ook (self, mock_ook):
self.assertIsNone(ook())
mock_ook.run.assert_called_once_with('')
```
When I run this test, I get a `ImportError: No mod... | From what I gather, with mock, you *need* to provide a dotted name when patching. Luckily, every module has access to a special module-level variable `__name__` which contains the module's name. Using this, if you want to patch variables local to your module, you *should* be able to do something like the following:
``... |
How to mock using patch relative paths? | 14,341,689 | 10 | 2013-01-15T16:00:44Z | 23,844,656 | 7 | 2014-05-24T11:48:19Z | [
"python",
"unit-testing",
"mocking"
] | I have something like this in a python test file:
```
from mock import patch,
from ..monkey import ook
[...]
@patch('monkey.ook', Mock(return_value=None))
def test_run_ook (self, mock_ook):
self.assertIsNone(ook())
mock_ook.run.assert_called_once_with('')
```
When I run this test, I get a `ImportError: No mod... | I used leo-the-manic's solution till I came across this one using `patch.object` â which looks even better to me:
```
from unittest.mock import patch,
from .. import monkey
[...]
@patch.object(monkey, 'ook', Mock(return_value=None))
def test_run_ook (self, mock_ook):
self.assertIsNone(monkey.ook())
mock_ook.... |
Pandas Merge (pd.merge) How to set the index and join | 14,341,805 | 7 | 2013-01-15T16:06:47Z | 14,342,825 | 12 | 2013-01-15T17:00:28Z | [
"python",
"pandas"
] | I have two pandas dataframes: dfLeft and dfRight with the date as the index.
dfLeft:
```
cusip factorL
date
2012-01-03 XXXX 4.5
2012-01-03 YYYY 6.2
....
2012-01-04 XXXX 4.7
2012-01-04 YYYY 6.1
....
```
dfRight:
```
idc__id factorR
date
2012-01-03 ... | Reset the indices and then merge on multiple (column-)keys:
```
dfLeft.reset_index(inplace=True)
dfRight.reset_index(inplace=True)
dfMerged = pd.merge(dfLeft, dfRight,
left_on=['date', 'cusip'],
right_on=['date', 'idc__id'],
how='inner')
```
You can then reset 'date' as an in... |
Pandas Merge (pd.merge) How to set the index and join | 14,341,805 | 7 | 2013-01-15T16:06:47Z | 14,342,919 | 8 | 2013-01-15T17:06:12Z | [
"python",
"pandas"
] | I have two pandas dataframes: dfLeft and dfRight with the date as the index.
dfLeft:
```
cusip factorL
date
2012-01-03 XXXX 4.5
2012-01-03 YYYY 6.2
....
2012-01-04 XXXX 4.7
2012-01-04 YYYY 6.1
....
```
dfRight:
```
idc__id factorR
date
2012-01-03 ... | You could append `'cuspin'` and `'idc_id'` as a indices to your DataFrames before you [`join`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html#pandas.DataFrame.join) (here's how it would work on the first couple of rows):
```
In [10]: dfL
Out[10]:
cuspin factorL
date ... |
flask-sqlalchemy or sqlalchemy | 14,343,740 | 26 | 2013-01-15T17:51:56Z | 14,353,542 | 11 | 2013-01-16T07:48:39Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I am new in both flask and sqlalchemy, I just start working on a flask app, and I am using sqlalchemy for now. I was wondering if there is any significant benefit I can get from using flask-sqlalchemy vs sqlalchemy. I could not find enough motivations in <http://packages.python.org/Flask-SQLAlchemy/index.html> or maybe... | The SQLAlchemy documentation clearly states that you should use Flask-SQLAlchemy (especially if you don't understand its benefits!):
> [...] products such as Flask-SQLAlchemy [...] SQLAlchemy strongly recommends that these products be used as available.
This quote and a detailed motivation you can find in the second ... |
flask-sqlalchemy or sqlalchemy | 14,343,740 | 26 | 2013-01-15T17:51:56Z | 15,194,033 | 9 | 2013-03-04T03:18:24Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I am new in both flask and sqlalchemy, I just start working on a flask app, and I am using sqlalchemy for now. I was wondering if there is any significant benefit I can get from using flask-sqlalchemy vs sqlalchemy. I could not find enough motivations in <http://packages.python.org/Flask-SQLAlchemy/index.html> or maybe... | To be honest, I don't see any benefits. IMHO, Flask-SQLAlchemy creates an additional layer you don't really need. In our case we have a fairly complex Flask application with multiple databases/connections (master-slave) using both ORM and Core where, among other things, we need to control our sessions / DB transactions... |
flask-sqlalchemy or sqlalchemy | 14,343,740 | 26 | 2013-01-15T17:51:56Z | 20,958,954 | 7 | 2014-01-06T20:46:09Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | I am new in both flask and sqlalchemy, I just start working on a flask app, and I am using sqlalchemy for now. I was wondering if there is any significant benefit I can get from using flask-sqlalchemy vs sqlalchemy. I could not find enough motivations in <http://packages.python.org/Flask-SQLAlchemy/index.html> or maybe... | as @schlamar suggests Flask-SqlAlchemy is defo a good thing. Id just like to add some extra context to the point made there.
Dont feel like your are choosing one over the other. For example lets say we want to grab all records from a table using a model using Flask-Sqlalchemy. It as simple as
```
Model.query.all()
``... |
Redirecting to URL in Flask | 14,343,812 | 54 | 2013-01-15T17:55:45Z | 14,343,940 | 24 | 2013-01-15T18:02:58Z | [
"python",
"flask"
] | I'm new to Python and Flask and I'm trying to do the equivalent of `Response.redirect` as in `C#` - ie: redirect to a specific URL - how do I go about this?
Here is my code:
```
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':... | From the [Flask API Documentation](http://flask.pocoo.org/docs/0.10/api/#flask.redirect):
> flask.**redirect**(`location`, `code=302`)
>
> Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported be... |
Redirecting to URL in Flask | 14,343,812 | 54 | 2013-01-15T17:55:45Z | 14,343,957 | 90 | 2013-01-15T18:03:43Z | [
"python",
"flask"
] | I'm new to Python and Flask and I'm trying to do the equivalent of `Response.redirect` as in `C#` - ie: redirect to a specific URL - how do I go about this?
Here is my code:
```
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':... | you have to return a redirect
```
import os
from flask import Flask,redirect
app = Flask(__name__)
@app.route('/')
def hello():
return redirect("http://www.example.com", code=302)
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
... |
Redirecting to URL in Flask | 14,343,812 | 54 | 2013-01-15T17:55:45Z | 14,343,978 | 29 | 2013-01-15T18:05:21Z | [
"python",
"flask"
] | I'm new to Python and Flask and I'm trying to do the equivalent of `Response.redirect` as in `C#` - ie: redirect to a specific URL - how do I go about this?
Here is my code:
```
import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
if __name__ == '__main__':... | ```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def hello():
return redirect(url_for('foo'))
@app.route('/foo')
def foo():
return 'Hello Foo!'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise def... |
Single legend for multiple axes | 14,344,063 | 14 | 2013-01-15T18:09:54Z | 14,344,146 | 27 | 2013-01-15T18:14:10Z | [
"python",
"matplotlib"
] | I have the following example code:
```
fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
legend([ax1,ax2], loc=2)
```
The subplot has two axes with different scales on the same subplot and I... | I figured it a solution that works! Is there a better way than this?
```
fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_han... |
Creating a profile model with both an InlineAdmin and a post_save signal in Django | 14,345,303 | 10 | 2013-01-15T19:23:55Z | 18,265,192 | 15 | 2013-08-16T03:05:11Z | [
"python",
"django",
"django-models",
"django-admin",
"django-signals"
] | I created a 'profile' model (with a 1-to-1 relationship to the User model) as described on [Extending the existing user model](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model). The profile model has an optional many-to-one relationship to another model:
```
class Profil... | The problem can be avoided by setting `primary_key=True` on the `OneToOneField` pointing at the `User` model, as you have figured out yourself.
The reason that this works seems to be rather simple.
When you try to create a model instance and set the `pk` manually before saving it, Django will try to find a record in ... |
Replacing part of string in python pandas dataframe | 14,345,739 | 16 | 2013-01-15T19:54:38Z | 14,345,875 | 29 | 2013-01-15T20:02:32Z | [
"python",
"csv",
"pandas"
] | I have a similar problem to the one posted here:
[Pandas DataFrame: remove unwanted parts from strings in a column](http://stackoverflow.com/questions/13682044/pandas-dataframe-remove-unwanted-parts-from-strings-in-a-column)
I need to remove newline characters from within a string in a DataFrame. Basically, I've acce... | `strip` only removes the specified characters at the beginning and end of the string. If you want to remove *all* `\n`, you need to use `replace`.
```
misc['product_desc'] = misc['product_desc'].str.replace('\n', '')
``` |
How to read named FIFO non-blockingly? | 14,345,816 | 12 | 2013-01-15T19:59:06Z | 14,345,882 | 10 | 2013-01-15T20:02:42Z | [
"python",
"nonblocking",
"fifo"
] | I create a FIFO, and periodically open it in read-only and non-blockingly mode from a.py:
```
os.mkfifo(cs_cmd_fifo_file, 0777)
io = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK)
buffer = os.read(io, BUFFER_SIZE)
```
From b.py, open the fifo for writing:
```
out = open(fifo, 'w')
out.write('sth')
```
Then a.py will ra... | According to the manpage of `read(2)`:
> ```
> EAGAIN or EWOULDBLOCK
> The file descriptor fd refers to a socket and has been marked
> nonblocking (O_NONBLOCK), and the read would block.
> POSIX.1-2001 allows either error to be returned for this case,
> and ... |
Upload image available at public URL to S3 using boto | 14,346,065 | 17 | 2013-01-15T20:14:55Z | 14,346,212 | 8 | 2013-01-15T20:24:27Z | [
"python",
"django",
"amazon-s3",
"boto"
] | I'm working in a Python web environment and I can simply upload a file from the filesystem to S3 using boto's key.set\_contents\_from\_filename(path/to/file). However, I'd like to upload an image that is already on the web (say <https://pbs.twimg.com/media/A9h_htACIAAaCf6.jpg:large>).
Should I somehow download the ima... | Unfortunately, there really isn't any way to do this. At least not at the moment. We could add a method to boto, say `set_contents_from_url`, but that method would still have to download the file to the local machine and then upload it. It might still be a convenient method but it wouldn't save you anything.
In order ... |
Upload image available at public URL to S3 using boto | 14,346,065 | 17 | 2013-01-15T20:14:55Z | 14,347,229 | 19 | 2013-01-15T21:26:00Z | [
"python",
"django",
"amazon-s3",
"boto"
] | I'm working in a Python web environment and I can simply upload a file from the filesystem to S3 using boto's key.set\_contents\_from\_filename(path/to/file). However, I'd like to upload an image that is already on the web (say <https://pbs.twimg.com/media/A9h_htACIAAaCf6.jpg:large>).
Should I somehow download the ima... | Ok, from @garnaat, it doesn't sound like S3 currently allows uploads by url. I managed to upload remote images to S3 by reading them into memory only. This works.
```
def upload(url):
try:
conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
bucket_name = settings.AWS_... |
ImportError: No module named _backend_gdk | 14,346,090 | 8 | 2013-01-15T20:16:28Z | 14,712,588 | 11 | 2013-02-05T16:48:08Z | [
"python",
"matplotlib",
"pygtk"
] | I am starting to get some insight into interactive plotting with python and matplotlib using pyGTK+. Therefore I took a look at the example given at the matplotlib website:
<http://matplotlib.org/examples/user_interfaces/gtk_spreadsheet.html>
This is a short exerpt of the Code:
```
#!/usr/bin/env python
"""
Example ... | Note that the Debian/Ubuntu package you need is not 'pygtk2-devel' but 'python-gtk2-dev':
```
sudo apt-get install python-gtk2-dev
```
should fix this error on these platforms. |
Single versus double quotes in json loads in Python | 14,347,047 | 6 | 2013-01-15T21:14:11Z | 14,347,168 | 17 | 2013-01-15T21:22:15Z | [
"python",
"json",
"simplejson"
] | I notice that single quotes cause `simplejson`'s `loads` function to fail:
```
>>> import simplejson as json
>>> json.loads("\"foo\"")
'foo'
>>> json.loads("\'foo\'")
Traceback (most recent call last):
...
ValueError: No JSON object could be decoded
```
I'm parsing things like: `foo = ["a", "b", "c"]` from a textfile... | Use the proper tool for the job, you are not parsing JSON but Python, so use [`ast.literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval) instead:
```
>>> import ast
>>> ast.literal_eval('["a", "b", "c"]')
['a', 'b', 'c']
>>> ast.literal_eval("['a', 'b', 'c']")
['a', 'b', 'c']
>>> ast.literal_eva... |
PyQt Irregularly Shaped Windows (e.g. A circular without a border/decorations) | 14,347,163 | 4 | 2013-01-15T21:22:01Z | 14,348,312 | 7 | 2013-01-15T22:42:42Z | [
"python",
"pyqt"
] | How do I create an irregularly shaped window in PyQt?
I found [this C++ solution](http://stackoverflow.com/questions/1333610/displaying-translucent-irregular-shaped-windows-with-qt), however I am unsure of how to do that in Python. | Here you go:
```
from PyQt4 import QtGui, QtWebKit
from PyQt4.QtCore import Qt, QSize
class RoundWindow(QtWebKit.QWebView):
def __init__(self):
super(RoundWindow, self).__init__()
self.initUI()
def initUI(self):
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.... |
How do I display a PIL Image object in a template? | 14,348,442 | 14 | 2013-01-15T22:53:32Z | 14,348,592 | 11 | 2013-01-15T23:05:46Z | [
"python",
"django",
"image",
"django-templates",
"python-imaging-library"
] | If a user uploads an image, and I resize it using PIL, I get a [PIL Image object](http://www.pythonware.com/library/pil/handbook/introduction.htm).
How do I display a `PIL Image` file in a template, before it has been saved to the database? Can it even be passed in as an image and rendered? | For a limited set of browsers, you can base64 encode the image and use inline images. See [Embedding Base64 Images](http://stackoverflow.com/questions/1207190/embedding-base64-images).
A solution that works for all browsers is an image tag referencing a [view that returns the image](http://effbot.org/zone/django-pil.h... |
How do I display a PIL Image object in a template? | 14,348,442 | 14 | 2013-01-15T22:53:32Z | 14,348,661 | 13 | 2013-01-15T23:11:39Z | [
"python",
"django",
"image",
"django-templates",
"python-imaging-library"
] | If a user uploads an image, and I resize it using PIL, I get a [PIL Image object](http://www.pythonware.com/library/pil/handbook/introduction.htm).
How do I display a `PIL Image` file in a template, before it has been saved to the database? Can it even be passed in as an image and rendered? | Yes and no.
Yes, you can put the images as raw Base64 data. Here's a little script you can use to test this:
```
import Image
import base64
import StringIO
output = StringIO.StringIO()
im = Image.open("test.png") # Your image here!
im.save(output, format='PNG')
output.seek(0)
output_s = output.read()
b64 = base64.b64... |
making matplotlib graphs look like R by default? | 14,349,055 | 49 | 2013-01-15T23:45:53Z | 14,349,645 | 10 | 2013-01-16T00:44:17Z | [
"python",
"matplotlib",
"plot",
"pandas"
] | Is there a way to make `matplotlib` behave identically to R, or almost like R, in terms of plotting defaults? For example R treats its axes pretty differently from `matplotlib`. The following histogram

has "floating axes" with outward ticks, such that... | I would check out [Bokeh](https://github.com/ContinuumIO/Bokeh/) which aims to "provide a compelling Python equivalent of ggplot in R". Example [here](http://htmlpreview.github.com/?https://github.com/ContinuumIO/Bokeh/blob/master/tests/cdx/bokeh-facets.html)
EDIT: Also check out [Seaborn](http://stanford.edu/~mwaskom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.